note.rs (1855B)
1 use crate::notecache::NoteCache; 2 use nostrdb::{Ndb, Note, NoteKey, QueryResult, Transaction}; 3 use std::cmp::Ordering; 4 5 #[derive(Debug, Eq, PartialEq, Copy, Clone)] 6 pub struct NoteRef { 7 pub key: NoteKey, 8 pub created_at: u64, 9 } 10 11 impl NoteRef { 12 pub fn new(key: NoteKey, created_at: u64) -> Self { 13 NoteRef { key, created_at } 14 } 15 16 pub fn from_note(note: &Note<'_>) -> Self { 17 let created_at = note.created_at(); 18 let key = note.key().expect("todo: implement NoteBuf"); 19 NoteRef::new(key, created_at) 20 } 21 22 pub fn from_query_result(qr: QueryResult<'_>) -> Self { 23 NoteRef { 24 key: qr.note_key, 25 created_at: qr.note.created_at(), 26 } 27 } 28 } 29 30 impl Ord for NoteRef { 31 fn cmp(&self, other: &Self) -> Ordering { 32 match self.created_at.cmp(&other.created_at) { 33 Ordering::Equal => self.key.cmp(&other.key), 34 Ordering::Less => Ordering::Greater, 35 Ordering::Greater => Ordering::Less, 36 } 37 } 38 } 39 40 impl PartialOrd for NoteRef { 41 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 42 Some(self.cmp(other)) 43 } 44 } 45 46 pub fn root_note_id_from_selected_id<'a>( 47 ndb: &Ndb, 48 note_cache: &mut NoteCache, 49 txn: &'a Transaction, 50 selected_note_id: &'a [u8; 32], 51 ) -> &'a [u8; 32] { 52 let selected_note_key = if let Ok(key) = ndb 53 .get_notekey_by_id(txn, selected_note_id) 54 .map(NoteKey::new) 55 { 56 key 57 } else { 58 return selected_note_id; 59 }; 60 61 let note = if let Ok(note) = ndb.get_note_by_key(txn, selected_note_key) { 62 note 63 } else { 64 return selected_note_id; 65 }; 66 67 note_cache 68 .cached_note_or_insert(selected_note_key, ¬e) 69 .reply 70 .borrow(note.tags()) 71 .root() 72 .map_or_else(|| selected_note_id, |nr| nr.id) 73 }