Skip to main content

vector_core/
emoji_packs.rs

1//! NIP-30 / NIP-51 custom emoji + pack support.
2//!
3//! Phase 1 (read path):
4//! - Parse kind 30030 emoji sets and kind 10030 user emoji lists.
5//! - Fetch a user's subscribed packs from relays, persist them locally.
6//! - Expose a flat `EmojiPack` API to the frontend for picker rendering.
7//!
8//! Spec: <https://nips.nostr.com/30>, <https://nips.nostr.com/51>.
9//!
10//! Metadata interop: NIP-51 standardises `title` / `image` / `description`
11//! tags on kind 30030. Ditto and Nostria emit non-standard `name` /
12//! `picture` / `about` instead. Vector reads both with spec preference
13//! and (eventually) dual-writes both on publish.
14
15use std::collections::HashMap;
16
17use nostr_sdk::prelude::*;
18use serde::{Deserialize, Serialize};
19
20use crate::state::nostr_client;
21use crate::ClientRelayExt;
22
23/// NIP-51 kind for a user's "Emojis" list (replaceable, per-user).
24const KIND_EMOJI_LIST: u16 = 10030;
25
26/// NIP-51 kind for an "Emoji set" (parameterised replaceable).
27pub const KIND_EMOJI_SET: u16 = 30030;
28
29/// Wire-form prefix for kind 30030 `a` tags / DB primary keys.
30/// `format!("{}:…", KIND_EMOJI_SET)` is the obvious construction but
31/// `format!` is heavy (Display dispatch, intermediate capacity probing);
32/// for an addr that's read on every pack save / load / subscribe, hold
33/// it as a literal and assert at compile time that the kind matches.
34const KIND_EMOJI_SET_ADDR_PREFIX: &str = "30030:";
35const _: () = assert!(
36    KIND_EMOJI_SET == 30030,
37    "KIND_EMOJI_SET_ADDR_PREFIX literal must match KIND_EMOJI_SET"
38);
39
40/// Build a canonical `kind:pubkey:identifier` addr string with a single
41/// allocation sized exactly to the result. ~3× faster than the
42/// equivalent `format!` in microbenchmarks and has no fmt machinery on
43/// the hot path (load, save, subscribe all hit this).
44fn build_pack_addr(pubkey: &str, identifier: &str) -> String {
45    let mut s = String::with_capacity(
46        KIND_EMOJI_SET_ADDR_PREFIX.len() + pubkey.len() + 1 + identifier.len(),
47    );
48    s.push_str(KIND_EMOJI_SET_ADDR_PREFIX);
49    s.push_str(pubkey);
50    s.push(':');
51    s.push_str(identifier);
52    s
53}
54
55/// Network fetch budget for resolving the user's pack list + each pack.
56/// 8s was too tight in practice — a single slow relay handshake would
57/// flash "Pack Unavailable" at the user when the event was still on its
58/// way. 20s comfortably covers a cold Tor circuit / sleepy relay
59/// without making a genuinely-missing pack feel sluggish.
60const FETCH_TIMEOUT_SECS: u64 = 20;
61
62/// Per-effective-tier caps (index = `badges::effective_tier()`, 0-3). These gate
63/// only the in-app add action; packs subscribed via other clients always load in
64/// full and are never sliced. Tier 3 (full premium) is effectively unlimited for
65/// the count cap.
66const EQUIPPED_PACKS_BY_TIER: [usize; 4] = [3, 6, 9, usize::MAX];
67/// Per-pack emoji cap by tier (authoring + display). Full premium tops out at 90.
68const EMOJIS_PER_PACK_BY_TIER: [usize; 4] = [30, 30, 60, 90];
69
70/// Base (free, tier-0) equipped-pack cap. Named const for the frontend mirror.
71pub const MAX_EQUIPPED_PACKS: usize = EQUIPPED_PACKS_BY_TIER[0];
72
73/// Base (free, tier-0) emojis-per-own-pack cap. Shared packs received from the
74/// network may exceed this — only what *we* author is capped, and the frontend
75/// truncates oversized received packs at display time.
76pub const MAX_EMOJIS_PER_PACK: usize = EMOJIS_PER_PACK_BY_TIER[0];
77
78/// In-app equipped-pack cap for the current account, scaled by effective tier.
79/// Gate the in-app subscribe/create action on this — never the load/display path.
80pub fn effective_max_equipped_packs() -> usize {
81    if crate::badges::is_bot() { return usize::MAX; }
82    EQUIPPED_PACKS_BY_TIER[crate::badges::effective_tier() as usize]
83}
84
85/// Per-pack emoji authoring cap for the current account, scaled by effective tier.
86pub fn effective_max_emojis_per_pack() -> usize {
87    if crate::badges::is_bot() { return usize::MAX; }
88    EMOJIS_PER_PACK_BY_TIER[crate::badges::effective_tier() as usize]
89}
90
91// ============================================================================
92// Types
93// ============================================================================
94
95#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
96pub struct PackEmoji {
97    pub shortcode: String,
98    pub url: String,
99    pub sha256: Option<String>,
100}
101
102#[derive(Serialize, Deserialize, Clone, Debug)]
103pub struct EmojiPack {
104    /// Canonical NIP-19 `naddr1...` for this pack (no relay hints).
105    /// Mirrors the `profile.id == npub` pattern — frontend / IPC code
106    /// only ever speaks bech32. Internal storage + kind 10030 `a` tags
107    /// still use the raw `kind:pubkey:identifier` coordinate (DB
108    /// columns named `addr`, helpers exposed via `parse_pack_address`
109    /// / `naddr_from_addr`).
110    pub id: String,
111    /// Author of the kind 30030 event (hex).
112    pub pubkey: String,
113    /// `d` tag identifier.
114    pub identifier: String,
115    /// NIP-51 `title` with Ditto `name` fallback.
116    pub title: String,
117    /// NIP-51 `image` with Ditto `picture` fallback. Empty if neither.
118    pub image_url: String,
119    /// NIP-51 `description` with Ditto `about` fallback.
120    pub description: String,
121    pub emojis: Vec<PackEmoji>,
122    /// Owned packs surface a different UI affordance (edit pencil).
123    pub is_own: bool,
124    /// Event `created_at` — fed back into the relay filter so re-fetches
125    /// don't process older events on top of a newer cached pack.
126    pub updated_at: u64,
127    /// Health verdict: [`PACK_STATUS_ACTIVE`] / [`PACK_STATUS_REVOKED`] /
128    /// [`PACK_STATUS_MISSING`]. Dead packs stay in the picker payload so the
129    /// UI can render the section greyed with an explanation + remove button,
130    /// but their emojis are excluded from sending and suggestions.
131    pub status: u8,
132}
133
134/// Pack is live on its relays (or hasn't been judged otherwise).
135pub const PACK_STATUS_ACTIVE: u8 = 0;
136/// A deterministic tombstone was seen: the author replaced the pack with an
137/// EMPTY kind 30030 (Vector's own delete flow) or published a kind-5
138/// deletion naming it.
139pub const PACK_STATUS_REVOKED: u8 = 1;
140/// No tombstone, but the pack has been absent across enough clean sweeps of
141/// live relays (see the gauntlet in [`apply_pack_health`]) that it's
142/// considered gone.
143pub const PACK_STATUS_MISSING: u8 = 2;
144
145/// What one refresh sweep learned about a subscribed pack.
146#[derive(Debug, Clone, PartialEq)]
147pub enum PackFetchOutcome {
148    /// A live (non-empty) pack event resolved.
149    Found,
150    /// Deterministic deletion evidence — no gauntlet needed.
151    Tombstoned,
152    /// Enough live relays answered EOSE and none had the pack.
153    CleanMiss,
154    /// Not enough connectivity to judge; counters must not move.
155    Unreachable,
156}
157
158/// Absence promotes to `missing` only after this many rate-limited clean
159/// misses AND [`PACK_MISS_PROMOTE_SECS`] since the first — strict enough
160/// that a weekend relay outage never flags a healthy pack.
161const PACK_MISS_PROMOTE_COUNT: i64 = 3;
162const PACK_MISS_PROMOTE_SECS: i64 = 48 * 3600;
163/// A clean miss moves the counter at most once per this window, so rapid
164/// app restarts can't fabricate the miss count.
165const PACK_MISS_RATELIMIT_SECS: i64 = 12 * 3600;
166
167impl EmojiPack {
168    /// Raw NIP-51 coordinate (`kind:pubkey:identifier`). Used for kind
169    /// 10030 `a` tags + DB keying. One pre-sized allocation, no fmt
170    /// machinery (see `build_pack_addr`).
171    pub fn addr(&self) -> String {
172        build_pack_addr(&self.pubkey, &self.identifier)
173    }
174}
175
176// ============================================================================
177// Parsing
178// ============================================================================
179
180/// Validate a NIP-30 shortcode: `[a-zA-Z0-9_-]+`, non-empty. Anything
181/// else would render brokenly against the `:[\w-]+:` regex our renderer
182/// uses, so we drop invalid items at parse time.
183fn is_valid_shortcode(s: &str) -> bool {
184    !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
185}
186
187/// Active theme pack's `(shortcode, url)` pairs, registered from the frontend.
188/// The theme pack is shown in the picker without being a real subscription, so
189/// its shortcodes never land in `emoji_pack_items`; this lets the send resolver
190/// still attach NIP-30 tags for them. Replaced wholesale on theme change.
191/// Per-account: leaving the prior account's set active would tag the next
192/// account's outbound messages with A's shortcodes, leaking A's pack URLs.
193struct ThemeEmojiTags;
194
195fn theme_emoji_tags() -> std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>> {
196    crate::db::current_session().scoped::<ThemeEmojiTags, _>()
197}
198
199/// Every shortcode that renders as an image for this account. A `:code:` outside
200/// this set reaches the reader as literal text, so text analysis must keep it.
201pub fn known_shortcodes() -> std::collections::HashSet<String> {
202    let mut out: std::collections::HashSet<String> = std::collections::HashSet::new();
203    if let Ok(conn) = crate::db::get_db_connection_guard_static() {
204        if let Ok(mut stmt) = conn.prepare("SELECT DISTINCT shortcode FROM emoji_pack_items") {
205            if let Ok(rows) = stmt.query_map([], |row| row.get::<_, String>(0)) {
206                out.extend(rows.flatten());
207            }
208        }
209    }
210    if let Ok(theme) = theme_emoji_tags().lock() {
211        out.extend(theme.iter().map(|(code, _)| code.clone()));
212    }
213    out
214}
215
216/// Register (or clear, with an empty vec) the active theme pack's emoji so the
217/// send resolver can tag them even though they aren't a DB subscription.
218pub fn set_theme_emoji_tags(tags: Vec<(String, String)>) {
219    if let Ok(mut g) = theme_emoji_tags().lock() {
220        *g = tags;
221    }
222}
223
224/// Per-pack emoji cap mirrored from the frontend's `MAX_DISPLAY_EMOJIS_PER_PACK`
225/// (`applyBadgeLimits`). The send resolver caps each subscribed pack to this
226/// many items so its `~N` disambiguation of duplicate shortcodes matches exactly
227/// what the picker displayed — otherwise a large pack's hidden tail (the picker
228/// only shows the first N) would enter the candidate set and shift the indices.
229pub fn effective_display_cap() -> usize {
230    if crate::badges::is_bot() { return usize::MAX; }
231    EMOJIS_PER_PACK_BY_TIER[crate::badges::effective_tier() as usize]
232}
233
234/// Resolve a (possibly `~N`-suffixed) shortcode token against the candidate map.
235/// Plain `base` → the first candidate; `base~N` → the N-th (1-based) candidate
236/// in the same URL-sorted order the picker assigns. A `~N` whose base is unknown
237/// or whose index is out of range yields nothing (renders as literal text).
238fn resolve_emoji_token(by_code: &HashMap<String, Vec<String>>, token: &str) -> Option<String> {
239    if let Some((base, suffix)) = token.rsplit_once('~') {
240        let n: usize = suffix.parse().ok()?;
241        if n == 0 { return None; }
242        return by_code.get(base).and_then(|urls| urls.get(n - 1).cloned());
243    }
244    by_code.get(token).and_then(|urls| urls.first().cloned())
245}
246
247/// Every `(pack addr, shortcode, url)` a send may tag, in picker order: subscribed
248/// live packs (each capped to what the picker displays), then the active theme pack.
249fn sendable_candidates() -> Vec<(Option<String>, String, String)> {
250    let cap = effective_display_cap();
251    let mut out = Vec::new();
252
253    // Soft-removed own packs and dead (revoked / missing) packs are retired from
254    // sending, matching `load_all_packs`.
255    if let Ok(conn) = crate::db::get_db_connection_guard_static() {
256        if let Ok(mut stmt) = conn.prepare(
257            "SELECT p.addr, i.shortcode, i.url
258             FROM emoji_pack_items i
259             INNER JOIN emoji_packs p ON p.addr = i.pack_addr
260             INNER JOIN emoji_pack_subscriptions s ON s.addr = p.addr
261             WHERE p.status = 0
262             ORDER BY p.is_own DESC, p.updated_at DESC, i.position ASC"
263        ) {
264            if let Ok(rows) = stmt.query_map([], |row| {
265                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?))
266            }) {
267                // A hidden tail past the display cap would shift the `~N` indices.
268                let mut per_pack: HashMap<String, usize> = HashMap::new();
269                for (addr, code, url) in rows.flatten() {
270                    let n = per_pack.entry(addr.clone()).or_insert(0);
271                    if *n >= cap { continue; }
272                    *n += 1;
273                    out.push((Some(addr), code, url));
274                }
275            }
276        }
277    }
278
279    // The theme pack shows in the picker without a subscription, registered via
280    // `set_theme_emoji_tags` (already capped there).
281    if let Ok(theme) = theme_emoji_tags().lock() {
282        out.extend(theme.iter().map(|(code, url)| (None, code.clone(), url.clone())));
283    }
284    out
285}
286
287/// Base shortcode -> its distinct images, URL-sorted: the order the picker's
288/// `_assignEmojiDisambig` numbers `~N` by, so two packs sharing an image collapse.
289fn candidates_by_code(candidates: &[(Option<String>, String, String)]) -> HashMap<String, Vec<String>> {
290    let mut by_code: HashMap<String, Vec<String>> = HashMap::new();
291    for (_, code, url) in candidates {
292        by_code.entry(code.clone()).or_default().push(url.clone());
293    }
294    for urls in by_code.values_mut() {
295        urls.sort();
296        urls.dedup();
297    }
298    by_code
299}
300
301/// One custom emoji this account can send: type `:code:` and the send tags it.
302#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
303pub struct SendableEmoji {
304    /// The shortcode to write between colons, `~N`-suffixed when packs collide.
305    pub code: String,
306    pub url: String,
307    /// The pack's `naddr1...`, or `None` for the active theme pack.
308    pub pack: Option<String>,
309}
310
311/// Every custom emoji a send resolves, named exactly as the picker names them:
312/// a shortcode two packs use with different images becomes `code~1`, `code~2`.
313pub fn sendable_emojis() -> Vec<SendableEmoji> {
314    let candidates = sendable_candidates();
315    let by_code = candidates_by_code(&candidates);
316    let mut seen = std::collections::HashSet::new();
317    let mut out = Vec::new();
318    for (addr, shortcode, url) in candidates {
319        if !seen.insert((shortcode.clone(), url.clone())) { continue; }
320        let urls = &by_code[&shortcode];
321        let code = match urls.iter().position(|u| *u == url) {
322            Some(i) if urls.len() > 1 => format!("{shortcode}~{}", i + 1),
323            _ => shortcode,
324        };
325        out.push(SendableEmoji { code, url, pack: addr.and_then(|a| naddr_from_addr(&a).ok()) });
326    }
327    out
328}
329
330/// Scan `content` for `:shortcode:` patterns and resolve them against the user's
331/// currently-subscribed packs (plus the active theme pack). Returns deduped emoji
332/// tags in first-match order. Used by the send pipeline to attach NIP-30 emoji
333/// tags so recipients without the pack subscribed still render.
334///
335/// Duplicate shortcodes across packs are disambiguated `base~N` (1-based) by a
336/// lexicographic URL sort — the SAME ordering the frontend's `_assignEmojiDisambig`
337/// uses — so a `:love~2:` the picker inserted resolves here to the same image.
338pub fn resolve_outbound_emoji_tags(content: &str) -> Vec<crate::types::EmojiTag> {
339    if content.is_empty() || !content.contains(':') {
340        return Vec::new();
341    }
342    let by_code = candidates_by_code(&sendable_candidates());
343    if by_code.is_empty() {
344        return Vec::new();
345    }
346
347    let mut out: Vec<crate::types::EmojiTag> = Vec::new();
348    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
349    let bytes = content.as_bytes();
350    let mut i = 0;
351    while i < bytes.len() {
352        if bytes[i] == b':' {
353            let start = i + 1;
354            let mut j = start;
355            while j < bytes.len() {
356                let c = bytes[j];
357                // `~` is the reserved disambiguation separator (`:love~2:`).
358                let ok = c.is_ascii_alphanumeric() || c == b'_' || c == b'-' || c == b'~';
359                if !ok { break; }
360                j += 1;
361            }
362            // A clock's `21:20:30` isn't a shortcode.
363            let clock = start >= 2 && bytes[start - 2].is_ascii_digit() && bytes[start..j].iter().all(u8::is_ascii_digit);
364            if clock {
365                i = j;
366                continue;
367            }
368            if j > start && j < bytes.len() && bytes[j] == b':' {
369                if let Ok(token) = std::str::from_utf8(&bytes[start..j]) {
370                    if !seen.contains(token) {
371                        if let Some(url) = resolve_emoji_token(&by_code, token) {
372                            out.push(crate::types::EmojiTag {
373                                shortcode: token.to_string(),
374                                url,
375                            });
376                            seen.insert(token.to_string());
377                        }
378                    }
379                }
380                i = j + 1;
381                continue;
382            }
383        }
384        i += 1;
385    }
386    out
387}
388
389/// Fetch the first single-string tag whose key matches any of `keys`,
390/// in order. Used for the dual NIP-51 / Ditto metadata lookup.
391fn first_tag(tags: &Tags, keys: &[&str]) -> Option<String> {
392    for key in keys {
393        for tag in tags.iter() {
394            let parts: Vec<&str> = tag.as_slice().iter().map(|s| s.as_str()).collect();
395            if parts.len() >= 2 && parts[0] == *key {
396                return Some(parts[1].to_string());
397            }
398        }
399    }
400    None
401}
402
403/// Parse a kind 30030 event into an EmojiPack. Returns `None` if the
404/// event is missing a `d` tag or has zero valid emoji rows.
405pub fn parse_pack_from_event(event: &Event, my_pubkey_hex: Option<&str>) -> Option<EmojiPack> {
406    if event.kind.as_u16() != KIND_EMOJI_SET {
407        return None;
408    }
409
410    let identifier = first_tag(&event.tags, &["d"])?;
411    let pubkey = event.pubkey.to_hex();
412    let addr = build_pack_addr(&pubkey, &identifier);
413    let id = match naddr_from_addr(&addr) {
414        Ok(s) => s,
415        Err(e) => {
416            crate::log_warn!(
417                "[EmojiPacks] naddr encode failed for `{}`: {} — pack dropped",
418                addr, e,
419            );
420            return None;
421        }
422    };
423
424    let title = first_tag(&event.tags, &["title", "name"]).unwrap_or_default();
425    let image_url = first_tag(&event.tags, &["image", "picture"]).unwrap_or_default();
426    let description = first_tag(&event.tags, &["description", "about"]).unwrap_or_default();
427
428    let mut emojis = Vec::new();
429    let mut seen = std::collections::HashSet::new();
430    for tag in event.tags.iter() {
431        let parts: Vec<&str> = tag.as_slice().iter().map(|s| s.as_str()).collect();
432        if parts.len() >= 3 && parts[0] == "emoji" {
433            let shortcode = parts[1];
434            if !is_valid_shortcode(shortcode) { continue; }
435            // Trim URL whitespace: some packs in the wild carry a stray leading/trailing space
436            // (e.g. "…/x.gif "), which the WebView strips for a raw <img> but the cache fetch does
437            // NOT — leaving the emoji blank everywhere it's served from cache. Skip if empty after.
438            let url = parts[2].trim();
439            if url.is_empty() { continue; }
440            if !seen.insert(shortcode.to_string()) { continue; }
441            emojis.push(PackEmoji {
442                shortcode: shortcode.to_string(),
443                url: url.to_string(),
444                sha256: None,
445            });
446        }
447    }
448
449    if emojis.is_empty() {
450        return None;
451    }
452
453    let is_own = my_pubkey_hex.is_some_and(|me| me == pubkey);
454
455    Some(EmojiPack {
456        id,
457        pubkey,
458        identifier,
459        title,
460        image_url,
461        description,
462        emojis,
463        is_own,
464        updated_at: event.created_at.as_secs(),
465        status: PACK_STATUS_ACTIVE,
466    })
467}
468
469/// Parsed NIP-19 / NIP-51 set address.
470#[derive(Debug, Clone, PartialEq)]
471pub struct PackAddress {
472    pub kind: u16,
473    pub pubkey: PublicKey,
474    pub identifier: String,
475}
476
477/// Parse a `kind:pubkey-hex:d-tag` address as found in kind 10030 `a` tags.
478/// Rejects anything that isn't kind 30030 — we don't want a malformed list
479/// pulling in random replaceable events.
480pub fn parse_pack_address(addr: &str) -> Result<PackAddress, String> {
481    let mut parts = addr.splitn(3, ':');
482    let kind_str = parts.next().ok_or_else(|| "missing kind".to_string())?;
483    let pubkey_str = parts.next().ok_or_else(|| "missing pubkey".to_string())?;
484    let identifier = parts.next().ok_or_else(|| "missing identifier".to_string())?;
485
486    let kind: u16 = kind_str.parse()
487        .map_err(|_| format!("invalid kind: {}", kind_str))?;
488    if kind != KIND_EMOJI_SET {
489        return Err(format!("expected kind {}, got {}", KIND_EMOJI_SET, kind));
490    }
491    let pubkey = PublicKey::from_hex(pubkey_str)
492        .map_err(|e| format!("invalid pubkey: {}", e))?;
493
494    Ok(PackAddress { kind, pubkey, identifier: identifier.to_string() })
495}
496
497impl PackAddress {
498    /// Serialise back to the wire form used in kind 10030 `a` tags.
499    /// `parse_pack_address` is the only constructor and it rejects any
500    /// kind ≠ KIND_EMOJI_SET, so we can route through the optimised
501    /// `build_pack_addr` and skip `format!` entirely.
502    pub fn to_addr_string(&self) -> String {
503        debug_assert_eq!(self.kind, KIND_EMOJI_SET,
504            "PackAddress kind mismatch — was it constructed bypassing parse_pack_address?");
505        build_pack_addr(&self.pubkey.to_hex(), &self.identifier)
506    }
507}
508
509/// Mint the SHAREABLE form of a pack naddr: the same coordinate plus up to 3
510/// relay hints naming the pack's own home. A pack lives on its AUTHOR's write
511/// relays (NIP-65), never the sharer's — a subscribed pack must not get the
512/// sharer's personal set stamped onto it. An author with no published kind
513/// 10002 falls back to this client's pool, which is where an own pack was
514/// published and where a subscribed one was actually seen.
515pub async fn share_naddr(naddr: &str) -> Result<String, String> {
516    let coordinate = match Nip19::from_bech32(naddr) {
517        Ok(Nip19::Coordinate(c)) => c.coordinate,
518        _ => return Err("not a pack naddr".to_string()),
519    };
520    if coordinate.kind != Kind::Custom(KIND_EMOJI_SET) {
521        return Err("not an emoji pack coordinate".to_string());
522    }
523    let client = nostr_client().ok_or_else(|| "Nostr client not initialized".to_string())?;
524    let mut relays = fetch_author_write_relays(&client, coordinate.public_key).await;
525    if relays.is_empty() {
526        // Write-capable pool relays only: GOSSIP-only community relays are
527        // foreign infrastructure a pack never publishes to.
528        relays = client
529            .relays()
530            .await
531            .into_iter()
532            .filter(|(_, r)| r.capabilities().load().can_write())
533            .map(|(url, _)| url)
534            .collect();
535    }
536    relays.truncate(3);
537    if relays.is_empty() {
538        return Ok(naddr.to_string());
539    }
540    Nip19::Coordinate(Nip19Coordinate { coordinate, relays })
541        .to_bech32()
542        .map_err(|e| format!("encode naddr: {}", e))
543}
544
545/// Encode a pack `addr` (`kind:pubkey:identifier`) into a NIP-19
546/// `naddr1...` bech32 string. Used by the share-pack flow to put a
547/// portable reference on the user's clipboard.
548pub fn naddr_from_addr(addr: &str) -> Result<String, String> {
549    let parsed = parse_pack_address(addr)?;
550    let coord = nostr_sdk::prelude::nip01::Coordinate {
551        kind: Kind::Custom(parsed.kind),
552        public_key: parsed.pubkey,
553        identifier: parsed.identifier,
554    };
555    let n19 = nostr_sdk::prelude::nip19::Nip19Coordinate {
556        coordinate: coord,
557        relays: Vec::new(),
558    };
559    nostr_sdk::prelude::nip19::Nip19::Coordinate(n19)
560        .to_bech32()
561        .map_err(|e| format!("encode naddr: {}", e))
562}
563
564/// Decode a NIP-19 `naddr1...` into a `PackAddress`. Rejects coordinates
565/// that don't point at kind 30030 so a malformed paste can't pull in
566/// an unrelated replaceable event.
567pub fn parse_naddr(naddr: &str) -> Result<PackAddress, String> {
568    let trimmed = naddr.trim().trim_start_matches("nostr:");
569    let parsed = nostr_sdk::prelude::nip19::Nip19::from_bech32(trimmed)
570        .map_err(|e| format!("invalid naddr: {}", e))?;
571    let coord = match parsed {
572        nostr_sdk::prelude::nip19::Nip19::Coordinate(c) => c,
573        _ => return Err("naddr expected (Nip19 was not a coordinate)".to_string()),
574    };
575    let kind = coord.kind.as_u16();
576    if kind != KIND_EMOJI_SET {
577        return Err(format!(
578            "expected kind {} (emoji set), got {}",
579            KIND_EMOJI_SET, kind,
580        ));
581    }
582    Ok(PackAddress {
583        kind,
584        pubkey: coord.public_key,
585        identifier: coord.identifier.clone(),
586    })
587}
588
589/// One-element sentinel tuple (`["theme_slot"]`) marking WHERE the theme pack
590/// renders in the equipped-pack order. Carried inside the kind-10030 encrypted
591/// content so the slot position syncs across devices. Ignored by
592/// `parse_inner_tag_list` (keeps only `a` tags) and by every other Nostr client
593/// (content is NIP-44 self-encrypted), so it degrades gracefully.
594const THEME_SLOT_TOKEN: &str = "theme_slot";
595
596/// Parse a NIP-51 inner tag list (the JSON array of tag tuples that
597/// lives inside the NIP-44-encrypted `content` of an encrypted-items
598/// list). Pulls out `a` tags as pack addresses; malformed inner
599/// entries are dropped silently so one bad row doesn't nuke the list.
600fn parse_inner_tag_list(plaintext: &str) -> Vec<PackAddress> {
601    let inner: Vec<Vec<String>> = match serde_json::from_str(plaintext) {
602        Ok(v) => v,
603        Err(e) => {
604            crate::log_warn!("[EmojiPacks] emoji list JSON parse failed: {}", e);
605            return Vec::new();
606        }
607    };
608    inner.into_iter()
609        .filter_map(|tup| {
610            if tup.len() >= 2 && tup[0] == "a" {
611                parse_pack_address(&tup[1]).ok()
612            } else {
613                None
614            }
615        })
616        .collect()
617}
618
619/// Like [`parse_inner_tag_list`], but preserves the raw addr order AND
620/// extracts the theme-slot anchor. The anchor is the raw addr of the pack the
621/// `["theme_slot"]` marker sits immediately after; `""` means the marker is at
622/// the top (before every pack). Returns `None` for the anchor when no marker
623/// tuple is present at all (an old-format list predating the theme-slot
624/// feature). Malformed `a` tags are dropped so one bad row can't nuke the list.
625fn parse_inner_tag_list_with_anchor(plaintext: &str) -> (Vec<String>, Option<String>) {
626    let inner: Vec<Vec<String>> = match serde_json::from_str(plaintext) {
627        Ok(v) => v,
628        Err(e) => {
629            crate::log_warn!("[EmojiPacks] emoji list JSON parse failed: {}", e);
630            return (Vec::new(), None);
631        }
632    };
633    let mut addrs: Vec<String> = Vec::new();
634    let mut anchor: Option<String> = None;
635    for tup in inner {
636        if tup.len() >= 2 && tup[0] == "a" {
637            // Normalise through parse → to_addr_string so the stored anchor
638            // matches what load_subscriptions/save_subscriptions round-trip.
639            if let Ok(pa) = parse_pack_address(&tup[1]) {
640                addrs.push(pa.to_addr_string());
641            }
642        } else if anchor.is_none() && tup.first().map(String::as_str) == Some(THEME_SLOT_TOKEN) {
643            // Anchor = last real addr before the marker, or "" (top) if the
644            // marker precedes every pack. First marker wins on a malformed list.
645            anchor = Some(addrs.last().cloned().unwrap_or_default());
646        }
647    }
648    (addrs, anchor)
649}
650
651/// Decrypt + parse a kind 10030 event's encrypted subscription list.
652///
653/// Vector's emoji list is fully private by design — every `a` tag is
654/// carried inside the NIP-44-self-encrypted `content`, never in the
655/// public `tags` field. A list event with empty / undecryptable /
656/// malformed content is treated as "no subscriptions" rather than
657/// failing the whole refresh. Spec: NIP-51 "encrypted items" section.
658pub async fn decrypt_subscribed_addresses(
659    client: &Client,
660    my_pk: &PublicKey,
661    event: &Event,
662) -> Vec<PackAddress> {
663    match decrypt_emoji_list_plaintext(client, my_pk, event).await {
664        Some(plaintext) => parse_inner_tag_list(&plaintext),
665        None => Vec::new(),
666    }
667}
668
669/// NIP-44-self-decrypt a kind 10030 event's content. `None` = empty /
670/// undecryptable / no-signer (all treated as "no subscriptions").
671async fn decrypt_emoji_list_plaintext(
672    _client: &Client,
673    my_pk: &PublicKey,
674    event: &Event,
675) -> Option<String> {
676    if event.content.is_empty() {
677        return None;
678    }
679    let signer = match crate::signer::active_signer() {
680        Ok(s) => s,
681        Err(e) => {
682            crate::log_warn!("[EmojiPacks] signer unavailable for emoji list decrypt: {}", e);
683            return None;
684        }
685    };
686    match signer.nip44_decrypt_async(my_pk, &event.content).await {
687        Ok(p) => Some(p),
688        Err(e) => {
689            crate::log_warn!("[EmojiPacks] emoji list decrypt failed: {}", e);
690            None
691        }
692    }
693}
694
695// ============================================================================
696// DB persistence
697// ============================================================================
698
699pub fn save_pack(pack: &EmojiPack) -> Result<(), String> {
700    let mut conn = crate::db::get_write_connection_guard_static()?;
701    let tx = conn.transaction()
702        .map_err(|e| format!("Failed to start tx: {}", e))?;
703
704    let addr = pack.addr();
705    tx.execute(
706        "INSERT OR REPLACE INTO emoji_packs
707            (addr, pubkey, identifier, title, image_url, description, is_own, updated_at, raw_event)
708         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, '')",
709        rusqlite::params![
710            addr, pack.pubkey, pack.identifier,
711            pack.title, pack.image_url, pack.description,
712            pack.is_own as i32, pack.updated_at as i64,
713        ],
714    ).map_err(|e| format!("Failed to upsert pack: {}", e))?;
715
716    // Replace the item set wholesale — kind 30030 is a replaceable event,
717    // older shortcodes that disappeared from the new version must not
718    // linger in our local mirror.
719    tx.execute(
720        "DELETE FROM emoji_pack_items WHERE pack_addr = ?1",
721        rusqlite::params![addr],
722    ).map_err(|e| format!("Failed to clear pack items: {}", e))?;
723
724    for (pos, emoji) in pack.emojis.iter().enumerate() {
725        tx.execute(
726            "INSERT INTO emoji_pack_items (pack_addr, shortcode, url, sha256, position)
727             VALUES (?1, ?2, ?3, ?4, ?5)",
728            rusqlite::params![
729                addr, emoji.shortcode, emoji.url, emoji.sha256, pos as i64,
730            ],
731        ).map_err(|e| format!("Failed to insert pack item: {}", e))?;
732    }
733
734    tx.commit().map_err(|e| format!("Failed to commit pack: {}", e))?;
735    Ok(())
736}
737
738/// Apply one refresh sweep's verdict to a pack's persisted health. Returns
739/// `true` when the pack's STATUS changed (caller emits a UI refresh).
740///
741/// Rules:
742/// - `Found` resets everything to active — self-healing from any state, even
743///   revoked (the author republished, or a relay restored from backup).
744/// - `Tombstoned` is deterministic: revoked immediately, no gauntlet.
745/// - `CleanMiss` runs the gauntlet: the counter moves at most once per
746///   `PACK_MISS_RATELIMIT_SECS`, and promotion to missing requires BOTH
747///   `PACK_MISS_PROMOTE_COUNT` misses and `PACK_MISS_PROMOTE_SECS` since
748///   the first — so neither rapid restarts nor one long offline stretch can
749///   false-positive. A revoked pack ignores misses (stronger evidence holds).
750/// - `Unreachable` never moves anything in either direction.
751///
752/// On a transition INTO revoked/missing, the pack's emojis are purged from
753/// the frequently-used engine so dead emojis stop being suggested.
754pub fn apply_pack_health(addr: &str, outcome: &PackFetchOutcome, now: i64) -> Result<bool, String> {
755    use rusqlite::OptionalExtension;
756    if matches!(outcome, PackFetchOutcome::Unreachable) {
757        return Ok(false);
758    }
759    // IMMEDIATE transaction: concurrent sweeps (boot trigger + panel refresh)
760    // each get their own pooled connection, so an unserialized read-modify-write
761    // could let a stale CleanMiss overwrite a just-written tombstone.
762    let mut conn = crate::db::get_write_connection_guard_static()?;
763    let tx = conn
764        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
765        .map_err(|e| format!("begin pack health tx: {}", e))?;
766
767    let row = tx
768        .query_row(
769            "SELECT status, miss_count, first_missed_at, last_miss_counted_at
770             FROM emoji_packs WHERE addr = ?1",
771            rusqlite::params![addr],
772            |r| {
773                Ok((
774                    r.get::<_, i64>(0)?,
775                    r.get::<_, i64>(1)?,
776                    r.get::<_, i64>(2)?,
777                    r.get::<_, i64>(3)?,
778                ))
779            },
780        )
781        .optional()
782        .map_err(|e| format!("read pack health: {}", e))?;
783    let Some((status, miss_count, first_missed_at, last_miss_counted_at)) = row else {
784        return Ok(false);
785    };
786
787    let (new_status, new_miss, new_first, new_last) = match outcome {
788        PackFetchOutcome::Found => (PACK_STATUS_ACTIVE as i64, 0, 0, 0),
789        PackFetchOutcome::Tombstoned => (PACK_STATUS_REVOKED as i64, 0, 0, 0),
790        PackFetchOutcome::CleanMiss => {
791            if status == PACK_STATUS_REVOKED as i64 || now - last_miss_counted_at < PACK_MISS_RATELIMIT_SECS {
792                (status, miss_count, first_missed_at, last_miss_counted_at)
793            } else {
794                let first = if miss_count == 0 { now } else { first_missed_at };
795                let count = miss_count + 1;
796                let promoted = count >= PACK_MISS_PROMOTE_COUNT
797                    && now - first >= PACK_MISS_PROMOTE_SECS;
798                (
799                    if promoted { PACK_STATUS_MISSING as i64 } else { status },
800                    count,
801                    first,
802                    now,
803                )
804            }
805        }
806        PackFetchOutcome::Unreachable => unreachable!(),
807    };
808
809    let changed = new_status != status;
810    tx.execute(
811        "UPDATE emoji_packs SET status = ?2, miss_count = ?3, first_missed_at = ?4,
812             last_miss_counted_at = ?5,
813             status_changed_at = CASE WHEN status != ?2 THEN ?6 ELSE status_changed_at END
814         WHERE addr = ?1",
815        rusqlite::params![addr, new_status, new_miss, new_first, new_last, now],
816    )
817    .map_err(|e| format!("write pack health: {}", e))?;
818
819    // Dead pack: retire its emojis from the frequently-used engine (kind 1 =
820    // custom emoji rows, matched by image URL — shortcodes collide across packs).
821    if changed && new_status != PACK_STATUS_ACTIVE as i64 {
822        tx.execute(
823            "DELETE FROM emoji_usage WHERE kind = 1 AND url IN
824                 (SELECT url FROM emoji_pack_items WHERE pack_addr = ?1)",
825            rusqlite::params![addr],
826        )
827        .map_err(|e| format!("purge dead pack usage: {}", e))?;
828    }
829
830    tx.commit().map_err(|e| format!("commit pack health: {}", e))?;
831    Ok(changed)
832}
833
834pub fn save_subscriptions(addrs: &[String]) -> Result<(), String> {
835    let mut conn = crate::db::get_write_connection_guard_static()?;
836    let tx = conn.transaction()
837        .map_err(|e| format!("Failed to start tx: {}", e))?;
838
839    tx.execute("DELETE FROM emoji_pack_subscriptions", [])
840        .map_err(|e| format!("Failed to clear subscriptions: {}", e))?;
841
842    let now = crate::clock::now_secs() as i64;
843    // `position` (the slice index) is the authoritative display order — the
844    // DELETE-all-reinsert stamps every row with the same `now`, so ordering
845    // by `subscribed_at` alone would be unstable.
846    for (pos, addr) in addrs.iter().enumerate() {
847        tx.execute(
848            "INSERT OR REPLACE INTO emoji_pack_subscriptions (addr, subscribed_at, position)
849             VALUES (?1, ?2, ?3)",
850            rusqlite::params![addr, now, pos as i64],
851        ).map_err(|e| format!("Failed to insert subscription: {}", e))?;
852    }
853
854    tx.commit().map_err(|e| format!("Failed to commit subscriptions: {}", e))?;
855    Ok(())
856}
857
858pub fn load_subscriptions() -> Result<Vec<String>, String> {
859    let conn = crate::db::get_db_connection_guard_static()?;
860    let mut stmt = conn.prepare("SELECT addr FROM emoji_pack_subscriptions ORDER BY position ASC, subscribed_at ASC")
861        .map_err(|e| format!("prepare: {}", e))?;
862    let rows = stmt.query_map([], |row| row.get::<_, String>(0))
863        .map_err(|e| format!("query: {}", e))?;
864    let mut out = Vec::new();
865    for r in rows {
866        out.push(r.map_err(|e| format!("row: {}", e))?);
867    }
868    Ok(out)
869}
870
871/// Load a single cached pack by its raw `kind:pubkey:identifier` addr,
872/// regardless of subscription status. Used by the theme-pack path: a theme
873/// pack is persisted via `save_pack` (so it loads instantly across sessions)
874/// but never gets a subscription row, so `load_all_packs` rightly hides it.
875pub fn load_cached_pack(addr: &str) -> Result<Option<EmojiPack>, String> {
876    let conn = crate::db::get_db_connection_guard_static()?;
877
878    let mut pack = match conn.query_row(
879        "SELECT pubkey, identifier, title, image_url, description, is_own, updated_at, status
880         FROM emoji_packs WHERE addr = ?1",
881        rusqlite::params![addr],
882        |row| {
883            Ok(EmojiPack {
884                id: naddr_from_addr(addr).unwrap_or_else(|_| addr.to_string()),
885                pubkey: row.get(0)?,
886                identifier: row.get(1)?,
887                title: row.get(2)?,
888                image_url: row.get(3)?,
889                description: row.get(4)?,
890                is_own: row.get::<_, i32>(5)? != 0,
891                updated_at: row.get::<_, i64>(6)? as u64,
892                emojis: Vec::new(),
893                status: row.get::<_, i64>(7)? as u8,
894            })
895        },
896    ) {
897        Ok(p) => p,
898        Err(rusqlite::Error::QueryReturnedNoRows) => return Ok(None),
899        Err(e) => return Err(format!("query cached pack: {}", e)),
900    };
901
902    let mut stmt = conn.prepare(
903        "SELECT shortcode, url, sha256 FROM emoji_pack_items
904         WHERE pack_addr = ?1 ORDER BY position ASC"
905    ).map_err(|e| format!("prepare items: {}", e))?;
906    let rows = stmt.query_map(rusqlite::params![addr], |row| {
907        Ok(PackEmoji {
908            shortcode: row.get(0)?,
909            url: row.get(1)?,
910            sha256: row.get(2)?,
911        })
912    }).map_err(|e| format!("query items: {}", e))?;
913    for r in rows {
914        pack.emojis.push(r.map_err(|e| format!("row item: {}", e))?);
915    }
916
917    Ok(Some(pack))
918}
919
920/// Load every locally-cached pack the user is currently subscribed to
921/// (plus their own packs, which always count). Hydrated with items.
922/// Cached non-subscribed pack rows stay in the DB so historic reactions
923/// still resolve their image URLs — they're just hidden from the picker.
924pub fn load_all_packs() -> Result<Vec<EmojiPack>, String> {
925    let conn = crate::db::get_db_connection_guard_static()?;
926
927    let mut packs: HashMap<String, EmojiPack> = HashMap::new();
928    let mut order: Vec<String> = Vec::new();
929
930    {
931        // INNER JOIN — only show subscribed packs. Own packs are
932        // auto-subscribed when published (see `publish_pack`), so this
933        // surfaces them by default; if the user explicitly unsubscribes
934        // their own pack via the right-click "Remove" path, it drops out
935        // of the picker but stays on Nostr and in `emoji_packs` so a
936        // later re-subscribe (paste naddr) restores it with `is_own` set.
937        let mut stmt = conn.prepare(
938            "SELECT p.addr, p.pubkey, p.identifier, p.title, p.image_url, p.description, p.is_own, p.updated_at, p.status
939             FROM emoji_packs p
940             INNER JOIN emoji_pack_subscriptions s ON s.addr = p.addr
941             ORDER BY s.position ASC"
942        ).map_err(|e| format!("prepare packs: {}", e))?;
943
944        let rows = stmt.query_map([], |row| {
945            // Row col 0 is the raw addr (kind:pubkey:identifier). Encode
946            // to naddr here so the public `id` field is consistent with
947            // what `parse_pack_from_event` produces.
948            let raw_addr: String = row.get(0)?;
949            let id = naddr_from_addr(&raw_addr).unwrap_or(raw_addr.clone());
950            Ok((raw_addr, EmojiPack {
951                id,
952                pubkey: row.get(1)?,
953                identifier: row.get(2)?,
954                title: row.get(3)?,
955                image_url: row.get(4)?,
956                description: row.get(5)?,
957                is_own: row.get::<_, i32>(6)? != 0,
958                updated_at: row.get::<_, i64>(7)? as u64,
959                emojis: Vec::new(),
960                status: row.get::<_, i64>(8)? as u8,
961            }))
962        }).map_err(|e| format!("query packs: {}", e))?;
963
964        for r in rows {
965            let (raw_addr, pack) = r.map_err(|e| format!("row pack: {}", e))?;
966            order.push(raw_addr.clone());
967            packs.insert(raw_addr, pack);
968        }
969    }
970
971    {
972        let mut stmt = conn.prepare(
973            "SELECT pack_addr, shortcode, url, sha256
974             FROM emoji_pack_items
975             ORDER BY pack_addr, position ASC"
976        ).map_err(|e| format!("prepare items: {}", e))?;
977
978        let rows = stmt.query_map([], |row| {
979            Ok((
980                row.get::<_, String>(0)?,
981                PackEmoji {
982                    shortcode: row.get(1)?,
983                    url: row.get(2)?,
984                    sha256: row.get(3)?,
985                },
986            ))
987        }).map_err(|e| format!("query items: {}", e))?;
988
989        for r in rows {
990            let (addr, emoji) = r.map_err(|e| format!("row item: {}", e))?;
991            if let Some(p) = packs.get_mut(&addr) {
992                p.emojis.push(emoji);
993            }
994        }
995    }
996
997    Ok(order.into_iter().filter_map(|a| packs.remove(&a)).collect())
998}
999
1000// ============================================================================
1001// Author outbox (NIP-65)
1002// ============================================================================
1003
1004/// How long a cached author relay list stays valid before re-fetching.
1005/// NIP-65 lists rarely change (relay-set edits are a deliberate user act);
1006/// an hour amortises the overhead without serving routing that's egregiously
1007/// stale. Mirrors the TTL the NIP-17 inbox cache uses.
1008const NIP65_CACHE_TTL_SECS: u64 = 3600;
1009/// Shorter TTL after an empty/failed lookup so a transient relay blip doesn't
1010/// suppress outbox routing for a whole hour.
1011const NIP65_CACHE_TTL_ERROR_SECS: u64 = 60;
1012const NIP65_FETCH_TIMEOUT_SECS: u64 = 10;
1013
1014#[derive(Clone)]
1015struct CachedRelayList {
1016    relays: Vec<RelayUrl>,
1017    fetched_at: web_time::Instant,
1018    /// Empty fetches use the shorter TTL so transient outages recover fast.
1019    empty: bool,
1020    /// True when the entry came from a SUCCESSFUL kind-10002 fetch. An
1021    /// error-cached placeholder (kept so previews don't refetch-storm) must
1022    /// never read as "author verifiably has no relays" to the health sweep.
1023    verified: bool,
1024}
1025
1026/// Pack-author relay lists. Author-keyed, so technically account-agnostic, but
1027/// the set of authors is contact-graph metadata belonging to one account.
1028struct Nip65Cache;
1029
1030fn nip65_cache() -> std::sync::Arc<std::sync::RwLock<HashMap<PublicKey, CachedRelayList>>> {
1031    crate::db::current_session().scoped::<Nip65Cache, _>()
1032}
1033
1034/// Read fresh write relays for `pubkey` from the cache, or `None` if absent /
1035/// expired. Honours the dual TTL (short for empty entries).
1036fn cached_write_relays(pubkey: &PublicKey) -> Option<Vec<RelayUrl>> {
1037    let owner = nip65_cache();
1038    let cache = owner.read().ok()?;
1039    let entry = cache.get(pubkey)?;
1040    let ttl = if entry.empty { NIP65_CACHE_TTL_ERROR_SECS } else { NIP65_CACHE_TTL_SECS };
1041    if entry.fetched_at.elapsed() < std::time::Duration::from_secs(ttl) {
1042        Some(entry.relays.clone())
1043    } else {
1044        None
1045    }
1046}
1047
1048/// Like [`cached_write_relays`], but only entries learned from a SUCCESSFUL
1049/// kind-10002 fetch. Judging a pack's absence needs its canonical home to
1050/// have really been resolved; an error placeholder must read as unknown.
1051fn cached_write_relays_verified(pubkey: &PublicKey) -> Option<Vec<RelayUrl>> {
1052    let owner = nip65_cache();
1053    let cache = owner.read().ok()?;
1054    let entry = cache.get(pubkey)?;
1055    if !entry.verified {
1056        return None;
1057    }
1058    let ttl = if entry.empty { NIP65_CACHE_TTL_ERROR_SECS } else { NIP65_CACHE_TTL_SECS };
1059    if entry.fetched_at.elapsed() < std::time::Duration::from_secs(ttl) {
1060        Some(entry.relays.clone())
1061    } else {
1062        None
1063    }
1064}
1065
1066/// Store a freshly-resolved write-relay list for `pubkey` in the cache.
1067fn cache_write_relays(pubkey: PublicKey, relays: Vec<RelayUrl>, verified: bool) {
1068    if let Ok(mut cache) = nip65_cache().write() {
1069        // An expired entry is never read again, only replaced.
1070        cache.retain(|_, e| {
1071            let ttl = if e.empty { NIP65_CACHE_TTL_ERROR_SECS } else { NIP65_CACHE_TTL_SECS };
1072            e.fetched_at.elapsed() < std::time::Duration::from_secs(ttl)
1073        });
1074        let empty = relays.is_empty();
1075        cache.insert(pubkey, CachedRelayList {
1076            relays,
1077            fetched_at: web_time::Instant::now(),
1078            empty,
1079            verified,
1080        });
1081    }
1082}
1083
1084/// Extract the write relays from a kind-10002 event. NIP-65: marker absent =
1085/// read+write (both), "write" = author publishes here, "read"-only = consumes
1086/// only (useless for finding their packs), so we keep both/write and drop read.
1087fn extract_write_relays(ev: &Event) -> Vec<RelayUrl> {
1088    let mut relays: Vec<RelayUrl> = Vec::new();
1089    for (url, marker) in nostr_sdk::prelude::nip65::extract_relay_list(ev) {
1090        match marker {
1091            None | Some(nostr_sdk::prelude::nip65::RelayMetadata::Write) => {
1092                if !relays.contains(&url) {
1093                    relays.push(url.clone());
1094                }
1095            }
1096            Some(nostr_sdk::prelude::nip65::RelayMetadata::Read) => {}
1097        }
1098    }
1099    relays
1100}
1101
1102/// Resolve the author's NIP-65 (kind-10002) write relays — where they publish.
1103/// Returns an empty Vec on absence or fetch error; callers must treat absence
1104/// as "no extra hints," not a failure. Cached per-pubkey. Used by the
1105/// single-pack path; the batched list path uses `prefetch_author_write_relays`.
1106pub(crate) async fn fetch_author_write_relays(client: &Client, pubkey: PublicKey) -> Vec<RelayUrl> {
1107    if let Some(relays) = cached_write_relays(&pubkey) {
1108        return relays;
1109    }
1110
1111    let filter = Filter::new()
1112        .author(pubkey)
1113        .kind(Kind::RelayList)
1114        .limit(1);
1115    let events = match client
1116        .fetch_events(filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(NIP65_FETCH_TIMEOUT_SECS)))
1117        .await
1118    {
1119        Ok(evs) => evs,
1120        Err(_) => {
1121            cache_write_relays(pubkey, Vec::new(), false);
1122            return Vec::new();
1123        }
1124    };
1125
1126    let relays = events.into_iter()
1127        .max_by_key(|e| e.created_at)
1128        .map(|ev| extract_write_relays(&ev))
1129        .unwrap_or_default();
1130    cache_write_relays(pubkey, relays.clone(), true);
1131    relays
1132}
1133
1134/// Warm the NIP-65 cache for many authors in ONE request. Used by the batched
1135/// subscribed-list path so a boot with N federated packs pays a single
1136/// kind-10002 fetch instead of N. Authors already cached-fresh are skipped;
1137/// authors with no kind-10002 are cached empty (short TTL) so we don't refetch
1138/// them every pass.
1139async fn prefetch_author_write_relays(client: &Client, authors: &[PublicKey]) {
1140    let uncached: Vec<PublicKey> = authors.iter()
1141        .filter(|pk| cached_write_relays(pk).is_none())
1142        .copied()
1143        .collect();
1144    if uncached.is_empty() {
1145        return;
1146    }
1147
1148    let filter = Filter::new()
1149        .authors(uncached.iter().copied())
1150        .kind(Kind::RelayList);
1151    let events = match client
1152        .fetch_events(filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(NIP65_FETCH_TIMEOUT_SECS)))
1153        .await
1154    {
1155        Ok(evs) => evs,
1156        // On error, leave the cache cold — the next pass retries rather than
1157        // poisoning every author with an empty entry off one failed batch.
1158        Err(_) => return,
1159    };
1160
1161    // Keep the newest kind-10002 per author, then cache each.
1162    let mut newest: HashMap<PublicKey, Event> = HashMap::new();
1163    for ev in events {
1164        match newest.get(&ev.pubkey) {
1165            Some(existing) if existing.created_at >= ev.created_at => {}
1166            _ => { newest.insert(ev.pubkey, ev); }
1167        }
1168    }
1169    for pk in uncached {
1170        let relays = newest.get(&pk).map(extract_write_relays).unwrap_or_default();
1171        cache_write_relays(pk, relays, true);
1172    }
1173}
1174
1175// ============================================================================
1176// Relay fetch
1177// ============================================================================
1178
1179/// Resolve a single pack from relays by its parsed address. Returns
1180/// `None` when no matching event is found within the timeout — callers
1181/// distinguish "unknown" from "fetch error" by the caller's own error
1182/// pathway (every relay call here that errors logs and proceeds).
1183async fn fetch_pack_from_relays(client: &Client, addr: &PackAddress) -> Option<EmojiPack> {
1184    let filter = Filter::new()
1185        .author(addr.pubkey)
1186        .kind(Kind::Custom(KIND_EMOJI_SET))
1187        .identifier(&addr.identifier)
1188        .limit(1);
1189    let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS));
1190    let me = crate::state::my_public_key().map(|pk| pk.to_hex());
1191
1192    // 1) Home relays first (the shared pool). Covers our own packs and any
1193    //    pack that's on Vector's default relays — the common, fast case.
1194    match client.fetch_events(filter.clone()).timeout(timeout).await {
1195        Ok(events) => {
1196            if let Some(ev) = events.into_iter().max_by_key(|e| e.created_at) {
1197                if let Some(pack) = parse_pack_from_event(&ev, me.as_deref()) {
1198                    return Some(pack);
1199                }
1200            }
1201        }
1202        Err(e) => crate::log_warn!("[EmojiPacks] home fetch {} failed: {}", &addr.identifier, e),
1203    }
1204
1205    // 2) Outbox fallback (NIP-65): the pack lives wherever the creator
1206    //    publishes, which may sit outside our relays. Fetch through an
1207    //    ISOLATED throwaway client so these third-party relays never enter
1208    //    the shared pool — the DM/community sync loops enumerate that pool and
1209    //    would otherwise reconcile against every pack author's relays.
1210    let outbox = fetch_author_write_relays(client, addr.pubkey).await;
1211    if outbox.is_empty() {
1212        return None;
1213    }
1214    fetch_pack_via_isolated_client(&outbox, filter, timeout, me.as_deref()).await
1215}
1216
1217/// Fetch a kind-30030 pack through a dedicated, short-lived client connected
1218/// only to the given relays. Built with Tor-aware options; fully torn down
1219/// before returning so nothing leaks into the app's relay pool or sync loops.
1220async fn fetch_pack_via_isolated_client(
1221    relays: &[RelayUrl],
1222    filter: Filter,
1223    timeout: std::time::Duration,
1224    my_pubkey_hex: Option<&str>,
1225) -> Option<EmojiPack> {
1226    let scratch = crate::nostr_client_builder()
1227        .build();
1228    for r in relays {
1229        let _ = scratch.add_managed_relay(r.as_str()).await;
1230    }
1231    scratch.connect().await;
1232
1233    let result = scratch.fetch_events(filter).timeout(timeout).await;
1234    // Tear the scratch client down regardless of outcome.
1235    scratch.shutdown().await;
1236
1237    let events = match result {
1238        Ok(events) => events,
1239        Err(e) => {
1240            crate::log_warn!("[EmojiPacks] outbox fetch failed: {}", e);
1241            return None;
1242        }
1243    };
1244    let event = events.into_iter().max_by_key(|e| e.created_at)?;
1245    parse_pack_from_event(&event, my_pubkey_hex)
1246}
1247
1248// ============================================================================
1249// Batched relay fetch (subscribed-list path ONLY)
1250// ============================================================================
1251//
1252// `fetch_pack_from_relays` (above) resolves ONE pack and is used by the
1253// per-pack flows: in-chat preview cards and the pinned theme pack, which
1254// arrive as independent render events and must stay independent.
1255//
1256// `fetch_packs_from_relays` (below) resolves MANY packs whose coordinates are
1257// all known up front — i.e. the user's own subscribed list. It collapses what
1258// used to be N requests into one batched home request plus, for any packs not
1259// on our relays, one batched NIP-65 prefetch and one batched outbox request.
1260// These two paths intentionally do NOT share fetch logic: the single path is
1261// kept byte-stable so the preview/theme behaviour can't regress.
1262
1263/// Coordinate key for matching a kind-30030 event back to a requested pack:
1264/// `pubkey_hex:identifier`. (Not the `30030:`-prefixed addr — just the parts a
1265/// fetched event exposes via its author + `d` tag.)
1266fn event_coord(ev: &Event) -> Option<String> {
1267    let d = first_tag(&ev.tags, &["d"])?;
1268    Some(format!("{}:{}", ev.pubkey.to_hex(), d))
1269}
1270fn addr_coord(addr: &PackAddress) -> String {
1271    format!("{}:{}", addr.pubkey.to_hex(), addr.identifier)
1272}
1273
1274/// One batched filter matches the cross-product of authors × identifiers, so it
1275/// can return events we didn't ask for (author A's `d` that belongs to author
1276/// B's pack). Match strictly by exact coordinate and keep the newest event per
1277/// coordinate; strays are dropped. Returns raw EVENTS (not parsed packs): an
1278/// empty kind 30030 is a deletion tombstone, and parsing would erase exactly
1279/// that evidence.
1280fn newest_events_by_coord(
1281    events: impl IntoIterator<Item = Event>,
1282    wanted: &std::collections::HashSet<String>,
1283) -> HashMap<String, Event> {
1284    let mut newest: HashMap<String, Event> = HashMap::new();
1285    for ev in events {
1286        if ev.kind.as_u16() != KIND_EMOJI_SET { continue; }
1287        let Some(coord) = event_coord(&ev) else { continue; };
1288        if !wanted.contains(&coord) { continue; }
1289        match newest.get(&coord) {
1290            Some(existing) if existing.created_at >= ev.created_at => {}
1291            _ => { newest.insert(coord, ev); }
1292        }
1293    }
1294    newest
1295}
1296
1297/// Merge a phase's newest-events into the accumulator, keeping the newer of
1298/// the two per coordinate.
1299fn merge_newest(acc: &mut HashMap<String, Event>, phase: HashMap<String, Event>) {
1300    for (coord, ev) in phase {
1301        match acc.get(&coord) {
1302            Some(existing) if existing.created_at >= ev.created_at => {}
1303            _ => { acc.insert(coord, ev); }
1304        }
1305    }
1306}
1307
1308/// Batched NIP-09 deletion filter for the given packs: author-signed kind 5s
1309/// that cite a pack coordinate in an `a` tag.
1310fn deletion_filter(addrs: &[&PackAddress]) -> Filter {
1311    Filter::new()
1312        .authors(addrs.iter().map(|a| a.pubkey))
1313        .kind(Kind::EventDeletion)
1314        .custom_tags(
1315            SingleLetterTag::LOWERCASE_A,
1316            addrs.iter().map(|a| a.to_addr_string()),
1317        )
1318}
1319
1320/// Does this kind-5, signed by the pack's author, cite the pack's coordinate?
1321/// Third-party deletions never count — only the author may revoke.
1322fn deletion_matches(ev: &Event, author: &PublicKey, raw_addr: &str) -> bool {
1323    ev.kind == Kind::EventDeletion
1324        && ev.pubkey == *author
1325        && ev.tags.iter().any(|t| {
1326            let s = t.as_slice();
1327            s.len() >= 2 && s[0] == "a" && s[1] == raw_addr
1328        })
1329}
1330
1331/// URLs of relays that are CONNECTED and readable right now — the basis for
1332/// judging whether an absence was observed against live relays or thin air.
1333/// READ-flagged only for the main pool (fetches never touch write-only or
1334/// GOSSIP-isolated community relays, so those must not inflate the count).
1335async fn connected_read_relays(client: &Client, read_only: bool) -> std::collections::HashSet<String> {
1336    client
1337        .relays()
1338        .await
1339        .iter()
1340        .filter(|(_, r)| r.status() == RelayStatus::Connected && (!read_only || r.capabilities().load().can_read()))
1341        .map(|(url, _)| url.to_string())
1342        .collect()
1343}
1344
1345/// Is a pack's ABSENCE from this sweep judgeable as a clean miss? Pure so the
1346/// gate combinations are table-testable.
1347///
1348/// - The home fetch must have completed against relays that were connected
1349///   both before AND after it ran (`connect()` is non-blocking, so an
1350///   after-only sample would bless a fetch that raced an empty pool).
1351/// - At least two distinct live relays across the phases.
1352/// - The author's NIP-65 write relays are the pack's canonical home:
1353///   unknown (cache cold / fetch failed) means it was never really checked —
1354///   not clean. Verifiably EMPTY means home evidence alone is the best
1355///   anyone can do. Known means the outbox phase must have completed there.
1356fn absence_is_clean(
1357    home_ok: bool,
1358    live_relays: usize,
1359    author_writes: Option<&Vec<RelayUrl>>,
1360    outbox_ok: bool,
1361    outbox_live: usize,
1362) -> bool {
1363    if !home_ok || live_relays < 2 {
1364        return false;
1365    }
1366    match author_writes {
1367        None => false,
1368        Some(w) if w.is_empty() => true,
1369        Some(_) => outbox_ok && outbox_live >= 1,
1370    }
1371}
1372
1373/// Classify one pack from a sweep's evidence. Pure so the verdict table is
1374/// unit-testable. Returns the parsed pack alongside `Found`.
1375fn classify_pack(
1376    newest_ev: Option<&Event>,
1377    newest_deletion: Option<&Event>,
1378    me: Option<&str>,
1379    absence_clean: bool,
1380) -> (PackFetchOutcome, Option<EmojiPack>) {
1381    match newest_ev {
1382        Some(ev) => match parse_pack_from_event(ev, me) {
1383            Some(pack) => {
1384                // A republish NEWER than the deletion revives the pack; on an
1385                // equal timestamp the pack wins (fail-safe toward alive).
1386                match newest_deletion {
1387                    Some(del) if del.created_at > ev.created_at => {
1388                        (PackFetchOutcome::Tombstoned, None)
1389                    }
1390                    _ => (PackFetchOutcome::Found, Some(pack)),
1391                }
1392            }
1393            None => {
1394                // No `emoji` tags at all: the author replaced the pack with an
1395                // empty one — Vector's own delete flow publishes exactly this
1396                // tombstone. An event that HAS emoji tags Vector merely can't
1397                // validate is not a deletion; judge nothing from it.
1398                let has_emoji_tags = ev.tags.iter().any(|t| {
1399                    t.as_slice().first().map(|k| k == "emoji").unwrap_or(false)
1400                });
1401                if has_emoji_tags {
1402                    (PackFetchOutcome::Unreachable, None)
1403                } else {
1404                    (PackFetchOutcome::Tombstoned, None)
1405                }
1406            }
1407        },
1408        None if newest_deletion.is_some() => (PackFetchOutcome::Tombstoned, None),
1409        None if absence_clean => (PackFetchOutcome::CleanMiss, None),
1410        None => (PackFetchOutcome::Unreachable, None),
1411    }
1412}
1413
1414/// Everything one refresh sweep learned: resolved packs (in `addrs` order)
1415/// plus a per-addr verdict for the health engine.
1416struct PackSweep {
1417    packs: Vec<EmojiPack>,
1418    /// raw `kind:pubkey:identifier` addr → verdict.
1419    outcomes: HashMap<String, PackFetchOutcome>,
1420}
1421
1422/// Resolve MANY packs in a batch and judge the ones that didn't resolve.
1423/// Home relays in one request; any unresolved packs then get one batched
1424/// NIP-65 prefetch + one batched outbox request via an isolated client, with
1425/// author-signed kind-5 deletions fetched alongside each phase. Callers keep
1426/// cached copies for anything that isn't `Found`.
1427async fn sweep_packs_from_relays(client: &Client, addrs: &[PackAddress]) -> PackSweep {
1428    if addrs.is_empty() {
1429        return PackSweep { packs: Vec::new(), outcomes: HashMap::new() };
1430    }
1431    let timeout = crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS));
1432    let me = crate::state::my_public_key().map(|pk| pk.to_hex());
1433    let wanted: std::collections::HashSet<String> = addrs.iter().map(addr_coord).collect();
1434    let all_refs: Vec<&PackAddress> = addrs.iter().collect();
1435
1436    // 1) One batched home request for every subscribed pack (+ deletions).
1437    // Live-relay evidence is the INTERSECTION of connected READ relays before
1438    // and after the fetch: `connect()` is non-blocking, so an after-only
1439    // sample would bless a fetch that actually ran against an empty pool
1440    // (boot, Tor cold start) — the exact false-positive the gauntlet must
1441    // never produce.
1442    let home_before = connected_read_relays(client, true).await;
1443    let home_filter = Filter::new()
1444        .authors(addrs.iter().map(|a| a.pubkey))
1445        .kind(Kind::Custom(KIND_EMOJI_SET))
1446        .identifiers(addrs.iter().map(|a| a.identifier.clone()));
1447    let mut newest: HashMap<String, Event> = HashMap::new();
1448    let mut deletions: Vec<Event> = Vec::new();
1449    let mut home_ok = false;
1450    match client.fetch_events(home_filter).timeout(timeout).await {
1451        Ok(events) => {
1452            home_ok = true;
1453            merge_newest(&mut newest, newest_events_by_coord(events, &wanted));
1454        }
1455        Err(e) => {
1456            crate::log_warn!("[EmojiPacks] batched home fetch failed: {}", e);
1457        }
1458    }
1459    if home_ok {
1460        match client.fetch_events(deletion_filter(&all_refs)).timeout(timeout).await {
1461            Ok(events) => deletions.extend(events),
1462            Err(e) => crate::log_warn!("[EmojiPacks] home deletion fetch failed: {}", e),
1463        }
1464    }
1465    let home_after = connected_read_relays(client, true).await;
1466    let mut live_relays: std::collections::HashSet<String> =
1467        home_before.intersection(&home_after).cloned().collect();
1468
1469    // 2) Outbox fallback for the misses, all in one shot. A pack's canonical
1470    // home is its author's NIP-65 write relays, so absence THERE is the
1471    // signal that matters for the health verdict.
1472    let misses: Vec<&PackAddress> = addrs.iter()
1473        .filter(|a| !newest.contains_key(&addr_coord(a)))
1474        .collect();
1475    let mut outbox_ok = false;
1476    let mut outbox_live = 0usize;
1477    if !misses.is_empty() {
1478        let miss_authors: Vec<PublicKey> = {
1479            let mut v: Vec<PublicKey> = misses.iter().map(|a| a.pubkey).collect();
1480            v.sort(); v.dedup();
1481            v
1482        };
1483        // Warm NIP-65 for all missed authors in one request, then union their
1484        // write relays into a single isolated client + one batched request.
1485        prefetch_author_write_relays(client, &miss_authors).await;
1486        let mut outbox: Vec<RelayUrl> = Vec::new();
1487        for pk in &miss_authors {
1488            for r in cached_write_relays(pk).unwrap_or_default() {
1489                if !outbox.contains(&r) { outbox.push(r); }
1490            }
1491        }
1492        if !outbox.is_empty() {
1493            let miss_filter = Filter::new()
1494                .authors(misses.iter().map(|a| a.pubkey))
1495                .kind(Kind::Custom(KIND_EMOJI_SET))
1496                .identifiers(misses.iter().map(|a| a.identifier.clone()));
1497            let wanted_misses: std::collections::HashSet<String> =
1498                misses.iter().map(|a| addr_coord(a)).collect();
1499            if let Some((events, dels, live)) = sweep_via_isolated_client(
1500                &outbox, miss_filter, deletion_filter(&misses), timeout,
1501            ).await {
1502                outbox_ok = true;
1503                outbox_live = live.len();
1504                live_relays.extend(live);
1505                merge_newest(&mut newest, newest_events_by_coord(events, &wanted_misses));
1506                deletions.extend(dels);
1507            }
1508        }
1509    }
1510
1511    // 3) Classify every pack (pure helpers; see their docs for the rules).
1512    let mut packs: Vec<EmojiPack> = Vec::new();
1513    let mut outcomes: HashMap<String, PackFetchOutcome> = HashMap::new();
1514    for addr in addrs {
1515        let coord = addr_coord(addr);
1516        let raw_addr = addr.to_addr_string();
1517        let newest_deletion = deletions.iter()
1518            .filter(|d| deletion_matches(d, &addr.pubkey, &raw_addr))
1519            .max_by_key(|d| d.created_at);
1520        let author_writes = cached_write_relays_verified(&addr.pubkey);
1521        let clean = absence_is_clean(
1522            home_ok,
1523            live_relays.len(),
1524            author_writes.as_ref(),
1525            outbox_ok,
1526            outbox_live,
1527        );
1528        let (outcome, pack) = classify_pack(
1529            newest.get(&coord),
1530            newest_deletion,
1531            me.as_deref(),
1532            clean,
1533        );
1534        if let Some(p) = pack {
1535            packs.push(p);
1536        }
1537        outcomes.insert(raw_addr, outcome);
1538    }
1539
1540    PackSweep { packs, outcomes }
1541}
1542
1543/// Batched sibling of `fetch_pack_via_isolated_client`: fetch pack events and
1544/// their kind-5 deletions from a throwaway client connected to the given
1545/// relays. Returns `None` when the pack fetch itself errored (the sweep must
1546/// not judge absences it never observed), plus the URLs of relays that were
1547/// connected across the fetch (before ∩ after — `connect()` is non-blocking,
1548/// so a fetch can race an empty pool) for the connectivity gate.
1549async fn sweep_via_isolated_client(
1550    relays: &[RelayUrl],
1551    pack_filter: Filter,
1552    del_filter: Filter,
1553    timeout: std::time::Duration,
1554) -> Option<(Vec<Event>, Vec<Event>, std::collections::HashSet<String>)> {
1555    let scratch = crate::nostr_client_builder()
1556        .build();
1557    for r in relays {
1558        let _ = scratch.add_managed_relay(r.as_str()).await;
1559    }
1560    scratch.connect().await;
1561    // `connect()` is non-blocking and this client is brand new, so wait for at
1562    // least one handshake to complete (bounded) before sampling connectivity —
1563    // an instant sample reads empty on every run, which would make before ∩
1564    // after a tautological zero and outbox absences permanently unjudgeable.
1565    let connect_deadline = web_time::Instant::now() + crate::relay_connect_timeout(std::time::Duration::from_secs(8));
1566    let before = loop {
1567        let connected = connected_read_relays(&scratch, false).await;
1568        if !connected.is_empty() || web_time::Instant::now() >= connect_deadline {
1569            break connected;
1570        }
1571        crate::rt::time::sleep(std::time::Duration::from_millis(200)).await;
1572    };
1573    let result = scratch.fetch_events(pack_filter).timeout(timeout).await;
1574    let dels = match &result {
1575        Ok(_) => scratch.fetch_events(del_filter).timeout(timeout).await.ok(),
1576        Err(_) => None,
1577    };
1578    let after = connected_read_relays(&scratch, false).await;
1579    scratch.shutdown().await;
1580
1581    match result {
1582        Ok(events) => Some((
1583            events.into_iter().collect(),
1584            dels.map(|d| d.into_iter().collect()).unwrap_or_default(),
1585            before.intersection(&after).cloned().collect(),
1586        )),
1587        Err(e) => {
1588            crate::log_warn!("[EmojiPacks] batched outbox fetch failed: {}", e);
1589            None
1590        }
1591    }
1592}
1593
1594/// Fetch the user's kind 10030 list, resolve every referenced pack, and
1595/// persist the result locally. Session-guarded against an account swap
1596/// landing the new account's pack list in account A's DB.
1597///
1598/// Non-destructive: a missing kind 10030 event or a transient per-pack
1599/// fetch failure must NOT nuke the user's local subscription list — that
1600/// would wipe their picker on every relay blip. Cached pack data is the
1601/// fallback whenever a fresh fetch fails.
1602pub async fn fetch_subscribed_packs(
1603    client: &Client,
1604    my_pubkey: PublicKey,
1605) -> Result<Vec<EmojiPack>, String> {
1606    crate::db::scoped(async move {
1607        let list_filter = Filter::new()
1608            .author(my_pubkey)
1609            .kind(Kind::Custom(KIND_EMOJI_LIST))
1610            .limit(1);
1611
1612        let list_events = client
1613            .fetch_events(list_filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS)))
1614            .await
1615            .map_err(|e| format!("fetch kind 10030: {}", e))?;
1616
1617
1618        // Source-of-truth selection. If relays returned a kind 10030, trust
1619        // its `a` tags as the canonical subscription set — UNLESS it predates
1620        // our own last publish, which means our latest republish hasn't
1621        // propagated yet and the relay is still serving a stale list. Trusting
1622        // a stale list would clobber a just-added pack (last-write-wins by
1623        // created_at). If relays returned *nothing*, that's a transient sync
1624        // gap — fall back to the local mirror either way.
1625        let local_addrs = || -> Vec<PackAddress> {
1626            load_subscriptions()
1627                .unwrap_or_default()
1628                .into_iter()
1629                .filter_map(|s| parse_pack_address(&s).ok())
1630                .collect()
1631        };
1632        let our_last_publish: u64 = crate::db::settings::get_sql_setting(EMOJI_LIST_PUBLISHED_AT_KEY.to_string())
1633            .ok()
1634            .flatten()
1635            .and_then(|s| s.parse().ok())
1636            .unwrap_or(0);
1637
1638        let list_event = list_events.into_iter().max_by_key(|e| e.created_at);
1639        // Anchor only rides in from a TRUSTED relay list — a stale/absent event
1640        // falls back to local subs and leaves the local KV anchor untouched.
1641        let mut fetched_anchor: Option<String> = None;
1642        let addrs: Vec<PackAddress> = match list_event {
1643            Some(ev) if ev.created_at.as_secs() < our_last_publish => {
1644                crate::log_debug!(
1645                    "[EmojiPacks] fetched kind 10030 (created_at {}) predates our publish ({}) — keeping local subs",
1646                    ev.created_at.as_secs(), our_last_publish,
1647                );
1648                local_addrs()
1649            }
1650            Some(ev) => {
1651                let public: Vec<Vec<String>> = ev.tags.iter().map(|t| t.as_slice().to_vec()).collect();
1652                let private = match decrypt_emoji_list_plaintext(client, &my_pubkey, &ev).await {
1653                    Some(plaintext) => {
1654                        let (raw, anchor) = parse_inner_tag_list_with_anchor(&plaintext);
1655                        fetched_anchor = anchor;
1656                        Some(raw)
1657                    }
1658                    None => None,
1659                };
1660                let local = load_subscriptions().unwrap_or_default();
1661                let merged = merge_emoji_list(private, &public_addrs(&public), &local, &public_addrs(&load_public_tags()));
1662                save_public_tags(&public);
1663                merged.iter().filter_map(|s| parse_pack_address(s).ok()).collect()
1664            }
1665            None => {
1666                crate::log_debug!(
1667                    "[EmojiPacks] kind 10030 not on relays — refreshing local subs only",
1668                );
1669                local_addrs()
1670            }
1671        };
1672
1673        let addr_strings: Vec<String> = addrs.iter().map(|a| a.to_addr_string()).collect();
1674
1675        // Batched resolve: one home request for every subscribed pack, plus one
1676        // batched outbox pass for any not on our relays. Packs that still don't
1677        // resolve keep their cached copy (we never shrink the subscription set on
1678        // a transient miss); the health engine below decides whether an absence
1679        // is judgeable at all. The per-pack `fetch_pack_from_relays` is reserved
1680        // for the independent preview/theme flows.
1681        let PackSweep { packs: fresh, outcomes } = sweep_packs_from_relays(client, &addrs).await;
1682        let tombstoned = outcomes.values().filter(|o| matches!(o, PackFetchOutcome::Tombstoned)).count();
1683        let unresolved = addrs.len().saturating_sub(fresh.len()).saturating_sub(tombstoned);
1684        if unresolved > 0 {
1685            crate::log_warn!(
1686                "[EmojiPacks] {} subscribed pack(s) not on relays — keeping cached copies",
1687                unresolved,
1688            );
1689        }
1690        if tombstoned > 0 {
1691            crate::log_info!("[EmojiPacks] {} subscribed pack(s) deleted by their creator", tombstoned);
1692        }
1693
1694
1695        // Health verdicts BEFORE the save loop: save_pack's REPLACE resets the
1696        // health columns, so `Found` must read the pre-save status or a revival
1697        // (revoked back to active) would go unreported. Own packs are skipped:
1698        // deleting an own pack removes its rows locally, so there's nothing to
1699        // grieve, and a self-authored pack must never grey out over relay state.
1700        let me_hex = my_pubkey.to_hex();
1701        let now = crate::clock::now_secs() as i64;
1702        let mut health_changed = false;
1703        for addr in &addrs {
1704            if addr.pubkey.to_hex() == me_hex { continue; }
1705            let raw = addr.to_addr_string();
1706            let Some(outcome) = outcomes.get(&raw) else { continue; };
1707            match apply_pack_health(&raw, outcome, now) {
1708                Ok(true) => {
1709                    health_changed = true;
1710                    crate::log_info!(
1711                        "[EmojiPacks] pack `{}` health changed ({:?})",
1712                        addr.identifier, outcome,
1713                    );
1714                }
1715                Ok(false) => {}
1716                Err(e) => crate::log_warn!("[EmojiPacks] health update for `{}` failed: {}", addr.identifier, e),
1717            }
1718        }
1719        for pack in &fresh {
1720            if let Err(e) = save_pack(pack) {
1721                crate::log_warn!("[EmojiPacks] save pack {} failed: {}", pack.identifier, e);
1722            }
1723        }
1724        // Detect a real list change (reorder, sub add/remove, or theme-slot move)
1725        // against the pre-save state, so a cross-device edit repaints an OPEN
1726        // picker live — not only on its next open. Our own republish echoes back
1727        // unchanged, so this stays quiet on self-echo.
1728        let list_changed = load_subscriptions().unwrap_or_default() != addr_strings
1729            || fetched_anchor.as_deref().is_some_and(|a| a != load_theme_slot_anchor());
1730
1731        // Persist the full subscription list (10030-driven, or local-mirror
1732        // when 10030 was missing). Per-pack fetch failures don't shrink it —
1733        // the user is still subscribed, they just have a cached copy for now.
1734        if let Err(e) = save_subscriptions(&addr_strings) {
1735            crate::log_warn!("[EmojiPacks] save subscriptions failed: {}", e);
1736        }
1737        // Sync the theme-slot position from the trusted list (old-format lists
1738        // carry no marker → leave the local anchor as-is).
1739        if let Some(anchor) = fetched_anchor {
1740            if let Err(e) = save_theme_slot_anchor(&anchor) {
1741                crate::log_warn!("[EmojiPacks] save theme slot anchor failed: {}", e);
1742            }
1743        }
1744        if health_changed || list_changed {
1745            crate::traits::emit_event("emoji_packs_updated", &());
1746        }
1747
1748        crate::log_info!(
1749            "[EmojiPacks] Resolved {} of {} subscribed pack(s){}",
1750            fresh.len(),
1751            addrs.len(),
1752            if unresolved > 0 {
1753                format!(" ({} via cache)", unresolved)
1754            } else {
1755                String::new()
1756            },
1757        );
1758
1759        // Return the unified view: freshly-fetched packs overlay the cached
1760        // ones, and load_all_packs filters to subscribed-only for us.
1761        load_all_packs()
1762    })
1763    .await
1764}
1765
1766/// Convenience entry point that grabs the client + my_pubkey internally
1767/// and runs the full subscribed-packs refresh. Intended for the boot
1768/// path; in-app commands pass an explicit `std::sync::Arc<crate::db::Session>` via the lower
1769/// helper to make the safety contract visible at every call site.
1770pub async fn refresh_subscribed_packs() -> Result<Vec<EmojiPack>, String> {
1771    let client = nostr_client().ok_or_else(|| "Nostr client not initialised".to_string())?;
1772    let me = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
1773    fetch_subscribed_packs(&client, me).await
1774}
1775
1776/// Preview-only fetch by naddr — resolves + parses but never touches
1777/// local DB. Lets the UI render a "Pack Preview" card without committing
1778/// to a subscription.
1779pub async fn fetch_pack_by_naddr(naddr: &str) -> Result<EmojiPack, String> {
1780    let addr = parse_naddr(naddr)?;
1781    let client = nostr_client().ok_or_else(|| "Nostr client not initialised".to_string())?;
1782    fetch_pack_from_relays(&client, &addr).await
1783        .ok_or_else(|| {
1784            // Coordinate goes to the log; the returned string is shown
1785            // verbatim in the preview card, so keep it human-readable.
1786            crate::log_debug!("[EmojiPacks] preview miss: {}:{}", addr.pubkey.to_hex(), addr.identifier);
1787            "Pack not found on any relay".to_string()
1788        })
1789}
1790
1791/// Resolve a theme pack cache-first: return the locally-persisted copy
1792/// instantly when present (and refresh it in the background), otherwise fetch
1793/// live, persist, and return. Theme packs are pinned by the active theme, not
1794/// subscribed — `save_pack` persists their data without a subscription row, so
1795/// they survive restarts (no per-session relay round-trip) yet never occupy an
1796/// equip slot or land in the kind-10030 list. Returns `None` if uncached and
1797/// the live fetch finds nothing.
1798pub async fn get_or_fetch_theme_pack(naddr: &str) -> Result<Option<EmojiPack>, String> {
1799    crate::db::scoped(async move {
1800        let addr = parse_naddr(naddr)?;
1801        let coord = addr.to_addr_string();
1802
1803        // Cache hit: return immediately, refresh in the background so a later
1804        // creator-side edit still propagates without blocking first paint.
1805        if let Some(cached) = load_cached_pack(&coord)? {
1806            let naddr_owned = naddr.to_string();
1807            crate::db::spawn_bound(async move {
1808                let Some(client) = nostr_client() else { return };
1809                if let Ok(parsed) = parse_naddr(&naddr_owned) {
1810                    if let Some(fresh) = fetch_pack_from_relays(&client, &parsed).await {
1811                        if fresh.updated_at > cached.updated_at {
1812                            if let Err(e) = save_pack(&fresh) {
1813                                crate::log_warn!("[EmojiPacks] theme pack refresh save failed: {}", e);
1814                            } else {
1815                                crate::traits::emit_event("emoji_packs_updated", &());
1816                            }
1817                        }
1818                    }
1819                }
1820            });
1821            return Ok(Some(cached));
1822        }
1823
1824        // Cache miss: fetch live, persist for next session, return.
1825        let client = nostr_client().ok_or_else(|| "Nostr client not initialised".to_string())?;
1826        match fetch_pack_from_relays(&client, &addr).await {
1827            Some(pack) => {
1828                // Still show the pack this session, but only persist if the account
1829                // didn't swap during the fetch — otherwise we'd write into the wrong
1830                // account's DB.
1831                if let Err(e) = save_pack(&pack) {
1832                    crate::log_warn!("[EmojiPacks] theme pack cache save failed: {}", e);
1833                }
1834                Ok(Some(pack))
1835            }
1836            None => Ok(None),
1837        }
1838    })
1839    .await
1840}
1841
1842/// KV setting holding the raw addr (`30030:pk:d`) of the pack the theme slot
1843/// sits immediately AFTER. Empty string = slot at the top (first); a never-set
1844/// key defaults to `""`, matching the historic "theme pinned first" behaviour.
1845/// Kept OUT of `emoji_pack_subscriptions` so the DELETE-all-reinsert in
1846/// `save_subscriptions` can't wipe it (the theme pack is not a real sub row).
1847const THEME_SLOT_ANCHOR_KEY: &str = "emoji_theme_slot_anchor";
1848
1849/// Read the theme-slot anchor (raw addr), defaulting to `""` (top).
1850fn load_theme_slot_anchor() -> String {
1851    crate::db::settings::get_sql_setting(THEME_SLOT_ANCHOR_KEY.to_string())
1852        .ok()
1853        .flatten()
1854        .unwrap_or_default()
1855}
1856
1857/// Persist the theme-slot anchor (raw addr, or `""` for top).
1858fn save_theme_slot_anchor(raw_addr: &str) -> Result<(), String> {
1859    crate::db::settings::set_sql_setting(THEME_SLOT_ANCHOR_KEY.to_string(), raw_addr.to_string())
1860}
1861
1862/// The public tags of the last kind-10030 we trusted, as JSON tuples. Other clients list packs
1863/// (and single emoji) there; ours carries them forward so a publish never erases them.
1864const EMOJI_LIST_PUBLIC_KEY: &str = "emoji_list_public_tags";
1865
1866fn load_public_tags() -> Vec<Vec<String>> {
1867    crate::db::settings::get_sql_setting(EMOJI_LIST_PUBLIC_KEY.to_string())
1868        .ok()
1869        .flatten()
1870        .and_then(|s| serde_json::from_str(&s).ok())
1871        .unwrap_or_default()
1872}
1873
1874fn save_public_tags(tags: &[Vec<String>]) {
1875    if let Ok(json) = serde_json::to_string(tags) {
1876        let _ = crate::db::settings::set_sql_setting(EMOJI_LIST_PUBLIC_KEY.to_string(), json);
1877    }
1878}
1879
1880/// The pack addresses among a list's public tags, normalised as subscriptions are stored.
1881fn public_addrs(tags: &[Vec<String>]) -> Vec<String> {
1882    tags.iter()
1883        .filter(|t| t.len() >= 2 && t[0] == "a")
1884        .filter_map(|t| parse_pack_address(&t[1]).ok())
1885        .map(|a| a.to_addr_string())
1886        .collect()
1887}
1888
1889/// The subscription set a kind-10030 stands for: its private items in their order, then the
1890/// public ones other clients listed. A list with no private part (another client wrote it)
1891/// keeps our earlier private picks, never the public ones it has since dropped.
1892fn merge_emoji_list(private: Option<Vec<String>>, public_now: &[String], local: &[String], public_before: &[String]) -> Vec<String> {
1893    let mut list = private.unwrap_or_else(|| local.iter().filter(|a| !public_before.contains(a)).cloned().collect());
1894    for addr in public_now {
1895        if !list.contains(addr) {
1896            list.push(addr.clone());
1897        }
1898    }
1899    list
1900}
1901
1902/// The public tags to publish: every one carried forward, but a pack only while still subscribed.
1903fn carried_public_tags(public: &[Vec<String>], subscribed: &[String]) -> Vec<Vec<String>> {
1904    public.iter()
1905        .filter(|t| t.first().map(String::as_str) != Some("a")
1906            || t.get(1).and_then(|a| parse_pack_address(a).ok()).is_some_and(|a| subscribed.contains(&a.to_addr_string())))
1907        .cloned()
1908        .collect()
1909}
1910
1911/// Build the kind-10030 inner tuple list from the subscription order, splicing
1912/// in exactly one `["theme_slot"]` marker at the anchored position. Empty
1913/// anchor (or an anchor naming a pack no longer subscribed) puts the marker at
1914/// the top. Pure so the interleave is unit-testable.
1915fn build_inner_tags_with_marker(addrs: &[String], anchor: &str) -> Vec<Vec<String>> {
1916    let mut inner: Vec<Vec<String>> = Vec::with_capacity(addrs.len() + 1);
1917    let mut placed = false;
1918    if anchor.is_empty() {
1919        inner.push(vec![THEME_SLOT_TOKEN.to_string()]);
1920        placed = true;
1921    }
1922    for addr in addrs {
1923        inner.push(vec!["a".to_string(), addr.clone()]);
1924        if !placed && addr == anchor {
1925            inner.push(vec![THEME_SLOT_TOKEN.to_string()]);
1926            placed = true;
1927        }
1928    }
1929    // Anchor named a pack that's gone: fall back to the top so we always emit
1930    // exactly one marker.
1931    if !placed {
1932        inner.insert(0, vec![THEME_SLOT_TOKEN.to_string()]);
1933    }
1934    inner
1935}
1936
1937/// Publish a kind 10030 "Emojis" list containing every subscribed pack.
1938///
1939/// Encrypted-items mode: the entire subscription set lives inside a
1940/// NIP-44-self-encrypted JSON array of `["a", "30030:pk:d"]` tuples
1941/// stored in `content`, plus one `["theme_slot"]` marker recording where the
1942/// theme pack renders. Packs followed in Vector stay private (the NIP-51
1943/// "encrypted items" pattern mute lists use); the public tags other clients
1944/// listed are carried forward, minus any pack unsubscribed here.
1945/// Replaceable per spec, so peers (the same npub on another device)
1946/// always read the freshest set on next sync.
1947pub async fn publish_emoji_list(client: &Client) -> Result<(), String> {
1948    let addrs = load_subscriptions()?;
1949    let anchor = load_theme_slot_anchor();
1950    let my_pk = crate::state::my_public_key()
1951        .ok_or_else(|| "Not logged in".to_string())?;
1952
1953    let inner_tags = build_inner_tags_with_marker(&addrs, &anchor);
1954    let plaintext = serde_json::to_string(&inner_tags)
1955        .map_err(|e| format!("Serialise emoji list: {}", e))?;
1956
1957    let signer = crate::signer::active_signer()
1958        .map_err(|e| format!("Signer unavailable: {}", e))?;
1959    let content = signer.nip44_encrypt_async(&my_pk, &plaintext).await
1960        .map_err(|e| format!("nip44 encrypt emoji list: {}", e))?;
1961
1962    let public = carried_public_tags(&load_public_tags(), &addrs);
1963    let builder = EventBuilder::new(Kind::Custom(KIND_EMOJI_LIST), content)
1964        .tags(public.iter().filter_map(|t| Tag::parse(t).ok()));
1965    crate::sign_and_send(client, builder).await
1966        .map_err(|e| format!("Failed to publish emoji list (kind 10030): {}", e))?;
1967    save_public_tags(&public);
1968
1969    crate::log_info!("[EmojiPacks] Published encrypted kind 10030 with {} pack subscription(s)", addrs.len());
1970    Ok(())
1971}
1972
1973/// Settings key holding the UNIX-seconds timestamp of our most recent local
1974/// subscription mutation. A refresh ignores any relay kind-10030 older than
1975/// this so our just-changed (not-yet-propagated) list can't be clobbered.
1976const EMOJI_LIST_PUBLISHED_AT_KEY: &str = "emoji_list_published_at";
1977
1978static REPUBLISH_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1979
1980/// Coalesce rapid subscribe/unsubscribe taps into one network publish.
1981/// Captures `std::sync::Arc<crate::db::Session>` BEFORE the spawn boundary so a mid-debounce
1982/// account swap can't sign account A's pack list with account B's key.
1983pub fn republish_emoji_list_debounced() {
1984    use std::sync::atomic::Ordering;
1985    // Stamp the mutation time NOW (synchronously, before the debounce sleep)
1986    // so a refresh racing the not-yet-fired publish still treats the local
1987    // set as newer than any stale relay copy. Every local subscription change
1988    // funnels through here; the refresh-persist path does not, so this can't
1989    // wrongly suppress a legit cross-device update.
1990    let _ = crate::db::settings::set_sql_setting(
1991        EMOJI_LIST_PUBLISHED_AT_KEY.to_string(),
1992        crate::clock::timestamp().as_secs().to_string(),
1993    );
1994    let gen = REPUBLISH_GEN.fetch_add(1, Ordering::SeqCst) + 1;
1995    crate::db::spawn_bound(async move {
1996        crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
1997        if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
1998        let client = match nostr_client() {
1999            Some(c) => c,
2000            None => return,
2001        };
2002        if let Err(e) = publish_emoji_list(&client).await {
2003            crate::log_warn!("[EmojiPacks] Republish failed: {} (retrying in 5s)", e);
2004            crate::rt::time::sleep(std::time::Duration::from_secs(5)).await;
2005            if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
2006            if let Err(e2) = publish_emoji_list(&client).await {
2007                crate::log_warn!("[EmojiPacks] Republish retry failed: {}", e2);
2008            }
2009        }
2010    });
2011}
2012
2013/// Subscribe to a pack by naddr: fetch the pack, persist it + the
2014/// subscription, then schedule a debounced republish of kind 10030.
2015/// Returns the hydrated pack on success.
2016pub async fn subscribe_pack(naddr: &str) -> Result<EmojiPack, String> {
2017    crate::db::scoped(async move {
2018        let pack = fetch_pack_by_naddr(naddr).await?;
2019
2020        // Equipped-pack cap. Idempotent re-subscribe to a pack we already
2021        // have stays free; only adding a brand-new addr counts toward the limit.
2022        let pack_addr = pack.addr();
2023        {
2024            let existing_subs = load_subscriptions()?;
2025            let is_new = !existing_subs.iter().any(|a| a == &pack_addr);
2026            let cap = effective_max_equipped_packs();
2027            if is_new && existing_subs.len() >= cap {
2028                return Err(format!(
2029                    "You can equip at most {} packs. Remove one to add another.",
2030                    cap,
2031                ));
2032            }
2033        }
2034
2035        save_pack(&pack)?;
2036
2037        let mut subs = load_subscriptions()?;
2038        if !subs.iter().any(|a| a == &pack_addr) {
2039            subs.push(pack_addr.clone());
2040        }
2041        save_subscriptions(&subs)?;
2042
2043        republish_emoji_list_debounced();
2044        crate::traits::emit_event("emoji_packs_updated", &());
2045
2046        Ok(pack)
2047    })
2048    .await
2049}
2050
2051// ============================================================================
2052// Pack publish (own creator path)
2053// ============================================================================
2054
2055/// Build a kind 30030 EventBuilder for one of the user's own packs.
2056/// Dual-writes the NIP-51 spec tags (`title`/`image`/`description`)
2057/// alongside the Ditto-style (`name`/`picture`/`about`) tags so packs
2058/// interop with both ecosystems — see `MEMORY.md` plan notes.
2059fn build_pack_event(pack: &EmojiPack) -> Result<EventBuilder, String> {
2060    if pack.identifier.is_empty() {
2061        return Err("pack identifier required".to_string());
2062    }
2063    let mut builder = EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2064        .tag(Tag::custom("d", [pack.identifier.clone()]))
2065        // Stamp Vector as the authoring client (same ["client","vector"] tag our kind-0
2066        // profile publishes carry) so packs made or edited here are attributable.
2067        .tag(Tag::custom("client", ["vector"]));
2068
2069    // Spec-compliant metadata (NIP-51).
2070    if !pack.title.is_empty() {
2071        builder = builder
2072            .tag(Tag::custom("title", [pack.title.clone()]))
2073            .tag(Tag::custom("name", [pack.title.clone()]));
2074    }
2075    if !pack.image_url.is_empty() {
2076        builder = builder
2077            .tag(Tag::custom("image", [pack.image_url.clone()]))
2078            .tag(Tag::custom("picture", [pack.image_url.clone()]));
2079    }
2080    if !pack.description.is_empty() {
2081        builder = builder
2082            .tag(Tag::custom("description", [pack.description.clone()]))
2083            .tag(Tag::custom("about", [pack.description.clone()]));
2084    }
2085
2086    for e in &pack.emojis {
2087        if e.shortcode.is_empty() || e.url.is_empty() { continue; }
2088        builder = builder.tag(Tag::custom(
2089            "emoji",
2090            [e.shortcode.clone(), e.url.clone()],
2091        ));
2092    }
2093    Ok(builder)
2094}
2095
2096/// Publish (or replace) one of the user's own packs as a kind 30030
2097/// event, persist it locally, and add it to the subscription list so
2098/// the picker surfaces it immediately. std::sync::Arc<crate::db::Session>-gated so a mid-
2099/// network account swap can't push account A's pack signed by B's key.
2100pub async fn publish_pack(pack: &EmojiPack) -> Result<EmojiPack, String> {
2101    crate::db::scoped(async move {
2102        let client = nostr_client().ok_or_else(|| "Nostr client not initialised".to_string())?;
2103        let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
2104
2105        // Per-pack emoji cap. Applies to own packs only — shared packs the
2106        // user receives can exceed this, the display layer truncates.
2107        let emoji_cap = effective_max_emojis_per_pack();
2108        if pack.emojis.len() > emoji_cap {
2109            return Err(format!(
2110                "A pack can hold at most {} emojis.",
2111                emoji_cap,
2112            ));
2113        }
2114
2115        // Force `pubkey` + `is_own` regardless of caller — protects against
2116        // a malformed payload claiming ownership of someone else's pack.
2117        let mut to_save = pack.clone();
2118        to_save.pubkey = my_pk.to_hex();
2119        to_save.is_own = true;
2120        let raw_addr = build_pack_addr(&to_save.pubkey, &to_save.identifier);
2121        to_save.id = naddr_from_addr(&raw_addr)?;
2122        to_save.updated_at = crate::clock::now_secs();
2123
2124        // Equipped-pack cap. Replacing an existing own pack is fine — only
2125        // a *new* identifier would push us over the limit.
2126        {
2127            let existing_subs = load_subscriptions()?;
2128            let is_new = !existing_subs.iter().any(|a| a == &raw_addr);
2129            let cap = effective_max_equipped_packs();
2130            if is_new && existing_subs.len() >= cap {
2131                return Err(format!(
2132                    "You can equip at most {} packs. Remove one to add another.",
2133                    cap,
2134                ));
2135            }
2136        }
2137
2138        let builder = build_pack_event(&to_save)?;
2139        crate::sign_and_send(&client, builder).await
2140            .map_err(|e| format!("publish kind 30030: {}", e))?;
2141
2142
2143        save_pack(&to_save)?;
2144
2145        // Add to local subscriptions so the picker shows it without waiting
2146        // for the next 10030 republish to land.
2147        let mut subs = load_subscriptions()?;
2148        if !subs.iter().any(|a| a == &raw_addr) {
2149            subs.push(raw_addr.clone());
2150            save_subscriptions(&subs)?;
2151            republish_emoji_list_debounced();
2152        }
2153
2154        crate::traits::emit_event("emoji_packs_updated", &());
2155        crate::log_info!("[EmojiPacks] Published own pack `{}` with {} emoji(s)",
2156            to_save.identifier, to_save.emojis.len());
2157
2158        Ok(to_save)
2159    })
2160    .await
2161}
2162
2163/// Tombstone one of the user's own packs by publishing an empty kind
2164/// 30030 with just the `d` tag (relays replace the prior payload), drop
2165/// the local subscription, and republish kind 10030.
2166pub async fn delete_own_pack(id: &str) -> Result<(), String> {
2167    crate::db::scoped(async move {
2168        let parsed = parse_naddr(id)?;
2169        let raw_addr = parsed.to_addr_string();
2170        let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
2171        if parsed.pubkey != my_pk {
2172            return Err("Cannot delete a pack you don't own".to_string());
2173        }
2174        let client = nostr_client().ok_or_else(|| "Nostr client not initialised".to_string())?;
2175
2176        let builder = EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2177            .tag(Tag::custom("d", [parsed.identifier.clone()]));
2178        crate::sign_and_send(&client, builder).await
2179            .map_err(|e| format!("publish empty kind 30030: {}", e))?;
2180
2181
2182        // Drop subscription + pack rows (CASCADE wipes pack items).
2183        // Wrapped in a transaction so a crash between the two deletes can't
2184        // leave an orphan subscription pointing at a pack row that's already gone.
2185        {
2186            let mut conn = crate::db::get_write_connection_guard_static()?;
2187            let tx = conn.transaction()
2188                .map_err(|e| format!("begin delete tx: {}", e))?;
2189            tx.execute("DELETE FROM emoji_pack_subscriptions WHERE addr = ?1",
2190                rusqlite::params![raw_addr])
2191                .map_err(|e| format!("drop subscription: {}", e))?;
2192            tx.execute("DELETE FROM emoji_packs WHERE addr = ?1",
2193                rusqlite::params![raw_addr])
2194                .map_err(|e| format!("drop pack row: {}", e))?;
2195            tx.commit()
2196                .map_err(|e| format!("commit delete tx: {}", e))?;
2197        }
2198
2199        republish_emoji_list_debounced();
2200        crate::traits::emit_event("emoji_packs_updated", &());
2201        crate::log_info!("[EmojiPacks] Deleted own pack `{}`", parsed.identifier);
2202        Ok(())
2203    })
2204    .await
2205}
2206
2207/// Unsubscribe locally and republish kind 10030 without the pack.
2208/// The pack row itself stays in `emoji_packs` (caller may still want
2209/// to render old reactions); only the subscription link is dropped.
2210pub async fn unsubscribe_pack(id: &str) -> Result<(), String> {
2211    crate::db::scoped(async move {
2212        let raw_addr = parse_naddr(id)?.to_addr_string();
2213        let mut subs = load_subscriptions()?;
2214        let before = subs.len();
2215        subs.retain(|a| a != &raw_addr);
2216        if subs.len() == before {
2217            return Ok(()); // not subscribed, noop
2218        }
2219        save_subscriptions(&subs)?;
2220        republish_emoji_list_debounced();
2221        crate::traits::emit_event("emoji_packs_updated", &());
2222        Ok(())
2223    })
2224    .await
2225}
2226
2227/// Persist a user-defined display order for the equipped packs (including the
2228/// theme slot) and republish kind 10030 so it syncs across devices.
2229///
2230/// `ordered_ids` is the FULL display order from the frontend: each element is a
2231/// pack `id` (naddr) for a real subscribed pack, or the literal
2232/// `THEME_SLOT_TOKEN` for the theme marker. Real packs are persisted in the
2233/// given order; the anchor is set to the raw addr of the pack immediately
2234/// before the marker (`""` = top / marker absent).
2235pub fn reorder_emoji_packs(ordered_ids: Vec<String>) -> Result<(), String> {
2236    let session = crate::db::current_session();
2237
2238    let mut real_addrs: Vec<String> = Vec::with_capacity(ordered_ids.len());
2239    let mut anchor = String::new();
2240    let mut marker_present = false;
2241    for id in &ordered_ids {
2242        if id == THEME_SLOT_TOKEN {
2243            marker_present = true;
2244            anchor = real_addrs.last().cloned().unwrap_or_default();
2245        } else {
2246            real_addrs.push(parse_naddr(id)?.to_addr_string());
2247        }
2248    }
2249
2250    if !session.is_live() {
2251        return Err("Account swapped during reorder — aborted".to_string());
2252    }
2253    save_subscriptions(&real_addrs)?;
2254    // Only the theme-slot's own drag moves the marker. A reorder that omits it
2255    // (theme pack inactive, so its tab isn't shown) leaves the anchor put, so
2256    // the user's theme-slot placement survives reordering the real packs.
2257    if marker_present {
2258        save_theme_slot_anchor(&anchor)?;
2259    }
2260    republish_emoji_list_debounced();
2261    crate::traits::emit_event("emoji_packs_updated", &());
2262    Ok(())
2263}
2264
2265/// Return the theme-slot anchor as a NADDR (the pack the theme slot renders
2266/// immediately after), or `""` when the slot is at the top. Degrades to top on
2267/// a malformed stored anchor rather than breaking the picker.
2268pub fn get_theme_slot_anchor() -> Result<String, String> {
2269    let raw = load_theme_slot_anchor();
2270    if raw.is_empty() {
2271        return Ok(String::new());
2272    }
2273    Ok(naddr_from_addr(&raw).unwrap_or_default())
2274}
2275
2276// ============================================================================
2277// Tests
2278// ============================================================================
2279
2280#[cfg(test)]
2281mod tests {
2282    use super::*;
2283
2284    fn keys() -> Keys {
2285        Keys::generate()
2286    }
2287
2288    fn build_pack_event(
2289        k: &Keys,
2290        d: &str,
2291        title_tag: Option<(&str, &str)>,
2292        image_tag: Option<(&str, &str)>,
2293        desc_tag: Option<(&str, &str)>,
2294        emojis: &[(&str, &str)],
2295    ) -> Event {
2296        let mut tags: Vec<Tag> = Vec::new();
2297        tags.push(Tag::custom("d", [d]));
2298        if let Some((key, val)) = title_tag {
2299            tags.push(Tag::custom(key, [val]));
2300        }
2301        if let Some((key, val)) = image_tag {
2302            tags.push(Tag::custom(key, [val]));
2303        }
2304        if let Some((key, val)) = desc_tag {
2305            tags.push(Tag::custom(key, [val]));
2306        }
2307        for (code, url) in emojis {
2308            tags.push(Tag::custom("emoji", [*code, *url]));
2309        }
2310        EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2311            .tags(tags)
2312            .finalize(k)
2313            .unwrap()
2314    }
2315
2316    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
2317        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2318        crate::db::close_database();
2319        // Per-account row-id caches survive close_database; stale entries would
2320        // point into a prior test's DB.
2321        crate::db::clear_id_caches();
2322        let tmp = tempfile::tempdir().unwrap();
2323        let account = keys().public_key().to_bech32().unwrap();
2324        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
2325        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
2326        crate::db::set_current_account(account.clone()).unwrap();
2327        crate::db::init_database(&account).unwrap();
2328        (tmp, guard)
2329    }
2330
2331    /// Save a parsed pack + return its raw addr.
2332    fn seed_pack(k: &Keys, d: &str, emojis: &[(&str, &str)]) -> String {
2333        let ev = build_pack_event(k, d, None, None, None, emojis);
2334        let pack = parse_pack_from_event(&ev, None).unwrap();
2335        save_pack(&pack).unwrap();
2336        pack.addr()
2337    }
2338
2339    fn seed_usage(url: &str) {
2340        let conn = crate::db::get_write_connection_guard_static().unwrap();
2341        conn.execute(
2342            "INSERT INTO emoji_usage (kind, id, url, score, last_used) VALUES (1, ?1, ?1, 1.0, 0)",
2343            rusqlite::params![url],
2344        ).unwrap();
2345    }
2346
2347    fn usage_count() -> i64 {
2348        let conn = crate::db::get_db_connection_guard_static().unwrap();
2349        conn.query_row("SELECT COUNT(*) FROM emoji_usage", [], |r| r.get(0)).unwrap()
2350    }
2351
2352    fn pack_status(addr: &str) -> u8 {
2353        load_cached_pack(addr).unwrap().unwrap().status
2354    }
2355
2356    fn build_deletion_event(k: &Keys, addr: &str) -> Event {
2357        EventBuilder::new(Kind::EventDeletion, "")
2358            .tag(Tag::custom("a", [addr]))
2359            .finalize(k)
2360            .unwrap()
2361    }
2362
2363    #[test]
2364    fn classify_verdict_table() {
2365        let k = keys();
2366        let live = build_pack_event(&k, "p", None, None, None, &[("a", "https://e.x/a.png")]);
2367        let empty = build_pack_event(&k, "p", None, None, None, &[]);
2368        let addr = format!("30030:{}:p", k.public_key().to_hex());
2369        let del = build_deletion_event(&k, &addr);
2370
2371        // Live event, no deletion → Found (regardless of the absence gate).
2372        let (o, p) = classify_pack(Some(&live), None, None, false);
2373        assert_eq!(o, PackFetchOutcome::Found);
2374        assert!(p.is_some());
2375
2376        // Empty replacement (Vector's own delete shape) → Tombstoned.
2377        let (o, _) = classify_pack(Some(&empty), None, None, true);
2378        assert_eq!(o, PackFetchOutcome::Tombstoned);
2379
2380        // Kind-5 only, no event at all → Tombstoned.
2381        let (o, _) = classify_pack(None, Some(&del), None, true);
2382        assert_eq!(o, PackFetchOutcome::Tombstoned);
2383
2384        // Timestamps pinned: a second boundary between two wall-clock builders
2385        // would otherwise flip the comparison and flake the test.
2386        let ts = Timestamp::from_secs(1_700_000_000);
2387        let live_pinned = EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2388            .tags(vec![
2389                Tag::custom("d", ["p"]),
2390                Tag::custom("emoji", ["a", "https://e.x/a.png"]),
2391            ])
2392            .custom_created_at(ts)
2393            .finalize(&k)
2394            .unwrap();
2395        let del_at = |secs: u64| {
2396            EventBuilder::new(Kind::EventDeletion, "")
2397                .tag(Tag::custom("a", [addr.as_str()]))
2398                .custom_created_at(Timestamp::from_secs(secs))
2399                .finalize(&k)
2400                .unwrap()
2401        };
2402
2403        // Kind-5 with an EQUAL timestamp to a live event: the pack wins
2404        // (fail-safe toward alive).
2405        let (o, _) = classify_pack(Some(&live_pinned), Some(&del_at(1_700_000_000)), None, false);
2406        assert_eq!(o, PackFetchOutcome::Found);
2407        // A NEWER deletion tombstones the older live event.
2408        let (o, _) = classify_pack(Some(&live_pinned), Some(&del_at(1_700_000_001)), None, false);
2409        assert_eq!(o, PackFetchOutcome::Tombstoned);
2410        // An OLDER deletion loses to a republish.
2411        let (o, _) = classify_pack(Some(&live_pinned), Some(&del_at(1_699_999_999)), None, false);
2412        assert_eq!(o, PackFetchOutcome::Found);
2413
2414        // Nothing found: gate decides.
2415        let (o, _) = classify_pack(None, None, None, true);
2416        assert_eq!(o, PackFetchOutcome::CleanMiss);
2417        let (o, _) = classify_pack(None, None, None, false);
2418        assert_eq!(o, PackFetchOutcome::Unreachable);
2419    }
2420
2421    #[test]
2422    fn classify_invalid_emojis_is_not_a_tombstone() {
2423        // An event that HAS emoji tags Vector merely can't validate (bad
2424        // shortcode charset) must judge nothing, not brand the author.
2425        let k = keys();
2426        let ev = build_pack_event(&k, "weird", None, None, None, &[("bad!code", "https://e.x/a.png")]);
2427        assert!(parse_pack_from_event(&ev, None).is_none(), "precondition: unparseable");
2428        let (o, _) = classify_pack(Some(&ev), None, None, true);
2429        assert_eq!(o, PackFetchOutcome::Unreachable);
2430    }
2431
2432    #[test]
2433    fn absence_gate_table() {
2434        let some_writes = vec![RelayUrl::parse("wss://relay.author.example").unwrap()];
2435        let no_writes: Vec<RelayUrl> = Vec::new();
2436
2437        // Home failed or too few live relays: never clean.
2438        assert!(!absence_is_clean(false, 5, Some(&no_writes), true, 1));
2439        assert!(!absence_is_clean(true, 1, Some(&no_writes), true, 1));
2440        // Author outbox unknown (NIP-65 cold / fetch failed): not clean —
2441        // the pack's canonical home was never really checked.
2442        assert!(!absence_is_clean(true, 3, None, true, 1));
2443        // Author verifiably lists no write relays: home evidence suffices.
2444        assert!(absence_is_clean(true, 2, Some(&no_writes), false, 0));
2445        // Author outbox known: it must have been swept live.
2446        assert!(!absence_is_clean(true, 3, Some(&some_writes), false, 0));
2447        assert!(!absence_is_clean(true, 3, Some(&some_writes), true, 0));
2448        assert!(absence_is_clean(true, 3, Some(&some_writes), true, 1));
2449    }
2450
2451    #[test]
2452    fn deletion_matching_is_author_bound() {
2453        let author = keys();
2454        let stranger = keys();
2455        let addr = format!("30030:{}:p", author.public_key().to_hex());
2456        // A third party citing the coordinate must never count as a revocation.
2457        let forged = build_deletion_event(&stranger, &addr);
2458        assert!(!deletion_matches(&forged, &author.public_key(), &addr));
2459        let real = build_deletion_event(&author, &addr);
2460        assert!(deletion_matches(&real, &author.public_key(), &addr));
2461    }
2462
2463    #[test]
2464    fn sendable_emojis_name_what_the_send_resolves() {
2465        let (_tmp, _guard) = init_test_db();
2466        let (a, b) = (keys(), keys());
2467        let pa = seed_pack(&a, "one", &[("love", "https://b.x/love.gif"), ("cat", "https://a.x/cat.png")]);
2468        let pb = seed_pack(&b, "two", &[("love", "https://a.x/love.gif"), ("cat", "https://a.x/cat.png")]);
2469        let off = seed_pack(&keys(), "unsubscribed", &[("dog", "https://a.x/dog.png")]);
2470        save_subscriptions(&[pa.clone(), pb.clone()]).unwrap();
2471
2472        let list = sendable_emojis();
2473        let mut codes: Vec<&str> = list.iter().map(|e| e.code.as_str()).collect();
2474        codes.sort();
2475        // A shared image collapses to one plain code; differing images number by URL.
2476        assert_eq!(codes, ["cat", "love~1", "love~2"]);
2477        assert!(!list.iter().any(|e| e.pack.as_deref() == naddr_from_addr(&off).ok().as_deref()));
2478        for e in &list {
2479            let tags = resolve_outbound_emoji_tags(&format!("hi :{}:", e.code));
2480            assert_eq!(tags.len(), 1);
2481            assert_eq!((tags[0].shortcode.as_str(), tags[0].url.as_str()), (e.code.as_str(), e.url.as_str()));
2482        }
2483    }
2484
2485    #[test]
2486    fn tombstone_revokes_immediately_and_purges_frecency() {
2487        let (_tmp, _guard) = init_test_db();
2488        let k = keys();
2489        let addr = seed_pack(&k, "deadpack", &[("boom", "https://e.x/boom.png")]);
2490        seed_usage("https://e.x/boom.png");
2491        seed_usage("https://e.x/unrelated.png");
2492
2493        let changed = apply_pack_health(&addr, &PackFetchOutcome::Tombstoned, 1_000).unwrap();
2494        assert!(changed, "tombstone must flip status in one sweep");
2495        assert_eq!(pack_status(&addr), PACK_STATUS_REVOKED);
2496        assert_eq!(usage_count(), 1, "only the dead pack's usage rows purge");
2497    }
2498
2499    #[test]
2500    fn found_self_heals_from_revoked() {
2501        let (_tmp, _guard) = init_test_db();
2502        let k = keys();
2503        let addr = seed_pack(&k, "phoenix", &[("rise", "https://e.x/r.png")]);
2504        apply_pack_health(&addr, &PackFetchOutcome::Tombstoned, 1_000).unwrap();
2505        assert_eq!(pack_status(&addr), PACK_STATUS_REVOKED);
2506
2507        let changed = apply_pack_health(&addr, &PackFetchOutcome::Found, 2_000).unwrap();
2508        assert!(changed);
2509        assert_eq!(pack_status(&addr), PACK_STATUS_ACTIVE, "a republished pack revives");
2510    }
2511
2512    #[test]
2513    fn clean_miss_gauntlet_rate_limit_and_promotion() {
2514        let (_tmp, _guard) = init_test_db();
2515        let k = keys();
2516        let addr = seed_pack(&k, "fading", &[("bye", "https://e.x/bye.png")]);
2517        let t0: i64 = 1_000_000;
2518        let h = 3_600;
2519
2520        // First miss counts; a second inside the rate-limit window doesn't.
2521        assert!(!apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t0).unwrap());
2522        assert!(!apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t0 + h).unwrap());
2523        // Two more spaced misses reach the count, but 48h hasn't elapsed yet.
2524        assert!(!apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t0 + 13 * h).unwrap());
2525        assert!(!apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t0 + 26 * h).unwrap());
2526        assert_eq!(pack_status(&addr), PACK_STATUS_ACTIVE, "count alone must not promote");
2527        // Past both thresholds: promoted.
2528        let changed = apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t0 + 49 * h).unwrap();
2529        assert!(changed);
2530        assert_eq!(pack_status(&addr), PACK_STATUS_MISSING);
2531    }
2532
2533    #[test]
2534    fn unreachable_never_moves_counters() {
2535        let (_tmp, _guard) = init_test_db();
2536        let k = keys();
2537        let addr = seed_pack(&k, "offline", &[("zz", "https://e.x/z.png")]);
2538        for t in [1_000i64, 200_000, 400_000, 800_000] {
2539            assert!(!apply_pack_health(&addr, &PackFetchOutcome::Unreachable, t).unwrap());
2540        }
2541        assert_eq!(pack_status(&addr), PACK_STATUS_ACTIVE);
2542        let conn = crate::db::get_db_connection_guard_static().unwrap();
2543        let miss: i64 = conn.query_row(
2544            "SELECT miss_count FROM emoji_packs WHERE addr = ?1",
2545            rusqlite::params![addr], |r| r.get(0),
2546        ).unwrap();
2547        assert_eq!(miss, 0, "offline sweeps must not accrue misses");
2548    }
2549
2550    #[test]
2551    fn revoked_ignores_clean_misses() {
2552        let (_tmp, _guard) = init_test_db();
2553        let k = keys();
2554        let addr = seed_pack(&k, "sealed", &[("x", "https://e.x/x.png")]);
2555        apply_pack_health(&addr, &PackFetchOutcome::Tombstoned, 1_000).unwrap();
2556        for t in [100_000i64, 300_000, 600_000] {
2557            assert!(!apply_pack_health(&addr, &PackFetchOutcome::CleanMiss, t).unwrap());
2558        }
2559        assert_eq!(pack_status(&addr), PACK_STATUS_REVOKED, "misses can't downgrade a tombstone verdict");
2560    }
2561
2562    #[test]
2563    fn empty_pack_event_is_the_tombstone_shape() {
2564        // Vector's own delete flow publishes an empty replacement; the parser
2565        // must keep rejecting it so the sweep can read that rejection as a
2566        // deterministic tombstone.
2567        let k = keys();
2568        let ev = build_pack_event(&k, "gone", None, None, None, &[]);
2569        assert!(parse_pack_from_event(&ev, None).is_none());
2570    }
2571
2572    #[test]
2573    fn parse_pack_reads_nip51_spec_tags() {
2574        let k = keys();
2575        let ev = build_pack_event(
2576            &k, "myPack",
2577            Some(("title", "Spec Pack")),
2578            Some(("image", "https://example.com/p.png")),
2579            Some(("description", "specd")),
2580            &[("smile", "https://e.x/s.png"), ("heart", "https://e.x/h.png")],
2581        );
2582        let pack = parse_pack_from_event(&ev, None).unwrap();
2583        assert_eq!(pack.identifier, "myPack");
2584        assert_eq!(pack.title, "Spec Pack");
2585        assert_eq!(pack.image_url, "https://example.com/p.png");
2586        assert_eq!(pack.description, "specd");
2587        assert_eq!(pack.emojis.len(), 2);
2588        assert_eq!(pack.addr(), format!("30030:{}:myPack", k.public_key().to_hex()));
2589    }
2590
2591    #[test]
2592    fn own_pack_event_carries_the_vector_client_tag() {
2593        // Packs we publish/edit must be attributable to Vector, matching the
2594        // ["client","vector"] tag our kind-0 profile publishes carry.
2595        let k = keys();
2596        let ev = build_pack_event(&k, "myPack", Some(("title", "Mine")), None, None, &[("smile", "https://e.x/s.png")]);
2597        let pack = parse_pack_from_event(&ev, None).unwrap();
2598        let built = super::build_pack_event(&pack).unwrap().finalize(&k).unwrap();
2599        let has_client = built.tags.iter().any(|t| {
2600            let s = t.as_slice();
2601            s.first().map(String::as_str) == Some("client") && s.get(1).map(String::as_str) == Some("vector")
2602        });
2603        assert!(has_client, "own pack event must carry the [\"client\",\"vector\"] tag");
2604    }
2605
2606    #[test]
2607    fn parse_pack_falls_back_to_ditto_tags_when_spec_missing() {
2608        let k = keys();
2609        let ev = build_pack_event(
2610            &k, "ditto",
2611            Some(("name", "Ditto Pack")),
2612            Some(("picture", "https://example.com/d.png")),
2613            Some(("about", "ditto-style")),
2614            &[("yes", "https://e.x/y.png")],
2615        );
2616        let pack = parse_pack_from_event(&ev, None).unwrap();
2617        assert_eq!(pack.title, "Ditto Pack");
2618        assert_eq!(pack.image_url, "https://example.com/d.png");
2619        assert_eq!(pack.description, "ditto-style");
2620    }
2621
2622    #[test]
2623    fn parse_pack_prefers_spec_tags_over_ditto() {
2624        let k = keys();
2625        let mut tags: Vec<Tag> = vec![
2626            Tag::custom("d", ["both"]),
2627            Tag::custom("title", ["SpecTitle"]),
2628            Tag::custom("name", ["DittoName"]),
2629            Tag::custom("image", ["spec.png"]),
2630            Tag::custom("picture", ["ditto.png"]),
2631            Tag::custom("emoji", ["a", "https://e.x/a.png"]),
2632        ];
2633        tags.extend(std::iter::empty());
2634        let ev = EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2635            .tags(tags).finalize(&k).unwrap();
2636        let pack = parse_pack_from_event(&ev, None).unwrap();
2637        assert_eq!(pack.title, "SpecTitle");
2638        assert_eq!(pack.image_url, "spec.png");
2639    }
2640
2641    #[test]
2642    fn parse_pack_returns_none_without_d_tag() {
2643        let k = keys();
2644        let ev = EventBuilder::new(Kind::Custom(KIND_EMOJI_SET), "")
2645            .tags(vec![
2646                Tag::custom("title", ["No D"]),
2647                Tag::custom("emoji", ["a", "https://e.x/a.png"]),
2648            ])
2649            .finalize(&k).unwrap();
2650        assert!(parse_pack_from_event(&ev, None).is_none());
2651    }
2652
2653    #[test]
2654    fn parse_pack_returns_none_when_no_valid_emojis() {
2655        let k = keys();
2656        let ev = build_pack_event(&k, "empty", Some(("title", "Empty")), None, None, &[]);
2657        assert!(parse_pack_from_event(&ev, None).is_none());
2658    }
2659
2660    #[test]
2661    fn parse_pack_rejects_invalid_shortcodes() {
2662        let k = keys();
2663        let ev = build_pack_event(
2664            &k, "mix", Some(("title", "Mix")), None, None,
2665            &[("ok_name", "https://e.x/a.png"),
2666              ("bad name", "https://e.x/b.png"),
2667              ("colons:no", "https://e.x/c.png"),
2668              ("", "https://e.x/d.png"),
2669              ("dash-ok", "https://e.x/e.png")],
2670        );
2671        let pack = parse_pack_from_event(&ev, None).unwrap();
2672        let codes: Vec<&str> = pack.emojis.iter().map(|e| e.shortcode.as_str()).collect();
2673        assert_eq!(codes, vec!["ok_name", "dash-ok"]);
2674    }
2675
2676    #[test]
2677    fn parse_pack_dedupes_shortcodes_first_wins() {
2678        let k = keys();
2679        let ev = build_pack_event(
2680            &k, "dup", Some(("title", "Dup")), None, None,
2681            &[("smile", "https://e.x/first.png"),
2682              ("smile", "https://e.x/second.png")],
2683        );
2684        let pack = parse_pack_from_event(&ev, None).unwrap();
2685        assert_eq!(pack.emojis.len(), 1);
2686        assert_eq!(pack.emojis[0].url, "https://e.x/first.png");
2687    }
2688
2689    #[test]
2690    fn parse_pack_marks_is_own_only_when_my_pubkey_matches() {
2691        let k = keys();
2692        let ev = build_pack_event(&k, "mine", Some(("title", "Mine")), None, None,
2693            &[("a", "https://e.x/a.png")]);
2694        let my_hex = k.public_key().to_hex();
2695        let pack_mine = parse_pack_from_event(&ev, Some(&my_hex)).unwrap();
2696        assert!(pack_mine.is_own);
2697
2698        let stranger = keys().public_key().to_hex();
2699        let pack_other = parse_pack_from_event(&ev, Some(&stranger)).unwrap();
2700        assert!(!pack_other.is_own);
2701    }
2702
2703    #[test]
2704    fn pack_address_to_string_round_trips() {
2705        let k = keys();
2706        let hex = k.public_key().to_hex();
2707        let addr = PackAddress {
2708            kind: 30030,
2709            pubkey: k.public_key(),
2710            identifier: "myPack".to_string(),
2711        };
2712        assert_eq!(addr.to_addr_string(), format!("30030:{}:myPack", hex));
2713        let parsed = parse_pack_address(&addr.to_addr_string()).unwrap();
2714        assert_eq!(parsed, addr);
2715    }
2716
2717    #[test]
2718    fn parse_naddr_round_trips_kind_30030_coordinate() {
2719        // Construct a synthetic naddr via nostr-sdk and verify our decoder
2720        // round-trips kind / pubkey / identifier.
2721        let k = keys();
2722        let coord = nostr_sdk::prelude::nip01::Coordinate {
2723            kind: Kind::Custom(30030),
2724            public_key: k.public_key(),
2725            identifier: "trip".to_string(),
2726        };
2727        let n19 = nostr_sdk::prelude::nip19::Nip19Coordinate {
2728            coordinate: coord,
2729            relays: Vec::new(),
2730        };
2731        let naddr = nostr_sdk::prelude::nip19::Nip19::Coordinate(n19).to_bech32().unwrap();
2732        let parsed = parse_naddr(&naddr).unwrap();
2733        assert_eq!(parsed.kind, 30030);
2734        assert_eq!(parsed.pubkey, k.public_key());
2735        assert_eq!(parsed.identifier, "trip");
2736    }
2737
2738    #[test]
2739    fn parse_naddr_rejects_non_30030_kinds() {
2740        let k = keys();
2741        let coord = nostr_sdk::prelude::nip01::Coordinate {
2742            kind: Kind::Custom(30023), // long-form article
2743            public_key: k.public_key(),
2744            identifier: "essay".to_string(),
2745        };
2746        let n19 = nostr_sdk::prelude::nip19::Nip19Coordinate {
2747            coordinate: coord,
2748            relays: Vec::new(),
2749        };
2750        let naddr = nostr_sdk::prelude::nip19::Nip19::Coordinate(n19).to_bech32().unwrap();
2751        let err = parse_naddr(&naddr).unwrap_err();
2752        assert!(err.contains("expected kind 30030"),
2753            "expected kind-rejection error, got: {}", err);
2754    }
2755
2756    #[test]
2757    fn parse_naddr_strips_nostr_uri_prefix() {
2758        let k = keys();
2759        let coord = nostr_sdk::prelude::nip01::Coordinate {
2760            kind: Kind::Custom(30030),
2761            public_key: k.public_key(),
2762            identifier: "prefixed".to_string(),
2763        };
2764        let n19 = nostr_sdk::prelude::nip19::Nip19Coordinate {
2765            coordinate: coord,
2766            relays: Vec::new(),
2767        };
2768        let naddr = nostr_sdk::prelude::nip19::Nip19::Coordinate(n19).to_bech32().unwrap();
2769        let with_prefix = format!("nostr:{}", naddr);
2770        let parsed = parse_naddr(&with_prefix).unwrap();
2771        assert_eq!(parsed.identifier, "prefixed");
2772    }
2773
2774    #[test]
2775    fn parse_naddr_rejects_garbage_input() {
2776        assert!(parse_naddr("not an naddr").is_err());
2777        assert!(parse_naddr("naddr1invalid").is_err());
2778        assert!(parse_naddr("").is_err());
2779    }
2780
2781    #[test]
2782    fn parse_pack_address_round_trips_valid_input() {
2783        let k = keys();
2784        let hex = k.public_key().to_hex();
2785        let addr = format!("30030:{}:myId", hex);
2786        let parsed = parse_pack_address(&addr).unwrap();
2787        assert_eq!(parsed.kind, 30030);
2788        assert_eq!(parsed.pubkey, k.public_key());
2789        assert_eq!(parsed.identifier, "myId");
2790    }
2791
2792    #[test]
2793    fn an_emoji_list_reads_its_public_packs_and_keeps_ours_when_another_client_wrote_it() {
2794        let hex = keys().public_key().to_hex();
2795        let addr = |d: &str| format!("30030:{hex}:{d}");
2796        let (ours, theirs, gone) = (addr("ours"), addr("theirs"), addr("gone"));
2797
2798        let merged = merge_emoji_list(Some(vec![ours.clone()]), &[theirs.clone(), ours.clone()], &[], &[]);
2799        assert_eq!(merged, [ours.clone(), theirs.clone()], "private order first, public appended once");
2800
2801        // Another client rewrote the list without our encrypted part, and dropped `gone`.
2802        let local = [ours.clone(), gone.clone()];
2803        let merged = merge_emoji_list(None, &[theirs.clone()], &local, &[gone.clone()]);
2804        assert_eq!(merged, [ours.clone(), theirs.clone()], "our private pick survives; a dropped public pack goes");
2805    }
2806
2807    #[test]
2808    fn a_published_emoji_list_carries_public_tags_but_not_unsubscribed_packs() {
2809        let hex = keys().public_key().to_hex();
2810        let kept = format!("30030:{hex}:kept");
2811        let dropped = format!("30030:{hex}:dropped");
2812        let public = vec![
2813            vec!["a".to_string(), kept.clone()],
2814            vec!["a".to_string(), dropped],
2815            vec!["emoji".to_string(), "wave".to_string(), "https://x/w.png".to_string()],
2816        ];
2817        let ours = format!("30030:{hex}:ours");
2818        let carried = carried_public_tags(&public, &[kept.clone(), ours]);
2819        assert_eq!(carried, [public[0].clone(), public[2].clone()], "a pack followed in Vector never goes public");
2820        assert!(carried_public_tags(&[], &[kept]).is_empty(), "nothing public to carry, nothing public written");
2821    }
2822
2823    #[test]
2824    fn parse_pack_address_rejects_wrong_kind() {
2825        let hex = keys().public_key().to_hex();
2826        let addr = format!("10030:{}:x", hex);
2827        assert!(parse_pack_address(&addr).is_err());
2828    }
2829
2830    #[test]
2831    fn parse_pack_address_rejects_malformed_pubkey() {
2832        let addr = "30030:not-hex:x".to_string();
2833        assert!(parse_pack_address(&addr).is_err());
2834    }
2835
2836    #[test]
2837    fn parse_pack_address_preserves_colons_in_identifier() {
2838        // d-tag values can be arbitrary strings, including colons.
2839        let hex = keys().public_key().to_hex();
2840        let addr = format!("30030:{}:id:with:colons", hex);
2841        let parsed = parse_pack_address(&addr).unwrap();
2842        assert_eq!(parsed.identifier, "id:with:colons");
2843    }
2844
2845    #[test]
2846    fn parse_inner_tag_list_extracts_valid_a_tags() {
2847        // The inner tag list lives JSON-encoded inside the NIP-44-encrypted
2848        // event content; exercise the parser directly so we don't pull a
2849        // signer + network into a unit test.
2850        let hex_a = keys().public_key().to_hex();
2851        let hex_b = keys().public_key().to_hex();
2852        let plaintext = format!(
2853            r#"[["a","30030:{a}:packA"],["a","30030:{b}:packB"],["a","malformed"],["a","10030:{a}:wrongkind"],["p","not-an-a-tag"]]"#,
2854            a = hex_a,
2855            b = hex_b,
2856        );
2857        let addrs = parse_inner_tag_list(&plaintext);
2858        assert_eq!(addrs.len(), 2);
2859        assert_eq!(addrs[0].identifier, "packA");
2860        assert_eq!(addrs[1].identifier, "packB");
2861    }
2862
2863    #[test]
2864    fn parse_inner_tag_list_returns_empty_on_malformed_json() {
2865        assert!(parse_inner_tag_list("not json").is_empty());
2866        assert!(parse_inner_tag_list("").is_empty());
2867    }
2868
2869    #[test]
2870    fn theme_slot_marker_round_trips_through_publish_and_parse() {
2871        // Three packs, theme slot anchored after the 2nd. Build the inner
2872        // tuples exactly as publish does, serialise, then parse back.
2873        let a = keys().public_key().to_hex();
2874        let b = keys().public_key().to_hex();
2875        let c = keys().public_key().to_hex();
2876        let addr_a = format!("30030:{}:packA", a);
2877        let addr_b = format!("30030:{}:packB", b);
2878        let addr_c = format!("30030:{}:packC", c);
2879        let addrs = vec![addr_a.clone(), addr_b.clone(), addr_c.clone()];
2880
2881        let inner = build_inner_tags_with_marker(&addrs, &addr_b);
2882        let marker_count = inner.iter()
2883            .filter(|t| t.first().map(String::as_str) == Some(THEME_SLOT_TOKEN))
2884            .count();
2885        assert_eq!(marker_count, 1, "exactly one marker is emitted");
2886
2887        let plaintext = serde_json::to_string(&inner).unwrap();
2888        let (parsed, anchor) = parse_inner_tag_list_with_anchor(&plaintext);
2889        assert_eq!(parsed, addrs, "addr order survives the round trip");
2890        assert_eq!(anchor.as_deref(), Some(addr_b.as_str()), "anchor is the 2nd pack");
2891
2892        // Old-format list (no marker tuple) → None anchor.
2893        let old = format!(r#"[["a","{}"],["a","{}"]]"#, addr_a, addr_b);
2894        let (old_addrs, old_anchor) = parse_inner_tag_list_with_anchor(&old);
2895        assert_eq!(old_addrs, vec![addr_a.clone(), addr_b.clone()]);
2896        assert_eq!(old_anchor, None, "a list without the marker has no anchor");
2897
2898        // Marker at the top → empty-string anchor.
2899        let top = build_inner_tags_with_marker(&addrs, "");
2900        assert_eq!(top[0], vec![THEME_SLOT_TOKEN.to_string()]);
2901        let (_, top_anchor) =
2902            parse_inner_tag_list_with_anchor(&serde_json::to_string(&top).unwrap());
2903        assert_eq!(top_anchor.as_deref(), Some(""), "top slot = empty anchor");
2904
2905        // Anchor naming a pack no longer subscribed falls back to the top.
2906        let gone = format!("30030:{}:ghost", keys().public_key().to_hex());
2907        let fallback = build_inner_tags_with_marker(&addrs, &gone);
2908        assert_eq!(fallback[0], vec![THEME_SLOT_TOKEN.to_string()]);
2909        let fb_markers = fallback.iter()
2910            .filter(|t| t.first().map(String::as_str) == Some(THEME_SLOT_TOKEN))
2911            .count();
2912        assert_eq!(fb_markers, 1, "still exactly one marker on the fallback path");
2913    }
2914
2915    #[test]
2916    fn shortcode_validator_accepts_alphanum_dash_underscore() {
2917        assert!(is_valid_shortcode("smile"));
2918        assert!(is_valid_shortcode("smile_face"));
2919        assert!(is_valid_shortcode("smile-face"));
2920        assert!(is_valid_shortcode("Smile2"));
2921        assert!(!is_valid_shortcode(""));
2922        assert!(!is_valid_shortcode("smile face"));
2923        assert!(!is_valid_shortcode("smile:face"));
2924        assert!(!is_valid_shortcode("😀"));
2925        // `~` is reserved for message-tag disambiguation, NOT valid in
2926        // pack-authored shortcodes.
2927        assert!(!is_valid_shortcode("love~2"));
2928    }
2929
2930    #[test]
2931    fn resolve_token_disambiguates_duplicate_shortcodes() {
2932        // Two distinct images share `:love:`, sorted lexicographically by URL.
2933        let mut by_code: HashMap<String, Vec<String>> = HashMap::new();
2934        by_code.insert(
2935            "love".to_string(),
2936            vec!["https://a.example/love.png".to_string(), "https://b.example/love.gif".to_string()],
2937        );
2938        by_code.insert("cat".to_string(), vec!["https://a.example/cat.png".to_string()]);
2939
2940        // Plain code → first candidate (matches a bare `:love:`).
2941        assert_eq!(resolve_emoji_token(&by_code, "love").as_deref(), Some("https://a.example/love.png"));
2942        // `~1` / `~2` select by 1-based index.
2943        assert_eq!(resolve_emoji_token(&by_code, "love~1").as_deref(), Some("https://a.example/love.png"));
2944        assert_eq!(resolve_emoji_token(&by_code, "love~2").as_deref(), Some("https://b.example/love.gif"));
2945        // Out-of-range / zero / unknown base → nothing (renders literal).
2946        assert_eq!(resolve_emoji_token(&by_code, "love~3"), None);
2947        assert_eq!(resolve_emoji_token(&by_code, "love~0"), None);
2948        assert_eq!(resolve_emoji_token(&by_code, "nope~1"), None);
2949        // Non-colliding code resolves bare; a stray `~N` on it is out of range.
2950        assert_eq!(resolve_emoji_token(&by_code, "cat").as_deref(), Some("https://a.example/cat.png"));
2951        assert_eq!(resolve_emoji_token(&by_code, "cat~2"), None);
2952    }
2953
2954    #[test]
2955    fn message_emoji_tags_accept_disambiguation_separator() {
2956        // Inbound `love~2` tags must survive parsing so the recipient renders.
2957        let tags = vec![
2958            vec!["emoji".to_string(), "love~2".to_string(), "https://b.example/love.gif".to_string()],
2959            vec!["emoji".to_string(), "bad name".to_string(), "https://x".to_string()],
2960        ];
2961        let out = crate::types::EmojiTag::extract_from_stored(&tags);
2962        assert_eq!(out.len(), 1);
2963        assert_eq!(out[0].shortcode, "love~2");
2964    }
2965}