5 header::{HeaderName, ACCEPT_ENCODING, HOST},
14 use futures::stream::{Stream, StreamExt};
15 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, LemmyError};
16 use lemmy_websocket::LemmyContext;
18 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
19 use serde::{Deserialize, Serialize};
20 use std::time::Duration;
22 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
24 .app_data(web::Data::new(client))
26 web::resource("/pictrs/image")
27 .wrap(rate_limit.image())
28 .route(web::post().to(upload)),
30 // This has optional query params: /image/{filename}?format=jpg&thumbnail=256
31 .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
32 .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
35 #[derive(Debug, Serialize, Deserialize)]
41 #[derive(Debug, Serialize, Deserialize)]
44 files: Option<Vec<Image>>,
47 #[derive(Deserialize)]
49 format: Option<String>,
50 thumbnail: Option<String>,
54 request: &HttpRequest,
55 client: &ClientWithMiddleware,
58 // remove accept-encoding header so that pictrs doesnt compress the response
59 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
61 let client_request = client
62 .request(request.method().clone(), url)
63 .timeout(Duration::from_secs(30));
68 .fold(client_request, |client_req, (key, value)| {
69 if INVALID_HEADERS.contains(key) {
72 client_req.header(key, value)
80 client: web::Data<ClientWithMiddleware>,
81 context: web::Data<LemmyContext>,
82 ) -> Result<HttpResponse, Error> {
83 // TODO: check rate limit here
86 .expect("No auth header for picture upload");
88 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
89 return Ok(HttpResponse::Unauthorized().finish());
92 let image_url = format!("{}/image", pictrs_url(context.settings().pictrs_url)?);
94 let mut client_req = adapt_request(&req, &client, image_url);
96 if let Some(addr) = req.head().peer_addr {
97 client_req = client_req.header("X-Forwarded-For", addr.to_string())
101 .body(Body::wrap_stream(make_send(body)))
104 .map_err(error::ErrorBadRequest)?;
106 let status = res.status();
107 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
109 Ok(HttpResponse::build(status).json(images))
113 filename: web::Path<String>,
114 web::Query(params): web::Query<PictrsParams>,
116 client: web::Data<ClientWithMiddleware>,
117 context: web::Data<LemmyContext>,
118 ) -> Result<HttpResponse, Error> {
119 let name = &filename.into_inner();
121 // If there are no query params, the URL is original
122 let pictrs_url_settings = context.settings().pictrs_url;
123 let url = if params.format.is_none() && params.thumbnail.is_none() {
125 "{}/image/original/{}",
126 pictrs_url(pictrs_url_settings)?,
130 // Use jpg as a default when none is given
131 let format = params.format.unwrap_or_else(|| "jpg".to_string());
133 let mut url = format!(
134 "{}/image/process.{}?src={}",
135 pictrs_url(pictrs_url_settings)?,
140 if let Some(size) = params.thumbnail {
141 url = format!("{}&thumbnail={}", url, size,);
146 image(url, req, client).await
152 client: web::Data<ClientWithMiddleware>,
153 ) -> Result<HttpResponse, Error> {
154 let mut client_req = adapt_request(&req, &client, url);
156 if let Some(addr) = req.head().peer_addr {
157 client_req = client_req.header("X-Forwarded-For", addr.to_string());
160 if let Some(addr) = req.head().peer_addr {
161 client_req = client_req.header("X-Forwarded-For", addr.to_string());
164 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
166 if res.status() == StatusCode::NOT_FOUND {
167 return Ok(HttpResponse::NotFound().finish());
170 let mut client_res = HttpResponse::build(res.status());
172 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
173 client_res.insert_header((name.clone(), value.clone()));
176 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
180 components: web::Path<(String, String)>,
182 client: web::Data<ClientWithMiddleware>,
183 context: web::Data<LemmyContext>,
184 ) -> Result<HttpResponse, Error> {
185 let (token, file) = components.into_inner();
188 "{}/image/delete/{}/{}",
189 pictrs_url(context.settings().pictrs_url)?,
194 let mut client_req = adapt_request(&req, &client, url);
196 if let Some(addr) = req.head().peer_addr {
197 client_req = client_req.header("X-Forwarded-For", addr.to_string());
200 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
202 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
205 fn pictrs_url(pictrs_url: Option<String>) -> Result<String, LemmyError> {
206 pictrs_url.ok_or_else(|| anyhow!("images_disabled").into())
209 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
211 S: Stream + Unpin + 'static,
214 // NOTE: the 8 here is arbitrary
215 let (tx, rx) = tokio::sync::mpsc::channel(8);
217 // NOTE: spawning stream into a new task can potentially hit this bug:
218 // - https://github.com/actix/actix-web/issues/1679
220 // Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
221 // That said, it is still technically possible to encounter.
222 actix_web::rt::spawn(async move {
223 while let Some(res) = stream.next().await {
224 if tx.send(res).await.is_err() {
233 struct SendStream<T> {
234 rx: tokio::sync::mpsc::Receiver<T>,
237 impl<T> Stream for SendStream<T>
244 mut self: std::pin::Pin<&mut Self>,
245 cx: &mut std::task::Context<'_>,
246 ) -> std::task::Poll<Option<Self::Item>> {
247 std::pin::Pin::new(&mut self.rx).poll_recv(cx)