Forum: the link module, with YouTube previews
- services/forum/src/links: recognises the links in a post and shows a preview for the ones a provider knows; for now YouTube (watch, shorts, live, embed and youtu.be links, with the start time). Title and channel come from YouTube's oEmbed answer, the thumbnail is cut to 16:9 and kept in our own storage, so reading a thread loads nothing from YouTube. Made when a post is written or edited; without it the link stays text. - The card: on a computer a click plays the video in place (youtube-nocookie.com); on a phone it opens the YouTube app (Android: an intent with the web page as fallback; iOS: the link the app takes over), and "Lejátszás itt" plays it in place. - The privacy notice (HU, EN) says what YouTube sees when one plays it. - "Pörgős most" is now "Élénk beszélgetések"; the new thread form lost its note about text and emoji. - docs: the Turnstile captcha is on the list before going live. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -16,6 +16,7 @@ anyhow.workspace = true
|
||||
axum = { workspace = true, features = ["ws"] }
|
||||
axum-extra.workspace = true
|
||||
deunicode.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sqlx.workspace = true
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! The link module: recognises links in a post and shows a preview for the
|
||||
//! ones a provider knows. For now only YouTube ([`youtube`]). Previews are
|
||||
//! fetched when a post is written or edited (a few seconds at most), kept in
|
||||
//! `forum.link_previews`, and found again from the text when posts are shown.
|
||||
//! Thumbnails are stored in our own object storage and served by the forum,
|
||||
//! so reading a thread sends nothing to the provider.
|
||||
|
||||
pub mod youtube;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::header;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::routes::St;
|
||||
|
||||
/// At most this many previews under one post.
|
||||
pub const MAX_PER_POST: usize = 3;
|
||||
/// The thumbnails' folder in the bucket.
|
||||
pub const FOLDER: &str = "forum-links";
|
||||
|
||||
/// Where the providers are asked (the tests point them at a fake server).
|
||||
#[derive(Clone)]
|
||||
pub struct LinkConfig {
|
||||
pub http: reqwest::Client,
|
||||
pub youtube_oembed: String,
|
||||
pub youtube_thumbs: String,
|
||||
}
|
||||
|
||||
impl LinkConfig {
|
||||
pub fn new(youtube_oembed: &str, youtube_thumbs: &str) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
.user_agent("Sorsfonalak-Forum/1.0 (link preview)")
|
||||
.build()
|
||||
.expect("an HTTP client");
|
||||
Self {
|
||||
http,
|
||||
youtube_oembed: youtube_oembed.trim_end_matches('/').to_string(),
|
||||
youtube_thumbs: youtube_thumbs.trim_end_matches('/').to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_env() -> Self {
|
||||
let var = |name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.to_string());
|
||||
Self::new(
|
||||
&var("YOUTUBE_OEMBED_URL", "https://www.youtube.com/oembed"),
|
||||
&var("YOUTUBE_THUMBS_URL", "https://i.ytimg.com"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A recognised link in a post's text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
pub provider: &'static str,
|
||||
pub key: String,
|
||||
/// As written in the post.
|
||||
pub url: String,
|
||||
/// Where to start playing, in seconds.
|
||||
pub start: Option<u32>,
|
||||
}
|
||||
|
||||
/// The links of a text the providers know (each video once, at most [`MAX_PER_POST`]).
|
||||
pub fn find(text: &str) -> Vec<Found> {
|
||||
let mut out: Vec<Found> = Vec::new();
|
||||
for word in text.split_whitespace() {
|
||||
let word = word.trim_matches(|c: char| matches!(c, '(' | ')' | '<' | '>' | '"' | '\'' | '„' | '”' | '«' | '»'));
|
||||
let word = word.trim_end_matches(['.', ',', ';', ':', '!', '?']);
|
||||
if !word.starts_with("http://") && !word.starts_with("https://") {
|
||||
continue;
|
||||
}
|
||||
let Ok(url) = reqwest::Url::parse(word) else { continue };
|
||||
if let Some((key, start)) = youtube::video(&url)
|
||||
&& !out.iter().any(|f| f.provider == youtube::PROVIDER && f.key == key)
|
||||
{
|
||||
out.push(Found { provider: youtube::PROVIDER, key, url: word.to_string(), start });
|
||||
}
|
||||
if out.len() == MAX_PER_POST {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Fetches the previews a text needs and does not have yet. Failures only
|
||||
/// leave a link without a preview (the next edit tries again).
|
||||
pub async fn process(state: &AppState, text: &str) {
|
||||
for found in find(text) {
|
||||
let known: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM forum.link_previews WHERE provider = $1 AND key = $2)")
|
||||
.bind(found.provider)
|
||||
.bind(&found.key)
|
||||
.fetch_one(&state.db)
|
||||
.await
|
||||
.unwrap_or(true);
|
||||
if known {
|
||||
continue;
|
||||
}
|
||||
let result = match found.provider {
|
||||
youtube::PROVIDER => youtube::fetch(state, &found.key).await,
|
||||
_ => continue,
|
||||
};
|
||||
if let Err(e) = result {
|
||||
tracing::warn!(provider = found.provider, key = %found.key, error = %e, "link preview not made");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The previews of these posts' texts, by post id, as the page shows them.
|
||||
pub async fn previews(
|
||||
db: &PgPool,
|
||||
texts: &[(i64, &str)],
|
||||
) -> Result<std::collections::HashMap<i64, Value>, sqlx::Error> {
|
||||
let found: Vec<(i64, Vec<Found>)> =
|
||||
texts.iter().map(|(id, text)| (*id, find(text))).filter(|(_, f)| !f.is_empty()).collect();
|
||||
if found.is_empty() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let keys: Vec<String> = found.iter().flat_map(|(_, f)| f.iter().map(|x| x.key.clone())).collect();
|
||||
type Row = (String, String, String, Option<String>, Option<String>);
|
||||
let rows: Vec<Row> =
|
||||
sqlx::query_as("SELECT provider, key, title, author, thumbnail FROM forum.link_previews WHERE key = ANY($1)")
|
||||
.bind(&keys)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(found
|
||||
.into_iter()
|
||||
.filter_map(|(id, links)| {
|
||||
let shown: Vec<Value> = links
|
||||
.iter()
|
||||
.filter_map(|f| {
|
||||
let (_, _, title, author, thumb) =
|
||||
rows.iter().find(|(provider, key, ..)| provider == f.provider && *key == f.key)?;
|
||||
Some(json!({
|
||||
"provider": f.provider,
|
||||
"id": f.key,
|
||||
"url": f.url,
|
||||
"start": f.start,
|
||||
"title": title,
|
||||
"author": author,
|
||||
"thumbnail": thumb.as_ref().map(|t| format!("/api/v1/forum/link-thumbs/{t}")),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
(!shown.is_empty()).then_some((id, Value::Array(shown)))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/link-thumbs/{file}`: a stored thumbnail (cached for good).
|
||||
pub async fn thumbnail(
|
||||
State(state): St,
|
||||
WithRejection(Path(file), _): WithRejection<Path<String>, ApiError>,
|
||||
) -> ApiResult<Response> {
|
||||
let valid = file.len() <= 64
|
||||
&& file.ends_with(".jpg")
|
||||
&& file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
|
||||
if !valid {
|
||||
return Err(ApiError::NotFound("thumbnail"));
|
||||
}
|
||||
let storage = state.storage.as_ref().ok_or(ApiError::NotFound("thumbnail"))?;
|
||||
let object = storage
|
||||
.get(&format!("{FOLDER}/{file}"))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("reading a thumbnail: {e}")))?
|
||||
.ok_or(ApiError::NotFound("thumbnail"))?;
|
||||
Ok((
|
||||
[(header::CONTENT_TYPE, "image/jpeg"), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")],
|
||||
object.bytes,
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_links_providers_know() {
|
||||
let text = "Nézzétek: https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s, és (https://youtu.be/dQw4w9WgXcQ) \
|
||||
meg https://youtube.com/shorts/abcdefghijk! Ez nem: https://example.com/watch?v=dQw4w9WgXcQ";
|
||||
let found = find(text);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert_eq!(found[0].key, "dQw4w9WgXcQ");
|
||||
assert_eq!(found[0].start, Some(90));
|
||||
assert_eq!(found[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1m30s");
|
||||
assert_eq!(found[1].key, "abcdefghijk");
|
||||
assert!(find("Nincs itt link, csak youtube.com/watch?v=dQw4w9WgXcQ").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! YouTube links: the video's id (and where to start) from the usual forms
|
||||
//! of address, its title and channel from YouTube's oEmbed answer, and its
|
||||
//! thumbnail cut to 16:9 and kept in our storage.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::imageops::FilterType;
|
||||
use image::{ImageFormat, ImageReader};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::FOLDER;
|
||||
use crate::AppState;
|
||||
|
||||
pub const PROVIDER: &str = "youtube";
|
||||
/// The stored thumbnail: 480×270.
|
||||
const WIDTH: u32 = 480;
|
||||
const HEIGHT: u32 = 270;
|
||||
|
||||
fn valid_id(id: &str) -> bool {
|
||||
id.len() == 11 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
}
|
||||
|
||||
/// "90", "90s", "1m30s", "1h2m3s" as seconds.
|
||||
fn seconds(raw: &str) -> Option<u32> {
|
||||
if let Ok(n) = raw.parse::<u32>() {
|
||||
return Some(n);
|
||||
}
|
||||
let (mut total, mut number) = (0u32, String::new());
|
||||
for c in raw.chars() {
|
||||
match c {
|
||||
'0'..='9' => number.push(c),
|
||||
'h' | 'm' | 's' => {
|
||||
let n: u32 = number.parse().ok()?;
|
||||
total += n * match c {
|
||||
'h' => 3600,
|
||||
'm' => 60,
|
||||
_ => 1,
|
||||
};
|
||||
number.clear();
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
number.is_empty().then_some(total).filter(|t| *t > 0)
|
||||
}
|
||||
|
||||
/// The video id and start (seconds) of a YouTube address: watch, shorts,
|
||||
/// live, embed and youtu.be links, on www., m. and music. too.
|
||||
pub fn video(url: &reqwest::Url) -> Option<(String, Option<u32>)> {
|
||||
let host = url.host_str()?.to_ascii_lowercase();
|
||||
let host = host.strip_prefix("www.").unwrap_or(&host);
|
||||
let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned());
|
||||
let mut segments = url.path_segments()?;
|
||||
let id = match host {
|
||||
"youtu.be" => segments.next().map(str::to_string),
|
||||
"youtube.com" | "m.youtube.com" | "music.youtube.com" => match segments.next() {
|
||||
Some("watch") => param("v"),
|
||||
Some("shorts" | "live" | "embed") => segments.next().map(str::to_string),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}?;
|
||||
if !valid_id(&id) {
|
||||
return None;
|
||||
}
|
||||
let start = param("t").or_else(|| param("start")).as_deref().and_then(seconds);
|
||||
Some((id, start))
|
||||
}
|
||||
|
||||
/// YouTube's oEmbed answer (live streams come without title and channel).
|
||||
#[derive(Deserialize)]
|
||||
struct OEmbed {
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
#[serde(default)]
|
||||
author_name: Option<String>,
|
||||
}
|
||||
|
||||
/// The card's title when YouTube gives none.
|
||||
const NO_TITLE: &str = "YouTube-videó";
|
||||
|
||||
/// The video's title and channel, and its thumbnail into the storage.
|
||||
pub async fn fetch(state: &AppState, id: &str) -> anyhow::Result<()> {
|
||||
let links = &state.links;
|
||||
let watch = format!("https://www.youtube.com/watch?v={id}");
|
||||
let answer = links
|
||||
.http
|
||||
.get(&links.youtube_oembed)
|
||||
.query(&[("url", watch.as_str()), ("format", "json")])
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.text()
|
||||
.await?;
|
||||
let meta: OEmbed = serde_json::from_str(&answer).map_err(|e| {
|
||||
anyhow::anyhow!("oEmbed answer not understood ({e}): {}", answer.chars().take(160).collect::<String>())
|
||||
})?;
|
||||
// Without a thumbnail the card still shows (title and play button).
|
||||
let thumbnail = match &state.storage {
|
||||
Some(storage) => match store_thumbnail(state, storage, id).await {
|
||||
Ok(file) => Some(file),
|
||||
Err(e) => {
|
||||
tracing::warn!(key = id, error = %e, "no thumbnail for a YouTube link");
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let title: String = meta.title.filter(|t| !t.trim().is_empty()).unwrap_or_else(|| NO_TITLE.into());
|
||||
let title: String = title.chars().take(200).collect();
|
||||
let author = meta.author_name.map(|a| a.chars().take(100).collect::<String>());
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.link_previews (provider, key, title, author, thumbnail) VALUES ($1, $2, $3, $4, $5) \
|
||||
ON CONFLICT (provider, key) DO UPDATE SET title = EXCLUDED.title, author = EXCLUDED.author, \
|
||||
thumbnail = COALESCE(EXCLUDED.thumbnail, forum.link_previews.thumbnail), fetched_at = now()",
|
||||
)
|
||||
.bind(PROVIDER)
|
||||
.bind(id)
|
||||
.bind(&title)
|
||||
.bind(&author)
|
||||
.bind(&thumbnail)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn store_thumbnail(state: &AppState, storage: &object_storage::Storage, id: &str) -> anyhow::Result<String> {
|
||||
let bytes = state
|
||||
.links
|
||||
.http
|
||||
.get(format!("{}/vi/{id}/hqdefault.jpg", state.links.youtube_thumbs))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.bytes()
|
||||
.await?;
|
||||
let jpeg = widescreen(&bytes)?;
|
||||
let file = format!("{PROVIDER}-{id}.jpg");
|
||||
storage.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg").await?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// YouTube's 4:3 thumbnail (with black bands) as a 16:9 JPEG.
|
||||
fn widescreen(bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
let img = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg).decode()?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let band_h = (w * 9 / 16).min(h);
|
||||
let cropped = img.crop_imm(0, (h - band_h) / 2, w, band_h);
|
||||
let small = cropped.resize_exact(WIDTH, HEIGHT, FilterType::Triangle).to_rgb8();
|
||||
let mut out = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut out, 82).encode_image(&small)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_youtube_addresses() {
|
||||
let id = |s: &str| video(&reqwest::Url::parse(s).unwrap());
|
||||
assert_eq!(id("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(
|
||||
id("https://m.youtube.com/watch?feature=share&v=dQw4w9WgXcQ&t=42"),
|
||||
Some(("dQw4w9WgXcQ".into(), Some(42)))
|
||||
);
|
||||
assert_eq!(id("https://youtu.be/dQw4w9WgXcQ?t=1h2m3s"), Some(("dQw4w9WgXcQ".into(), Some(3723))));
|
||||
assert_eq!(id("https://youtube.com/shorts/dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(id("https://music.youtube.com/watch?v=dQw4w9WgXcQ&list=x"), Some(("dQw4w9WgXcQ".into(), None)));
|
||||
assert_eq!(id("https://www.youtube.com/@csatorna"), None);
|
||||
assert_eq!(id("https://www.youtube.com/watch?v=rovid"), None);
|
||||
assert_eq!(id("https://notyoutube.com/watch?v=dQw4w9WgXcQ"), None);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
mod auth;
|
||||
mod error;
|
||||
mod links;
|
||||
mod live;
|
||||
mod mail;
|
||||
mod rank;
|
||||
@@ -40,6 +41,8 @@ pub struct AppState {
|
||||
pub hub: live::Hub,
|
||||
/// Where uploaded avatars are kept (`S3_*`); `None`: no uploads.
|
||||
pub storage: Option<object_storage::Storage>,
|
||||
/// The link module's providers (YouTube previews).
|
||||
pub links: links::LinkConfig,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -50,6 +53,7 @@ impl AppState {
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
hub: live::Hub::default(),
|
||||
storage,
|
||||
links: links::LinkConfig::from_env(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// Threads on one page of a topic.
|
||||
const PAGE_SIZE: i64 = 30;
|
||||
/// "Pörgős most": at least this many replies in the last 24 hours.
|
||||
/// "Élénk beszélgetések": at least this many replies in the last 24 hours.
|
||||
const HOT_MIN_REPLIES: i64 = 3;
|
||||
/// "Várják a válaszod": threads without a reply from the last two weeks.
|
||||
const UNANSWERED_DAYS: i32 = 14;
|
||||
|
||||
@@ -55,6 +55,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/forum/replies", get(replies::list))
|
||||
.route("/v1/forum/search", get(search::search))
|
||||
.route("/v1/forum/share-card/{slug}", get(attachments::preview))
|
||||
.route("/v1/forum/link-thumbs/{file}", get(crate::links::thumbnail))
|
||||
.route("/v1/forum/posts/{id}/share", axum::routing::delete(posts::detach_share))
|
||||
.route("/v1/forum/sitemap", get(search::sitemap))
|
||||
.route("/v1/forum/replies/read", post(replies::read_all))
|
||||
|
||||
@@ -60,6 +60,7 @@ pub async fn edit(
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
crate::links::process(&state, &body).await;
|
||||
announce(&state, post.thread_id).await;
|
||||
super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
|
||||
@@ -114,6 +114,9 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
||||
let people = authors(db, posts.iter().filter_map(|p| p.author_id)).await?;
|
||||
let shares: Vec<Uuid> = posts.iter().filter(|p| p.deleted_at.is_none()).filter_map(|p| p.share_id).collect();
|
||||
let cards = super::attachments::cards(db, viewer, &shares).await?;
|
||||
let texts: Vec<(i64, &str)> =
|
||||
posts.iter().filter(|p| p.deleted_at.is_none()).map(|p| (p.id, p.body.as_str())).collect();
|
||||
let previews = crate::links::previews(db, &texts).await?;
|
||||
let counts: Vec<(i64, String, i64)> =
|
||||
sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
|
||||
.bind(&ids)
|
||||
@@ -192,6 +195,8 @@ pub async fn posts_json(db: &PgPool, viewer: &Viewer, posts: &[PostRow]) -> ApiR
|
||||
// The viewer muted the author: the page folds it up.
|
||||
"muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)),
|
||||
"share": p.share_id.and_then(|id| cards.get(&id).cloned()),
|
||||
// Previews of the links a provider knows (YouTube).
|
||||
"links": previews.get(&p.id),
|
||||
});
|
||||
if moderator {
|
||||
post["down"] = json!(down);
|
||||
@@ -381,6 +386,7 @@ pub async fn create(
|
||||
tx.commit().await?;
|
||||
tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
|
||||
super::mentions::after_post(&state, thread_id, post_id, member.user_id, &body).await;
|
||||
crate::links::process(&state, &body).await;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": thread_id, "slug": text::slug(&title) }))))
|
||||
}
|
||||
|
||||
@@ -485,6 +491,7 @@ pub async fn reply(
|
||||
// The one answered hears of it (on the second level, not the branch's first post).
|
||||
crate::mail::after_reply(&state, id, post.id, member.user_id, post.reply_to_id.or(post.parent_id), &body).await;
|
||||
super::mentions::after_post(&state, id, post.id, member.user_id, &body).await;
|
||||
crate::links::process(&state, &body).await;
|
||||
let followers = crate::live::followers(&state.db, id, member.user_id).await;
|
||||
crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
|
||||
.await;
|
||||
|
||||
@@ -30,12 +30,18 @@ struct User {
|
||||
|
||||
impl TestApp {
|
||||
fn new(pool: PgPool) -> Self {
|
||||
Self::with_links(pool, crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"))
|
||||
}
|
||||
|
||||
/// With the link providers at these (fake) addresses.
|
||||
fn with_links(pool: PgPool, links: crate::links::LinkConfig) -> Self {
|
||||
let state = AppState {
|
||||
db: pool.clone(),
|
||||
flood_secs: 0,
|
||||
base_url: "https://sorsfonalak.test".into(),
|
||||
hub: crate::live::Hub::default(),
|
||||
storage: None,
|
||||
links,
|
||||
};
|
||||
Self { router: routes::router(Arc::new(state)), pool }
|
||||
}
|
||||
@@ -272,7 +278,7 @@ async fn threads_replies_and_what_is_new(pool: PgPool) {
|
||||
assert_eq!(followed["threads"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(followed["threads"][0]["reply_count"], 3);
|
||||
|
||||
// Busy today: three replies make it "pörgős".
|
||||
// Busy today: three replies make it lively ("Élénk beszélgetések").
|
||||
assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["hot"][0]["id"], heart);
|
||||
|
||||
// Editing one's own post only.
|
||||
@@ -869,6 +875,7 @@ async fn live_doorbell_over_websocket(pool: PgPool) {
|
||||
base_url: "https://sorsfonalak.test".into(),
|
||||
hub: crate::live::Hub::default(),
|
||||
storage: None,
|
||||
links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
|
||||
});
|
||||
tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
|
||||
let router = routes::router(state.clone());
|
||||
@@ -1350,3 +1357,47 @@ async fn the_first_fifteen_are_founders(pool: PgPool) {
|
||||
let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await;
|
||||
assert_eq!(shown["posts"][2]["author"]["founder"], true);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn youtube_links_get_a_preview(pool: PgPool) {
|
||||
// A fake YouTube: the oEmbed answer for one video, 404 for the rest.
|
||||
let fake = Router::new().route(
|
||||
"/oembed",
|
||||
axum::routing::get(|q: axum::extract::Query<std::collections::HashMap<String, String>>| async move {
|
||||
if q.get("url").is_some_and(|u| u.ends_with("v=dQw4w9WgXcQ")) {
|
||||
Ok(axum::Json(json!({ "title": "Telihold meditáció", "author_name": "Csendes Csatorna" })))
|
||||
} else {
|
||||
Err(StatusCode::NOT_FOUND)
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, fake).await.unwrap() });
|
||||
let app = TestApp::with_links(
|
||||
pool,
|
||||
crate::links::LinkConfig::new(&format!("http://{addr}/oembed"), &format!("http://{addr}")),
|
||||
);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Esti meditáció").await;
|
||||
let post = app
|
||||
.reply(
|
||||
&anna,
|
||||
thread,
|
||||
"Ezt hallgatom esténként: https://youtu.be/dQw4w9WgXcQ?t=95 – és ez nincs: https://youtu.be/aaaaaaaaaaa",
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(post["links"].as_array().unwrap().len(), 1, "{post}");
|
||||
let link = &post["links"][0];
|
||||
assert_eq!(link["provider"], "youtube");
|
||||
assert_eq!(link["id"], "dQw4w9WgXcQ");
|
||||
assert_eq!(link["start"], 95);
|
||||
assert_eq!(link["title"], "Telihold meditáció");
|
||||
assert_eq!(link["author"], "Csendes Csatorna");
|
||||
assert!(link["thumbnail"].is_null(), "no storage in the tests");
|
||||
// Shown again with the thread, from the stored preview; a deleted post shows none.
|
||||
let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await;
|
||||
assert_eq!(shown["posts"][1]["links"][0]["title"], "Telihold meditáció");
|
||||
assert!(shown["posts"][0]["links"].is_null());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user