]> Untitled Git - lemmy.git/blob - src/routes/images.rs
Fixing clippy.
[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_rate_limit::RateLimit;
5 use lemmy_utils::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 pub struct Image {
28   file: String,
29   delete_token: String,
30 }
31
32 #[derive(Debug, Serialize, Deserialize)]
33 pub struct Images {
34   msg: String,
35   files: Option<Vec<Image>>,
36 }
37
38 #[derive(Deserialize)]
39 pub 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 auth and rate limit here
50
51   let mut res = client
52     .request_from(format!("{}/image", Settings::get().pictrs_url), req.head())
53     .if_some(req.head().peer_addr, |addr, req| {
54       req.header("X-Forwarded-For", addr.to_string())
55     })
56     .send_stream(body)
57     .await?;
58
59   let images = res.json::<Images>().await?;
60
61   Ok(HttpResponse::build(res.status()).json(images))
62 }
63
64 async fn full_res(
65   filename: web::Path<String>,
66   web::Query(params): web::Query<PictrsParams>,
67   req: HttpRequest,
68   client: web::Data<Client>,
69 ) -> Result<HttpResponse, Error> {
70   let name = &filename.into_inner();
71
72   // If there are no query params, the URL is original
73   let url = if params.format.is_none() && params.thumbnail.is_none() {
74     format!("{}/image/original/{}", Settings::get().pictrs_url, name,)
75   } else {
76     // Use jpg as a default when none is given
77     let format = params.format.unwrap_or_else(|| "jpg".to_string());
78
79     let mut url = format!(
80       "{}/image/process.{}?src={}",
81       Settings::get().pictrs_url,
82       format,
83       name,
84     );
85
86     if let Some(size) = params.thumbnail {
87       url = format!("{}&thumbnail={}", url, size,);
88     }
89     url
90   };
91
92   image(url, req, client).await
93 }
94
95 async fn image(
96   url: String,
97   req: HttpRequest,
98   client: web::Data<Client>,
99 ) -> Result<HttpResponse, Error> {
100   let res = client
101     .request_from(url, req.head())
102     .if_some(req.head().peer_addr, |addr, req| {
103       req.header("X-Forwarded-For", addr.to_string())
104     })
105     .no_decompress()
106     .send()
107     .await?;
108
109   if res.status() == StatusCode::NOT_FOUND {
110     return Ok(HttpResponse::NotFound().finish());
111   }
112
113   let mut client_res = HttpResponse::build(res.status());
114
115   for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
116     client_res.header(name.clone(), value.clone());
117   }
118
119   Ok(client_res.body(BodyStream::new(res)))
120 }
121
122 async fn delete(
123   components: web::Path<(String, String)>,
124   req: HttpRequest,
125   client: web::Data<Client>,
126 ) -> Result<HttpResponse, Error> {
127   let (token, file) = components.into_inner();
128
129   let url = format!(
130     "{}/image/delete/{}/{}",
131     Settings::get().pictrs_url,
132     &token,
133     &file
134   );
135   let res = client
136     .request_from(url, req.head())
137     .if_some(req.head().peer_addr, |addr, req| {
138       req.header("X-Forwarded-For", addr.to_string())
139     })
140     .no_decompress()
141     .send()
142     .await?;
143
144   Ok(HttpResponse::build(res.status()).body(BodyStream::new(res)))
145 }