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