diff --git a/Cargo.lock b/Cargo.lock index 8f45c6c..431ccf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -716,6 +716,7 @@ dependencies = [ "http-body-util", "image", "object-storage", + "reqwest", "serde", "serde_json", "service-kit", diff --git a/crates/db/migrations/0045_forum_link_previews.sql b/crates/db/migrations/0045_forum_link_previews.sql new file mode 100644 index 0000000..8f22d7d --- /dev/null +++ b/crates/db/migrations/0045_forum_link_previews.sql @@ -0,0 +1,13 @@ +-- The forum's link module: what a recognised link shows under a post. For +-- now YouTube: title, channel and a thumbnail kept in our own storage, so a +-- page loads nothing from YouTube until someone plays the video. +CREATE TABLE forum.link_previews ( + provider text NOT NULL, + key text NOT NULL, + title text NOT NULL, + author text, + -- The thumbnail's file in the object storage (NULL: none). + thumbnail text, + fetched_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (provider, key) +); diff --git a/docs/kozosseg.md b/docs/kozosseg.md index aa77a14..c23ec6f 100644 --- a/docs/kozosseg.md +++ b/docs/kozosseg.md @@ -36,7 +36,7 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több - Az új tag reakciója látszik, de pontot nem ad. - Rangok pontból és tagsági időből: Vándor 0 → Kereső 5 pont és 3 nap → Fonó 30 és 14 → Csillagfonó 100 és 45 → Sorsfonó 300 és 120. - **Új tag korlátai:** naponta 3 szál és 20 hozzászólás, 5 másodperc két hozzászólás között. A vásárlás (Stripe-csomag) feloldja a napi korlátokat, rangot nem ad. -- **Főoldal:** „Mióta nem jártál itt” sáv, Mai égbolt (a Hold aznap), Várják a válaszod, Pörgős most (legalább 3 válasz 24 órán belül), Témák. +- **Főoldal:** „Mióta nem jártál itt” sáv, Mai égbolt (a Hold aznap), Várják a válaszod, Élénk beszélgetések (legalább 3 válasz 24 órán belül; korábban „Pörgős most”), Témák. - **Online pötty:** - Zöld, ha a tag 5 percen belül járt itt. - A megnyitott oldal percenként jelez. @@ -185,12 +185,20 @@ Jelölés: ami mellett **(javaslat)** áll, azt még nem hagytuk jóvá, a több - **A válasz-e-mail** a második szinten annak megy, akinek valóban válaszoltak. - **Adatvédelem:** a tájékoztató (magyar és angol) kiegészült a csatolt képlettel és a némítással. +### Ami elkészült (9. kör) + +- **Kitalált tartalom helyben** (csak a helyi adatbázisban): 30 tag 18–70 év között, valódi képlettel és kézzel írt tömör elemzéssel, 20 szál, 139 hozzászólás. A szkriptek a munkamenet ideiglenes mappájában vannak, nem a repóban; élesre nem kerülhet. +- **Alapító tag:** az első 15 tag jelvénye, véglegesen; az admin a profilon elveheti (például próbafióktól) vagy megadhatja, a felszabaduló hely a következő új tagé. +- **Link-modul** (`services/forum/src/links`): a hozzászólásokban felismeri a linkeket, és amit egy szolgáltató ismer, ahhoz előnézetet mutat. Most a YouTube: cím, csatorna, és a bélyegkép a saját tárolónkban (`forum-links/`), így a fórum olvasásakor semmi nem töltődik a YouTube-ról. Gépen a kártyára kattintva ott helyben lejátssza (youtube-nocookie.com), telefonon a YouTube alkalmazást nyitja (Androidon intenttel, a weboldal a tartalék), és ott is van „Lejátszás itt”. Az előnézet íráskor és szerkesztéskor készül; ha nem sikerül, a link sima szöveg marad. Új szolgáltatót a `links/` alá lehet tenni. +- **„Élénk beszélgetések”** lett a „Pörgős most”. + ### Élesítéskor +- **Turnstile (Cloudflare captcha)** az e-mailes regisztrációra és az elfelejtett jelszó űrlapra, mellé egy gépenkénti korlát a szerveren: élesítés előtt meg kell csinálni (a Cloudflare-felületen létre kell hozni a widgetet; a kulcs az `.env`-be, a titok a `.env.secrets`-be). - `FORUM_URL=http://forum:8083` az éles `.env`-be. - Az adatvédelmi tájékoztató dátumát (`PRIVACY_UPDATED` és `PRIVACY_UPDATED_EN` a `legal.ts`-ben) szintén az élesítés napjára kell írni. - Az ÁSZF hatálybalépési dátumát (`TERMS_UPDATED` a `services/frontend/src/lib/legal.ts`-ben és `TERMS_VERSION` a `services/backend/src/routes/payments.rs`-ben) az élesítés napjára kell átírni, ha az nem 2026. november 26. -- Ha közben a `main`-re új migráció került, a fórumé (0038–0043) ütközhet vele, és át kell számozni. A 0043 az `unaccent` bővítményt is létrehozza (megbízható bővítmény, az adatbázis tulajdonosa létrehozhatja). +- Ha közben a `main`-re új migráció került, a fórumé (0038–0045) ütközhet vele, és át kell számozni. A 0043 az `unaccent` bővítményt is létrehozza (megbízható bővítmény, az adatbázis tulajdonosa létrehozhatja). - A fórum szolgáltatásnak kell az `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (az éles `.env`-ben, ugyanaz, mint a backendé) és a kulcsok (`.env.secrets`); a workernek a `BACKEND_URL` (a compose fájlban már benne van). ### Ami még hátravan @@ -380,7 +388,7 @@ Mobilon, fentről lefelé (javaslat): - **adatvédelem:** csak a nyilvános témákból készül, az „Ami a szívemen van” témát nem olvassa, tagot nem idéz és nem nevez meg; - **AI-címke:** jól láthatóan AI-összefoglalóként van jelölve. Nem tagként szól, így nem ütközik azzal az elvvel, hogy az AI nem szól hozzá a beszélgetésekhez. 4. **Várják a válaszod:** 1–3 válasz nélküli szál, finoman kiemelve. A meghallgatás elve miatt ez közel van a tetejéhez. -5. **Pörgős most:** +5. **Élénk beszélgetések** (korábban „Pörgős most”): - az utóbbi 24 óra legélénkebb szálai, a válaszok és a résztvevők száma szerint; - átlátható, felcímkézett sorrend, nem rejtett algoritmus; - amíg kevés a forgalom, nem jelenik meg. diff --git a/services/forum/Cargo.toml b/services/forum/Cargo.toml index a0d6abb..c1f6b15 100644 --- a/services/forum/Cargo.toml +++ b/services/forum/Cargo.toml @@ -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 diff --git a/services/forum/src/links/mod.rs b/services/forum/src/links/mod.rs new file mode 100644 index 0000000..d643d33 --- /dev/null +++ b/services/forum/src/links/mod.rs @@ -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, +} + +/// The links of a text the providers know (each video once, at most [`MAX_PER_POST`]). +pub fn find(text: &str) -> Vec { + let mut out: Vec = 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, sqlx::Error> { + let found: Vec<(i64, Vec)> = + 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 = found.iter().flat_map(|(_, f)| f.iter().map(|x| x.key.clone())).collect(); + type Row = (String, String, String, Option, Option); + let rows: Vec = + 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 = 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, ApiError>, +) -> ApiResult { + 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()); + } +} diff --git a/services/forum/src/links/youtube.rs b/services/forum/src/links/youtube.rs new file mode 100644 index 0000000..30128b3 --- /dev/null +++ b/services/forum/src/links/youtube.rs @@ -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 { + if let Ok(n) = raw.parse::() { + 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)> { + 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, + #[serde(default)] + author_name: Option, +} + +/// 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::()) + })?; + // 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::()); + 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 { + 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> { + 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); + } +} diff --git a/services/forum/src/main.rs b/services/forum/src/main.rs index 0defc08..21ea48d 100644 --- a/services/forum/src/main.rs +++ b/services/forum/src/main.rs @@ -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, + /// 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(), } } } diff --git a/services/forum/src/routes/home.rs b/services/forum/src/routes/home.rs index 9f6215b..9048cdb 100644 --- a/services/forum/src/routes/home.rs +++ b/services/forum/src/routes/home.rs @@ -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; diff --git a/services/forum/src/routes/mod.rs b/services/forum/src/routes/mod.rs index e278121..ba71f78 100644 --- a/services/forum/src/routes/mod.rs +++ b/services/forum/src/routes/mod.rs @@ -55,6 +55,7 @@ pub fn router(state: Arc) -> 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)) diff --git a/services/forum/src/routes/posts.rs b/services/forum/src/routes/posts.rs index 6ad4c17..4ef0750 100644 --- a/services/forum/src/routes/posts.rs +++ b/services/forum/src/routes/posts.rs @@ -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))) diff --git a/services/forum/src/routes/threads.rs b/services/forum/src/routes/threads.rs index d893283..1f12ad7 100644 --- a/services/forum/src/routes/threads.rs +++ b/services/forum/src/routes/threads.rs @@ -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 = 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; diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 20112ac..c20f670 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -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>| 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()); +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 21c5604..f917053 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -237,7 +237,11 @@ export default async function PrivacyPage() { belépett tagok látják: a rajzot fokokkal és házakkal, a rövid összefoglalót vagy az előrejelzés szövegét, nevek, születési dátum, idő és hely nélkül. A fokokból egy jártas asztrológus nagyjából kiszámolhatja a születési napot és időt, az előrejelzés kezdőnapjából pedig a születésnap kiderül. A csatolt képletet - bármikor leveheted, és a kérdés törlésével a link is megszűnik. A fórum szabályai az{" "} + bármikor leveheted, és a kérdés törlésével a link is megszűnik. Ha egy hozzászólásban YouTube-link van, a + videó címét és képét a szerverünk kéri le, és a saját szerverünkről mutatjuk: a fórum olvasásakor a YouTube + nem kap rólad adatot. Ha a videót a fórumon elindítod, a lejátszó a YouTube (Google) szerveréről töltődik be + (youtube-nocookie.com), amely látja az IP-címedet és a lejátszás adatait; telefonon a megnyitás a YouTube + alkalmazásába visz. A fórum szabályai az{" "} ÁSZF 8. pontjában vannak.

diff --git a/services/frontend/src/app/forum/forum.css b/services/frontend/src/app/forum/forum.css index 9b235dc..83f64bb 100644 --- a/services/frontend/src/app/forum/forum.css +++ b/services/frontend/src/app/forum/forum.css @@ -702,3 +702,26 @@ a.fh-online-item:hover { color: var(--gold); } .fshare-open { margin-top: 4px; } .fnew-share { display: flex; flex-direction: column; gap: 8px; } .fnew-share .fshare { margin-top: 0; } + +/* --- link previews (YouTube) --- */ +.flinks { display: flex; flex-direction: column; gap: 10px; margin-top: 10px; } +.flink { + display: flex; flex-direction: column; max-width: 480px; overflow: hidden; + border: 1px solid var(--line-2); border-radius: 14px; background: var(--panel); +} +.flink-thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: #0e1424; } +.flink-thumb img { display: block; width: 100%; height: 100%; object-fit: cover; } +.flink-noimg { display: block; width: 100%; height: 100%; } +.flink-play { + position: absolute; left: 50%; top: 50%; width: 56px; height: 40px; transform: translate(-50%, -50%); + display: grid; place-items: center; border-radius: 12px; background: rgba(15, 15, 15, 0.78); + transition: background 0.15s; +} +.flink-play svg { width: 22px; height: 22px; fill: #fff; } +.flink-thumb:hover .flink-play, .flink-thumb:focus-visible .flink-play { background: #d32020; } +.flink-meta { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px 12px; } +.flink-title { font-weight: 600; font-size: 15px; line-height: 1.35; } +.flink-here { align-self: flex-start; margin-top: 4px; } +.flink-frame { position: relative; aspect-ratio: 16 / 9; background: #000; } +.flink-frame iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; } +.flink .fp-link { display: inline-flex; align-items: center; padding: 0; text-decoration: none; } diff --git a/services/frontend/src/app/forum/page.tsx b/services/frontend/src/app/forum/page.tsx index 2c8a25e..eb58a0f 100644 --- a/services/frontend/src/app/forum/page.tsx +++ b/services/frontend/src/app/forum/page.tsx @@ -159,8 +159,8 @@ export default async function ForumHomePage() { {hot.length > 0 && (
-

Pörgős most

- az utóbbi 24 órában +

Élénk beszélgetések

+ ma sokan írtak bennük
diff --git a/services/frontend/src/app/forum/uj/NewThreadForm.tsx b/services/frontend/src/app/forum/uj/NewThreadForm.tsx index b8f7206..087841a 100644 --- a/services/frontend/src/app/forum/uj/NewThreadForm.tsx +++ b/services/frontend/src/app/forum/uj/NewThreadForm.tsx @@ -145,10 +145,6 @@ export function NewThreadForm({ required placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"} /> - - Szöveg és emoji: a :) és a {"<3"} magától emojivá alakul. Képet és videót nem lehet beilleszteni, a linkek - sima szövegként látszanak. -

diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index a7733e7..607ab3e 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -203,7 +203,11 @@ export default async function PrivacyPolicyPage() { yearly forecast or a comparison to a question, only logged-in members see it: the drawing with degrees and houses, the short summary or the forecast text, without names, birth date, time or place. A practised astrologer can roughly work out the birth date and time from the degrees, and a forecast's first day is the - birthday. You can take it off at any time, and deleting the question ends the link. The forum rules are in + birthday. You can take it off at any time, and deleting the question ends the link. If a post has a YouTube + link, our server fetches the video's title and picture and we show them from our own server: reading the + forum sends YouTube nothing about you. If you play the video on the forum, the player loads from YouTube's + (Google's) servers (youtube-nocookie.com), which see your IP address and what you play; on a phone, opening + it takes you to the YouTube app. The forum rules are in point 8 of the terms (ÁSZF, in Hungarian).

diff --git a/services/frontend/src/components/forum/LinkPreviews.tsx b/services/frontend/src/components/forum/LinkPreviews.tsx new file mode 100644 index 0000000..17964aa --- /dev/null +++ b/services/frontend/src/components/forum/LinkPreviews.tsx @@ -0,0 +1,111 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import type { LinkPreview } from "@/lib/forum"; + +type Device = "android" | "ios" | "desktop"; + +function detect(): Device { + const ua = navigator.userAgent; + if (/Android/i.test(ua)) return "android"; + // iPadOS reports itself as a Mac with touch. + if (/iPhone|iPad|iPod/i.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return "ios"; + return "desktop"; +} + +/** + * A YouTube link under a post: our own copy of the thumbnail (nothing is + * loaded from YouTube until someone plays it). On a computer a click plays + * it here; on a phone it opens the YouTube app (Android: an intent with the + * web page as fallback; iOS: the link, which the app takes over), and + * "Lejátszás itt" plays it here. + */ +function YouTubeCard({ link }: { link: LinkPreview }) { + const [playing, setPlaying] = useState(false); + const [device, setDevice] = useState("desktop"); + useEffect(() => setDevice(detect()), []); + const at = link.start ? `&t=${link.start}s` : ""; + const watch = `https://www.youtube.com/watch?v=${link.id}${at}`; + const app = + device === "android" + ? `intent://www.youtube.com/watch?v=${link.id}${at}#Intent;scheme=https;package=com.google.android.youtube;` + + `S.browser_fallback_url=${encodeURIComponent(watch)};end` + : watch; + const mobile = device !== "desktop"; + + if (playing) { + const start = link.start ? `&start=${link.start}` : ""; + return ( +
+
+