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:
feco
2026-11-26 16:26:37 +00:00
co-authored by Claude Opus 5.5
parent 493539bf56
commit 1d4f18b5d6
21 changed files with 653 additions and 26 deletions
Generated
+1
View File
@@ -716,6 +716,7 @@ dependencies = [
"http-body-util", "http-body-util",
"image", "image",
"object-storage", "object-storage",
"reqwest",
"serde", "serde",
"serde_json", "serde_json",
"service-kit", "service-kit",
@@ -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)
);
+11 -3
View File
@@ -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. - 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. - 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. - **Ú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:** - **Online pötty:**
- Zöld, ha a tag 5 percen belül járt itt. - Zöld, ha a tag 5 percen belül járt itt.
- A megnyitott oldal percenként jelez. - 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. - **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. - **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 ### É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. - `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 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. - 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). - 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 ### 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; - **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. - **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. 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; - 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; - átlátható, felcímkézett sorrend, nem rejtett algoritmus;
- amíg kevés a forgalom, nem jelenik meg. - amíg kevés a forgalom, nem jelenik meg.
+1
View File
@@ -16,6 +16,7 @@ anyhow.workspace = true
axum = { workspace = true, features = ["ws"] } axum = { workspace = true, features = ["ws"] }
axum-extra.workspace = true axum-extra.workspace = true
deunicode.workspace = true deunicode.workspace = true
reqwest.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
sqlx.workspace = true sqlx.workspace = true
+195
View File
@@ -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());
}
}
+175
View File
@@ -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);
}
}
+4
View File
@@ -14,6 +14,7 @@
mod auth; mod auth;
mod error; mod error;
mod links;
mod live; mod live;
mod mail; mod mail;
mod rank; mod rank;
@@ -40,6 +41,8 @@ pub struct AppState {
pub hub: live::Hub, pub hub: live::Hub,
/// Where uploaded avatars are kept (`S3_*`); `None`: no uploads. /// Where uploaded avatars are kept (`S3_*`); `None`: no uploads.
pub storage: Option<object_storage::Storage>, pub storage: Option<object_storage::Storage>,
/// The link module's providers (YouTube previews).
pub links: links::LinkConfig,
} }
impl AppState { impl AppState {
@@ -50,6 +53,7 @@ impl AppState {
base_url: base_url.trim_end_matches('/').to_string(), base_url: base_url.trim_end_matches('/').to_string(),
hub: live::Hub::default(), hub: live::Hub::default(),
storage, storage,
links: links::LinkConfig::from_env(),
} }
} }
} }
+1 -1
View File
@@ -14,7 +14,7 @@ use crate::error::{ApiError, ApiResult};
/// Threads on one page of a topic. /// Threads on one page of a topic.
const PAGE_SIZE: i64 = 30; 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; const HOT_MIN_REPLIES: i64 = 3;
/// "Várják a válaszod": threads without a reply from the last two weeks. /// "Várják a válaszod": threads without a reply from the last two weeks.
const UNANSWERED_DAYS: i32 = 14; const UNANSWERED_DAYS: i32 = 14;
+1
View File
@@ -55,6 +55,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/forum/replies", get(replies::list)) .route("/v1/forum/replies", get(replies::list))
.route("/v1/forum/search", get(search::search)) .route("/v1/forum/search", get(search::search))
.route("/v1/forum/share-card/{slug}", get(attachments::preview)) .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/posts/{id}/share", axum::routing::delete(posts::detach_share))
.route("/v1/forum/sitemap", get(search::sitemap)) .route("/v1/forum/sitemap", get(search::sitemap))
.route("/v1/forum/replies/read", post(replies::read_all)) .route("/v1/forum/replies/read", post(replies::read_all))
+1
View File
@@ -60,6 +60,7 @@ pub async fn edit(
.bind(&body) .bind(&body)
.fetch_one(&state.db) .fetch_one(&state.db)
.await?; .await?;
crate::links::process(&state, &body).await;
announce(&state, post.thread_id).await; announce(&state, post.thread_id).await;
super::mentions::after_post(&state, post.thread_id, post.id, member.user_id, &body).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))) Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
+7
View File
@@ -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 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 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 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)> = 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") sqlx::query_as("SELECT post_id, kind, count(*) FROM forum.reactions WHERE post_id = ANY($1) GROUP BY 1, 2")
.bind(&ids) .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. // The viewer muted the author: the page folds it up.
"muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)), "muted": p.author_id.is_some_and(|a| viewer.mutes.contains(&a)),
"share": p.share_id.and_then(|id| cards.get(&id).cloned()), "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 { if moderator {
post["down"] = json!(down); post["down"] = json!(down);
@@ -381,6 +386,7 @@ pub async fn create(
tx.commit().await?; tx.commit().await?;
tracing::info!(thread = thread_id, topic = %req.topic, "thread started"); tracing::info!(thread = thread_id, topic = %req.topic, "thread started");
super::mentions::after_post(&state, thread_id, post_id, member.user_id, &body).await; 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) })))) 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). // 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; 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; 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; 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)) crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
.await; .await;
+52 -1
View File
@@ -30,12 +30,18 @@ struct User {
impl TestApp { impl TestApp {
fn new(pool: PgPool) -> Self { 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 { let state = AppState {
db: pool.clone(), db: pool.clone(),
flood_secs: 0, flood_secs: 0,
base_url: "https://sorsfonalak.test".into(), base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(), hub: crate::live::Hub::default(),
storage: None, storage: None,
links,
}; };
Self { router: routes::router(Arc::new(state)), pool } 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"].as_array().unwrap().len(), 2);
assert_eq!(followed["threads"][0]["reply_count"], 3); 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); assert_eq!(app.get("/v1/forum/home", Some(&bea)).await["hot"][0]["id"], heart);
// Editing one's own post only. // Editing one's own post only.
@@ -869,6 +875,7 @@ async fn live_doorbell_over_websocket(pool: PgPool) {
base_url: "https://sorsfonalak.test".into(), base_url: "https://sorsfonalak.test".into(),
hub: crate::live::Hub::default(), hub: crate::live::Hub::default(),
storage: None, 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())); tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
let router = routes::router(state.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; let shown = app.get(&format!("/v1/forum/threads/{thread}"), None).await;
assert_eq!(shown["posts"][2]["author"]["founder"], true); 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());
}
@@ -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, 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 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 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{" "}
<Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak. <Link href="/aszf#forum">ÁSZF 8. pontjában</Link> vannak.
</p> </p>
</section> </section>
+23
View File
@@ -702,3 +702,26 @@ a.fh-online-item:hover { color: var(--gold); }
.fshare-open { margin-top: 4px; } .fshare-open { margin-top: 4px; }
.fnew-share { display: flex; flex-direction: column; gap: 8px; } .fnew-share { display: flex; flex-direction: column; gap: 8px; }
.fnew-share .fshare { margin-top: 0; } .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; }
+2 -2
View File
@@ -159,8 +159,8 @@ export default async function ForumHomePage() {
{hot.length > 0 && ( {hot.length > 0 && (
<section className="fh-section o-5" aria-labelledby="fh-hot"> <section className="fh-section o-5" aria-labelledby="fh-hot">
<div className="fh-section-head"> <div className="fh-section-head">
<h2 id="fh-hot">Pörgős most</h2> <h2 id="fh-hot">Élénk beszélgetések</h2>
<span className="hint">az utóbbi 24 órában</span> <span className="hint">ma sokan írtak bennük</span>
</div> </div>
<div className="fh-card fh-flush"> <div className="fh-card fh-flush">
<ThreadList threads={hot} /> <ThreadList threads={hot} />
@@ -145,10 +145,6 @@ export function NewThreadForm({
required required
placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"} placeholder={intent === "listen" ? "Írd le, ami benned van…" : "Írd le a gondolataidat…"}
/> />
<span className="hint">
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.
</span>
</div> </div>
<p className="hint"> <p className="hint">
+5 -1
View File
@@ -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 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 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 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 <Link href="/aszf#forum">terms (ÁSZF, in Hungarian)</Link>. point 8 of the <Link href="/aszf#forum">terms (ÁSZF, in Hungarian)</Link>.
</p> </p>
</section> </section>
@@ -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<Device>("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 (
<div className="flink flink-playing">
<div className="flink-frame">
<iframe
src={`https://www.youtube-nocookie.com/embed/${link.id}?autoplay=1&rel=0&playsinline=1${start}`}
title={link.title}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
referrerPolicy="strict-origin-when-cross-origin"
/>
</div>
<div className="flink-meta">
<span className="flink-title">{link.title}</span>
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link">
Megnyitás a YouTube-on
</a>
</div>
</div>
);
}
return (
<div className="flink">
<a
className="flink-thumb"
href={mobile ? app : watch}
onClick={(e) => {
if (!mobile) {
e.preventDefault();
setPlaying(true);
}
}}
aria-label={mobile ? `Megnyitás a YouTube alkalmazásban: ${link.title}` : `Lejátszás: ${link.title}`}
>
{link.thumbnail ? (
// Our own copy of the thumbnail (already small).
<img src={link.thumbnail} alt="" width={480} height={270} loading="lazy" />
) : (
<span className="flink-noimg" />
)}
<span className="flink-play" aria-hidden="true">
<svg viewBox="0 0 24 24">
<path d="M8 5.5v13l11-6.5z" />
</svg>
</span>
</a>
<div className="flink-meta">
<span className="flink-title">{link.title}</span>
<span className="hint">
YouTube{link.author ? ` · ${link.author}` : ""}
{link.start ? ` · ${Math.floor(link.start / 60)}:${String(link.start % 60).padStart(2, "0")}-tól` : ""}
</span>
{mobile ? (
<button type="button" className="fp-link flink-here" onClick={() => setPlaying(true)}>
Lejátszás itt
</button>
) : (
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link flink-here">
Megnyitás a YouTube-on
</a>
)}
</div>
</div>
);
}
/** The previews of the links in a post (the link module: YouTube for now). */
export function LinkPreviews({ links }: { links: LinkPreview[] }) {
return (
<div className="flinks">
{links.map((link) => (link.provider === "youtube" ? <YouTubeCard key={link.id} link={link} /> : null))}
</div>
);
}
@@ -26,11 +26,25 @@ function withMentions(line: string, mentions: string[]): React.ReactNode[] {
return out; return out;
} }
/** A post's text: paragraphs and line breaks as typed; links stay plain text; mentions link to profiles. */ /**
export function PostBody({ text, mentions = [] }: { text: string; mentions?: string[] }) { * A post's text: paragraphs and line breaks as typed; links stay plain text;
* mentions link to profiles. `hide`: links shown as a preview below, left
* out where they stand on a line of their own.
*/
export function PostBody({ text, mentions = [], hide = [] }: { text: string; mentions?: string[]; hide?: string[] }) {
const shown = hide.length
? text
.split("\n")
.filter((line) => !hide.includes(line.trim()))
.join("\n")
.trim()
: text;
return ( return (
<div className="fp-body"> <div className="fp-body">
{text.split(/\n{2,}/).map((para, i) => ( {shown
.split(/\n{2,}/)
.filter((para) => para.trim() !== "")
.map((para, i) => (
<p key={i}> <p key={i}>
{para.split("\n").map((line, j) => ( {para.split("\n").map((line, j) => (
<span key={j}> <span key={j}>
@@ -13,6 +13,7 @@ import { PostBody } from "./PostBody";
import type { LiveNotice } from "./ForumNav"; import type { LiveNotice } from "./ForumNav";
import { ReactionIcon } from "./ReactionIcon"; import { ReactionIcon } from "./ReactionIcon";
import { ReportForm } from "./ReportButton"; import { ReportForm } from "./ReportButton";
import { LinkPreviews } from "./LinkPreviews";
import { ShareCard } from "./ShareCard"; import { ShareCard } from "./ShareCard";
import { TypingLine, useTypingSender, useTypingWatch } from "./typing"; import { TypingLine, useTypingSender, useTypingWatch } from "./typing";
import { Badge, RankBadge } from "./Badges"; import { Badge, RankBadge } from "./Badges";
@@ -336,7 +337,8 @@ function PostCard({
) : ( ) : (
post.body !== null && ( post.body !== null && (
<> <>
<PostBody text={post.body} mentions={post.mentions} /> <PostBody text={post.body} mentions={post.mentions} hide={post.links?.map((l) => l.url) ?? []} />
{post.links && post.links.length > 0 && <LinkPreviews links={post.links} />}
{post.share && <ShareCard share={post.share} />} {post.share && <ShareCard share={post.share} />}
</> </>
) )
+16
View File
@@ -121,6 +121,22 @@ export interface ForumPost {
muted?: boolean; muted?: boolean;
/** A chart, forecast or synastry shared with the question. */ /** A chart, forecast or synastry shared with the question. */
share?: ShareCardData | null; share?: ShareCardData | null;
/** Previews of the links a provider knows (YouTube for now). */
links?: LinkPreview[] | null;
}
/** A link the forum's link module knows, under a post. */
export interface LinkPreview {
provider: "youtube";
id: string;
/** As written in the post. */
url: string;
/** Where to start playing, in seconds. */
start: number | null;
title: string;
author: string | null;
/** Our own copy of the thumbnail. */
thumbnail: string | null;
} }
/** A shared chart in a post: in full for members, `locked` for visitors, `revoked` when taken down. */ /** A shared chart in a post: in full for members, `locked` for visitors, `revoked` when taken down. */