1 use crate::rate_limit::RateLimit;
2 use actix::clock::Duration;
3 use actix_web::{body::BodyStream, http::StatusCode, *};
5 use lemmy_utils::settings::Settings;
6 use serde::{Deserialize, Serialize};
8 const THUMBNAIL_SIZES: &[u64] = &[256];
10 pub fn config(cfg: &mut web::ServiceConfig, rate_limit: &RateLimit) {
11 let client = Client::build()
12 .header("User-Agent", "pict-rs-frontend, v0.1.0")
13 .timeout(Duration::from_secs(30))
19 web::resource("/pictrs/image")
20 .wrap(rate_limit.image())
21 .route(web::post().to(upload)),
23 .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
25 web::resource("/pictrs/image/thumbnail{size}/{filename}").route(web::get().to(thumbnail)),
27 .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
30 #[derive(Debug, Serialize, Deserialize)]
36 #[derive(Debug, Serialize, Deserialize)]
39 files: Option<Vec<Image>>,
45 client: web::Data<Client>,
46 ) -> Result<HttpResponse, Error> {
47 // TODO: check auth and rate limit here
50 .request_from(format!("{}/image", Settings::get().pictrs_url), req.head())
51 .if_some(req.head().peer_addr, |addr, req| {
52 req.header("X-Forwarded-For", addr.to_string())
57 let images = res.json::<Images>().await?;
59 Ok(HttpResponse::build(res.status()).json(images))
63 filename: web::Path<String>,
65 client: web::Data<Client>,
66 ) -> Result<HttpResponse, Error> {
69 Settings::get().pictrs_url,
70 &filename.into_inner()
72 image(url, req, client).await
76 parts: web::Path<(u64, String)>,
78 client: web::Data<Client>,
79 ) -> Result<HttpResponse, Error> {
80 let (size, file) = parts.into_inner();
82 if THUMBNAIL_SIZES.contains(&size) {
84 "{}/image/thumbnail{}/{}",
85 Settings::get().pictrs_url,
90 return image(url, req, client).await;
93 Ok(HttpResponse::NotFound().finish())
99 client: web::Data<Client>,
100 ) -> Result<HttpResponse, Error> {
102 .request_from(url, req.head())
103 .if_some(req.head().peer_addr, |addr, req| {
104 req.header("X-Forwarded-For", addr.to_string())
110 if res.status() == StatusCode::NOT_FOUND {
111 return Ok(HttpResponse::NotFound().finish());
114 let mut client_res = HttpResponse::build(res.status());
116 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
117 client_res.header(name.clone(), value.clone());
120 Ok(client_res.body(BodyStream::new(res)))
124 components: web::Path<(String, String)>,
126 client: web::Data<Client>,
127 ) -> Result<HttpResponse, Error> {
128 let (token, file) = components.into_inner();
131 "{}/image/delete/{}/{}",
132 Settings::get().pictrs_url,
137 .request_from(url, req.head())
138 .if_some(req.head().peer_addr, |addr, req| {
139 req.header("X-Forwarded-For", addr.to_string())
145 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res)))