2022-03-02 18:05:48 +00:00
|
|
|
use actix_web::{
|
|
|
|
body::BodyStream,
|
|
|
|
error,
|
|
|
|
http::{
|
|
|
|
header::{HeaderName, ACCEPT_ENCODING, HOST},
|
|
|
|
StatusCode,
|
|
|
|
},
|
|
|
|
web,
|
|
|
|
Error,
|
|
|
|
HttpRequest,
|
|
|
|
HttpResponse,
|
|
|
|
};
|
2021-12-08 15:56:43 +00:00
|
|
|
use futures::stream::{Stream, StreamExt};
|
2023-05-25 14:50:07 +00:00
|
|
|
use lemmy_api_common::{context::LemmyContext, utils::local_user_view_from_jwt};
|
2022-11-02 12:10:40 +00:00
|
|
|
use lemmy_db_schema::source::local_site::LocalSite;
|
2022-11-16 19:06:22 +00:00
|
|
|
use lemmy_utils::{claims::Claims, rate_limit::RateLimitCell, REQWEST_TIMEOUT};
|
2021-12-08 15:56:43 +00:00
|
|
|
use reqwest::Body;
|
|
|
|
use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
|
2020-08-05 16:00:00 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
2022-11-16 19:06:22 +00:00
|
|
|
pub fn config(
|
|
|
|
cfg: &mut web::ServiceConfig,
|
|
|
|
client: ClientWithMiddleware,
|
|
|
|
rate_limit: &RateLimitCell,
|
|
|
|
) {
|
2020-08-05 16:00:00 +00:00
|
|
|
cfg
|
2022-03-02 18:05:48 +00:00
|
|
|
.app_data(web::Data::new(client))
|
2020-08-05 16:00:00 +00:00
|
|
|
.service(
|
|
|
|
web::resource("/pictrs/image")
|
|
|
|
.wrap(rate_limit.image())
|
|
|
|
.route(web::post().to(upload)),
|
|
|
|
)
|
2020-10-14 16:48:10 +00:00
|
|
|
// This has optional query params: /image/{filename}?format=jpg&thumbnail=256
|
2020-08-05 16:00:00 +00:00
|
|
|
.service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
|
2022-07-11 20:38:37 +00:00
|
|
|
.service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2020-11-16 15:44:04 +00:00
|
|
|
struct Image {
|
2020-08-05 16:00:00 +00:00
|
|
|
file: String,
|
|
|
|
delete_token: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2020-11-16 15:44:04 +00:00
|
|
|
struct Images {
|
2020-08-05 16:00:00 +00:00
|
|
|
msg: String,
|
|
|
|
files: Option<Vec<Image>>,
|
|
|
|
}
|
|
|
|
|
2020-10-14 16:48:10 +00:00
|
|
|
#[derive(Deserialize)]
|
2020-11-16 15:44:04 +00:00
|
|
|
struct PictrsParams {
|
2020-10-14 16:48:10 +00:00
|
|
|
format: Option<String>,
|
2022-10-28 14:34:40 +00:00
|
|
|
thumbnail: Option<i32>,
|
2020-10-14 16:48:10 +00:00
|
|
|
}
|
|
|
|
|
2022-06-13 19:15:04 +00:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
enum PictrsPurgeParams {
|
|
|
|
#[serde(rename = "file")]
|
|
|
|
File(String),
|
|
|
|
#[serde(rename = "alias")]
|
|
|
|
Alias(String),
|
|
|
|
}
|
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
fn adapt_request(
|
|
|
|
request: &HttpRequest,
|
|
|
|
client: &ClientWithMiddleware,
|
|
|
|
url: String,
|
|
|
|
) -> RequestBuilder {
|
|
|
|
// remove accept-encoding header so that pictrs doesnt compress the response
|
|
|
|
const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
|
|
|
|
|
2022-06-13 19:15:04 +00:00
|
|
|
let client_request = client
|
|
|
|
.request(request.method().clone(), url)
|
|
|
|
.timeout(REQWEST_TIMEOUT);
|
2021-12-08 15:56:43 +00:00
|
|
|
|
|
|
|
request
|
|
|
|
.headers()
|
|
|
|
.iter()
|
|
|
|
.fold(client_request, |client_req, (key, value)| {
|
|
|
|
if INVALID_HEADERS.contains(key) {
|
|
|
|
client_req
|
|
|
|
} else {
|
|
|
|
client_req.header(key, value)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-08-05 16:00:00 +00:00
|
|
|
async fn upload(
|
|
|
|
req: HttpRequest,
|
|
|
|
body: web::Payload,
|
2021-12-08 15:56:43 +00:00
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2021-09-22 15:57:09 +00:00
|
|
|
context: web::Data<LemmyContext>,
|
2020-08-05 16:00:00 +00:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2020-12-01 17:48:39 +00:00
|
|
|
// TODO: check rate limit here
|
|
|
|
let jwt = req
|
|
|
|
.cookie("jwt")
|
|
|
|
.expect("No auth header for picture upload");
|
|
|
|
|
2021-09-22 15:57:09 +00:00
|
|
|
if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
|
2020-12-01 17:48:39 +00:00
|
|
|
return Ok(HttpResponse::Unauthorized().finish());
|
|
|
|
};
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2022-06-13 19:15:04 +00:00
|
|
|
let pictrs_config = context.settings().pictrs_config()?;
|
2022-08-16 15:20:41 +00:00
|
|
|
let image_url = format!("{}image", pictrs_config.url);
|
2021-12-08 15:56:43 +00:00
|
|
|
|
|
|
|
let mut client_req = adapt_request(&req, &client, image_url);
|
2020-12-04 14:00:15 +00:00
|
|
|
|
|
|
|
if let Some(addr) = req.head().peer_addr {
|
2021-12-08 15:56:43 +00:00
|
|
|
client_req = client_req.header("X-Forwarded-For", addr.to_string())
|
2020-12-04 14:00:15 +00:00
|
|
|
};
|
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
let res = client_req
|
|
|
|
.body(Body::wrap_stream(make_send(body)))
|
|
|
|
.send()
|
2021-07-06 13:26:46 +00:00
|
|
|
.await
|
|
|
|
.map_err(error::ErrorBadRequest)?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
let status = res.status();
|
2021-07-06 13:26:46 +00:00
|
|
|
let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
Ok(HttpResponse::build(status).json(images))
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn full_res(
|
|
|
|
filename: web::Path<String>,
|
2020-10-14 16:48:10 +00:00
|
|
|
web::Query(params): web::Query<PictrsParams>,
|
2020-08-05 16:00:00 +00:00
|
|
|
req: HttpRequest,
|
2021-12-08 15:56:43 +00:00
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2021-09-22 15:57:09 +00:00
|
|
|
context: web::Data<LemmyContext>,
|
2020-08-05 16:00:00 +00:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2022-10-28 14:43:33 +00:00
|
|
|
// block access to images if instance is private and unauthorized, public
|
2023-07-11 13:09:59 +00:00
|
|
|
let local_site = LocalSite::read(&mut context.pool())
|
2022-11-09 10:05:00 +00:00
|
|
|
.await
|
2022-11-02 12:10:40 +00:00
|
|
|
.map_err(error::ErrorBadRequest)?;
|
|
|
|
if local_site.private_instance {
|
|
|
|
let jwt = req
|
|
|
|
.cookie("jwt")
|
|
|
|
.expect("No auth header for picture access");
|
2023-05-25 14:50:07 +00:00
|
|
|
if local_user_view_from_jwt(jwt.value(), &context)
|
2022-11-02 12:10:40 +00:00
|
|
|
.await
|
|
|
|
.is_err()
|
|
|
|
{
|
|
|
|
return Ok(HttpResponse::Unauthorized().finish());
|
|
|
|
};
|
2022-10-28 14:43:33 +00:00
|
|
|
}
|
2020-10-14 16:48:10 +00:00
|
|
|
let name = &filename.into_inner();
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2020-10-14 16:48:10 +00:00
|
|
|
// If there are no query params, the URL is original
|
2022-06-13 19:15:04 +00:00
|
|
|
let pictrs_config = context.settings().pictrs_config()?;
|
2020-10-14 16:48:10 +00:00
|
|
|
let url = if params.format.is_none() && params.thumbnail.is_none() {
|
2022-08-16 15:20:41 +00:00
|
|
|
format!("{}image/original/{}", pictrs_config.url, name,)
|
2020-10-14 16:48:10 +00:00
|
|
|
} else {
|
2022-10-28 14:34:40 +00:00
|
|
|
// Take file type from name, or jpg if nothing is given
|
|
|
|
let format = params
|
|
|
|
.format
|
|
|
|
.unwrap_or_else(|| name.split('.').last().unwrap_or("jpg").to_string());
|
2020-10-14 16:48:10 +00:00
|
|
|
|
2022-08-16 15:20:41 +00:00
|
|
|
let mut url = format!("{}image/process.{}?src={}", pictrs_config.url, format, name,);
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2020-10-14 16:48:10 +00:00
|
|
|
if let Some(size) = params.thumbnail {
|
2023-01-30 19:17:24 +00:00
|
|
|
url = format!("{url}&thumbnail={size}",);
|
2020-10-14 16:48:10 +00:00
|
|
|
}
|
|
|
|
url
|
|
|
|
};
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2020-08-05 17:53:59 +00:00
|
|
|
image(url, req, client).await
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn image(
|
|
|
|
url: String,
|
|
|
|
req: HttpRequest,
|
2021-12-08 15:56:43 +00:00
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2020-08-05 16:00:00 +00:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2021-12-08 15:56:43 +00:00
|
|
|
let mut client_req = adapt_request(&req, &client, url);
|
2020-12-04 14:00:15 +00:00
|
|
|
|
|
|
|
if let Some(addr) = req.head().peer_addr {
|
2021-12-08 15:56:43 +00:00
|
|
|
client_req = client_req.header("X-Forwarded-For", addr.to_string());
|
|
|
|
}
|
2020-12-04 14:00:15 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
if let Some(addr) = req.head().peer_addr {
|
|
|
|
client_req = client_req.header("X-Forwarded-For", addr.to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
|
|
|
if res.status() == StatusCode::NOT_FOUND {
|
|
|
|
return Ok(HttpResponse::NotFound().finish());
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut client_res = HttpResponse::build(res.status());
|
|
|
|
|
|
|
|
for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
|
2021-07-06 13:26:46 +00:00
|
|
|
client_res.insert_header((name.clone(), value.clone()));
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
Ok(client_res.body(BodyStream::new(res.bytes_stream())))
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn delete(
|
|
|
|
components: web::Path<(String, String)>,
|
|
|
|
req: HttpRequest,
|
2021-12-08 15:56:43 +00:00
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2021-09-22 15:57:09 +00:00
|
|
|
context: web::Data<LemmyContext>,
|
2020-08-05 16:00:00 +00:00
|
|
|
) -> Result<HttpResponse, Error> {
|
|
|
|
let (token, file) = components.into_inner();
|
|
|
|
|
2022-06-13 19:15:04 +00:00
|
|
|
let pictrs_config = context.settings().pictrs_config()?;
|
2022-08-16 15:20:41 +00:00
|
|
|
let url = format!("{}image/delete/{}/{}", pictrs_config.url, &token, &file);
|
2020-12-04 14:00:15 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
let mut client_req = adapt_request(&req, &client, url);
|
2020-12-04 14:00:15 +00:00
|
|
|
|
|
|
|
if let Some(addr) = req.head().peer_addr {
|
2021-12-08 15:56:43 +00:00
|
|
|
client_req = client_req.header("X-Forwarded-For", addr.to_string());
|
|
|
|
}
|
2020-12-04 14:00:15 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
2021-08-04 21:13:51 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
|
|
|
|
where
|
|
|
|
S: Stream + Unpin + 'static,
|
|
|
|
S::Item: Send,
|
|
|
|
{
|
|
|
|
// NOTE: the 8 here is arbitrary
|
|
|
|
let (tx, rx) = tokio::sync::mpsc::channel(8);
|
|
|
|
|
|
|
|
// NOTE: spawning stream into a new task can potentially hit this bug:
|
|
|
|
// - https://github.com/actix/actix-web/issues/1679
|
|
|
|
//
|
|
|
|
// Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
|
|
|
|
// That said, it is still technically possible to encounter.
|
|
|
|
actix_web::rt::spawn(async move {
|
|
|
|
while let Some(res) = stream.next().await {
|
|
|
|
if tx.send(res).await.is_err() {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
SendStream { rx }
|
|
|
|
}
|
|
|
|
|
|
|
|
struct SendStream<T> {
|
|
|
|
rx: tokio::sync::mpsc::Receiver<T>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Stream for SendStream<T>
|
|
|
|
where
|
|
|
|
T: Send,
|
|
|
|
{
|
|
|
|
type Item = T;
|
|
|
|
|
|
|
|
fn poll_next(
|
|
|
|
mut self: std::pin::Pin<&mut Self>,
|
|
|
|
cx: &mut std::task::Context<'_>,
|
|
|
|
) -> std::task::Poll<Option<Self::Item>> {
|
|
|
|
std::pin::Pin::new(&mut self.rx).poll_recv(cx)
|
|
|
|
}
|
|
|
|
}
|