]> Untitled Git - lemmy.git/blob - crates/routes/src/images.rs
Rewrite settings implementation. Fixes #1270 (#1433)
[lemmy.git] / crates / routes / src / images.rs
1 use actix::clock::Duration;
2 use actix_web::{body::BodyStream, http::StatusCode, *};
3 use awc::Client;
4 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, settings::structs::Settings};
5 use serde::{Deserialize, Serialize};
6
7 pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimit) {
8   let client = Client::builder()
9     .header("User-Agent", "pict-rs-frontend, v0.1.0")
10     .timeout(Duration::from_secs(30))
11     .finish();
12
13   cfg
14     .data(client)
15     .service(
16       web::resource("/pictrs/image")
17         .wrap(rate_limit.image())
18         .route(web::post().to(upload)),
19     )
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)));
23 }
24
25 #[derive(Debug, Serialize, Deserialize)]
26 struct Image {
27   file: String,
28   delete_token: String,
29 }
30
31 #[derive(Debug, Serialize, Deserialize)]
32 struct Images {
33   msg: String,
34   files: Option<Vec<Image>>,
35 }
36
37 #[derive(Deserialize)]
38 struct PictrsParams {
39   format: Option<String>,
40   thumbnail: Option<String>,
41 }
42
43 async fn upload(
44   req: HttpRequest,
45   body: web::Payload,
46   client: web::Data<Client>,
47 ) -> Result<HttpResponse, Error> {
48   // TODO: check rate limit here
49   let jwt = req
50     .cookie("jwt")
51     .expect("No auth header for picture upload");
52
53   if Claims::decode(jwt.value()).is_err() {
54     return Ok(HttpResponse::Unauthorized().finish());
55   };
56
57   let mut client_req = client.request_from(
58     format!("{}/image", Settings::get().pictrs_url()),
59     req.head(),
60   );
61
62   if let Some(addr) = req.head().peer_addr {
63     client_req = client_req.header("X-Forwarded-For", addr.to_string())
64   };
65
66   let mut res = client_req.send_stream(body).await?;
67
68   let images = res.json::<Images>().await?;
69
70   Ok(HttpResponse::build(res.status()).json(images))
71 }
72
73 async fn full_res(
74   filename: web::Path<String>,
75   web::Query(params): web::Query<PictrsParams>,
76   req: HttpRequest,
77   client: web::Data<Client>,
78 ) -> Result<HttpResponse, Error> {
79   let name = &filename.into_inner();
80
81   // If there are no query params, the URL is original
82   let url = if params.format.is_none() && params.thumbnail.is_none() {
83     format!("{}/image/original/{}", Settings::get().pictrs_url(), name,)
84   } else {
85     // Use jpg as a default when none is given
86     let format = params.format.unwrap_or_else(|| "jpg".to_string());
87
88     let mut url = format!(
89       "{}/image/process.{}?src={}",
90       Settings::get().pictrs_url(),
91       format,
92       name,
93     );
94
95     if let Some(size) = params.thumbnail {
96       url = format!("{}&thumbnail={}", url, size,);
97     }
98     url
99   };
100
101   image(url, req, client).await
102 }
103
104 async fn image(
105   url: String,
106   req: HttpRequest,
107   client: web::Data<Client>,
108 ) -> Result<HttpResponse, Error> {
109   let mut client_req = client.request_from(url, req.head());
110
111   if let Some(addr) = req.head().peer_addr {
112     client_req = client_req.header("X-Forwarded-For", addr.to_string())
113   };
114
115   let res = client_req.no_decompress().send().await?;
116
117   if res.status() == StatusCode::NOT_FOUND {
118     return Ok(HttpResponse::NotFound().finish());
119   }
120
121   let mut client_res = HttpResponse::build(res.status());
122
123   for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
124     client_res.header(name.clone(), value.clone());
125   }
126
127   Ok(client_res.body(BodyStream::new(res)))
128 }
129
130 async fn delete(
131   components: web::Path<(String, String)>,
132   req: HttpRequest,
133   client: web::Data<Client>,
134 ) -> Result<HttpResponse, Error> {
135   let (token, file) = components.into_inner();
136
137   let url = format!(
138     "{}/image/delete/{}/{}",
139     Settings::get().pictrs_url(),
140     &token,
141     &file
142   );
143
144   let mut client_req = client.request_from(url, req.head());
145
146   if let Some(addr) = req.head().peer_addr {
147     client_req = client_req.header("X-Forwarded-For", addr.to_string())
148   };
149
150   let res = client_req.no_decompress().send().await?;
151
152   Ok(HttpResponse::build(res.status()).body(BodyStream::new(res)))
153 }