Skip to main content

vector_core/db/
miniapps.rs

1//! Mini Apps database operations.
2//!
3//! This module handles:
4//! - Mini App history (recently opened apps)
5//! - Mini App favorites
6//! - Mini App permissions (per-app permission grants)
7//! - Marketplace app version tracking
8//! - Package metadata by content hash, and the hash of each package file
9
10use serde::{Deserialize, Serialize};
11
12// ============================================================================
13// Mini Apps History Functions
14// ============================================================================
15
16/// Mini App history entry
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct MiniAppHistoryEntry {
19    pub id: i64,
20    pub name: String,
21    pub src_url: String,
22    pub attachment_ref: String,
23    pub open_count: i64,
24    pub last_opened_at: i64,
25    pub is_favorite: bool,
26    /// Comma-separated list of categories (e.g., "game" or "app")
27    pub categories: String,
28    /// Optional marketplace app ID for linking to marketplace
29    pub marketplace_id: Option<String>,
30    /// Installed version of the app (for marketplace apps)
31    pub installed_version: Option<String>,
32}
33
34/// Record a Mini App being opened (upsert - insert or update)
35/// If the same name+src_url combo exists, update the attachment_ref, increment count, and update timestamp
36pub fn record_miniapp_opened(
37    name: String,
38    src_url: String,
39    attachment_ref: String,
40) -> Result<(), String> {
41    record_miniapp_opened_with_metadata(name, src_url, attachment_ref, String::new(), None, None)
42}
43
44/// Record a Mini App being opened with additional metadata (categories, marketplace_id, and version)
45pub fn record_miniapp_opened_with_metadata(
46    name: String,
47    src_url: String,
48    attachment_ref: String,
49    categories: String,
50    marketplace_id: Option<String>,
51    installed_version: Option<String>,
52) -> Result<(), String> {
53    let conn = super::get_write_connection_guard_static()?;
54
55    let now = crate::clock::now_secs() as i64;
56
57    // Use INSERT OR REPLACE with a subquery to preserve/increment open_count
58    // Uses UNIQUE(name) constraint - same app name always updates the existing entry
59    conn.execute(
60        r#"
61        INSERT INTO miniapps_history (name, src_url, attachment_ref, open_count, last_opened_at, categories, marketplace_id, installed_version)
62        VALUES (?1, ?2, ?3, 1, ?4, ?5, ?6, ?7)
63        ON CONFLICT(name) DO UPDATE SET
64            src_url = excluded.src_url,
65            attachment_ref = excluded.attachment_ref,
66            open_count = open_count + 1,
67            last_opened_at = excluded.last_opened_at,
68            categories = CASE WHEN excluded.categories != '' THEN excluded.categories ELSE categories END,
69            marketplace_id = CASE WHEN excluded.marketplace_id IS NOT NULL THEN excluded.marketplace_id ELSE marketplace_id END,
70            installed_version = CASE WHEN excluded.installed_version IS NOT NULL THEN excluded.installed_version ELSE installed_version END
71        "#,
72        rusqlite::params![name, src_url, attachment_ref, now, categories, marketplace_id, installed_version],
73    ).map_err(|e| format!("Failed to record Mini App opened: {}", e))?;
74
75
76    Ok(())
77}
78
79/// Get Mini Apps history sorted by last opened (most recent first)
80pub fn get_miniapps_history(
81    limit: Option<i64>,
82) -> Result<Vec<MiniAppHistoryEntry>, String> {
83    let conn = super::get_db_connection_guard_static()?;
84
85    let limit_val = limit.unwrap_or(50);
86
87    let mut stmt = conn.prepare(
88        r#"
89        SELECT id, name, src_url, attachment_ref, open_count, last_opened_at, is_favorite, categories, marketplace_id, installed_version
90        FROM miniapps_history
91        ORDER BY is_favorite DESC, last_opened_at DESC
92        LIMIT ?1
93        "#
94    ).map_err(|e| format!("Failed to prepare Mini Apps history query: {}", e))?;
95
96    let result: Vec<MiniAppHistoryEntry> = {
97        let entries = stmt.query_map(rusqlite::params![limit_val], |row| {
98            Ok(MiniAppHistoryEntry {
99                id: row.get(0)?,
100                name: row.get(1)?,
101                src_url: row.get(2)?,
102                attachment_ref: row.get(3)?,
103                open_count: row.get(4)?,
104                last_opened_at: row.get(5)?,
105                is_favorite: row.get::<_, i64>(6)? != 0,
106                categories: row.get(7)?,
107                marketplace_id: row.get(8)?,
108                installed_version: row.get(9)?,
109            })
110        }).map_err(|e| format!("Failed to query Mini Apps history: {}", e))?;
111
112        entries.filter_map(|e| e.ok()).collect()
113    };
114
115    Ok(result)
116}
117
118/// Toggle the favorite status of a Mini App by its ID
119pub fn toggle_miniapp_favorite(
120    id: i64,
121) -> Result<bool, String> {
122    let conn = super::get_write_connection_guard_static()?;
123
124    // Toggle the is_favorite value and return the new state
125    conn.execute(
126        "UPDATE miniapps_history SET is_favorite = NOT is_favorite WHERE id = ?1",
127        rusqlite::params![id],
128    ).map_err(|e| format!("Failed to toggle Mini App favorite: {}", e))?;
129
130    // Get the new favorite state
131    let new_state: bool = conn.query_row(
132        "SELECT is_favorite FROM miniapps_history WHERE id = ?1",
133        rusqlite::params![id],
134        |row| row.get::<_, i64>(0).map(|v| v != 0)
135    ).map_err(|e| format!("Failed to get Mini App favorite state: {}", e))?;
136
137
138    Ok(new_state)
139}
140
141/// Set the favorite status of a Mini App by its ID
142pub fn set_miniapp_favorite(
143    id: i64,
144    is_favorite: bool,
145) -> Result<(), String> {
146    let conn = super::get_write_connection_guard_static()?;
147
148    conn.execute(
149        "UPDATE miniapps_history SET is_favorite = ?1 WHERE id = ?2",
150        rusqlite::params![if is_favorite { 1 } else { 0 }, id],
151    ).map_err(|e| format!("Failed to set Mini App favorite: {}", e))?;
152
153
154    Ok(())
155}
156
157/// Remove a Mini App from history by name
158pub fn remove_miniapp_from_history(
159    name: &str,
160) -> Result<(), String> {
161    let conn = super::get_write_connection_guard_static()?;
162
163    conn.execute(
164        "DELETE FROM miniapps_history WHERE name = ?1",
165        rusqlite::params![name],
166    ).map_err(|e| format!("Failed to remove Mini App from history: {}", e))?;
167
168
169    Ok(())
170}
171
172/// Remove history entries whose package file no longer exists on disk (e.g.
173/// after a storage clear deleted the .xdc). A dead ref renders a broken tile
174/// that can only ever open to a file-not-found error.
175#[cfg(not(target_arch = "wasm32"))]
176pub fn prune_dangling_miniapp_history() -> Result<u32, String> {
177    let conn = super::get_write_connection_guard_static()?;
178
179    let rows: Vec<(i64, Option<String>)> = {
180        let mut stmt = conn.prepare(
181            "SELECT id, attachment_ref FROM miniapps_history"
182        ).map_err(|e| format!("Failed to query Mini Apps history: {}", e))?;
183        let mapped = stmt.query_map([], |row| {
184            Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(1)?))
185        }).map_err(|e| format!("Failed to iterate Mini Apps history: {}", e))?;
186        mapped.filter_map(|r| r.ok()).collect()
187    };
188
189    let mut removed = 0u32;
190    for (id, path) in rows {
191        // attachment_ref is the local package path; entries without one can't be validated
192        let Some(path) = path else { continue };
193        if path.is_empty() {
194            continue;
195        }
196        let gone = match crate::media::MediaRef::parse(&path) {
197            // An app kept in Vector is there while the store holds it.
198            Some(crate::media::MediaRef::Held(hash)) => !crate::media::store::holds(&hash),
199            // Fail closed: only prune on a definite "missing". A stat error
200            // (permissions, unmounted Android storage) must not delete valid rows
201            _ => matches!(std::path::Path::new(&path).try_exists(), Ok(false)),
202        };
203        if !gone {
204            continue;
205        }
206        conn.execute(
207            "DELETE FROM miniapps_history WHERE id = ?1",
208            rusqlite::params![id],
209        ).map_err(|e| format!("Failed to prune Mini App history entry: {}", e))?;
210        removed += 1;
211    }
212
213    // The same for package metadata: a file gone from disk, then whatever no file holds.
214    let files: Vec<String> = {
215        let mut stmt = conn.prepare("SELECT path FROM miniapp_files")
216            .map_err(|e| format!("Failed to query Mini App files: {}", e))?;
217        let mapped = stmt.query_map([], |row| row.get::<_, String>(0))
218            .map_err(|e| format!("Failed to iterate Mini App files: {}", e))?;
219        mapped.filter_map(|r| r.ok()).collect()
220    };
221    for path in files {
222        if matches!(std::path::Path::new(&path).try_exists(), Ok(false)) {
223            conn.execute("DELETE FROM miniapp_files WHERE path = ?1", rusqlite::params![path])
224                .map_err(|e| format!("Failed to prune Mini App file: {}", e))?;
225        }
226    }
227    conn.execute("DELETE FROM miniapp_meta WHERE file_hash NOT IN (SELECT file_hash FROM miniapp_files)", [])
228        .map_err(|e| format!("Failed to prune Mini App metadata: {}", e))?;
229
230    Ok(removed)
231}
232
233/// OPFS can't be probed synchronously, so the web never prunes.
234#[cfg(target_arch = "wasm32")]
235pub fn prune_dangling_miniapp_history() -> Result<u32, String> {
236    Ok(0)
237}
238
239// ============================================================================
240// Mini App Package Metadata
241// ============================================================================
242
243/// The content hash recorded for the package at `path`, while its size and modification time
244/// (nanoseconds since the epoch) are still the ones it was hashed at.
245pub fn miniapp_file_hash(path: &str, size: u64, modified: i64) -> Result<Option<[u8; 32]>, String> {
246    let conn = super::get_db_connection_guard_static()?;
247    let result = conn.query_row(
248        "SELECT file_hash FROM miniapp_files WHERE path = ?1 AND size = ?2 AND modified = ?3",
249        rusqlite::params![path, size as i64, modified],
250        |row| row.get::<_, Vec<u8>>(0),
251    );
252    match result {
253        Ok(hash) => Ok(hash.try_into().ok()),
254        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
255        Err(e) => Err(format!("Failed to read Mini App file hash: {}", e)),
256    }
257}
258
259pub fn set_miniapp_file_hash(path: &str, size: u64, modified: i64, file_hash: &[u8; 32]) -> Result<(), String> {
260    let conn = super::get_write_connection_guard_static()?;
261    conn.execute(
262        "INSERT OR REPLACE INTO miniapp_files (path, size, modified, file_hash) VALUES (?1, ?2, ?3, ?4)",
263        rusqlite::params![path, size as i64, modified, &file_hash[..]],
264    ).map_err(|e| format!("Failed to record Mini App file hash: {}", e))?;
265    Ok(())
266}
267
268/// A package's metadata, as the reader that stored it serialised it.
269pub fn miniapp_meta(file_hash: &[u8; 32]) -> Result<Option<String>, String> {
270    let conn = super::get_db_connection_guard_static()?;
271    let result = conn.query_row(
272        "SELECT data FROM miniapp_meta WHERE file_hash = ?1",
273        rusqlite::params![&file_hash[..]],
274        |row| row.get::<_, String>(0),
275    );
276    match result {
277        Ok(data) => Ok(Some(data)),
278        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
279        Err(e) => Err(format!("Failed to read Mini App metadata: {}", e)),
280    }
281}
282
283pub fn set_miniapp_meta(file_hash: &[u8; 32], data: &str) -> Result<(), String> {
284    let conn = super::get_write_connection_guard_static()?;
285    conn.execute(
286        "INSERT OR REPLACE INTO miniapp_meta (file_hash, data) VALUES (?1, ?2)",
287        rusqlite::params![&file_hash[..], data],
288    ).map_err(|e| format!("Failed to store Mini App metadata: {}", e))?;
289    Ok(())
290}
291
292/// Update the installed version for a marketplace app
293pub fn update_miniapp_version(
294    marketplace_id: &str,
295    version: &str,
296) -> Result<(), String> {
297    let conn = super::get_write_connection_guard_static()?;
298
299    conn.execute(
300        "UPDATE miniapps_history SET installed_version = ?1 WHERE marketplace_id = ?2",
301        rusqlite::params![version, marketplace_id],
302    ).map_err(|e| format!("Failed to update Mini App version: {}", e))?;
303
304
305    Ok(())
306}
307
308/// Get the installed version for a marketplace app by its marketplace_id
309pub fn get_miniapp_installed_version(
310    marketplace_id: &str,
311) -> Result<Option<String>, String> {
312    let conn = super::get_db_connection_guard_static()?;
313
314    let result = conn.query_row(
315        "SELECT installed_version FROM miniapps_history WHERE marketplace_id = ?1",
316        rusqlite::params![marketplace_id],
317        |row| row.get::<_, Option<String>>(0)
318    );
319
320
321
322    match result {
323        Ok(version) => Ok(version),
324        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
325        Err(e) => Err(format!("Failed to get Mini App installed version: {}", e)),
326    }
327}
328
329/// Backfill marketplace_id + installed_version for history entries that predate tracking.
330/// Matches the blossom hash in src_url filenames against the marketplace cache.
331/// Only hash-based matching is used — name matching is intentionally avoided to prevent
332/// phishing when public publishing is enabled.
333pub fn backfill_marketplace_ids(apps: &[crate::webxdc::MarketplaceApp]) -> Result<u32, String> {
334    let conn = super::get_write_connection_guard_static()?;
335
336    // Get history entries missing marketplace_id
337    let mut stmt = conn.prepare(
338        "SELECT id, src_url FROM miniapps_history WHERE marketplace_id IS NULL"
339    ).map_err(|e| format!("Failed to query orphan history: {}", e))?;
340
341    let orphans: Vec<(i64, String)> = stmt.query_map([], |row| {
342        Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
343    }).map_err(|e| format!("Failed to iterate orphans: {}", e))?
344      .filter_map(|r| r.ok())
345      .collect();
346
347    let mut updated = 0u32;
348    for (id, src_url) in &orphans {
349        // Extract hash from filename (e.g. ".../c7069f82...6fae.xdc" → "c7069f82...6fae")
350        let hash = src_url
351            .rsplit('/')
352            .next()
353            .and_then(|f| f.strip_suffix(".xdc"));
354        let hash = match hash {
355            Some(h) => h,
356            None => continue,
357        };
358
359        // Exact hash match → user has this exact file from the marketplace
360        if let Some(app) = apps.iter().find(|a| a.blossom_hash == hash) {
361            conn.execute(
362                "UPDATE miniapps_history SET marketplace_id = ?1, installed_version = ?2 WHERE id = ?3",
363                rusqlite::params![app.id, app.version, id],
364            ).map_err(|e| format!("Failed to backfill marketplace_id: {}", e))?;
365            updated += 1;
366        }
367    }
368
369    Ok(updated)
370}
371
372// ============================================================================
373// Mini App Permissions Functions
374// ============================================================================
375
376/// Get all granted permissions for a Mini App by its file hash
377/// Returns a comma-separated string of granted permission names
378pub fn get_miniapp_granted_permissions(
379    file_hash: &str,
380) -> Result<String, String> {
381    let conn = super::get_db_connection_guard_static()?;
382
383    let mut stmt = conn.prepare(
384        "SELECT permission FROM miniapp_permissions WHERE file_hash = ?1 AND granted = 1"
385    ).map_err(|e| format!("Failed to prepare permission query: {}", e))?;
386
387    let permissions: Vec<String> = stmt.query_map(rusqlite::params![file_hash], |row| {
388        row.get::<_, String>(0)
389    })
390    .map_err(|e| format!("Failed to query permissions: {}", e))?
391    .filter_map(|r| r.ok())
392    .collect();
393
394    Ok(permissions.join(","))
395}
396
397/// Set the granted status of a permission for a Mini App by its file hash
398pub fn set_miniapp_permission(
399    file_hash: &str,
400    permission: &str,
401    granted: bool,
402) -> Result<(), String> {
403    let conn = super::get_write_connection_guard_static()?;
404
405    let now = crate::clock::now_secs() as i64;
406
407    conn.execute(
408        r#"
409        INSERT INTO miniapp_permissions (file_hash, permission, granted, granted_at)
410        VALUES (?1, ?2, ?3, ?4)
411        ON CONFLICT(file_hash, permission) DO UPDATE SET
412            granted = excluded.granted,
413            granted_at = CASE WHEN excluded.granted = 1 THEN excluded.granted_at ELSE granted_at END
414        "#,
415        rusqlite::params![file_hash, permission, granted as i32, if granted { Some(now) } else { None::<i64> }],
416    ).map_err(|e| format!("Failed to set Mini App permission: {}", e))?;
417
418
419    Ok(())
420}
421
422/// Set multiple permissions at once for a Mini App by its file hash
423/// Uses a transaction to ensure all permissions are set atomically
424pub fn set_miniapp_permissions(
425    file_hash: &str,
426    permissions: &[(&str, bool)],
427) -> Result<(), String> {
428    let mut conn = super::get_write_connection_guard_static()?;
429
430    let now = crate::clock::now_secs() as i64;
431
432    let tx = conn.transaction()
433        .map_err(|e| format!("Failed to start transaction: {}", e))?;
434
435    for (permission, granted) in permissions {
436        tx.execute(
437            r#"
438            INSERT INTO miniapp_permissions (file_hash, permission, granted, granted_at)
439            VALUES (?1, ?2, ?3, ?4)
440            ON CONFLICT(file_hash, permission) DO UPDATE SET
441                granted = excluded.granted,
442                granted_at = CASE WHEN excluded.granted = 1 THEN excluded.granted_at ELSE granted_at END
443            "#,
444            rusqlite::params![file_hash, permission, *granted as i32, if *granted { Some(now) } else { None::<i64> }],
445        ).map_err(|e| format!("Failed to set Mini App permission: {}", e))?;
446    }
447
448    tx.commit()
449        .map_err(|e| format!("Failed to commit permission changes: {}", e))?;
450
451    Ok(())
452}
453
454/// Check if an app has been prompted for permissions yet (by file hash)
455/// Returns true if any permission record exists for this hash
456pub fn has_miniapp_permission_prompt(
457    file_hash: &str,
458) -> Result<bool, String> {
459    let conn = super::get_db_connection_guard_static()?;
460
461    let exists: bool = conn.query_row(
462        "SELECT EXISTS(SELECT 1 FROM miniapp_permissions WHERE file_hash = ?1)",
463        rusqlite::params![file_hash],
464        |row| row.get(0)
465    ).map_err(|e| format!("Failed to check permission prompt: {}", e))?;
466
467
468    Ok(exists)
469}
470
471/// Revoke all permissions for a Mini App by its file hash
472pub fn revoke_all_miniapp_permissions(
473    file_hash: &str,
474) -> Result<(), String> {
475    let conn = super::get_write_connection_guard_static()?;
476
477    conn.execute(
478        "DELETE FROM miniapp_permissions WHERE file_hash = ?1",
479        rusqlite::params![file_hash],
480    ).map_err(|e| format!("Failed to revoke Mini App permissions: {}", e))?;
481
482
483    Ok(())
484}
485
486// ============================================================================
487// Marketplace Cache Functions
488// ============================================================================
489
490/// Save marketplace apps to the SQLite cache (full replace).
491/// Upserts all provided apps and deletes any IDs not in the new set.
492pub fn save_marketplace_cache(apps: &[crate::webxdc::MarketplaceApp]) -> Result<(), String> {
493    let mut conn = super::get_write_connection_guard_static()?;
494
495    let now = crate::clock::now_secs() as i64;
496
497    let tx = conn.transaction()
498        .map_err(|e| format!("Failed to start marketplace cache transaction: {}", e))?;
499
500    // Upsert each app
501    for app in apps {
502        let json = serde_json::to_string(app)
503            .map_err(|e| format!("Failed to serialize marketplace app {}: {}", app.id, e))?;
504        tx.execute(
505            "INSERT OR REPLACE INTO marketplace_cache (id, data, fetched_at) VALUES (?1, ?2, ?3)",
506            rusqlite::params![app.id, json, now],
507        ).map_err(|e| format!("Failed to upsert marketplace app {}: {}", app.id, e))?;
508    }
509
510    // Delete any cached apps that are no longer in the fetched set
511    if !apps.is_empty() {
512        let placeholders: Vec<String> = (1..=apps.len()).map(|i| format!("?{}", i)).collect();
513        let sql = format!(
514            "DELETE FROM marketplace_cache WHERE id NOT IN ({})",
515            placeholders.join(",")
516        );
517        let ids: Vec<&str> = apps.iter().map(|a| a.id.as_str()).collect();
518        let params: Vec<&dyn rusqlite::types::ToSql> = ids.iter().map(|s| s as &dyn rusqlite::types::ToSql).collect();
519        tx.execute(&sql, params.as_slice())
520            .map_err(|e| format!("Failed to clean stale marketplace cache entries: {}", e))?;
521    }
522
523    tx.commit()
524        .map_err(|e| format!("Failed to commit marketplace cache: {}", e))?;
525
526    Ok(())
527}
528
529/// Load all marketplace apps from the SQLite cache.
530pub fn load_marketplace_cache() -> Result<Vec<crate::webxdc::MarketplaceApp>, String> {
531    let conn = super::get_db_connection_guard_static()?;
532
533    let mut stmt = conn.prepare(
534        "SELECT data FROM marketplace_cache"
535    ).map_err(|e| format!("Failed to prepare marketplace cache query: {}", e))?;
536
537    let apps: Vec<crate::webxdc::MarketplaceApp> = stmt.query_map([], |row| {
538        let json: String = row.get(0)?;
539        serde_json::from_str(&json).map_err(|e| {
540            rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e))
541        })
542    })
543    .map_err(|e| format!("Failed to query marketplace cache: {}", e))?
544    .filter_map(|r| r.ok())
545    .collect();
546
547    Ok(apps)
548}
549
550/// Copy all permissions from one file hash to another (for app updates)
551pub fn copy_miniapp_permissions(
552    old_hash: &str,
553    new_hash: &str,
554) -> Result<(), String> {
555    let conn = super::get_write_connection_guard_static()?;
556
557    // Copy all permission records from old hash to new hash
558    conn.execute(
559        r#"
560        INSERT OR REPLACE INTO miniapp_permissions (file_hash, permission, granted, granted_at)
561        SELECT ?2, permission, granted, granted_at
562        FROM miniapp_permissions
563        WHERE file_hash = ?1
564        "#,
565        rusqlite::params![old_hash, new_hash],
566    ).map_err(|e| format!("Failed to copy Mini App permissions: {}", e))?;
567
568
569    Ok(())
570}
571
572// ============================================================================
573// Peer Advertisement Queries (for realtime channel discovery)
574// ============================================================================
575
576/// A persisted peer advertisement record from SQLite.
577pub struct PeerAdvertisementRecord {
578    pub npub: String,
579    pub node_addr_encoded: String,
580}
581
582/// Get active peer advertisements for a topic.
583///
584/// Returns advertisements where the sender's most recent event for this topic
585/// is a "peer-advertisement" (not invalidated by a subsequent "peer-left").
586/// Excludes our own npub. Uses `reference_id` = topic_encoded (indexed).
587pub fn get_active_peer_advertisements(
588    topic_encoded: &str,
589    my_npub: &str,
590) -> Result<Vec<PeerAdvertisementRecord>, String> {
591    let conn = super::get_db_connection_guard_static()?;
592
593    // Latest ad per npub, dropped when a peer-left exists at the SAME OR LATER second —
594    // timestamps are second-granular, so an open-then-instant-close lands ad and left in
595    // the same second and the tombstone must win the tie (else a phantom "active" player
596    // survives for the hours-later rediscovery this table exists for).
597    let mut stmt = conn.prepare(
598        r#"
599        SELECT e.npub, e.tags
600        FROM events e
601        INNER JOIN (
602            SELECT npub, MAX(created_at) as max_ts
603            FROM events
604            WHERE kind = 30078
605              AND reference_id = ?1
606              AND content = 'peer-advertisement'
607              AND npub IS NOT NULL
608              AND npub != ?2
609            GROUP BY npub
610        ) latest ON e.npub = latest.npub AND e.created_at = latest.max_ts
611        WHERE e.kind = 30078
612          AND e.reference_id = ?1
613          AND e.content = 'peer-advertisement'
614          AND NOT EXISTS (
615              SELECT 1 FROM events l
616              WHERE l.kind = 30078
617                AND l.reference_id = ?1
618                AND l.npub = e.npub
619                AND l.content = 'peer-left'
620                AND l.created_at >= e.created_at
621          )
622        "#
623    ).map_err(|e| format!("Failed to prepare peer advertisement query: {}", e))?;
624
625    let records = stmt.query_map(
626        rusqlite::params![topic_encoded, my_npub],
627        |row| {
628            let npub: String = row.get(0)?;
629            let tags_json: String = row.get(1)?;
630
631            // Extract node_addr from tags JSON
632            let tags: Vec<Vec<String>> = serde_json::from_str(&tags_json).unwrap_or_default();
633            let node_addr = tags.iter()
634                .find(|t| t.first().map(|s| s.as_str()) == Some("webxdc-node-addr"))
635                .and_then(|t| t.get(1))
636                .cloned()
637                .unwrap_or_default();
638
639            Ok(PeerAdvertisementRecord {
640                npub,
641                node_addr_encoded: node_addr,
642            })
643        }
644    ).map_err(|e| format!("Failed to query peer advertisements: {}", e))?;
645
646    Ok(records.filter_map(|r| r.ok()).filter(|r| !r.node_addr_encoded.is_empty()).collect())
647}
648
649/// [`get_active_peer_advertisements`] limited to one chat, newest first, at most
650/// `limit`. A topic is one chat's session; an advertisement for it that arrived
651/// through any other chat (a stranger's DM, a channel whose ban dropped the live
652/// signal) names nobody who is playing here.
653pub fn get_active_peer_advertisements_in(
654    topic_encoded: &str,
655    chat_identifier: &str,
656    my_npub: &str,
657    limit: usize,
658) -> Result<Vec<PeerAdvertisementRecord>, String> {
659    let Ok(chat) = super::id_cache::get_chat_id_by_identifier(chat_identifier) else {
660        return Ok(Vec::new());
661    };
662    let conn = super::get_db_connection_guard_static()?;
663    let mut stmt = conn.prepare(
664        r#"
665        SELECT e.npub, e.tags
666        FROM events e
667        INNER JOIN (
668            SELECT npub, MAX(created_at) as max_ts
669            FROM events
670            WHERE kind = 30078 AND reference_id = ?1 AND chat_id = ?3
671              AND content = 'peer-advertisement' AND npub IS NOT NULL AND npub != ?2
672            GROUP BY npub
673        ) latest ON e.npub = latest.npub AND e.created_at = latest.max_ts
674        WHERE e.kind = 30078 AND e.reference_id = ?1 AND e.chat_id = ?3
675          AND e.content = 'peer-advertisement'
676          AND NOT EXISTS (
677              SELECT 1 FROM events l
678              WHERE l.kind = 30078 AND l.reference_id = ?1 AND l.chat_id = ?3
679                AND l.npub = e.npub AND l.content = 'peer-left' AND l.created_at >= e.created_at
680          )
681        ORDER BY e.created_at DESC
682        LIMIT ?4
683        "#,
684    ).map_err(|e| format!("Failed to prepare peer advertisement query: {}", e))?;
685    let records = stmt.query_map(rusqlite::params![topic_encoded, my_npub, chat, limit as i64], |row| {
686        let npub: String = row.get(0)?;
687        let tags: Vec<Vec<String>> = serde_json::from_str(&row.get::<_, String>(1)?).unwrap_or_default();
688        let node_addr_encoded = tags
689            .iter()
690            .find(|t| t.first().map(|s| s.as_str()) == Some("webxdc-node-addr"))
691            .and_then(|t| t.get(1))
692            .cloned()
693            .unwrap_or_default();
694        Ok(PeerAdvertisementRecord { npub, node_addr_encoded })
695    }).map_err(|e| format!("Failed to query peer advertisements: {}", e))?;
696    Ok(records.filter_map(|r| r.ok()).filter(|r| !r.node_addr_encoded.is_empty()).collect())
697}
698
699/// Is this peer signal still the CURRENT word on `npub`'s participation in `topic`?
700/// Gates the LIVE side of signal handling (session-peer add/remove, Iroh feed, lobby
701/// emit) so a replayed or out-of-order historical event can't resurrect a departed
702/// player (ad after left) or evict an active one (stale left after a newer ad).
703/// Tie-break mirrors `get_active_peer_advertisements`: on equal seconds the tombstone wins.
704pub fn peer_signal_is_current(
705    topic_encoded: &str,
706    npub: &str,
707    created_at: u64,
708    is_advertisement: bool,
709) -> Result<bool, String> {
710    let conn = super::get_db_connection_guard_static()?;
711    // An AD is superseded by ANY strictly-newer signal or a same-second left;
712    // a LEFT only by a strictly-newer ad.
713    let sql = if is_advertisement {
714        r#"SELECT EXISTS(
715            SELECT 1 FROM events
716            WHERE kind = 30078 AND reference_id = ?1 AND npub = ?2
717              AND ((content IN ('peer-advertisement','peer-left') AND created_at > ?3)
718                   OR (content = 'peer-left' AND created_at = ?3))
719        )"#
720    } else {
721        r#"SELECT EXISTS(
722            SELECT 1 FROM events
723            WHERE kind = 30078 AND reference_id = ?1 AND npub = ?2
724              AND content = 'peer-advertisement' AND created_at > ?3
725        )"#
726    };
727    let superseded: bool = conn
728        .query_row(sql, rusqlite::params![topic_encoded, npub, created_at as i64], |row| row.get(0))
729        .map_err(|e| format!("Failed to check peer signal currency: {}", e))?;
730    Ok(!superseded)
731}