1 use actix_http::header::{HeaderName, ACCEPT_ENCODING, HOST};
2 use actix_web::{body::BodyStream, http::StatusCode, web::Data, *};
4 use futures::stream::{Stream, StreamExt};
5 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, LemmyError};
6 use lemmy_websocket::LemmyContext;
8 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
9 use serde::{Deserialize, Serialize};
10 use std::time::Duration;
12 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
14 .app_data(Data::new(client))
16 web::resource("/pictrs/image")
17 .wrap(rate_limit.image())
18 .route(web::post().to(upload)),
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)));
25 #[derive(Debug, Serialize, Deserialize)]
31 #[derive(Debug, Serialize, Deserialize)]
34 files: Option<Vec<Image>>,
37 #[derive(Deserialize)]
39 format: Option<String>,
40 thumbnail: Option<String>,
44 request: &HttpRequest,
45 client: &ClientWithMiddleware,
48 // remove accept-encoding header so that pictrs doesnt compress the response
49 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
51 let client_request = client
52 .request(request.method().clone(), url)
53 .timeout(Duration::from_secs(30));
58 .fold(client_request, |client_req, (key, value)| {
59 if INVALID_HEADERS.contains(key) {
62 client_req.header(key, value)
70 client: web::Data<ClientWithMiddleware>,
71 context: web::Data<LemmyContext>,
72 ) -> Result<HttpResponse, Error> {
73 // TODO: check rate limit here
76 .expect("No auth header for picture upload");
78 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
79 return Ok(HttpResponse::Unauthorized().finish());
82 let image_url = format!("{}/image", pictrs_url(context.settings().pictrs_url)?);
84 let mut client_req = adapt_request(&req, &client, image_url);
86 if let Some(addr) = req.head().peer_addr {
87 client_req = client_req.header("X-Forwarded-For", addr.to_string())
91 .body(Body::wrap_stream(make_send(body)))
94 .map_err(error::ErrorBadRequest)?;
96 let status = res.status();
97 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
99 Ok(HttpResponse::build(status).json(images))
103 filename: web::Path<String>,
104 web::Query(params): web::Query<PictrsParams>,
106 client: web::Data<ClientWithMiddleware>,
107 context: web::Data<LemmyContext>,
108 ) -> Result<HttpResponse, Error> {
109 let name = &filename.into_inner();
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() {
115 "{}/image/original/{}",
116 pictrs_url(pictrs_url_settings)?,
120 // Use jpg as a default when none is given
121 let format = params.format.unwrap_or_else(|| "jpg".to_string());
123 let mut url = format!(
124 "{}/image/process.{}?src={}",
125 pictrs_url(pictrs_url_settings)?,
130 if let Some(size) = params.thumbnail {
131 url = format!("{}&thumbnail={}", url, size,);
136 image(url, req, client).await
142 client: web::Data<ClientWithMiddleware>,
143 ) -> Result<HttpResponse, Error> {
144 let mut client_req = adapt_request(&req, &client, url);
146 if let Some(addr) = req.head().peer_addr {
147 client_req = client_req.header("X-Forwarded-For", addr.to_string());
150 if let Some(addr) = req.head().peer_addr {
151 client_req = client_req.header("X-Forwarded-For", addr.to_string());
154 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
156 if res.status() == StatusCode::NOT_FOUND {
157 return Ok(HttpResponse::NotFound().finish());
160 let mut client_res = HttpResponse::build(res.status());
162 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
163 client_res.insert_header((name.clone(), value.clone()));
166 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
170 components: web::Path<(String, String)>,
172 client: web::Data<ClientWithMiddleware>,
173 context: web::Data<LemmyContext>,
174 ) -> Result<HttpResponse, Error> {
175 let (token, file) = components.into_inner();
178 "{}/image/delete/{}/{}",
179 pictrs_url(context.settings().pictrs_url)?,
184 let mut client_req = adapt_request(&req, &client, url);
186 if let Some(addr) = req.head().peer_addr {
187 client_req = client_req.header("X-Forwarded-For", addr.to_string());
190 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
192 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
195 fn pictrs_url(pictrs_url: Option<String>) -> Result<String, LemmyError> {
196 pictrs_url.ok_or_else(|| anyhow!("images_disabled").into())
199 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
201 S: Stream + Unpin + 'static,
204 // NOTE: the 8 here is arbitrary
205 let (tx, rx) = tokio::sync::mpsc::channel(8);
207 // NOTE: spawning stream into a new task can potentially hit this bug:
208 // - https://github.com/actix/actix-web/issues/1679
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() {
223 struct SendStream<T> {
224 rx: tokio::sync::mpsc::Receiver<T>,
227 impl<T> Stream for SendStream<T>
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)