Skip to main content

cosmic_applet_avestruz/nostr/
contacts.rs

1// SPDX-License-Identifier: MIT
2
3//! A contact list (kind 3): who an account follows.
4//!
5//! There is one list for an account, and every new one replaces the last
6//! everywhere. Following or unfollowing someone is therefore the newest
7//! list written again with one person more or less, and everything else in
8//! it as it was: the others followed, whatever else their tags say, and the
9//! content, where older clients keep their relays.
10
11use nostr_sdk::prelude::{Event, EventBuilder, Kind, PublicKey, Tag, Timestamp};
12
13/// The people `list` follows, each once, in the list's order.
14pub fn followed(list: &Event) -> Vec<PublicKey> {
15    let mut seen = std::collections::HashSet::new();
16    list.tags.public_keys().filter(|followed| seen.insert(*followed)).collect()
17}
18
19/// Whether `tag` says `person` is followed.
20fn follows(tag: &Tag, person: &PublicKey) -> bool {
21    let fields = tag.as_slice();
22    fields.first().map(String::as_str) == Some("p") && fields.get(1).is_some_and(|key| *key == person.to_hex())
23}
24
25/// The list that follows `person` (`follow`) or doesn't, and is otherwise
26/// `list`, written at `now` or, if `list` claims to be from later, after
27/// it: it has to be the newer of the two. With no list to start from, one
28/// that follows `person` alone.
29///
30/// `None` when there is nothing to change: `person` is already followed,
31/// or already isn't.
32pub fn changed(list: Option<&Event>, person: PublicKey, follow: bool, now: Timestamp) -> Option<EventBuilder> {
33    let is_followed = list.is_some_and(|list| list.tags.iter().any(|tag| follows(tag, &person)));
34    if is_followed == follow {
35        return None;
36    }
37    let mut tags: Vec<Tag> =
38        list.map(|list| list.tags.iter().filter(|tag| !follows(tag, &person)).cloned().collect()).unwrap_or_default();
39    if follow {
40        tags.push(Tag::public_key(person));
41    }
42    let content = list.map_or("", |list| list.content.as_str());
43    let after = list.map_or(now, |list| now.max(Timestamp::from_secs(list.created_at.as_secs() + 1)));
44    Some(EventBuilder::new(Kind::ContactList, content).tags(tags).custom_created_at(after))
45}
46
47#[cfg(test)]
48mod tests {
49    use super::{changed, followed};
50    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, PublicKey, Tag, Timestamp};
51
52    fn person() -> PublicKey {
53        Keys::generate().public_key()
54    }
55
56    /// A contact list with `tags`, written at `at`.
57    fn list(keys: &Keys, tags: Vec<Tag>, content: &str, at: u64) -> Event {
58        EventBuilder::new(Kind::ContactList, content)
59            .tags(tags)
60            .custom_created_at(Timestamp::from_secs(at))
61            .finalize(keys)
62            .unwrap()
63    }
64
65    #[test]
66    fn following_adds_one_person_and_keeps_everything_else() {
67        let keys = Keys::generate();
68        let (a, b, c) = (person(), person(), person());
69        // With a relay and a pet name, as some clients write them, and a
70        // tag that is not a person at all.
71        let with_hints = Tag::parse(["p", &a.to_hex(), "wss://relay.example.com", "ana"]).unwrap();
72        let hashtag = Tag::hashtag("birds");
73        let old = list(
74            &keys,
75            vec![with_hints.clone(), hashtag.clone(), Tag::public_key(b)],
76            r#"{"wss://relay.example.com":{}}"#,
77            1_000,
78        );
79
80        let new = changed(Some(&old), c, true, Timestamp::from_secs(2_000)).unwrap().finalize(&keys).unwrap();
81
82        assert_eq!(new.kind, Kind::ContactList);
83        assert_eq!(new.tags.clone().to_vec(), vec![with_hints, hashtag, Tag::public_key(b), Tag::public_key(c)]);
84        assert_eq!(new.content, old.content);
85        assert_eq!(new.created_at.as_secs(), 2_000);
86        assert_eq!(followed(&new), [a, b, c]);
87    }
88
89    #[test]
90    fn unfollowing_takes_one_person_out_however_often_they_are_in() {
91        let keys = Keys::generate();
92        let (a, b) = (person(), person());
93        let old = list(&keys, vec![Tag::public_key(a), Tag::public_key(b), Tag::public_key(a)], "", 1_000);
94
95        let new = changed(Some(&old), a, false, Timestamp::from_secs(2_000)).unwrap().finalize(&keys).unwrap();
96
97        assert_eq!(followed(&new), [b]);
98    }
99
100    #[test]
101    fn nothing_is_written_when_nothing_would_change() {
102        let keys = Keys::generate();
103        let (a, b) = (person(), person());
104        let old = list(&keys, vec![Tag::public_key(a)], "", 1_000);
105        let now = Timestamp::from_secs(2_000);
106
107        assert!(changed(Some(&old), a, true, now).is_none(), "already followed");
108        assert!(changed(Some(&old), b, false, now).is_none(), "not followed anyway");
109        assert!(changed(None, a, false, now).is_none(), "no list, nobody followed");
110    }
111
112    #[test]
113    fn a_first_list_follows_the_one_person() {
114        let keys = Keys::generate();
115        let a = person();
116        let new = changed(None, a, true, Timestamp::from_secs(2_000)).unwrap().finalize(&keys).unwrap();
117        assert_eq!((followed(&new), new.content.as_str()), (vec![a], ""));
118    }
119
120    #[test]
121    fn the_new_list_is_newer_than_one_that_claims_to_be_from_the_future() {
122        let keys = Keys::generate();
123        let old = list(&keys, Vec::new(), "", 5_000);
124        let new = changed(Some(&old), person(), true, Timestamp::from_secs(2_000)).unwrap().finalize(&keys).unwrap();
125        assert_eq!(new.created_at.as_secs(), 5_001);
126    }
127
128    #[test]
129    fn a_list_names_each_person_once_and_may_name_nobody() {
130        let keys = Keys::generate();
131        let person = person();
132        let twice = list(&keys, vec![Tag::public_key(person), Tag::public_key(person)], "", 1_000);
133        assert_eq!(followed(&twice), [person]);
134        assert!(followed(&list(&keys, Vec::new(), "", 3_000)).is_empty());
135    }
136}