5 header::{HeaderName, ACCEPT_ENCODING, HOST},
13 use futures::stream::{Stream, StreamExt};
14 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, REQWEST_TIMEOUT};
15 use lemmy_websocket::LemmyContext;
17 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
18 use serde::{Deserialize, Serialize};
20 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
22 .app_data(web::Data::new(client))
24 web::resource("/pictrs/image")
25 .wrap(rate_limit.image())
26 .route(web::post().to(upload)),
28 // This has optional query params: /image/{filename}?format=jpg&thumbnail=256
29 .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
30 .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
33 #[derive(Debug, Serialize, Deserialize)]
39 #[derive(Debug, Serialize, Deserialize)]
42 files: Option<Vec<Image>>,
45 #[derive(Deserialize)]
47 format: Option<String>,
48 thumbnail: Option<String>,
51 #[derive(Deserialize)]
52 enum PictrsPurgeParams {
53 #[serde(rename = "file")]
55 #[serde(rename = "alias")]
60 request: &HttpRequest,
61 client: &ClientWithMiddleware,
64 // remove accept-encoding header so that pictrs doesnt compress the response
65 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
67 let client_request = client
68 .request(request.method().clone(), url)
69 .timeout(REQWEST_TIMEOUT);
74 .fold(client_request, |client_req, (key, value)| {
75 if INVALID_HEADERS.contains(key) {
78 client_req.header(key, value)
86 client: web::Data<ClientWithMiddleware>,
87 context: web::Data<LemmyContext>,
88 ) -> Result<HttpResponse, Error> {
89 // TODO: check rate limit here
92 .expect("No auth header for picture upload");
94 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
95 return Ok(HttpResponse::Unauthorized().finish());
98 let pictrs_config = context.settings().pictrs_config()?;
99 let image_url = format!("{}/image", pictrs_config.url);
101 let mut client_req = adapt_request(&req, &client, image_url);
103 if let Some(addr) = req.head().peer_addr {
104 client_req = client_req.header("X-Forwarded-For", addr.to_string())
108 .body(Body::wrap_stream(make_send(body)))
111 .map_err(error::ErrorBadRequest)?;
113 let status = res.status();
114 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
116 Ok(HttpResponse::build(status).json(images))
120 filename: web::Path<String>,
121 web::Query(params): web::Query<PictrsParams>,
123 client: web::Data<ClientWithMiddleware>,
124 context: web::Data<LemmyContext>,
125 ) -> Result<HttpResponse, Error> {
126 let name = &filename.into_inner();
128 // If there are no query params, the URL is original
129 let pictrs_config = context.settings().pictrs_config()?;
130 let url = if params.format.is_none() && params.thumbnail.is_none() {
131 format!("{}/image/original/{}", pictrs_config.url, name,)
133 // Use jpg as a default when none is given
134 let format = params.format.unwrap_or_else(|| "jpg".to_string());
136 let mut url = format!(
137 "{}/image/process.{}?src={}",
138 pictrs_config.url, format, name,
141 if let Some(size) = params.thumbnail {
142 url = format!("{}&thumbnail={}", url, size,);
147 image(url, req, client).await
153 client: web::Data<ClientWithMiddleware>,
154 ) -> Result<HttpResponse, Error> {
155 let mut client_req = adapt_request(&req, &client, url);
157 if let Some(addr) = req.head().peer_addr {
158 client_req = client_req.header("X-Forwarded-For", addr.to_string());
161 if let Some(addr) = req.head().peer_addr {
162 client_req = client_req.header("X-Forwarded-For", addr.to_string());
165 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
167 if res.status() == StatusCode::NOT_FOUND {
168 return Ok(HttpResponse::NotFound().finish());
171 let mut client_res = HttpResponse::build(res.status());
173 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
174 client_res.insert_header((name.clone(), value.clone()));
177 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
181 components: web::Path<(String, String)>,
183 client: web::Data<ClientWithMiddleware>,
184 context: web::Data<LemmyContext>,
185 ) -> Result<HttpResponse, Error> {
186 let (token, file) = components.into_inner();
188 let pictrs_config = context.settings().pictrs_config()?;
189 let url = format!("{}/image/delete/{}/{}", pictrs_config.url, &token, &file);
191 let mut client_req = adapt_request(&req, &client, url);
193 if let Some(addr) = req.head().peer_addr {
194 client_req = client_req.header("X-Forwarded-For", addr.to_string());
197 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
199 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
202 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
204 S: Stream + Unpin + 'static,
207 // NOTE: the 8 here is arbitrary
208 let (tx, rx) = tokio::sync::mpsc::channel(8);
210 // NOTE: spawning stream into a new task can potentially hit this bug:
211 // - https://github.com/actix/actix-web/issues/1679
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() {
226 struct SendStream<T> {
227 rx: tokio::sync::mpsc::Receiver<T>,
230 impl<T> Stream for SendStream<T>
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)