1use crate::profile::{SlimProfile, Status};
4
5pub fn get_all_profiles() -> Result<Vec<SlimProfile>, String> {
7 let conn = super::get_db_connection_guard_static()?;
8
9 let mut stmt = conn.prepare(
10 "SELECT npub, name, display_name, nickname, lud06, lud16, banner, avatar, \
11 about, website, nip05, status_content, status_url, bot, avatar_cached, \
12 banner_cached, is_blocked, status_emoji_tags, stream_consent, checked_at FROM profiles"
13 ).map_err(|e| format!("Failed to prepare statement: {}", e))?;
14
15 let profiles = stmt.query_map([], |row| {
16 Ok(SlimProfile {
17 id: row.get(0)?,
18 name: row.get(1)?,
19 display_name: row.get(2)?,
20 nickname: row.get(3)?,
21 lud06: row.get(4)?,
22 lud16: row.get(5)?,
23 banner: row.get(6)?,
24 avatar: row.get(7)?,
25 about: row.get(8)?,
26 website: row.get(9)?,
27 nip05: row.get(10)?,
28 status: Status {
29 title: row.get(11)?,
30 purpose: String::new(),
31 url: row.get(12)?,
32 emoji_tags: {
33 let json: String = row.get(17)?;
34 if json.is_empty() { Vec::new() }
35 else { serde_json::from_str(&json).unwrap_or_default() }
36 },
37 },
38 last_updated: row.get::<_, i64>(19)?.max(0) as u64,
39 mine: false,
40 bot: row.get::<_, i32>(13)? != 0,
41 avatar_cached: {
42 let p: String = row.get(14)?;
43 if !p.is_empty() && !cached_file_present(&p) { String::new() } else { p }
44 },
45 banner_cached: {
46 let p: String = row.get(15)?;
47 if !p.is_empty() && !cached_file_present(&p) { String::new() } else { p }
48 },
49 is_blocked: row.get::<_, i32>(16).unwrap_or(0) != 0,
50 stream_consent: row.get::<_, i32>(18)? != 0,
51 })
52 })
53 .map_err(|e| format!("Failed to query profiles: {}", e))?
54 .collect::<Result<Vec<_>, _>>()
55 .map_err(|e| format!("Failed to collect profiles: {}", e))?;
56
57 Ok(profiles)
58}
59
60pub fn set_profile(profile: &SlimProfile) -> Result<(), String> {
62 let conn = super::get_write_connection_guard_static()?;
63
64 let status_emoji_tags = if profile.status.emoji_tags.is_empty() {
67 String::new()
68 } else {
69 serde_json::to_string(&profile.status.emoji_tags).unwrap_or_default()
70 };
71
72 conn.execute(
73 "INSERT INTO profiles (npub, name, display_name, nickname, lud06, lud16, banner, avatar, \
74 about, website, nip05, status_content, status_url, bot, avatar_cached, banner_cached, is_blocked, \
75 status_emoji_tags, stream_consent, checked_at) \
76 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20) \
77 ON CONFLICT(npub) DO UPDATE SET \
78 name = excluded.name, display_name = excluded.display_name, \
79 nickname = excluded.nickname, lud06 = excluded.lud06, lud16 = excluded.lud16, \
80 banner = excluded.banner, avatar = excluded.avatar, about = excluded.about, \
81 website = excluded.website, nip05 = excluded.nip05, \
82 status_content = excluded.status_content, status_url = excluded.status_url, \
83 bot = excluded.bot, avatar_cached = excluded.avatar_cached, \
84 banner_cached = excluded.banner_cached, is_blocked = excluded.is_blocked, \
85 status_emoji_tags = excluded.status_emoji_tags, stream_consent = excluded.stream_consent, \
86 checked_at = MAX(checked_at, excluded.checked_at)",
87 rusqlite::params![
88 profile.id,
89 profile.name,
90 profile.display_name,
91 profile.nickname,
92 profile.lud06,
93 profile.lud16,
94 profile.banner,
95 profile.avatar,
96 profile.about,
97 profile.website,
98 profile.nip05,
99 profile.status.title,
100 profile.status.url,
101 profile.bot as i32,
102 profile.avatar_cached,
103 profile.banner_cached,
104 profile.is_blocked as i32,
105 status_emoji_tags,
106 profile.stream_consent as i32,
107 profile.last_updated as i64,
108 ],
109 ).map_err(|e| format!("Failed to insert profile: {}", e))?;
110
111 Ok(())
112}
113
114pub fn mark_profile_checked(npub: &str, secs: u64) -> Result<(), String> {
116 let conn = super::get_write_connection_guard_static()?;
117 conn.execute(
118 "UPDATE profiles SET checked_at = MAX(checked_at, ?2) WHERE npub = ?1",
119 rusqlite::params![npub, secs as i64],
120 )
121 .map_err(|e| format!("Failed to mark profile checked: {e}"))?;
122 Ok(())
123}
124
125fn cached_file_present(path: &str) -> bool {
128 #[cfg(target_arch = "wasm32")]
129 {
130 path.starts_with('/')
132 }
133 #[cfg(not(target_arch = "wasm32"))]
134 {
135 std::path::Path::new(path).exists()
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
144 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
145 crate::db::close_database();
146 crate::db::clear_id_caches();
147 use nostr_sdk::prelude::ToBech32;
148 let tmp = tempfile::tempdir().unwrap();
149 let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
150 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
151 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
152 crate::db::set_current_account(account.clone()).unwrap();
153 crate::db::init_database(&account).unwrap();
154 (tmp, guard)
155 }
156
157 fn stored(npub: &str) -> SlimProfile {
158 get_all_profiles().unwrap().into_iter().find(|p| p.id == npub).unwrap()
159 }
160
161 #[test]
162 fn stream_consent_survives_the_database() {
163 let (_tmp, _guard) = init_test_db();
164 let npub = "npub1streamconsent";
165 let mut slim = SlimProfile { id: npub.into(), name: "a".into(), stream_consent: true, ..Default::default() };
166 set_profile(&slim).unwrap();
167 assert!(stored(npub).stream_consent);
168
169 slim.stream_consent = false;
170 set_profile(&slim).unwrap();
171 assert!(!stored(npub).stream_consent, "the upsert clears it too");
172 }
173
174 #[test]
175 fn a_row_written_without_the_column_reads_as_no_consent() {
176 let (_tmp, _guard) = init_test_db();
177 crate::db::get_write_connection_guard_static()
178 .unwrap()
179 .execute("INSERT INTO profiles (npub, name) VALUES ('npub1legacyrow', 'old')", [])
180 .unwrap();
181 assert!(!stored("npub1legacyrow").stream_consent);
182 }
183}