5 header::{HeaderName, ACCEPT_ENCODING, HOST},
14 use futures::stream::{Stream, StreamExt};
15 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, LemmyError, REQWEST_TIMEOUT};
16 use lemmy_websocket::LemmyContext;
18 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
19 use serde::{Deserialize, Serialize};
21 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
23 .app_data(web::Data::new(client))
25 web::resource("/pictrs/image")
26 .wrap(rate_limit.image())
27 .route(web::post().to(upload)),
29 // This has optional query params: /image/{filename}?format=jpg&thumbnail=256
30 .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
31 .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
34 #[derive(Debug, Serialize, Deserialize)]
40 #[derive(Debug, Serialize, Deserialize)]
43 files: Option<Vec<Image>>,
46 #[derive(Deserialize)]
48 format: Option<String>,
49 thumbnail: Option<String>,
53 request: &HttpRequest,
54 client: &ClientWithMiddleware,
57 // remove accept-encoding header so that pictrs doesnt compress the response
58 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
60 let client_request = client
61 .request(request.method().clone(), url)
62 .timeout(REQWEST_TIMEOUT);
67 .fold(client_request, |client_req, (key, value)| {
68 if INVALID_HEADERS.contains(key) {
71 client_req.header(key, value)
79 client: web::Data<ClientWithMiddleware>,
80 context: web::Data<LemmyContext>,
81 ) -> Result<HttpResponse, Error> {
82 // TODO: check rate limit here
85 .expect("No auth header for picture upload");
87 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
88 return Ok(HttpResponse::Unauthorized().finish());
91 let image_url = format!("{}/image", pictrs_url(context.settings().pictrs_url)?);
93 let mut client_req = adapt_request(&req, &client, image_url);
95 if let Some(addr) = req.head().peer_addr {
96 client_req = client_req.header("X-Forwarded-For", addr.to_string())
100 .body(Body::wrap_stream(make_send(body)))
103 .map_err(error::ErrorBadRequest)?;
105 let status = res.status();
106 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
108 Ok(HttpResponse::build(status).json(images))
112 filename: web::Path<String>,
113 web::Query(params): web::Query<PictrsParams>,
115 client: web::Data<ClientWithMiddleware>,
116 context: web::Data<LemmyContext>,
117 ) -> Result<HttpResponse, Error> {
118 let name = &filename.into_inner();
120 // If there are no query params, the URL is original
121 let pictrs_url_settings = context.settings().pictrs_url;
122 let url = if params.format.is_none() && params.thumbnail.is_none() {
124 "{}/image/original/{}",
125 pictrs_url(pictrs_url_settings)?,
129 // Use jpg as a default when none is given
130 let format = params.format.unwrap_or_else(|| "jpg".to_string());
132 let mut url = format!(
133 "{}/image/process.{}?src={}",
134 pictrs_url(pictrs_url_settings)?,
139 if let Some(size) = params.thumbnail {
140 url = format!("{}&thumbnail={}", url, size,);
145 image(url, req, client).await
151 client: web::Data<ClientWithMiddleware>,
152 ) -> Result<HttpResponse, Error> {
153 let mut client_req = adapt_request(&req, &client, url);
155 if let Some(addr) = req.head().peer_addr {
156 client_req = client_req.header("X-Forwarded-For", addr.to_string());
159 if let Some(addr) = req.head().peer_addr {
160 client_req = client_req.header("X-Forwarded-For", addr.to_string());
163 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
165 if res.status() == StatusCode::NOT_FOUND {
166 return Ok(HttpResponse::NotFound().finish());
169 let mut client_res = HttpResponse::build(res.status());
171 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
172 client_res.insert_header((name.clone(), value.clone()));
175 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
179 components: web::Path<(String, String)>,
181 client: web::Data<ClientWithMiddleware>,
182 context: web::Data<LemmyContext>,
183 ) -> Result<HttpResponse, Error> {
184 let (token, file) = components.into_inner();
187 "{}/image/delete/{}/{}",
188 pictrs_url(context.settings().pictrs_url)?,
193 let mut client_req = adapt_request(&req, &client, url);
195 if let Some(addr) = req.head().peer_addr {
196 client_req = client_req.header("X-Forwarded-For", addr.to_string());
199 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
201 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
204 fn pictrs_url(pictrs_url: Option<String>) -> Result<String, LemmyError> {
205 pictrs_url.ok_or_else(|| anyhow!("images_disabled").into())
208 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
210 S: Stream + Unpin + 'static,
213 // NOTE: the 8 here is arbitrary
214 let (tx, rx) = tokio::sync::mpsc::channel(8);
216 // NOTE: spawning stream into a new task can potentially hit this bug:
217 // - https://github.com/actix/actix-web/issues/1679
219 // Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
220 // That said, it is still technically possible to encounter.
221 actix_web::rt::spawn(async move {
222 while let Some(res) = stream.next().await {
223 if tx.send(res).await.is_err() {
232 struct SendStream<T> {
233 rx: tokio::sync::mpsc::Receiver<T>,
236 impl<T> Stream for SendStream<T>
243 mut self: std::pin::Pin<&mut Self>,
244 cx: &mut std::task::Context<'_>,
245 ) -> std::task::Poll<Option<Self::Item>> {
246 std::pin::Pin::new(&mut self.rx).poll_recv(cx)