Skip to main content

vector_core/
nostr_embed.rs

1//! Nostr content referenced from a chat message (a post, an article, a video),
2//! fetched from relays and shaped for an inline card.
3//!
4//! A reference is a `note1`/`nevent1`/`naddr1` entity, bare, as a `nostr:` URI, or
5//! as the last path segment of a web link. The web site itself is never contacted:
6//! the event comes from relays and is verified before it is shown.
7
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::sync::{Arc, Mutex};
10
11use nostr_sdk::prelude::*;
12use serde::Serialize;
13
14use crate::ClientRelayExt;
15
16pub const KIND_POST: u16 = 1;
17pub const KIND_ARTICLE: u16 = 30023;
18pub const KIND_VIDEO: u16 = 21;
19pub const KIND_SHORT: u16 = 22;
20pub const KIND_VIDEO_ADDRESSABLE: u16 = 34235;
21pub const KIND_SHORT_ADDRESSABLE: u16 = 34236;
22pub const KIND_REPOST: u16 = 6;
23pub const KIND_GENERIC_REPOST: u16 = 16;
24/// NIP-22: a plaintext reply scoped to what it answers, outside kind 1's own threads.
25pub const KIND_COMMENT: u16 = 1111;
26
27/// Asked when neither our relays, the reference's hints nor the author's outbox
28/// have it: the large general-purpose relays most public content reaches.
29const PUBLIC_RELAYS: &[&str] = &["wss://relay.damus.io", "wss://relay.primal.net", "wss://nos.lol"];
30const MAX_REMOTE_RELAYS: usize = 8;
31const POOL_TIMEOUT_SECS: u64 = 6;
32const REMOTE_TIMEOUT_SECS: u64 = 8;
33/// A miss is retried after this long, so a relay blip doesn't blank a card all session.
34const MISS_TTL_SECS: u64 = 30;
35const CACHE_CAP: usize = 512;
36/// What the remembered cards may hold between them; past it the oldest go.
37const CACHE_BYTES: usize = 4 * 1024 * 1024;
38/// Longest a second ask waits on a first still fetching before fetching itself: past every
39/// relay budget, so it only fires when the first was lost.
40const WAIT_DEADLINE_SECS: u64 = 150;
41/// A post's files beyond these are never shown, so they are never worked on either.
42const MAX_MEDIA: usize = 16;
43const MAX_CONTENT_URLS: usize = 32;
44const MAX_FALLBACKS: usize = 3;
45/// Bounds what a card or modal is handed: a post or video description is never
46/// this long, an article rarely is.
47const MAX_TEXT_CHARS: usize = 100_000;
48
49fn supported(kind: u16) -> bool {
50    shown(kind) || is_repost_kind(kind)
51}
52
53/// What a card shows itself; a repost shows the event it carries.
54fn shown(kind: u16) -> bool {
55    matches!(kind, KIND_POST | KIND_COMMENT | KIND_ARTICLE | KIND_VIDEO | KIND_SHORT | KIND_VIDEO_ADDRESSABLE | KIND_SHORT_ADDRESSABLE)
56}
57
58fn is_repost_kind(kind: u16) -> bool {
59    matches!(kind, KIND_REPOST | KIND_GENERIC_REPOST)
60}
61
62/// What a reference points at, as decoded from its bech32.
63#[derive(Debug, Clone, PartialEq)]
64pub enum EmbedRef {
65    Event { id: EventId, author: Option<PublicKey>, kind: Option<u16>, relays: Vec<RelayUrl> },
66    Address { coordinate: Coordinate, relays: Vec<RelayUrl> },
67}
68
69impl EmbedRef {
70    /// A bare entity or a `nostr:` URI. `None` for anything that isn't a post,
71    /// article or video reference, so an emoji pack or invite naddr is never one.
72    pub fn parse(s: &str) -> Option<Self> {
73        let s = s.trim();
74        let bech = s.strip_prefix("nostr:").unwrap_or(s);
75        let r = match Nip19::from_bech32(bech).ok()? {
76            Nip19::EventId(id) => EmbedRef::Event { id, author: None, kind: None, relays: Vec::new() },
77            Nip19::Event(e) => EmbedRef::Event {
78                id: e.event_id,
79                author: e.author,
80                kind: e.kind.map(|k| k.as_u16()),
81                relays: e.relays,
82            },
83            Nip19::Coordinate(c) => EmbedRef::Address { coordinate: c.coordinate, relays: c.relays },
84            _ => return None,
85        };
86        match &r {
87            EmbedRef::Event { kind: Some(k), .. } if !supported(*k) => None,
88            EmbedRef::Address { coordinate, .. } if !supported(coordinate.kind.as_u16()) => None,
89            _ => Some(r),
90        }
91    }
92
93    /// An https link whose last path segment is a reference (njump, primal, habla
94    /// and the like all put it there).
95    pub fn from_url(url: &str) -> Option<Self> {
96        let rest = url.strip_prefix("https://")?;
97        let path = rest.split(['?', '#']).next()?;
98        let (_host, path) = path.split_once('/')?;
99        let last = path.trim_end_matches('/').rsplit('/').next()?;
100        let last = last.trim_end_matches(['!', '\'', '"', '.', ',', ';', ':', '?', ')', ']']);
101        let last = last.strip_suffix(".html").unwrap_or(last);
102        let entity = last.strip_prefix("nostr:").unwrap_or(last);
103        if !(entity.starts_with("note1") || entity.starts_with("nevent1") || entity.starts_with("naddr1")) {
104            return None;
105        }
106        Self::parse(entity)
107    }
108
109    fn key(&self) -> String {
110        match self {
111            EmbedRef::Event { id, .. } => format!("e:{}", id.to_hex()),
112            EmbedRef::Address { coordinate, .. } => format!(
113                "a:{}:{}:{}",
114                coordinate.kind.as_u16(),
115                coordinate.public_key.to_hex(),
116                coordinate.identifier
117            ),
118        }
119    }
120
121    fn author(&self) -> Option<PublicKey> {
122        match self {
123            EmbedRef::Event { author, .. } => *author,
124            EmbedRef::Address { coordinate, .. } => Some(coordinate.public_key),
125        }
126    }
127
128    fn hints(&self) -> &[RelayUrl] {
129        match self {
130            EmbedRef::Event { relays, .. } | EmbedRef::Address { relays, .. } => relays,
131        }
132    }
133
134    fn filter(&self) -> Filter {
135        match self {
136            EmbedRef::Event { id, .. } => Filter::new().id(*id).limit(1),
137            EmbedRef::Address { coordinate, .. } => Filter::new()
138                .author(coordinate.public_key)
139                .kind(coordinate.kind)
140                .identifier(coordinate.identifier.clone())
141                .limit(1),
142        }
143    }
144
145    /// A relay's answer is only believed when it is exactly what was asked for.
146    fn matches(&self, ev: &Event) -> bool {
147        if ev.verify().is_err() {
148            return false;
149        }
150        match self {
151            EmbedRef::Event { id, author, kind, .. } => {
152                ev.id == *id && author.is_none_or(|a| a == ev.pubkey) && kind.is_none_or(|k| k == ev.kind.as_u16())
153            }
154            EmbedRef::Address { coordinate, .. } => {
155                ev.kind == coordinate.kind
156                    && ev.pubkey == coordinate.public_key
157                    && ev.tags.identifier().as_deref().unwrap_or("") == coordinate.identifier
158            }
159        }
160    }
161}
162
163/// A playable or viewable file a post or video carries.
164#[derive(Debug, Clone, Serialize, PartialEq)]
165pub struct EmbedMedia {
166    pub url: String,
167    pub is_video: bool,
168    pub mime: Option<String>,
169    pub width: Option<u32>,
170    pub height: Option<u32>,
171    pub size: Option<u64>,
172    pub duration: Option<f64>,
173    pub poster: Option<String>,
174    pub sha256: Option<String>,
175    pub fallbacks: Vec<String>,
176}
177
178/// One referenced event, shaped for its card.
179#[derive(Debug, Clone, Serialize)]
180pub struct Embed {
181    /// "post", "article", "video" or "short".
182    pub class: &'static str,
183    pub kind: u16,
184    pub id: String,
185    pub author: String,
186    pub created_at: u64,
187    pub published_at: Option<u64>,
188    pub title: Option<String>,
189    pub summary: Option<String>,
190    /// Article cover or video poster.
191    pub image: Option<String>,
192    /// A post's text without its media links, an article's markdown, or a video's description.
193    pub text: String,
194    pub media: Vec<EmbedMedia>,
195    pub video: Option<EmbedMedia>,
196    /// A video event's page when it names no file that can be fetched (a YouTube link).
197    pub link: Option<String>,
198    pub content_warning: Option<String>,
199    /// NIP-30 custom emoji the text's `:shortcode:`s name.
200    pub emoji: Vec<crate::types::EmojiTag>,
201    /// The canonical nevent/naddr, relay hints included, for copying.
202    pub bech32: String,
203    /// Who reposted it, when the reference named a repost (NIP-18).
204    pub reposted_by: Option<String>,
205    /// What a comment answers (NIP-22).
206    pub reply_to: Option<ReplyTo>,
207}
208
209/// A comment's parent: a Nostr event, or a scope outside Nostr (NIP-73).
210#[derive(Debug, Clone, Serialize, PartialEq)]
211pub struct ReplyTo {
212    /// The parent's kind, as its `k` tag says; None outside Nostr.
213    pub kind: Option<u16>,
214    /// The parent as a nevent or naddr, when it's an event a card can show.
215    pub entity: Option<String>,
216    /// A scope outside Nostr, by its NIP-73 value: a URL, a `#hashtag`, and the like.
217    pub external: Option<String>,
218}
219
220/// The parent a NIP-22 comment names in its lowercase tags; the uppercase ones are its thread's root.
221fn comment_parent(ev: &Event) -> Option<ReplyTo> {
222    let tag = |name: &str| ev.tags.iter().map(|t| t.as_slice()).find(|s| s.first().map(String::as_str) == Some(name) && s.len() > 1);
223    let hint = |s: &[String]| s.get(2).and_then(|r| RelayUrl::parse(r).ok()).into_iter().collect::<Vec<_>>();
224    let kind = tag_value(ev, "k").and_then(|k| k.trim().parse::<u16>().ok());
225    if let Some(a) = tag("a") {
226        if let Ok(coordinate) = Coordinate::parse(&a[1]) {
227            let parent = coordinate.kind.as_u16();
228            let entity = supported(parent).then(|| Nip19Coordinate::new(coordinate, hint(a)).to_bech32().ok()).flatten();
229            return Some(ReplyTo { kind: kind.or(Some(parent)), entity, external: None });
230        }
231    }
232    if let Some(e) = tag("e") {
233        let id = EventId::from_hex(&e[1]).ok()?;
234        let mut nevent = Nip19Event::new(id).relays(hint(e));
235        if let Some(author) = e.get(3).and_then(|p| PublicKey::from_hex(p).ok()) {
236            nevent = nevent.author(author);
237        }
238        if let Some(k) = kind {
239            nevent = nevent.kind(Kind::from(k));
240        }
241        let entity = kind.is_none_or(supported).then(|| nevent.to_bech32().ok()).flatten();
242        return Some(ReplyTo { kind, entity, external: None });
243    }
244    tag("i").map(|i| ReplyTo { kind: None, entity: None, external: Some(i[1].chars().take(300).collect()) })
245}
246
247/// Fetch and shape the event `reference` (a bare entity, a `nostr:` URI, or a web
248/// link ending in one). Repeated asks within a session are answered from memory.
249pub async fn fetch(reference: &str) -> Result<Embed, String> {
250    let r = EmbedRef::parse(reference)
251        .or_else(|| EmbedRef::from_url(reference))
252        .ok_or("Not a post, article or video reference")?;
253    let key = r.key();
254    // Held for the whole ask: an account swap mid-fetch must not file it under the next one.
255    let owner = cache();
256    let started = web_time::Instant::now();
257    let _claim = loop {
258        match cache_lookup(&owner, &key) {
259            Lookup::Hit(result) => return result.map(Arc::unwrap_or_clone),
260            Lookup::Fetch => break InFlight { owner: owner.clone(), key: key.clone() },
261            Lookup::Wait if started.elapsed().as_secs() >= WAIT_DEADLINE_SECS => {
262                break InFlight { owner: owner.clone(), key: key.clone() };
263            }
264            Lookup::Wait => crate::rt::time::sleep(std::time::Duration::from_millis(100)).await,
265        }
266    };
267    let result = match fetch_event(&r).await {
268        Some(ev) if is_repost_kind(ev.kind.as_u16()) => shape_repost(&ev).await,
269        Some(ev) => to_embed(&ev, r.hints()),
270        None => Err("Not found on any relay".to_string()),
271    };
272    cache_store(&owner, &key, &result);
273    result
274}
275
276/// Clears a key's in-flight mark however its fetch ends, a dropped future or a panic included,
277/// or every later ask for it would wait on nothing.
278struct InFlight {
279    owner: Arc<Mutex<EmbedCache>>,
280    key: String,
281}
282
283impl Drop for InFlight {
284    fn drop(&mut self) {
285        self.owner.lock().unwrap_or_else(|e| e.into_inner()).in_flight.remove(&self.key);
286    }
287}
288
289struct EmbedCacheKey;
290
291#[derive(Default)]
292struct EmbedCache {
293    entries: HashMap<Arc<str>, Cached>,
294    order: VecDeque<Arc<str>>,
295    in_flight: HashSet<String>,
296    /// Sum of the entries' [`Cached::weight`].
297    bytes: usize,
298}
299
300enum Cached {
301    Hit { embed: Arc<Embed>, weight: usize },
302    Miss { error: Box<str>, at: web_time::Instant },
303}
304
305impl Cached {
306    fn weight(&self) -> usize {
307        match self {
308            Cached::Hit { weight, .. } => *weight,
309            Cached::Miss { error, .. } => error.len(),
310        }
311    }
312}
313
314/// The bytes an embed holds, near enough to budget the cache by.
315fn weight(e: &Embed) -> usize {
316    fn opt(s: &Option<String>) -> usize {
317        s.as_ref().map_or(0, String::len)
318    }
319    fn media(m: &EmbedMedia) -> usize {
320        m.url.len() + opt(&m.mime) + opt(&m.poster) + opt(&m.sha256) + m.fallbacks.iter().map(String::len).sum::<usize>()
321    }
322    std::mem::size_of::<Embed>()
323        + e.id.len()
324        + e.author.len()
325        + opt(&e.title)
326        + opt(&e.summary)
327        + opt(&e.image)
328        + e.text.len()
329        + e.media.iter().map(|m| std::mem::size_of::<EmbedMedia>() + media(m)).sum::<usize>()
330        + e.video.as_ref().map_or(0, media)
331        + opt(&e.link)
332        + opt(&e.content_warning)
333        + e.emoji.iter().map(|t| t.shortcode.len() + t.url.len()).sum::<usize>()
334        + e.bech32.len()
335        + opt(&e.reposted_by)
336}
337
338enum Lookup {
339    Hit(Result<Arc<Embed>, String>),
340    Wait,
341    Fetch,
342}
343
344/// Which posts this account looked at is its own business, so the cache lives on its session.
345fn cache() -> Arc<Mutex<EmbedCache>> {
346    crate::db::current_session().scoped::<EmbedCacheKey, _>()
347}
348
349fn cache_lookup(owner: &Mutex<EmbedCache>, key: &str) -> Lookup {
350    let mut c = owner.lock().unwrap_or_else(|e| e.into_inner());
351    match c.entries.get(key) {
352        Some(Cached::Hit { embed, .. }) => return Lookup::Hit(Ok(embed.clone())),
353        Some(Cached::Miss { error, at }) if at.elapsed().as_secs() < MISS_TTL_SECS => {
354            return Lookup::Hit(Err(error.to_string()));
355        }
356        _ => {}
357    }
358    if c.in_flight.contains(key) {
359        return Lookup::Wait;
360    }
361    c.in_flight.insert(key.to_string());
362    Lookup::Fetch
363}
364
365fn cache_store(owner: &Mutex<EmbedCache>, key: &str, result: &Result<Embed, String>) {
366    let mut c = owner.lock().unwrap_or_else(|e| e.into_inner());
367    let entry = match result {
368        Ok(embed) => Cached::Hit { embed: Arc::new(embed.clone()), weight: weight(embed) },
369        Err(error) => Cached::Miss { error: error.as_str().into(), at: web_time::Instant::now() },
370    };
371    c.bytes += entry.weight();
372    let key: Arc<str> = Arc::from(key);
373    if let Some(old) = c.entries.insert(key.clone(), entry) {
374        c.bytes -= old.weight();
375        // Newest again, so the budget below never takes what was just stored.
376        if let Some(at) = c.order.iter().position(|k| **k == *key) {
377            c.order.remove(at);
378        }
379    }
380    c.order.push_back(key);
381    while c.order.len() > 1 && (c.order.len() > CACHE_CAP || c.bytes > CACHE_BYTES) {
382        if let Some(old) = c.order.pop_front() {
383            if let Some(gone) = c.entries.remove(&old) {
384                c.bytes -= gone.weight();
385            }
386        }
387    }
388}
389
390/// Our own relays first, then the reference's hints, the author's outbox and the
391/// big public relays through a throwaway client.
392async fn fetch_event(r: &EmbedRef) -> Option<Event> {
393    let filter = r.filter();
394    let client = crate::state::nostr_client();
395    if let Some(client) = &client {
396        let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(POOL_TIMEOUT_SECS));
397        match client.fetch_events(filter.clone()).timeout(timeout).await {
398            Ok(events) => {
399                if let Some(ev) = best(r, events) {
400                    return Some(ev);
401                }
402            }
403            Err(e) => crate::log_debug!("[Embeds] pool fetch failed: {e}"),
404        }
405    }
406
407    // Hints and the author's outbox are chosen by whoever sent the reference: on Clearnet with
408    // the privacy proxy on, dialing them would hand that sender this device's address.
409    let mut relays: Vec<RelayUrl> = Vec::new();
410    let decided = crate::transport::preference();
411    let strangers = may_dial_strangers();
412    if strangers {
413        relays.extend(r.hints().iter().filter(|u| dialable(u)).take(4).cloned());
414        if let (Some(client), Some(author)) = (&client, r.author()) {
415            let outbox = crate::emoji_packs::fetch_author_write_relays(client, author).await;
416            for url in outbox.into_iter().filter(dialable).take(4) {
417                if !relays.contains(&url) {
418                    relays.push(url);
419                }
420            }
421        }
422    }
423    for url in PUBLIC_RELAYS.iter().filter_map(|u| RelayUrl::parse(u).ok()) {
424        if !relays.contains(&url) {
425            relays.push(url);
426        }
427    }
428    relays.truncate(MAX_REMOTE_RELAYS);
429
430    let _lane = REMOTE_LANE.acquire().await.ok();
431    // The wait for a lane can be long: a switch meanwhile leaves only the public relays, and
432    // strangers' relays allowed only off Clearnet are never dialed direct, however late it lands.
433    let mut off_clearnet_only = strangers && crate::proxy::enabled();
434    if strangers && (crate::transport::preference() != decided || !may_dial_strangers()) {
435        relays.retain(|u| PUBLIC_RELAYS.contains(&u.as_str().trim_end_matches('/')));
436        off_clearnet_only = false;
437    }
438    // No authenticator: a relay that asks who is reading learns nothing about the user.
439    let scratch = if off_clearnet_only {
440        crate::transport::ws::apply_transport_without_direct(ClientBuilder::new(), crate::transport::Lane::Shared).build()
441    } else {
442        crate::apply_transport(ClientBuilder::new(), crate::transport::Lane::Shared).build()
443    };
444    for url in &relays {
445        let _ = scratch.add_managed_relay(url.as_str()).await;
446    }
447    scratch.connect().await;
448    let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(REMOTE_TIMEOUT_SECS));
449    let result = scratch.fetch_events(filter).timeout(timeout).await;
450    scratch.shutdown().await;
451    match result {
452        Ok(events) => best(r, events),
453        Err(e) => {
454            crate::log_debug!("[Embeds] remote fetch failed: {e}");
455            None
456        }
457    }
458}
459
460/// A repost shows what it reposted, under the reposter's name. Only one level: a repost of a
461/// repost is refused, so a chain can't send the fetch round in circles.
462async fn shape_repost(ev: &Event) -> Result<Embed, String> {
463    let target = repost_target(ev);
464    let inner = match reposted_inline(ev, target.as_ref()) {
465        Some(inner) => inner,
466        None => fetch_event(target.as_ref().ok_or("This repost doesn't say what it reposted")?)
467            .await
468            .ok_or("The reposted post wasn't found")?,
469    };
470    if !shown(inner.kind.as_u16()) {
471        return Err(format!("Unsupported Nostr event (kind {})", inner.kind.as_u16()));
472    }
473    let hints: Vec<RelayUrl> = target.as_ref().map(|t| t.hints().to_vec()).unwrap_or_default();
474    let mut embed = to_embed(&inner, &hints)?;
475    embed.reposted_by = Some(ev.pubkey.to_bech32().map_err(|e| e.to_string())?);
476    Ok(embed)
477}
478
479/// The event a repost names: its `a` coordinate, else its `e` id with the relay and kind it gives.
480fn repost_target(ev: &Event) -> Option<EmbedRef> {
481    let tag = |name: &str| {
482        ev.tags.iter().find_map(|t| {
483            let s = t.as_slice();
484            (s.first().map(String::as_str) == Some(name)).then(|| s.to_vec())
485        })
486    };
487    let hint = |s: &[String]| s.get(2).and_then(|u| RelayUrl::parse(u).ok()).into_iter().collect::<Vec<_>>();
488    if let Some(a) = tag("a") {
489        let coordinate = Coordinate::parse(a.get(1)?).ok()?;
490        return Some(EmbedRef::Address { coordinate, relays: hint(&a) });
491    }
492    let e = tag("e")?;
493    Some(EmbedRef::Event {
494        id: EventId::from_hex(e.get(1)?).ok()?,
495        author: tag("p").and_then(|p| PublicKey::from_hex(p.get(1)?).ok()),
496        kind: tag("k").and_then(|k| k.get(1)?.parse().ok()),
497        relays: hint(&e),
498    })
499}
500
501/// The reposted event carried in the repost's content, believed only if it is signed and is
502/// the event the repost's tags name.
503fn reposted_inline(ev: &Event, target: Option<&EmbedRef>) -> Option<Event> {
504    let inner = crate::event_json::event(ev.content.trim()).ok()?;
505    match target {
506        Some(t) => t.matches(&inner).then_some(inner),
507        None => inner.verify().is_ok().then_some(inner),
508    }
509}
510
511/// Scratch clients open at once; each dials up to MAX_REMOTE_RELAYS sockets.
512static REMOTE_LANE: std::sync::LazyLock<tokio::sync::Semaphore> = std::sync::LazyLock::new(|| tokio::sync::Semaphore::new(4));
513
514/// Whether relays named by a stranger may be dialed: over an anonymity network, or when the
515/// user has chosen to connect directly anyway (the privacy proxy off).
516pub(crate) fn may_dial_strangers() -> bool {
517    match crate::transport::preference() {
518        Some(crate::transport::Kind::Clearnet) => !crate::proxy::enabled(),
519        Some(_) => true,
520        // Not loaded yet: nothing says the address is hidden.
521        None => false,
522    }
523}
524
525/// A stranger's relay is dialed only over TLS and only on the public internet; an `.i2p`
526/// relay also over plain `ws://` while the account is on I2P, where the network itself is
527/// end to end.
528fn dialable(url: &RelayUrl) -> bool {
529    let s = url.as_str();
530    if s.starts_with("ws://") && crate::transport::preference() == Some(crate::transport::Kind::I2p) {
531        return url.domain().is_some_and(|d| d.ends_with(".i2p"));
532    }
533    s.starts_with("wss://") && crate::net::validate_url_not_private(&s.replacen("wss://", "https://", 1)).is_ok()
534}
535
536/// The newest event that is exactly what `r` names.
537fn best(r: &EmbedRef, events: impl IntoIterator<Item = Event>) -> Option<Event> {
538    events.into_iter().filter(|ev| r.matches(ev)).max_by_key(|ev| ev.created_at)
539}
540
541fn tag_value<'a>(ev: &'a Event, name: &str) -> Option<&'a str> {
542    ev.tags.iter().find_map(|t| {
543        let s = t.as_slice();
544        (s.first().map(String::as_str) == Some(name)).then(|| s.get(1).map(String::as_str)).flatten()
545    })
546}
547
548fn non_empty(s: Option<&str>) -> Option<String> {
549    s.map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
550}
551
552fn cap_text(mut s: String) -> String {
553    if let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) {
554        s.truncate(i);
555    }
556    s
557}
558
559pub(crate) fn to_embed(ev: &Event, hints: &[RelayUrl]) -> Result<Embed, String> {
560    let kind = ev.kind.as_u16();
561    let class = match kind {
562        KIND_POST | KIND_COMMENT => "post",
563        KIND_ARTICLE => "article",
564        KIND_VIDEO | KIND_VIDEO_ADDRESSABLE => "video",
565        KIND_SHORT | KIND_SHORT_ADDRESSABLE => "short",
566        other => return Err(format!("Unsupported Nostr event (kind {other})")),
567    };
568    let author = ev.pubkey.to_bech32().map_err(|e| e.to_string())?;
569    let hints: Vec<RelayUrl> = hints.iter().take(3).cloned().collect();
570    let bech32 = if ev.kind.is_addressable() {
571        let coordinate = Coordinate::new(ev.kind, ev.pubkey).identifier(ev.tags.identifier().unwrap_or_default());
572        Nip19Coordinate::new(coordinate, hints).to_bech32()
573    } else {
574        Nip19Event::new(ev.id).author(ev.pubkey).kind(ev.kind).relays(hints).to_bech32()
575    }
576    .map_err(|e| e.to_string())?;
577    let published_at = tag_value(ev, "published_at").and_then(|v| v.trim().parse::<u64>().ok());
578    let content_warning = ev.tags.iter().find_map(|t| {
579        let s = t.as_slice();
580        (s.first().map(String::as_str) == Some("content-warning")).then(|| s.get(1).cloned().unwrap_or_default())
581    });
582
583    let content = cap_text(ev.content.clone());
584    let imeta = imeta_media(ev);
585    let mut embed = Embed {
586        class,
587        kind,
588        id: ev.id.to_hex(),
589        author,
590        created_at: ev.created_at.as_secs(),
591        published_at,
592        title: None,
593        summary: None,
594        image: None,
595        text: String::new(),
596        media: Vec::new(),
597        video: None,
598        link: None,
599        content_warning,
600        emoji: crate::types::EmojiTag::extract_from_tags(ev.tags.iter()),
601        bech32,
602        reposted_by: None,
603        reply_to: (kind == KIND_COMMENT).then(|| comment_parent(ev)).flatten(),
604    };
605    match class {
606        "post" => {
607            let mut media = imeta;
608            let mut seen: HashSet<String> = media.iter().map(|m| m.url.clone()).collect();
609            for url in content_urls(&content).into_iter().take(MAX_CONTENT_URLS) {
610                if media.len() >= MAX_MEDIA {
611                    break;
612                }
613                if let Some(is_video) = media_kind_by_extension(&url) {
614                    if seen.insert(url.clone()) {
615                        media.push(EmbedMedia::bare(url, is_video));
616                    }
617                }
618            }
619            let mut text = content;
620            for m in &media {
621                text = text.replace(&m.url, "");
622            }
623            embed.text = npubs_for_nprofiles(text.trim());
624            embed.media = media;
625        }
626        "article" => {
627            embed.title = non_empty(tag_value(ev, "title"));
628            embed.summary = non_empty(tag_value(ev, "summary"));
629            embed.image = non_empty(tag_value(ev, "image"));
630            embed.text = npubs_for_nprofiles(&content);
631        }
632        _ => {
633            embed.title = non_empty(tag_value(ev, "title")).or_else(|| non_empty(tag_value(ev, "alt")));
634            embed.text = npubs_for_nprofiles(content.trim());
635            let mut variants: Vec<EmbedMedia> = imeta.iter().filter(|m| m.is_video).cloned().collect();
636            if variants.is_empty() {
637                variants.extend(legacy_video(ev));
638            }
639            let video = best_variant(variants);
640            embed.image = video
641                .as_ref()
642                .and_then(|v| v.poster.clone())
643                .or_else(|| imeta.iter().find_map(|m| m.poster.clone()))
644                .or_else(|| non_empty(tag_value(ev, "thumb")))
645                .or_else(|| non_empty(tag_value(ev, "image")));
646            if video.is_none() {
647                // The page, never its thumbnail: an image link is not where the video plays.
648                embed.link = imeta
649                    .iter()
650                    .filter(|m| media_kind_by_extension(&m.url) != Some(false))
651                    .map(|m| m.url.clone())
652                    .chain(tag_value(ev, "url").filter(|u| is_https(u)).map(str::to_string))
653                    .next();
654            }
655            embed.video = video;
656        }
657    }
658    Ok(embed)
659}
660
661impl EmbedMedia {
662    fn bare(url: String, is_video: bool) -> Self {
663        EmbedMedia {
664            url,
665            is_video,
666            mime: None,
667            width: None,
668            height: None,
669            size: None,
670            duration: None,
671            poster: None,
672            sha256: None,
673            fallbacks: Vec::new(),
674        }
675    }
676}
677
678fn is_https(url: &str) -> bool {
679    url.starts_with("https://")
680}
681
682/// Image or video, judged from the link's extension; `None` for anything else.
683fn media_kind_by_extension(url: &str) -> Option<bool> {
684    let path = url.split(['?', '#']).next()?.to_ascii_lowercase();
685    let ext = path.rsplit_once('.')?.1;
686    match ext {
687        "jpg" | "jpeg" | "png" | "gif" | "webp" | "avif" | "svg" => Some(false),
688        "mp4" | "webm" | "mov" | "m4v" => Some(true),
689        _ => None,
690    }
691}
692
693fn mime_is_video(mime: &str) -> bool {
694    matches!(mime, "video/mp4" | "video/webm" | "video/quicktime" | "video/x-m4v")
695}
696
697/// The https links in a post's text, with trailing punctuation dropped.
698fn content_urls(content: &str) -> Vec<String> {
699    content
700        .split_whitespace()
701        .filter_map(|word| {
702            let start = word.find("https://")?;
703            let url = word[start..].trim_end_matches(['.', ',', ';', ':', '!', '?', ')', ']', '}', '"', '\'']);
704            (url.len() > "https://".len()).then(|| url.to_string())
705        })
706        .collect()
707}
708
709/// NIP-92 `imeta` entries: one `key value` pair per element after the tag name.
710fn imeta_media(ev: &Event) -> Vec<EmbedMedia> {
711    let mut out = Vec::new();
712    for tag in ev.tags.iter() {
713        let s = tag.as_slice();
714        if s.first().map(String::as_str) != Some("imeta") {
715            continue;
716        }
717        let mut fields: HashMap<&str, Vec<&str>> = HashMap::new();
718        for entry in &s[1..] {
719            if let Some((k, v)) = entry.split_once(' ') {
720                fields.entry(k).or_default().push(v.trim());
721            }
722        }
723        let first = |k: &str| fields.get(k).and_then(|v| v.first()).copied();
724        let Some(url) = first("url").filter(|u| is_https(u)) else { continue };
725        if out.iter().any(|m: &EmbedMedia| m.url == url) {
726            continue;
727        }
728        let mime = first("m").map(str::to_ascii_lowercase);
729        let is_video = match mime.as_deref() {
730            Some(m) if m.starts_with("video/") => {
731                if !mime_is_video(m) {
732                    continue; // a stream manifest (HLS, DASH) can't be fetched as one file
733                }
734                true
735            }
736            Some(m) if m.starts_with("image/") => false,
737            _ => match media_kind_by_extension(url) {
738                Some(v) => v,
739                None => continue,
740            },
741        };
742        let (width, height) = first("dim").and_then(parse_dim).map_or((None, None), |(w, h)| (Some(w), Some(h)));
743        out.push(EmbedMedia {
744            url: url.to_string(),
745            is_video,
746            mime,
747            width,
748            height,
749            size: first("size").and_then(|v| v.parse().ok()),
750            duration: first("duration").and_then(|v| v.parse().ok()).filter(|d: &f64| d.is_finite() && *d > 0.0),
751            poster: first("image").filter(|u| is_https(u)).map(str::to_string),
752            sha256: first("x").filter(|x| x.len() == 64).map(str::to_ascii_lowercase),
753            fallbacks: fields
754                .get("fallback")
755                .map(|v| v.iter().filter(|u| is_https(u)).take(MAX_FALLBACKS).map(|u| u.to_string()).collect())
756                .unwrap_or_default(),
757        });
758        if out.len() >= MAX_MEDIA {
759            break;
760        }
761    }
762    out
763}
764
765/// The pre-imeta NIP-71 shape: the file described by top-level tags.
766fn legacy_video(ev: &Event) -> Option<EmbedMedia> {
767    let url = tag_value(ev, "url").filter(|u| is_https(u))?;
768    let mime = tag_value(ev, "m").map(str::to_ascii_lowercase);
769    if mime.as_deref().is_some_and(|m| m.starts_with("video/") && !mime_is_video(m)) {
770        return None;
771    }
772    let (width, height) = tag_value(ev, "dim").and_then(parse_dim).map_or((None, None), |(w, h)| (Some(w), Some(h)));
773    Some(EmbedMedia {
774        url: url.to_string(),
775        is_video: true,
776        mime,
777        width,
778        height,
779        size: tag_value(ev, "size").and_then(|v| v.parse().ok()),
780        duration: tag_value(ev, "duration").and_then(|v| v.parse().ok()).filter(|d: &f64| d.is_finite() && *d > 0.0),
781        poster: tag_value(ev, "thumb").or_else(|| tag_value(ev, "image")).filter(|u| is_https(u)).map(str::to_string),
782        sha256: tag_value(ev, "x").filter(|x| x.len() == 64).map(str::to_ascii_lowercase),
783        fallbacks: Vec::new(),
784    })
785}
786
787fn parse_dim(dim: &str) -> Option<(u32, u32)> {
788    let (w, h) = dim.trim().split_once('x')?;
789    Some((w.parse().ok()?, h.parse().ok()?))
790}
791
792/// The variant a chat bubble should play: the sharpest one up to 1080p, else the smallest.
793fn best_variant(variants: Vec<EmbedMedia>) -> Option<EmbedMedia> {
794    let short_side = |m: &EmbedMedia| match (m.width, m.height) {
795        (Some(w), Some(h)) => Some(w.min(h)),
796        _ => None,
797    };
798    let mut fitting: Vec<&EmbedMedia> = variants.iter().filter(|m| short_side(m).is_none_or(|s| s <= 1080)).collect();
799    fitting.sort_by_key(|m| short_side(m).unwrap_or(0));
800    if let Some(m) = fitting.last() {
801        return Some((*m).clone());
802    }
803    variants.into_iter().min_by_key(|m| short_side(m).unwrap_or(u32::MAX))
804}
805
806/// `nostr:nprofile1…` mentions become `nostr:npub1…`, which chat already renders as a name.
807fn npubs_for_nprofiles(text: &str) -> String {
808    let mut out = String::with_capacity(text.len());
809    let mut rest = text;
810    while let Some(i) = rest.find("nostr:nprofile1") {
811        out.push_str(&rest[..i]);
812        let tail = &rest[i + "nostr:".len()..];
813        let end = tail.find(|c: char| !c.is_ascii_alphanumeric()).unwrap_or(tail.len());
814        let entity = &tail[..end];
815        match Nip19Profile::from_bech32(entity).ok().and_then(|p| p.public_key.to_bech32().ok()) {
816            Some(npub) => {
817                out.push_str("nostr:");
818                out.push_str(&npub);
819            }
820            None => out.push_str(&rest[i..i + "nostr:".len() + end]),
821        }
822        rest = &tail[end..];
823    }
824    out.push_str(rest);
825    out
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831
832    fn signed(kind: u16, content: &str, tags: Vec<Tag>) -> (Keys, Event) {
833        let keys = Keys::generate();
834        let ev = EventBuilder::new(Kind::from(kind), content).tags(tags).finalize(&keys).unwrap();
835        (keys, ev)
836    }
837
838    fn raw(parts: &[&str]) -> Tag {
839        Tag::parse(parts.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
840    }
841
842    #[test]
843    fn a_comment_shows_as_a_post_that_names_its_parent() {
844        let author = Keys::generate().public_key().to_hex();
845        let article = format!("30023:{author}:essay");
846        let (_, top) = signed(KIND_COMMENT, "Great essay", vec![
847            raw(&["A", &article]), raw(&["K", "30023"]), raw(&["P", &author]),
848            raw(&["a", &article, "wss://relay.example"]), raw(&["k", "30023"]), raw(&["p", &author]),
849        ]);
850        let e = to_embed(&top, &[]).unwrap();
851        assert_eq!((e.class, e.kind, e.text.as_str()), ("post", KIND_COMMENT, "Great essay"));
852        let parent = e.reply_to.expect("a comment names its parent");
853        assert_eq!(parent.kind, Some(KIND_ARTICLE));
854        assert!(parent.entity.as_deref().is_some_and(|n| n.starts_with("naddr1")));
855
856        let (_, reply) = signed(KIND_COMMENT, "Agreed", vec![
857            raw(&["A", &article]), raw(&["K", "30023"]),
858            raw(&["e", &top.id.to_hex(), "", &top.pubkey.to_hex()]), raw(&["k", "1111"]), raw(&["p", &top.pubkey.to_hex()]),
859        ]);
860        let parent = to_embed(&reply, &[]).unwrap().reply_to.unwrap();
861        assert_eq!(parent.kind, Some(KIND_COMMENT), "a reply in a thread names the comment, not the article");
862        let nevent = Nip19Event::from_bech32(parent.entity.as_deref().unwrap()).unwrap();
863        assert_eq!((nevent.event_id, nevent.author), (top.id, Some(top.pubkey)));
864
865        let file = "11".repeat(32);
866        let (_, on_file) = signed(KIND_COMMENT, "Nice file", vec![raw(&["e", &file]), raw(&["k", "1063"])]);
867        let parent = to_embed(&on_file, &[]).unwrap().reply_to.unwrap();
868        assert_eq!((parent.kind, parent.entity), (Some(1063), None), "a kind no card shows is named, never opened");
869
870        let (_, on_web) = signed(KIND_COMMENT, "Nice article", vec![raw(&["I", "https://abc.com/a"]), raw(&["K", "web"]), raw(&["i", "https://abc.com/a"]), raw(&["k", "web"])]);
871        let parent = to_embed(&on_web, &[]).unwrap().reply_to.unwrap();
872        assert_eq!((parent.kind, parent.external.as_deref()), (None, Some("https://abc.com/a")));
873
874        let (_, post) = signed(KIND_POST, "hi", vec![raw(&["e", &file])]);
875        assert!(to_embed(&post, &[]).unwrap().reply_to.is_none(), "kind 1 threads are NIP-10's");
876    }
877
878    #[test]
879    fn references_parse_from_every_form_and_only_for_supported_kinds() {
880        let keys = Keys::generate();
881        let id = EventId::from_byte_array([0u8; 32]);
882        let note = id.to_bech32().unwrap();
883        assert!(matches!(EmbedRef::parse(&note), Some(EmbedRef::Event { kind: None, .. })));
884        assert!(EmbedRef::parse(&format!("nostr:{note}")).is_some());
885
886        let nevent = Nip19Event::new(id).kind(Kind::from(KIND_SHORT)).to_bech32().unwrap();
887        assert!(EmbedRef::parse(&nevent).is_some());
888        let reaction = Nip19Event::new(id).kind(Kind::from(7)).to_bech32().unwrap();
889        assert_eq!(EmbedRef::parse(&reaction), None, "a known unsupported kind is no embed");
890
891        let article = Nip19Coordinate::new(Coordinate::new(Kind::from(KIND_ARTICLE), keys.public_key()).identifier("essay"), Vec::<RelayUrl>::new())
892            .to_bech32()
893            .unwrap();
894        assert!(matches!(EmbedRef::parse(&article), Some(EmbedRef::Address { .. })));
895        let pack = Nip19Coordinate::new(Coordinate::new(Kind::from(30030), keys.public_key()).identifier("pack"), Vec::<RelayUrl>::new())
896            .to_bech32()
897            .unwrap();
898        assert_eq!(EmbedRef::parse(&pack), None, "an emoji pack keeps its own card");
899        assert_eq!(EmbedRef::parse(&keys.public_key().to_bech32().unwrap()), None);
900        assert_eq!(EmbedRef::parse("nevent1garbage"), None);
901    }
902
903    #[test]
904    fn web_links_carry_a_reference_only_in_their_last_segment() {
905        let keys = Keys::generate();
906        let nevent = Nip19Event::new(EventId::from_byte_array([0u8; 32])).to_bech32().unwrap();
907        let naddr = Nip19Coordinate::new(Coordinate::new(Kind::from(KIND_ARTICLE), keys.public_key()).identifier("x"), Vec::<RelayUrl>::new())
908            .to_bech32()
909            .unwrap();
910        assert!(EmbedRef::from_url(&format!("https://njump.me/{nevent}")).is_some());
911        assert!(EmbedRef::from_url(&format!("https://primal.net/e/{nevent}/?ref=1#top")).is_some());
912        assert!(EmbedRef::from_url(&format!("https://habla.news/a/{naddr}")).is_some());
913        assert!(EmbedRef::from_url(&format!("https://example.com/nostr:{nevent}")).is_some());
914        assert_eq!(EmbedRef::from_url(&format!("https://example.com/{nevent}/comments")), None);
915        assert_eq!(EmbedRef::from_url(&format!("https://example.com/?id={nevent}")), None);
916        assert_eq!(EmbedRef::from_url(&format!("http://njump.me/{nevent}")), None);
917
918        let pack = Nip19Coordinate::new(Coordinate::new(Kind::from(30030), keys.public_key()).identifier("p"), Vec::<RelayUrl>::new())
919            .to_bech32()
920            .unwrap();
921        assert_eq!(EmbedRef::from_url(&format!("https://vectorapp.io/emojis/pack/{pack}")), None);
922    }
923
924    #[test]
925    fn only_the_exact_signed_event_is_believed() {
926        let (keys, ev) = signed(KIND_POST, "hello", vec![]);
927        let r = EmbedRef::Event { id: ev.id, author: Some(keys.public_key()), kind: Some(KIND_POST), relays: vec![] };
928        assert!(r.matches(&ev));
929        let wrong_author = EmbedRef::Event { id: ev.id, author: Some(Keys::generate().public_key()), kind: None, relays: vec![] };
930        assert!(!wrong_author.matches(&ev));
931        let (_, other) = signed(KIND_POST, "other", vec![]);
932        assert!(!r.matches(&other), "a different id is not the event");
933
934        let mut forged: serde_json::Value = serde_json::from_str(&ev.as_json()).unwrap();
935        forged["content"] = "tampered".into();
936        let forged = Event::from_json(forged.to_string()).unwrap();
937        assert!(!r.matches(&forged), "a bad signature is never believed");
938
939        let (keys, article) = signed(KIND_ARTICLE, "# Hi", vec![Tag::identifier("essay")]);
940        let addr = EmbedRef::Address { coordinate: Coordinate::new(Kind::from(KIND_ARTICLE), keys.public_key()).identifier("essay"), relays: vec![] };
941        assert!(addr.matches(&article));
942        let elsewhere = EmbedRef::Address { coordinate: Coordinate::new(Kind::from(KIND_ARTICLE), keys.public_key()).identifier("other"), relays: vec![] };
943        assert!(!elsewhere.matches(&article));
944    }
945
946    #[test]
947    fn a_post_splits_its_media_from_its_text() {
948        let mention = Nip19Profile::new(Keys::generate().public_key(), Vec::<RelayUrl>::new()).to_bech32().unwrap();
949        let content = format!(
950            "Look at this https://cdn.example/a.jpg and https://cdn.example/clip.mp4?x=1, says nostr:{mention}. More: https://example.com/page"
951        );
952        let (_, ev) = signed(
953            KIND_POST,
954            &content,
955            vec![
956                raw(&["imeta", "url https://cdn.example/a.jpg", "m image/jpeg", "dim 800x600"]),
957                raw(&["content-warning", "spoilers"]),
958            ],
959        );
960        let e = to_embed(&ev, &[]).unwrap();
961        assert_eq!(e.class, "post");
962        assert_eq!(e.media.len(), 2);
963        assert_eq!((e.media[0].url.as_str(), e.media[0].is_video, e.media[0].width), ("https://cdn.example/a.jpg", false, Some(800)));
964        assert!(e.media[1].is_video && e.media[1].url == "https://cdn.example/clip.mp4?x=1");
965        assert!(!e.text.contains("cdn.example"), "media links leave the text: {}", e.text);
966        assert!(e.text.contains("https://example.com/page"), "other links stay");
967        assert!(e.text.contains("nostr:npub1") && !e.text.contains("nprofile"), "{}", e.text);
968        assert_eq!(e.content_warning.as_deref(), Some("spoilers"));
969        assert!(e.bech32.starts_with("nevent1"));
970    }
971
972    #[test]
973    fn an_article_keeps_its_markdown_and_metadata() {
974        let (_, ev) = signed(
975            KIND_ARTICLE,
976            "# Title\n\nBody ![pic](https://cdn.example/p.png)",
977            vec![
978                Tag::identifier("essay"),
979                raw(&["title", "On Embeds"]),
980                raw(&["summary", "Why cards"]),
981                raw(&["image", "https://cdn.example/cover.jpg"]),
982                raw(&["published_at", "1700000000"]),
983            ],
984        );
985        let e = to_embed(&ev, &[]).unwrap();
986        assert_eq!(e.class, "article");
987        assert_eq!(e.title.as_deref(), Some("On Embeds"));
988        assert_eq!(e.summary.as_deref(), Some("Why cards"));
989        assert_eq!(e.image.as_deref(), Some("https://cdn.example/cover.jpg"));
990        assert_eq!(e.published_at, Some(1_700_000_000));
991        assert!(e.text.contains("![pic]"), "the markdown is passed whole");
992        assert!(e.bech32.starts_with("naddr1"));
993    }
994
995    #[test]
996    fn a_video_picks_a_playable_variant_and_its_poster() {
997        let (_, ev) = signed(
998            KIND_VIDEO,
999            "A description",
1000            vec![
1001                raw(&["title", "Clip"]),
1002                raw(&["imeta", "url https://v.example/master.m3u8", "m application/x-mpegURL"]),
1003                raw(&["imeta", "url https://v.example/hls.m3u8", "m video/mp2t"]),
1004                raw(&["imeta", "url https://v.example/4k.mp4", "m video/mp4", "dim 3840x2160", "image https://v.example/4k.jpg"]),
1005                raw(&["imeta", "url https://v.example/720.mp4", "m video/mp4", "dim 1280x720", "image https://v.example/p.jpg", "duration 29.5", "size 4000000", "fallback https://m.example/720.mp4"]),
1006                raw(&["imeta", "url https://v.example/480.mp4", "m video/mp4", "dim 854x480"]),
1007            ],
1008        );
1009        let e = to_embed(&ev, &[]).unwrap();
1010        assert_eq!(e.class, "video");
1011        let v = e.video.unwrap();
1012        assert_eq!(v.url, "https://v.example/720.mp4", "the sharpest up to 1080p");
1013        assert_eq!((v.duration, v.size), (Some(29.5), Some(4_000_000)));
1014        assert_eq!(v.fallbacks, vec!["https://m.example/720.mp4".to_string()]);
1015        assert_eq!(e.image.as_deref(), Some("https://v.example/p.jpg"));
1016        assert_eq!(e.title.as_deref(), Some("Clip"));
1017
1018        let (_, short) = signed(
1019            KIND_SHORT_ADDRESSABLE,
1020            "",
1021            vec![Tag::identifier("s"), raw(&["url", "https://v.example/s.mp4"]), raw(&["thumb", "https://v.example/s.jpg"]), raw(&["dim", "1080x1920"])],
1022        );
1023        let e = to_embed(&short, &[]).unwrap();
1024        assert_eq!(e.class, "short");
1025        assert_eq!(e.video.as_ref().map(|v| v.url.as_str()), Some("https://v.example/s.mp4"), "the pre-imeta shape still plays");
1026        assert_eq!(e.image.as_deref(), Some("https://v.example/s.jpg"));
1027    }
1028
1029    #[test]
1030    fn a_video_page_without_a_file_links_out_with_its_poster() {
1031        let (_, ev) = signed(
1032            KIND_VIDEO,
1033            "Watch this",
1034            vec![raw(&["title", "Talk"]), raw(&["imeta", "url https://www.youtube.com/watch?v=abc", "image https://i.ytimg.com/vi/abc/hq.jpg", "m image/jpeg"])],
1035        );
1036        let e = to_embed(&ev, &[]).unwrap();
1037        assert!(e.video.is_none(), "a web page is not a file to fetch");
1038        assert_eq!(e.image.as_deref(), Some("https://i.ytimg.com/vi/abc/hq.jpg"));
1039        assert_eq!(e.link.as_deref(), Some("https://www.youtube.com/watch?v=abc"));
1040    }
1041
1042    #[test]
1043    fn a_huge_post_is_shaped_in_bounded_time() {
1044        let words: Vec<String> = (0..60_000).map(|i| format!("https://a.b/{i}.png")).collect();
1045        let (_, ev) = signed(KIND_POST, &words.join(" "), vec![]);
1046        let started = std::time::Instant::now();
1047        let e = to_embed(&ev, &[]).unwrap();
1048        assert!(started.elapsed() < std::time::Duration::from_secs(2), "took {:?}", started.elapsed());
1049        assert_eq!(e.media.len(), MAX_MEDIA);
1050        assert!(e.text.chars().count() <= MAX_TEXT_CHARS);
1051    }
1052
1053    #[test]
1054    fn a_repeated_file_is_listed_once_with_few_mirrors() {
1055        let mirrors: Vec<String> = (0..50).map(|i| format!("fallback https://m{i}.example/a.mp4")).collect();
1056        let mut imeta = vec!["imeta".to_string(), "url https://v.example/a.mp4".to_string(), "m video/mp4".to_string()];
1057        imeta.extend(mirrors);
1058        let imeta: Vec<&str> = imeta.iter().map(String::as_str).collect();
1059        let (_, ev) = signed(KIND_POST, "clip", vec![raw(&imeta), raw(&["imeta", "url https://v.example/a.mp4", "m video/mp4"])]);
1060        let e = to_embed(&ev, &[]).unwrap();
1061        assert_eq!(e.media.len(), 1, "one card per file, or the list's keys collide");
1062        assert_eq!(e.media[0].fallbacks.len(), MAX_FALLBACKS);
1063    }
1064
1065    #[test]
1066    fn a_link_ending_in_punctuation_still_names_its_event() {
1067        let nevent = Nip19Event::new(EventId::from_byte_array([0u8; 32])).to_bech32().unwrap();
1068        assert!(EmbedRef::from_url(&format!("https://njump.me/{nevent}!")).is_some());
1069        assert!(EmbedRef::from_url(&format!("https://njump.me/{nevent}'")).is_some());
1070    }
1071
1072    #[test]
1073    fn a_strangers_relay_must_be_public_and_encrypted() {
1074        let ok = |u: &str| dialable(&RelayUrl::parse(u).unwrap());
1075        assert!(ok("wss://relay.damus.io"));
1076        assert!(!ok("ws://relay.damus.io"), "plain text");
1077        assert!(!ok("wss://127.0.0.1:631"), "loopback");
1078        assert!(!ok("wss://192.168.1.1"), "LAN");
1079        assert!(!ok("wss://localhost"));
1080    }
1081
1082    fn post_of(text_len: usize) -> Embed {
1083        let (_, ev) = signed(KIND_POST, "hi", vec![]);
1084        let mut embed = to_embed(&ev, &[]).unwrap();
1085        embed.text = "x".repeat(text_len);
1086        embed
1087    }
1088
1089    #[test]
1090    fn the_cache_lets_its_oldest_cards_go_past_its_byte_budget() {
1091        let owner: Arc<Mutex<EmbedCache>> = Arc::default();
1092        let big = CACHE_BYTES / 4;
1093        for k in 0..6 {
1094            cache_store(&owner, &format!("k{k}"), &Ok(post_of(big)));
1095        }
1096        let c = owner.lock().unwrap();
1097        assert!(c.bytes <= CACHE_BYTES, "{} over {}", c.bytes, CACHE_BYTES);
1098        assert_eq!(c.bytes, c.entries.values().map(Cached::weight).sum::<usize>());
1099        assert!(!c.entries.contains_key("k0") && !c.entries.contains_key("k2"), "the oldest went");
1100        assert!(c.entries.contains_key("k3") && c.entries.contains_key("k5"));
1101        assert_eq!(c.order.front().map(|k| &**k), Some("k3"));
1102    }
1103
1104    #[test]
1105    fn a_card_past_the_whole_budget_is_still_kept_alone() {
1106        let owner: Arc<Mutex<EmbedCache>> = Arc::default();
1107        cache_store(&owner, "small", &Err("Not found on any relay".into()));
1108        cache_store(&owner, "huge", &Ok(post_of(CACHE_BYTES + 1)));
1109        let c = owner.lock().unwrap();
1110        assert_eq!(c.entries.len(), 1);
1111        assert!(matches!(c.entries.get("huge"), Some(Cached::Hit { .. })));
1112        drop(c);
1113        assert!(matches!(cache_lookup(&owner, "huge"), Lookup::Hit(Ok(e)) if e.text.len() == CACHE_BYTES + 1));
1114    }
1115
1116    #[test]
1117    fn storing_a_key_again_keeps_one_entry_and_makes_it_newest() {
1118        let owner: Arc<Mutex<EmbedCache>> = Arc::default();
1119        cache_store(&owner, "a", &Err("Not found on any relay".into()));
1120        cache_store(&owner, "b", &Ok(post_of(10)));
1121        cache_store(&owner, "a", &Ok(post_of(20)));
1122        let c = owner.lock().unwrap();
1123        assert_eq!(c.order.iter().map(|k| &**k).collect::<Vec<_>>(), ["b", "a"]);
1124        assert_eq!(c.bytes, c.entries.values().map(Cached::weight).sum::<usize>());
1125    }
1126
1127    #[test]
1128    fn an_abandoned_fetch_releases_its_key() {
1129        let owner: Arc<Mutex<EmbedCache>> = Arc::default();
1130        assert!(matches!(cache_lookup(&owner, "k"), Lookup::Fetch));
1131        assert!(matches!(cache_lookup(&owner, "k"), Lookup::Wait), "a second ask waits on the first");
1132        drop(InFlight { owner: owner.clone(), key: "k".into() });
1133        assert!(matches!(cache_lookup(&owner, "k"), Lookup::Fetch), "the dropped fetch no longer holds it");
1134    }
1135
1136    #[test]
1137    fn a_repost_carries_the_event_it_names() {
1138        let (author, post) = signed(KIND_POST, "the original", vec![]);
1139        let (_, repost) = signed(
1140            KIND_REPOST,
1141            &post.as_json(),
1142            vec![Tag::parse(["e".to_string(), post.id.to_hex(), "wss://r.example".to_string()]).unwrap(), Tag::public_key(author.public_key())],
1143        );
1144        let target = repost_target(&repost).unwrap();
1145        assert!(matches!(&target, EmbedRef::Event { id, relays, .. } if *id == post.id && relays.len() == 1));
1146        assert_eq!(reposted_inline(&repost, Some(&target)).map(|e| e.id), Some(post.id));
1147
1148        let (_, other) = signed(KIND_POST, "not what the tag names", vec![]);
1149        let (_, lying) = signed(KIND_REPOST, &other.as_json(), vec![Tag::parse(["e".to_string(), post.id.to_hex()]).unwrap()]);
1150        assert!(reposted_inline(&lying, repost_target(&lying).as_ref()).is_none(), "content must be the tagged event");
1151
1152        let mut forged: serde_json::Value = serde_json::from_str(&post.as_json()).unwrap();
1153        forged["content"] = "tampered".into();
1154        let (_, forged_repost) = signed(KIND_REPOST, &forged.to_string(), vec![]);
1155        assert!(reposted_inline(&forged_repost, None).is_none(), "an unsigned copy is never believed");
1156    }
1157
1158    #[test]
1159    fn a_generic_repost_of_an_article_names_its_coordinate() {
1160        let (keys, _) = signed(KIND_ARTICLE, "", vec![]);
1161        let a = format!("{KIND_ARTICLE}:{}:essay", keys.public_key().to_hex());
1162        let (_, repost) = signed(KIND_GENERIC_REPOST, "", vec![Tag::parse(["a".to_string(), a, "wss://r.example".to_string()]).unwrap()]);
1163        assert!(matches!(repost_target(&repost), Some(EmbedRef::Address { coordinate, .. }) if coordinate.identifier == "essay"));
1164    }
1165
1166    #[test]
1167    fn an_unsupported_kind_is_reported_not_shown() {
1168        let (_, ev) = signed(6, "", vec![]);
1169        assert!(to_embed(&ev, &[]).unwrap_err().contains("kind 6"));
1170    }
1171}