vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
//! Profile database operations — read/write SlimProfile to SQLite.

use crate::profile::{SlimProfile, Status};

/// Load all profiles from the database.
pub fn get_all_profiles() -> Result<Vec<SlimProfile>, String> {
    let conn = super::get_db_connection_guard_static()?;

    let mut stmt = conn.prepare(
        "SELECT npub, name, display_name, nickname, lud06, lud16, banner, avatar, \
         about, website, nip05, status_content, status_url, bot, avatar_cached, \
         banner_cached, is_blocked, status_emoji_tags, stream_consent, checked_at FROM profiles"
    ).map_err(|e| format!("Failed to prepare statement: {}", e))?;

    let profiles = stmt.query_map([], |row| {
        Ok(SlimProfile {
            id: row.get(0)?,
            name: row.get(1)?,
            display_name: row.get(2)?,
            nickname: row.get(3)?,
            lud06: row.get(4)?,
            lud16: row.get(5)?,
            banner: row.get(6)?,
            avatar: row.get(7)?,
            about: row.get(8)?,
            website: row.get(9)?,
            nip05: row.get(10)?,
            status: Status {
                title: row.get(11)?,
                purpose: String::new(),
                url: row.get(12)?,
                emoji_tags: {
                    let json: String = row.get(17)?;
                    if json.is_empty() { Vec::new() }
                    else { serde_json::from_str(&json).unwrap_or_default() }
                },
            },
            last_updated: row.get::<_, i64>(19)?.max(0) as u64,
            mine: false,
            bot: row.get::<_, i32>(13)? != 0,
            avatar_cached: {
                let p: String = row.get(14)?;
                if !p.is_empty() && !cached_file_present(&p) { String::new() } else { p }
            },
            banner_cached: {
                let p: String = row.get(15)?;
                if !p.is_empty() && !cached_file_present(&p) { String::new() } else { p }
            },
            is_blocked: row.get::<_, i32>(16).unwrap_or(0) != 0,
            stream_consent: row.get::<_, i32>(18)? != 0,
        })
    })
    .map_err(|e| format!("Failed to query profiles: {}", e))?
    .collect::<Result<Vec<_>, _>>()
    .map_err(|e| format!("Failed to collect profiles: {}", e))?;

    Ok(profiles)
}

/// Upsert a profile to the database (INSERT ... ON CONFLICT DO UPDATE).
pub fn set_profile(profile: &SlimProfile) -> Result<(), String> {
    let conn = super::get_write_connection_guard_static()?;

    // Tags ride the row so a fresh boot renders status emojis without
    // waiting on (or even needing) a relay answer.
    let status_emoji_tags = if profile.status.emoji_tags.is_empty() {
        String::new()
    } else {
        serde_json::to_string(&profile.status.emoji_tags).unwrap_or_default()
    };

    conn.execute(
        "INSERT INTO profiles (npub, name, display_name, nickname, lud06, lud16, banner, avatar, \
         about, website, nip05, status_content, status_url, bot, avatar_cached, banner_cached, is_blocked, \
         status_emoji_tags, stream_consent, checked_at) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20) \
         ON CONFLICT(npub) DO UPDATE SET \
            name = excluded.name, display_name = excluded.display_name, \
            nickname = excluded.nickname, lud06 = excluded.lud06, lud16 = excluded.lud16, \
            banner = excluded.banner, avatar = excluded.avatar, about = excluded.about, \
            website = excluded.website, nip05 = excluded.nip05, \
            status_content = excluded.status_content, status_url = excluded.status_url, \
            bot = excluded.bot, avatar_cached = excluded.avatar_cached, \
            banner_cached = excluded.banner_cached, is_blocked = excluded.is_blocked, \
            status_emoji_tags = excluded.status_emoji_tags, stream_consent = excluded.stream_consent, \
            checked_at = MAX(checked_at, excluded.checked_at)",
        rusqlite::params![
            profile.id,
            profile.name,
            profile.display_name,
            profile.nickname,
            profile.lud06,
            profile.lud16,
            profile.banner,
            profile.avatar,
            profile.about,
            profile.website,
            profile.nip05,
            profile.status.title,
            profile.status.url,
            profile.bot as i32,
            profile.avatar_cached,
            profile.banner_cached,
            profile.is_blocked as i32,
            status_emoji_tags,
            profile.stream_consent as i32,
            profile.last_updated as i64,
        ],
    ).map_err(|e| format!("Failed to insert profile: {}", e))?;

    Ok(())
}

/// Record that the relays were asked for this profile at `secs`, whether or not it changed.
pub fn mark_profile_checked(npub: &str, secs: u64) -> Result<(), String> {
    let conn = super::get_write_connection_guard_static()?;
    conn.execute(
        "UPDATE profiles SET checked_at = MAX(checked_at, ?2) WHERE npub = ?1",
        rusqlite::params![npub, secs as i64],
    )
    .map_err(|e| format!("Failed to mark profile checked: {e}"))?;
    Ok(())
}

/// Whether a cached image path still points at a file. The web keeps its cache
/// in OPFS, which only answers asynchronously, so a local path is trusted there.
fn cached_file_present(path: &str) -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        // A remote URL stands in when no proxy could fetch it; don't keep it past this session.
        path.starts_with('/')
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        std::path::Path::new(path).exists()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        use nostr_sdk::prelude::ToBech32;
        let tmp = tempfile::tempdir().unwrap();
        let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        (tmp, guard)
    }

    fn stored(npub: &str) -> SlimProfile {
        get_all_profiles().unwrap().into_iter().find(|p| p.id == npub).unwrap()
    }

    #[test]
    fn stream_consent_survives_the_database() {
        let (_tmp, _guard) = init_test_db();
        let npub = "npub1streamconsent";
        let mut slim = SlimProfile { id: npub.into(), name: "a".into(), stream_consent: true, ..Default::default() };
        set_profile(&slim).unwrap();
        assert!(stored(npub).stream_consent);

        slim.stream_consent = false;
        set_profile(&slim).unwrap();
        assert!(!stored(npub).stream_consent, "the upsert clears it too");
    }

    #[test]
    fn a_row_written_without_the_column_reads_as_no_consent() {
        let (_tmp, _guard) = init_test_db();
        crate::db::get_write_connection_guard_static()
            .unwrap()
            .execute("INSERT INTO profiles (npub, name) VALUES ('npub1legacyrow', 'old')", [])
            .unwrap();
        assert!(!stored("npub1legacyrow").stream_consent);
    }
}