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