5 header::{HeaderName, ACCEPT_ENCODING, HOST},
13 use futures::stream::{Stream, StreamExt};
14 use lemmy_api_common::utils::{blocking, get_local_user_view_from_jwt};
15 use lemmy_db_schema::source::local_site::LocalSite;
16 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, REQWEST_TIMEOUT};
17 use lemmy_websocket::LemmyContext;
19 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
20 use serde::{Deserialize, Serialize};
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<i32>,
53 #[derive(Deserialize)]
54 enum PictrsPurgeParams {
55 #[serde(rename = "file")]
57 #[serde(rename = "alias")]
62 request: &HttpRequest,
63 client: &ClientWithMiddleware,
66 // remove accept-encoding header so that pictrs doesnt compress the response
67 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
69 let client_request = client
70 .request(request.method().clone(), url)
71 .timeout(REQWEST_TIMEOUT);
76 .fold(client_request, |client_req, (key, value)| {
77 if INVALID_HEADERS.contains(key) {
80 client_req.header(key, value)
88 client: web::Data<ClientWithMiddleware>,
89 context: web::Data<LemmyContext>,
90 ) -> Result<HttpResponse, Error> {
91 // TODO: check rate limit here
94 .expect("No auth header for picture upload");
96 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
97 return Ok(HttpResponse::Unauthorized().finish());
100 let pictrs_config = context.settings().pictrs_config()?;
101 let image_url = format!("{}image", pictrs_config.url);
103 let mut client_req = adapt_request(&req, &client, image_url);
105 if let Some(addr) = req.head().peer_addr {
106 client_req = client_req.header("X-Forwarded-For", addr.to_string())
110 .body(Body::wrap_stream(make_send(body)))
113 .map_err(error::ErrorBadRequest)?;
115 let status = res.status();
116 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
118 Ok(HttpResponse::build(status).json(images))
122 filename: web::Path<String>,
123 web::Query(params): web::Query<PictrsParams>,
125 client: web::Data<ClientWithMiddleware>,
126 context: web::Data<LemmyContext>,
127 ) -> Result<HttpResponse, Error> {
128 // block access to images if instance is private and unauthorized, public
129 let local_site = blocking(context.pool(), LocalSite::read)
131 .map_err(error::ErrorBadRequest)?;
132 // The site might not be set up yet
133 if local_site.private_instance {
136 .expect("No auth header for picture access");
137 if get_local_user_view_from_jwt(jwt.value(), context.pool(), context.secret())
141 return Ok(HttpResponse::Unauthorized().finish());
144 let name = &filename.into_inner();
146 // If there are no query params, the URL is original
147 let pictrs_config = context.settings().pictrs_config()?;
148 let url = if params.format.is_none() && params.thumbnail.is_none() {
149 format!("{}image/original/{}", pictrs_config.url, name,)
151 // Take file type from name, or jpg if nothing is given
154 .unwrap_or_else(|| name.split('.').last().unwrap_or("jpg").to_string());
156 let mut url = format!("{}image/process.{}?src={}", pictrs_config.url, format, name,);
158 if let Some(size) = params.thumbnail {
159 url = format!("{}&thumbnail={}", url, size,);
164 image(url, req, client).await
170 client: web::Data<ClientWithMiddleware>,
171 ) -> Result<HttpResponse, Error> {
172 let mut client_req = adapt_request(&req, &client, url);
174 if let Some(addr) = req.head().peer_addr {
175 client_req = client_req.header("X-Forwarded-For", addr.to_string());
178 if let Some(addr) = req.head().peer_addr {
179 client_req = client_req.header("X-Forwarded-For", addr.to_string());
182 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
184 if res.status() == StatusCode::NOT_FOUND {
185 return Ok(HttpResponse::NotFound().finish());
188 let mut client_res = HttpResponse::build(res.status());
190 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
191 client_res.insert_header((name.clone(), value.clone()));
194 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
198 components: web::Path<(String, String)>,
200 client: web::Data<ClientWithMiddleware>,
201 context: web::Data<LemmyContext>,
202 ) -> Result<HttpResponse, Error> {
203 let (token, file) = components.into_inner();
205 let pictrs_config = context.settings().pictrs_config()?;
206 let url = format!("{}image/delete/{}/{}", pictrs_config.url, &token, &file);
208 let mut client_req = adapt_request(&req, &client, url);
210 if let Some(addr) = req.head().peer_addr {
211 client_req = client_req.header("X-Forwarded-For", addr.to_string());
214 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
216 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
219 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
221 S: Stream + Unpin + 'static,
224 // NOTE: the 8 here is arbitrary
225 let (tx, rx) = tokio::sync::mpsc::channel(8);
227 // NOTE: spawning stream into a new task can potentially hit this bug:
228 // - https://github.com/actix/actix-web/issues/1679
230 // Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
231 // That said, it is still technically possible to encounter.
232 actix_web::rt::spawn(async move {
233 while let Some(res) = stream.next().await {
234 if tx.send(res).await.is_err() {
243 struct SendStream<T> {
244 rx: tokio::sync::mpsc::Receiver<T>,
247 impl<T> Stream for SendStream<T>
254 mut self: std::pin::Pin<&mut Self>,
255 cx: &mut std::task::Context<'_>,
256 ) -> std::task::Poll<Option<Self::Item>> {
257 std::pin::Pin::new(&mut self.rx).poll_recv(cx)