2022-03-02 18:05:48 +00:00
|
|
|
use actix_web::{
|
|
|
|
body::BodyStream,
|
|
|
|
http::{
|
|
|
|
header::{HeaderName, ACCEPT_ENCODING, HOST},
|
|
|
|
StatusCode,
|
|
|
|
},
|
|
|
|
web,
|
2024-01-25 14:22:11 +00:00
|
|
|
web::Query,
|
2022-03-02 18:05:48 +00:00
|
|
|
HttpRequest,
|
|
|
|
HttpResponse,
|
|
|
|
};
|
2021-12-08 15:56:43 +00:00
|
|
|
use futures::stream::{Stream, StreamExt};
|
2024-05-22 08:28:47 +00:00
|
|
|
use lemmy_api_common::{context::LemmyContext, request::PictrsResponse};
|
2023-09-21 10:42:28 +00:00
|
|
|
use lemmy_db_schema::source::{
|
2024-01-25 14:22:11 +00:00
|
|
|
images::{LocalImage, LocalImageForm, RemoteImage},
|
2023-09-21 10:42:28 +00:00
|
|
|
local_site::LocalSite,
|
2023-09-06 13:13:30 +00:00
|
|
|
};
|
2023-09-21 10:42:28 +00:00
|
|
|
use lemmy_db_views::structs::LocalUserView;
|
2024-01-25 14:22:11 +00:00
|
|
|
use lemmy_utils::{error::LemmyResult, rate_limit::RateLimitCell, REQWEST_TIMEOUT};
|
2021-12-08 15:56:43 +00:00
|
|
|
use reqwest::Body;
|
|
|
|
use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
|
2024-05-22 08:28:47 +00:00
|
|
|
use serde::Deserialize;
|
2023-09-29 15:20:14 +00:00
|
|
|
use std::time::Duration;
|
2024-01-25 14:22:11 +00:00
|
|
|
use url::Url;
|
|
|
|
use urlencoding::decode;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2024-07-11 15:31:31 +00:00
|
|
|
trait ProcessUrl {
|
|
|
|
/// If thumbnail or format is given, this uses the pictrs process endpoint.
|
|
|
|
/// Otherwise, it uses the normal pictrs url (IE image/original).
|
|
|
|
fn process_url(&self, image_url: &str, pictrs_url: &Url) -> String;
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize, Clone)]
|
2024-05-22 08:28:47 +00:00
|
|
|
struct PictrsGetParams {
|
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
|
|
|
}
|
|
|
|
|
2024-07-11 15:31:31 +00:00
|
|
|
impl ProcessUrl for PictrsGetParams {
|
|
|
|
fn process_url(&self, src: &str, pictrs_url: &Url) -> String {
|
|
|
|
if self.format.is_none() && self.thumbnail.is_none() {
|
|
|
|
format!("{}image/original/{}", pictrs_url, src)
|
|
|
|
} else {
|
|
|
|
// Take file type from name, or jpg if nothing is given
|
|
|
|
let format = self
|
|
|
|
.clone()
|
|
|
|
.format
|
|
|
|
.unwrap_or_else(|| src.split('.').last().unwrap_or("jpg").to_string());
|
|
|
|
|
|
|
|
let mut url = format!("{}image/process.{}?src={}", pictrs_url, format, src);
|
|
|
|
|
|
|
|
if let Some(size) = self.thumbnail {
|
|
|
|
url = format!("{url}&thumbnail={size}",);
|
|
|
|
}
|
|
|
|
url
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize, Clone)]
|
|
|
|
pub struct ImageProxyParams {
|
|
|
|
url: String,
|
|
|
|
format: Option<String>,
|
|
|
|
thumbnail: Option<i32>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ProcessUrl for ImageProxyParams {
|
|
|
|
fn process_url(&self, proxy_url: &str, pictrs_url: &Url) -> String {
|
|
|
|
if self.format.is_none() && self.thumbnail.is_none() {
|
|
|
|
format!("{}image/original?proxy={}", pictrs_url, proxy_url)
|
|
|
|
} else {
|
|
|
|
// Take file type from name, or jpg if nothing is given
|
|
|
|
let format = self
|
|
|
|
.clone()
|
|
|
|
.format
|
|
|
|
.unwrap_or_else(|| proxy_url.split('.').last().unwrap_or("jpg").to_string());
|
|
|
|
|
|
|
|
let mut url = format!("{}image/process.{}?proxy={}", pictrs_url, format, proxy_url);
|
|
|
|
|
|
|
|
if let Some(size) = self.thumbnail {
|
|
|
|
url = format!("{url}&thumbnail={size}",);
|
|
|
|
}
|
|
|
|
url
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-12-08 15:56:43 +00:00
|
|
|
fn adapt_request(
|
|
|
|
request: &HttpRequest,
|
|
|
|
client: &ClientWithMiddleware,
|
|
|
|
url: String,
|
|
|
|
) -> RequestBuilder {
|
2024-04-17 12:35:54 +00:00
|
|
|
// remove accept-encoding header so that pictrs doesn't compress the response
|
2021-12-08 15:56:43 +00:00
|
|
|
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,
|
2023-09-21 10:42:28 +00:00
|
|
|
// require login
|
|
|
|
local_user_view: LocalUserView,
|
2024-01-25 14:22:11 +00:00
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2023-10-09 10:46:12 +00:00
|
|
|
context: web::Data<LemmyContext>,
|
2024-05-22 08:28:47 +00:00
|
|
|
) -> LemmyResult<HttpResponse> {
|
2020-12-01 17:48:39 +00:00
|
|
|
// TODO: check rate limit here
|
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
|
|
|
|
2024-01-25 14:22:11 +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
|
2023-11-17 09:01:32 +00:00
|
|
|
.timeout(Duration::from_secs(pictrs_config.upload_timeout))
|
2021-12-08 15:56:43 +00:00
|
|
|
.body(Body::wrap_stream(make_send(body)))
|
|
|
|
.send()
|
2024-05-22 08:28:47 +00:00
|
|
|
.await?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2021-12-08 15:56:43 +00:00
|
|
|
let status = res.status();
|
2024-05-22 08:28:47 +00:00
|
|
|
let images = res.json::<PictrsResponse>().await?;
|
2023-09-06 13:13:30 +00:00
|
|
|
if let Some(images) = &images.files {
|
2024-05-22 08:28:47 +00:00
|
|
|
for image in images {
|
2024-01-25 14:22:11 +00:00
|
|
|
let form = LocalImageForm {
|
2024-03-08 15:17:26 +00:00
|
|
|
local_user_id: Some(local_user_view.local_user.id),
|
2024-05-22 08:28:47 +00:00
|
|
|
pictrs_alias: image.file.to_string(),
|
|
|
|
pictrs_delete_token: image.delete_token.to_string(),
|
2023-09-06 13:13:30 +00:00
|
|
|
};
|
2024-06-20 10:44:06 +00:00
|
|
|
|
|
|
|
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
|
|
|
|
let thumbnail_url = image.thumbnail_url(&protocol_and_hostname)?;
|
|
|
|
|
|
|
|
// Also store the details for the image
|
|
|
|
let details_form = image.details.build_image_details_form(&thumbnail_url);
|
|
|
|
LocalImage::create(&mut context.pool(), &form, &details_form).await?;
|
2023-09-06 13:13:30 +00:00
|
|
|
}
|
|
|
|
}
|
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>,
|
2024-05-22 08:28:47 +00:00
|
|
|
web::Query(params): web::Query<PictrsGetParams>,
|
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>,
|
2023-09-21 10:42:28 +00:00
|
|
|
local_user_view: Option<LocalUserView>,
|
2024-05-22 08:28:47 +00:00
|
|
|
) -> LemmyResult<HttpResponse> {
|
2022-10-28 14:43:33 +00:00
|
|
|
// block access to images if instance is private and unauthorized, public
|
2024-05-22 08:28:47 +00:00
|
|
|
let local_site = LocalSite::read(&mut context.pool()).await?;
|
2023-09-21 10:42:28 +00:00
|
|
|
if local_site.private_instance && local_user_view.is_none() {
|
|
|
|
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-08-05 16:00:00 +00:00
|
|
|
|
2024-07-11 15:31:31 +00:00
|
|
|
let processed_url = params.process_url(name, &pictrs_config.url);
|
|
|
|
|
|
|
|
image(processed_url, req, &client).await
|
2020-08-05 16:00:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn image(
|
|
|
|
url: String,
|
|
|
|
req: HttpRequest,
|
2024-01-25 14:22:11 +00:00
|
|
|
client: &ClientWithMiddleware,
|
2024-05-22 08:28:47 +00:00
|
|
|
) -> LemmyResult<HttpResponse> {
|
2024-01-25 14:22:11 +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());
|
|
|
|
}
|
|
|
|
|
2024-05-22 08:28:47 +00:00
|
|
|
let res = client_req.send().await?;
|
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>,
|
2023-09-21 10:42:28 +00:00
|
|
|
// require login
|
|
|
|
_local_user_view: LocalUserView,
|
2024-05-22 08:28:47 +00:00
|
|
|
) -> LemmyResult<HttpResponse> {
|
2020-08-05 16:00:00 +00:00
|
|
|
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
|
|
|
|
2024-05-22 08:28:47 +00:00
|
|
|
let res = client_req.send().await?;
|
2020-08-05 16:00:00 +00:00
|
|
|
|
2024-05-22 08:28:47 +00:00
|
|
|
LocalImage::delete_by_alias(&mut context.pool(), &file).await?;
|
2023-09-06 13:13:30 +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
|
|
|
|
2024-01-25 14:22:11 +00:00
|
|
|
pub async fn image_proxy(
|
|
|
|
Query(params): Query<ImageProxyParams>,
|
2024-05-22 08:28:47 +00:00
|
|
|
req: HttpRequest,
|
|
|
|
client: web::Data<ClientWithMiddleware>,
|
2024-01-25 14:22:11 +00:00
|
|
|
context: web::Data<LemmyContext>,
|
|
|
|
) -> LemmyResult<HttpResponse> {
|
|
|
|
let url = Url::parse(&decode(¶ms.url)?)?;
|
|
|
|
|
|
|
|
// Check that url corresponds to a federated image so that this can't be abused as a proxy
|
|
|
|
// for arbitrary purposes.
|
|
|
|
RemoteImage::validate(&mut context.pool(), url.clone().into()).await?;
|
|
|
|
|
|
|
|
let pictrs_config = context.settings().pictrs_config()?;
|
|
|
|
|
2024-07-11 15:31:31 +00:00
|
|
|
let processed_url = params.process_url(¶ms.url, &pictrs_config.url);
|
|
|
|
|
|
|
|
image(processed_url, req, &client).await
|
2024-01-25 14:22:11 +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)
|
|
|
|
}
|
|
|
|
}
|