]> Untitled Git - lemmy.git/blob - crates/routes/src/images.rs
30a6a378ff811fc1806e86733e08a0d84b8ff474
[lemmy.git] / crates / routes / src / images.rs
1 use actix_http::header::{HeaderName, ACCEPT_ENCODING, HOST};
2 use actix_web::{body::BodyStream, http::StatusCode, web::Data, *};
3 use anyhow::anyhow;
4 use futures::stream::{Stream, StreamExt};
5 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, LemmyError};
6 use lemmy_websocket::LemmyContext;
7 use reqwest::Body;
8 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
9 use serde::{Deserialize, Serialize};
10 use std::time::Duration;
11
12 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
13   cfg
14     .app_data(Data::new(client))
15     .service(
16       web::resource("/pictrs/image")
17         .wrap(rate_limit.image())
18         .route(web::post().to(upload)),
19     )
20     // This has optional query params: /image/{filename}?format=jpg&thumbnail=256
21     .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
22     .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
23 }
24
25 #[derive(Debug, Serialize, Deserialize)]
26 struct Image {
27   file: String,
28   delete_token: String,
29 }
30
31 #[derive(Debug, Serialize, Deserialize)]
32 struct Images {
33   msg: String,
34   files: Option<Vec<Image>>,
35 }
36
37 #[derive(Deserialize)]
38 struct PictrsParams {
39   format: Option<String>,
40   thumbnail: Option<String>,
41 }
42
43 fn adapt_request(
44   request: &HttpRequest,
45   client: &ClientWithMiddleware,
46   url: String,
47 ) -> RequestBuilder {
48   // remove accept-encoding header so that pictrs doesnt compress the response
49   const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
50
51   let client_request = client
52     .request(request.method().clone(), url)
53     .timeout(Duration::from_secs(30));
54
55   request
56     .headers()
57     .iter()
58     .fold(client_request, |client_req, (key, value)| {
59       if INVALID_HEADERS.contains(key) {
60         client_req
61       } else {
62         client_req.header(key, value)
63       }
64     })
65 }
66
67 async fn upload(
68   req: HttpRequest,
69   body: web::Payload,
70   client: web::Data<ClientWithMiddleware>,
71   context: web::Data<LemmyContext>,
72 ) -> Result<HttpResponse, Error> {
73   // TODO: check rate limit here
74   let jwt = req
75     .cookie("jwt")
76     .expect("No auth header for picture upload");
77
78   if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
79     return Ok(HttpResponse::Unauthorized().finish());
80   };
81
82   let image_url = format!("{}/image", pictrs_url(context.settings().pictrs_url)?);
83
84   let mut client_req = adapt_request(&req, &client, image_url);
85
86   if let Some(addr) = req.head().peer_addr {
87     client_req = client_req.header("X-Forwarded-For", addr.to_string())
88   };
89
90   let res = client_req
91     .body(Body::wrap_stream(make_send(body)))
92     .send()
93     .await
94     .map_err(error::ErrorBadRequest)?;
95
96   let status = res.status();
97   let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
98
99   Ok(HttpResponse::build(status).json(images))
100 }
101
102 async fn full_res(
103   filename: web::Path<String>,
104   web::Query(params): web::Query<PictrsParams>,
105   req: HttpRequest,
106   client: web::Data<ClientWithMiddleware>,
107   context: web::Data<LemmyContext>,
108 ) -> Result<HttpResponse, Error> {
109   let name = &filename.into_inner();
110
111   // If there are no query params, the URL is original
112   let pictrs_url_settings = context.settings().pictrs_url;
113   let url = if params.format.is_none() && params.thumbnail.is_none() {
114     format!(
115       "{}/image/original/{}",
116       pictrs_url(pictrs_url_settings)?,
117       name,
118     )
119   } else {
120     // Use jpg as a default when none is given
121     let format = params.format.unwrap_or_else(|| "jpg".to_string());
122
123     let mut url = format!(
124       "{}/image/process.{}?src={}",
125       pictrs_url(pictrs_url_settings)?,
126       format,
127       name,
128     );
129
130     if let Some(size) = params.thumbnail {
131       url = format!("{}&thumbnail={}", url, size,);
132     }
133     url
134   };
135
136   image(url, req, client).await
137 }
138
139 async fn image(
140   url: String,
141   req: HttpRequest,
142   client: web::Data<ClientWithMiddleware>,
143 ) -> Result<HttpResponse, Error> {
144   let mut client_req = adapt_request(&req, &client, url);
145
146   if let Some(addr) = req.head().peer_addr {
147     client_req = client_req.header("X-Forwarded-For", addr.to_string());
148   }
149
150   if let Some(addr) = req.head().peer_addr {
151     client_req = client_req.header("X-Forwarded-For", addr.to_string());
152   }
153
154   let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
155
156   if res.status() == StatusCode::NOT_FOUND {
157     return Ok(HttpResponse::NotFound().finish());
158   }
159
160   let mut client_res = HttpResponse::build(res.status());
161
162   for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
163     client_res.insert_header((name.clone(), value.clone()));
164   }
165
166   Ok(client_res.body(BodyStream::new(res.bytes_stream())))
167 }
168
169 async fn delete(
170   components: web::Path<(String, String)>,
171   req: HttpRequest,
172   client: web::Data<ClientWithMiddleware>,
173   context: web::Data<LemmyContext>,
174 ) -> Result<HttpResponse, Error> {
175   let (token, file) = components.into_inner();
176
177   let url = format!(
178     "{}/image/delete/{}/{}",
179     pictrs_url(context.settings().pictrs_url)?,
180     &token,
181     &file
182   );
183
184   let mut client_req = adapt_request(&req, &client, url);
185
186   if let Some(addr) = req.head().peer_addr {
187     client_req = client_req.header("X-Forwarded-For", addr.to_string());
188   }
189
190   let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
191
192   Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
193 }
194
195 fn pictrs_url(pictrs_url: Option<String>) -> Result<String, LemmyError> {
196   pictrs_url.ok_or_else(|| anyhow!("images_disabled").into())
197 }
198
199 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
200 where
201   S: Stream + Unpin + 'static,
202   S::Item: Send,
203 {
204   // NOTE: the 8 here is arbitrary
205   let (tx, rx) = tokio::sync::mpsc::channel(8);
206
207   // NOTE: spawning stream into a new task can potentially hit this bug:
208   // - https://github.com/actix/actix-web/issues/1679
209   //
210   // Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
211   // That said, it is still technically possible to encounter.
212   actix_web::rt::spawn(async move {
213     while let Some(res) = stream.next().await {
214       if tx.send(res).await.is_err() {
215         break;
216       }
217     }
218   });
219
220   SendStream { rx }
221 }
222
223 struct SendStream<T> {
224   rx: tokio::sync::mpsc::Receiver<T>,
225 }
226
227 impl<T> Stream for SendStream<T>
228 where
229   T: Send,
230 {
231   type Item = T;
232
233   fn poll_next(
234     mut self: std::pin::Pin<&mut Self>,
235     cx: &mut std::task::Context<'_>,
236   ) -> std::task::Poll<Option<Self::Item>> {
237     std::pin::Pin::new(&mut self.rx).poll_recv(cx)
238   }
239 }