5 header::{HeaderName, ACCEPT_ENCODING, HOST},
13 use futures::stream::{Stream, StreamExt};
14 use lemmy_api_common::{context::LemmyContext, utils::get_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};
18 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
19 use serde::{Deserialize, Serialize};
22 cfg: &mut web::ServiceConfig,
23 client: ClientWithMiddleware,
24 rate_limit: &RateLimitCell,
27 .app_data(web::Data::new(client))
29 web::resource("/pictrs/image")
30 .wrap(rate_limit.image())
31 .route(web::post().to(upload)),
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)));
38 #[derive(Debug, Serialize, Deserialize)]
44 #[derive(Debug, Serialize, Deserialize)]
47 files: Option<Vec<Image>>,
50 #[derive(Deserialize)]
52 format: Option<String>,
53 thumbnail: Option<i32>,
56 #[derive(Deserialize)]
57 enum PictrsPurgeParams {
58 #[serde(rename = "file")]
60 #[serde(rename = "alias")]
65 request: &HttpRequest,
66 client: &ClientWithMiddleware,
69 // remove accept-encoding header so that pictrs doesnt compress the response
70 const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
72 let client_request = client
73 .request(request.method().clone(), url)
74 .timeout(REQWEST_TIMEOUT);
79 .fold(client_request, |client_req, (key, value)| {
80 if INVALID_HEADERS.contains(key) {
83 client_req.header(key, value)
91 client: web::Data<ClientWithMiddleware>,
92 context: web::Data<LemmyContext>,
93 ) -> Result<HttpResponse, Error> {
94 // TODO: check rate limit here
97 .expect("No auth header for picture upload");
99 if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
100 return Ok(HttpResponse::Unauthorized().finish());
103 let pictrs_config = context.settings().pictrs_config()?;
104 let image_url = format!("{}image", pictrs_config.url);
106 let mut client_req = adapt_request(&req, &client, image_url);
108 if let Some(addr) = req.head().peer_addr {
109 client_req = client_req.header("X-Forwarded-For", addr.to_string())
113 .body(Body::wrap_stream(make_send(body)))
116 .map_err(error::ErrorBadRequest)?;
118 let status = res.status();
119 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
121 Ok(HttpResponse::build(status).json(images))
125 filename: web::Path<String>,
126 web::Query(params): web::Query<PictrsParams>,
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(context.pool())
134 .map_err(error::ErrorBadRequest)?;
135 if local_site.private_instance {
138 .expect("No auth header for picture access");
139 if get_local_user_view_from_jwt(jwt.value(), context.pool(), context.secret())
143 return Ok(HttpResponse::Unauthorized().finish());
146 let name = &filename.into_inner();
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,)
153 // Take file type from name, or jpg if nothing is given
156 .unwrap_or_else(|| name.split('.').last().unwrap_or("jpg").to_string());
158 let mut url = format!("{}image/process.{}?src={}", pictrs_config.url, format, name,);
160 if let Some(size) = params.thumbnail {
161 url = format!("{}&thumbnail={}", url, size,);
166 image(url, req, client).await
172 client: web::Data<ClientWithMiddleware>,
173 ) -> Result<HttpResponse, Error> {
174 let mut client_req = adapt_request(&req, &client, url);
176 if let Some(addr) = req.head().peer_addr {
177 client_req = client_req.header("X-Forwarded-For", addr.to_string());
180 if let Some(addr) = req.head().peer_addr {
181 client_req = client_req.header("X-Forwarded-For", addr.to_string());
184 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
186 if res.status() == StatusCode::NOT_FOUND {
187 return Ok(HttpResponse::NotFound().finish());
190 let mut client_res = HttpResponse::build(res.status());
192 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
193 client_res.insert_header((name.clone(), value.clone()));
196 Ok(client_res.body(BodyStream::new(res.bytes_stream())))
200 components: web::Path<(String, String)>,
202 client: web::Data<ClientWithMiddleware>,
203 context: web::Data<LemmyContext>,
204 ) -> Result<HttpResponse, Error> {
205 let (token, file) = components.into_inner();
207 let pictrs_config = context.settings().pictrs_config()?;
208 let url = format!("{}image/delete/{}/{}", pictrs_config.url, &token, &file);
210 let mut client_req = adapt_request(&req, &client, url);
212 if let Some(addr) = req.head().peer_addr {
213 client_req = client_req.header("X-Forwarded-For", addr.to_string());
216 let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
218 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
221 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
223 S: Stream + Unpin + 'static,
226 // NOTE: the 8 here is arbitrary
227 let (tx, rx) = tokio::sync::mpsc::channel(8);
229 // NOTE: spawning stream into a new task can potentially hit this bug:
230 // - https://github.com/actix/actix-web/issues/1679
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() {
245 struct SendStream<T> {
246 rx: tokio::sync::mpsc::Receiver<T>,
249 impl<T> Stream for SendStream<T>
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)