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