subscription.rs (2885B)
1 use crate::filter::RadrootsNostrNdbFilterSpec; 2 3 #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] 4 pub struct RadrootsNostrNdbSubscriptionHandle { 5 id: u64, 6 } 7 8 impl RadrootsNostrNdbSubscriptionHandle { 9 pub(crate) fn new(id: u64) -> Self { 10 Self { id } 11 } 12 13 pub fn id(self) -> u64 { 14 self.id 15 } 16 } 17 18 #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] 19 pub struct RadrootsNostrNdbNoteKey { 20 key: u64, 21 } 22 23 impl RadrootsNostrNdbNoteKey { 24 pub(crate) fn new(key: u64) -> Self { 25 Self { key } 26 } 27 28 pub fn as_u64(self) -> u64 { 29 self.key 30 } 31 } 32 33 #[derive(Debug, Clone, Eq, PartialEq)] 34 pub struct RadrootsNostrNdbSubscriptionSpec { 35 filters: Vec<RadrootsNostrNdbFilterSpec>, 36 } 37 38 impl RadrootsNostrNdbSubscriptionSpec { 39 pub fn new(filters: Vec<RadrootsNostrNdbFilterSpec>) -> Self { 40 Self { filters } 41 } 42 43 pub fn single(filter: RadrootsNostrNdbFilterSpec) -> Self { 44 Self { 45 filters: vec![filter], 46 } 47 } 48 49 pub fn text_notes(limit: Option<u64>, since_unix: Option<u64>) -> Self { 50 Self::single(RadrootsNostrNdbFilterSpec::text_notes(limit, since_unix)) 51 } 52 53 pub fn filters(&self) -> &[RadrootsNostrNdbFilterSpec] { 54 &self.filters 55 } 56 } 57 58 #[cfg(feature = "rt")] 59 pub struct RadrootsNostrNdbSubscriptionStream { 60 pub(crate) inner: nostrdb::SubscriptionStream, 61 } 62 63 #[cfg(feature = "rt")] 64 impl futures::Stream for RadrootsNostrNdbSubscriptionStream { 65 type Item = Vec<RadrootsNostrNdbNoteKey>; 66 67 fn poll_next( 68 mut self: std::pin::Pin<&mut Self>, 69 cx: &mut std::task::Context<'_>, 70 ) -> std::task::Poll<Option<Self::Item>> { 71 std::pin::Pin::new(&mut self.inner) 72 .poll_next(cx) 73 .map(|note_keys| { 74 note_keys.map(|keys| { 75 keys.into_iter() 76 .map(|note_key| RadrootsNostrNdbNoteKey::new(note_key.as_u64())) 77 .collect() 78 }) 79 }) 80 } 81 } 82 83 #[cfg(test)] 84 mod tests { 85 use super::*; 86 use crate::filter::RadrootsNostrNdbFilterSpec; 87 88 #[test] 89 fn subscription_types_expose_builders_and_accessors() { 90 let handle = RadrootsNostrNdbSubscriptionHandle::new(42); 91 assert_eq!(handle.id(), 42); 92 93 let note_key = RadrootsNostrNdbNoteKey::new(7); 94 assert_eq!(note_key.as_u64(), 7); 95 96 let filter = RadrootsNostrNdbFilterSpec::new().with_kind(1); 97 let from_new = RadrootsNostrNdbSubscriptionSpec::new(vec![filter.clone()]); 98 assert_eq!(from_new.filters(), &[filter.clone()]); 99 100 let from_single = RadrootsNostrNdbSubscriptionSpec::single(filter.clone()); 101 assert_eq!(from_single.filters(), &[filter.clone()]); 102 103 let text_notes = RadrootsNostrNdbSubscriptionSpec::text_notes(Some(10), Some(123)); 104 assert_eq!(text_notes.filters().len(), 1); 105 } 106 }