1 use actix_web::{body::BodyStream, http::StatusCode, web::Data, *};
4 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, settings::structs::Settings, LemmyError};
5 use serde::{Deserialize, Serialize};
6 use std::time::Duration;
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))
15 .app_data(Data::new(client))
17 web::resource("/pictrs/image")
18 .wrap(rate_limit.image())
19 .route(web::post().to(upload)),
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)));
26 #[derive(Debug, Serialize, Deserialize)]
32 #[derive(Debug, Serialize, Deserialize)]
35 files: Option<Vec<Image>>,
38 #[derive(Deserialize)]
40 format: Option<String>,
41 thumbnail: Option<String>,
47 client: web::Data<Client>,
48 ) -> Result<HttpResponse, Error> {
49 // TODO: check rate limit here
52 .expect("No auth header for picture upload");
54 if Claims::decode(jwt.value()).is_err() {
55 return Ok(HttpResponse::Unauthorized().finish());
58 let mut client_req = client.request_from(format!("{}/image", pictrs_url()?), req.head());
60 if let Some(addr) = req.head().peer_addr {
61 client_req = client_req.insert_header(("X-Forwarded-For", addr.to_string()))
64 let mut res = client_req
67 .map_err(error::ErrorBadRequest)?;
69 let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
71 Ok(HttpResponse::build(res.status()).json(images))
75 filename: web::Path<String>,
76 web::Query(params): web::Query<PictrsParams>,
78 client: web::Data<Client>,
79 ) -> Result<HttpResponse, Error> {
80 let name = &filename.into_inner();
82 // If there are no query params, the URL is original
83 let url = if params.format.is_none() && params.thumbnail.is_none() {
84 format!("{}/image/original/{}", pictrs_url()?, name,)
86 // Use jpg as a default when none is given
87 let format = params.format.unwrap_or_else(|| "jpg".to_string());
89 let mut url = format!("{}/image/process.{}?src={}", pictrs_url()?, format, name,);
91 if let Some(size) = params.thumbnail {
92 url = format!("{}&thumbnail={}", url, size,);
97 image(url, req, client).await
103 client: web::Data<Client>,
104 ) -> Result<HttpResponse, Error> {
105 let mut client_req = client.request_from(url, req.head());
107 if let Some(addr) = req.head().peer_addr {
108 client_req = client_req.insert_header(("X-Forwarded-For", addr.to_string()))
115 .map_err(error::ErrorBadRequest)?;
117 if res.status() == StatusCode::NOT_FOUND {
118 return Ok(HttpResponse::NotFound().finish());
121 let mut client_res = HttpResponse::build(res.status());
123 for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
124 client_res.insert_header((name.clone(), value.clone()));
127 Ok(client_res.body(BodyStream::new(res)))
131 components: web::Path<(String, String)>,
133 client: web::Data<Client>,
134 ) -> Result<HttpResponse, Error> {
135 let (token, file) = components.into_inner();
137 let url = format!("{}/image/delete/{}/{}", pictrs_url()?, &token, &file);
139 let mut client_req = client.request_from(url, req.head());
141 if let Some(addr) = req.head().peer_addr {
142 client_req = client_req.insert_header(("X-Forwarded-For", addr.to_string()))
149 .map_err(error::ErrorBadRequest)?;
151 Ok(HttpResponse::build(res.status()).body(BodyStream::new(res)))
154 fn pictrs_url() -> Result<String, LemmyError> {
157 .ok_or_else(|| anyhow!("images_disabled").into())