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