1use nostr_sdk::prelude::*;
26use serde::{Deserialize, Serialize};
27
28use crate::stored_event::event_kind;
29
30pub const PINNED_D_TAG: &str = "vector/pinned";
32
33const LOCAL_PINNED_KEY: &str = "pinned_chats_local";
36
37const PINNED_PUBLISHED_AT_KEY: &str = "pinned_chats_published_at";
40
41const PINNED_BY_TIER: [usize; 4] = [3, 6, 9, usize::MAX];
49
50pub const MAX_PINNED: usize = PINNED_BY_TIER[0];
52
53pub fn effective_max_pinned() -> usize {
56 PINNED_BY_TIER[crate::badges::effective_tier() as usize]
57}
58
59const FETCH_TIMEOUT_SECS: u64 = 10;
60
61#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
64pub struct PinnedChats {
65 #[serde(default = "one")]
66 pub v: u32,
67 #[serde(default)]
69 pub chats: Vec<String>,
70}
71
72fn one() -> u32 {
73 1
74}
75
76impl PinnedChats {
77 pub fn from_json(s: &str) -> Self {
80 serde_json::from_str(s).unwrap_or_default()
81 }
82
83 pub fn to_json(&self) -> String {
84 serde_json::to_string(self).unwrap_or_else(|_| "{\"v\":1,\"chats\":[]}".to_string())
85 }
86
87 pub fn contains(&self, id: &str) -> bool {
88 self.chats.iter().any(|c| c == id)
89 }
90
91 pub fn pin(&mut self, id: &str, max: usize) -> Result<(), String> {
96 if id.trim().is_empty() {
97 return Err("cannot pin a chat with no id".to_string());
98 }
99 if self.contains(id) {
100 return Ok(());
101 }
102 if self.chats.len() >= max {
103 return Err(format!("you can pin up to {max} chats — unpin one first"));
104 }
105 self.chats.push(id.to_string());
106 Ok(())
107 }
108
109 pub fn unpin(&mut self, id: &str) {
112 self.chats.retain(|c| c != id);
113 }
114
115 pub fn move_before(&mut self, id: &str, before: Option<&str>) -> bool {
119 let Some(from) = self.chats.iter().position(|c| c == id) else { return false };
120 let moved = self.chats.remove(from);
121 let to = before.and_then(|b| self.chats.iter().position(|c| c == b)).unwrap_or(self.chats.len());
122 self.chats.insert(to, moved);
123 true
124 }
125}
126
127pub fn load_local() -> PinnedChats {
130 crate::db::settings::get_sql_setting(LOCAL_PINNED_KEY.to_string())
131 .ok()
132 .flatten()
133 .map(|s| PinnedChats::from_json(&s))
134 .unwrap_or_default()
135}
136
137pub fn save_local(list: &PinnedChats) -> Result<(), String> {
138 crate::db::settings::set_sql_setting(LOCAL_PINNED_KEY.to_string(), list.to_json())
139}
140
141pub fn is_pinned(id: &str) -> bool {
145 load_local().contains(id)
146}
147
148pub fn pin_position(id: &str) -> Option<usize> {
150 load_local().chats.iter().position(|c| c == id)
151}
152
153fn our_last_publish() -> u64 {
154 crate::db::settings::get_sql_setting(PINNED_PUBLISHED_AT_KEY.to_string())
155 .ok()
156 .flatten()
157 .and_then(|s| s.parse().ok())
158 .unwrap_or(0)
159}
160
161fn mark_published() {
162 let now = crate::clock::now_secs();
163 let _ = crate::db::settings::set_sql_setting(PINNED_PUBLISHED_AT_KEY.to_string(), now.to_string());
164}
165
166async fn decrypt_event(my_pk: &PublicKey, event: &Event) -> PinnedChats {
167 if event.content.is_empty() {
168 return PinnedChats::default();
169 }
170 let signer = match crate::signer::active_signer() {
171 Ok(s) => s,
172 Err(e) => {
173 crate::log_warn!("[PinnedChats] signer unavailable for decrypt: {}", e);
174 return PinnedChats::default();
175 }
176 };
177 match signer.nip44_decrypt_async(my_pk, &event.content).await {
178 Ok(plaintext) => PinnedChats::from_json(&plaintext),
179 Err(e) => {
180 crate::log_warn!("[PinnedChats] decrypt failed: {}", e);
181 PinnedChats::default()
182 }
183 }
184}
185
186pub async fn fetch_pinned(client: &Client, my_pk: PublicKey) -> Result<PinnedChats, String> {
190 crate::db::scoped(async move {
191 let filter = Filter::new()
192 .author(my_pk)
193 .kind(Kind::Custom(event_kind::APPLICATION_SPECIFIC))
194 .identifier(PINNED_D_TAG)
195 .limit(1);
196 let events = client
197 .fetch_events(filter)
198 .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS)))
199 .await
200 .map_err(|e| format!("fetch pinned chats (kind 30078): {}", e))?;
201
202 Ok(match events.into_iter().next() {
203 Some(ev) if ev.created_at.as_secs() < our_last_publish() => load_local(),
204 Some(ev) => decrypt_event(&my_pk, &ev).await,
205 None => load_local(),
206 })
207 })
208 .await
209}
210
211pub async fn publish(client: &Client, list: &PinnedChats) -> Result<(), String> {
213 save_local(list)?;
214 publish_only(client, list).await
215}
216
217async fn publish_only(client: &Client, list: &PinnedChats) -> Result<(), String> {
219 let my_pk = crate::state::my_public_key().ok_or_else(|| "Not logged in".to_string())?;
220
221 let signer = crate::signer::active_signer().map_err(|e| format!("Signer unavailable: {}", e))?;
222 let content = signer
223 .nip44_encrypt_async(&my_pk, &list.to_json())
224 .await
225 .map_err(|e| format!("nip44 encrypt pinned chats: {}", e))?;
226
227 let builder = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), content)
228 .tag(Tag::identifier(PINNED_D_TAG));
229 crate::sign_and_send(client, builder)
230 .await
231 .map_err(|e| format!("Failed to publish pinned chats (kind 30078): {}", e))?;
232
233 mark_published();
234 crate::log_info!("[PinnedChats] published {} pin(s)", list.chats.len());
235 Ok(())
236}
237
238pub async fn pin_chat(client: &Client, id: &str) -> Result<PinnedChats, String> {
247 let mut list = load_local();
248 list.pin(id, effective_max_pinned())?;
249 save_local(&list)?;
250 publish_in_background(client, &list);
251 Ok(list)
252}
253
254pub async fn unpin_chat(client: &Client, id: &str) -> Result<PinnedChats, String> {
256 let mut list = load_local();
257 list.unpin(id);
258 save_local(&list)?;
259 publish_in_background(client, &list);
260 Ok(list)
261}
262
263pub async fn move_pinned_chat(client: &Client, id: &str, before: Option<&str>) -> Result<PinnedChats, String> {
266 let mut list = load_local();
267 if !list.move_before(id, before) {
268 return Err("that chat is not pinned".to_string());
269 }
270 save_local(&list)?;
271 publish_in_background(client, &list);
272 Ok(list)
273}
274
275fn publish_in_background(client: &Client, list: &PinnedChats) {
278 let client = client.clone();
279 let list = list.clone();
280 crate::db::spawn_bound(async move {
281 if let Err(e) = publish_only(&client, &list).await {
282 crate::log_warn!("[PinnedChats] background publish failed: {e}");
283 }
284 });
285}
286
287pub async fn ingest_remote_event(my_pk: &PublicKey, event: &Event) -> Result<PinnedChats, String> {
291 crate::db::scoped(async move {
292 if event.created_at.as_secs() < our_last_publish() {
295 return Ok(load_local());
296 }
297 let incoming = decrypt_event(my_pk, event).await;
298 save_local(&incoming)?;
299 Ok(incoming)
300 })
301 .await
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn a_community_pin_survives_a_dm_pin_and_unpin() {
310 let community = "c".repeat(64);
311 let mut l = PinnedChats::default();
312 l.pin(&community, MAX_PINNED).unwrap();
313 l.pin("npub1alice", MAX_PINNED).unwrap();
314 l.unpin("npub1alice");
315 assert_eq!(l.chats, vec![community]);
316 }
317
318 #[test]
319 fn a_move_lands_before_its_neighbour_and_leaves_the_rest_in_place() {
320 let ids = |l: &PinnedChats| l.chats.iter().map(String::as_str).collect::<Vec<_>>().join(",");
321 let mut l = PinnedChats::from_json("{\"v\":1,\"chats\":[\"a\",\"hidden\",\"b\",\"c\"]}");
322 assert!(l.move_before("c", Some("a")));
323 assert_eq!(ids(&l), "c,a,hidden,b");
324 assert!(l.move_before("c", Some("b")));
325 assert_eq!(ids(&l), "a,hidden,c,b", "a pin this device can't show keeps its slot");
326 assert!(l.move_before("a", None));
327 assert_eq!(ids(&l), "hidden,c,b,a");
328 assert!(l.move_before("b", Some("gone")), "an unknown neighbour sends it to the end");
329 assert_eq!(ids(&l), "hidden,c,a,b");
330 assert!(l.move_before("b", Some("b")), "before itself is a no-op");
331 assert_eq!(ids(&l), "hidden,c,a,b");
332 assert!(!l.move_before("never-pinned", Some("a")));
333 assert_eq!(ids(&l), "hidden,c,a,b");
334 }
335
336 #[test]
337 fn pinning_is_capped_but_reading_over_the_cap_is_not() {
338 let mut l = PinnedChats::default();
339 for i in 0..MAX_PINNED {
340 l.pin(&format!("id{i}"), MAX_PINNED).unwrap();
341 }
342 let err = l.pin("one-too-many", MAX_PINNED).unwrap_err();
343 assert!(err.contains(&MAX_PINNED.to_string()), "the refusal names the cap: {err}");
344 assert_eq!(l.chats.len(), MAX_PINNED);
345
346 let over = PinnedChats::from_json("{\"v\":1,\"chats\":[\"a\",\"b\",\"c\",\"d\",\"e\"]}");
349 assert_eq!(over.chats.len(), 5, "read tolerates what write refuses");
350 }
351
352 #[test]
353 fn the_badge_tiers_step_the_cap_up_to_unlimited() {
354 assert_eq!(PINNED_BY_TIER, [3, 6, 9, usize::MAX]);
357 assert_eq!(MAX_PINNED, 3, "the frontend mirror is the free-tier cap");
358
359 let mut premium = PinnedChats::default();
362 for i in 0..MAX_PINNED + 5 {
363 premium
364 .pin(&format!("id{i}"), PINNED_BY_TIER[3])
365 .unwrap_or_else(|e| panic!("full premium refused pin {i}: {e}"));
366 }
367 assert_eq!(premium.chats.len(), MAX_PINNED + 5, "no ceiling at the top tier");
368
369 let mut free = PinnedChats::from_json(&premium.to_json());
372 assert_eq!(free.chats.len(), MAX_PINNED + 5, "a premium list survives a free-tier read");
373 assert!(free.pin("one-more", MAX_PINNED).is_err(), "but adding past the free cap is refused");
374 assert_eq!(free.chats.len(), MAX_PINNED + 5, "and the refusal changed nothing");
375 }
376
377 #[test]
378 fn pinning_is_idempotent_and_unpinning_an_absent_id_is_success() {
379 let mut l = PinnedChats::default();
380 l.pin("a", MAX_PINNED).unwrap();
381 l.pin("a", MAX_PINNED).unwrap();
382 assert_eq!(l.chats, vec!["a".to_string()], "a second pin is not a second entry");
383 l.unpin("never-pinned");
384 l.unpin("a");
385 assert!(l.chats.is_empty());
386 }
387
388 #[test]
389 fn order_is_preserved_across_a_round_trip() {
390 let mut l = PinnedChats::default();
391 l.pin("first", MAX_PINNED).unwrap();
392 l.pin("second", MAX_PINNED).unwrap();
393 let back = PinnedChats::from_json(&l.to_json());
394 assert_eq!(back.chats, vec!["first".to_string(), "second".to_string()], "order IS the display order");
395 }
396
397 #[test]
398 fn an_unknown_id_survives_a_parse_and_republish() {
399 let json = "{\"v\":1,\"chats\":[\"stranger\"]}";
402 let mut l = PinnedChats::from_json(json);
403 l.pin("mine", usize::MAX).unwrap();
404 let out = PinnedChats::from_json(&l.to_json());
405 assert!(out.contains("stranger"), "an id we cannot resolve is never dropped");
406 assert!(out.contains("mine"));
407 }
408
409 #[test]
410 fn a_malformed_or_future_payload_never_errors() {
411 assert!(PinnedChats::from_json("not json").chats.is_empty());
412 assert!(PinnedChats::from_json("{}").chats.is_empty());
413 let future = PinnedChats::from_json("{\"v\":99,\"chats\":[\"a\"],\"unknown\":true}");
415 assert_eq!(future.chats, vec!["a".to_string()]);
416 }
417}