garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /contacts/src/book.rs

raw

//! The address book as the p2p service holds it, without its disk or its
//! node: which entry an edit or an import replaces, and the ids entries
//! are known by.

use alloc::string::String;
use alloc::vec::Vec;

use crate::{Entry, Key, hex};

/// Fills a buffer with random bytes: the kernel's, on the device.
pub type Random<'a> = &'a mut dyn FnMut(&mut [u8]);

/// Every entry, in the order shown: by name, then id.
#[derive(Default, Debug)]
pub struct Book {
    pub entries: Vec<Entry>,
}

impl Book {
    /// The book from what [`Book::to_kept`] wrote: an entry with no id, or
    /// one another has, gets a new one.
    pub fn from_kept(text: &str, random: Random) -> Book {
        let mut book = Book::default();
        for mut entry in crate::parse(text) {
            if entry.id.is_empty() || book.entries.iter().any(|e| e.id == entry.id) {
                entry.id = book.fresh_id(None, random);
            }
            book.entries.push(entry);
        }
        book.sort();
        book
    }

    /// Every entry as a vCard with its id, for the book's own file. Cards
    /// are left out: they are kept apart, signed.
    pub fn to_kept(&self) -> String {
        self.entries
            .iter()
            .map(|e| {
                Entry {
                    card: None,
                    ..e.clone()
                }
                .to_vcard()
            })
            .collect()
    }

    pub fn sort(&mut self) {
        self.entries
            .sort_by_cached_key(|e| (e.title().to_lowercase(), e.id.clone()));
    }

    /// An id no entry has: the key's first half in hex (the name its card
    /// is kept under) when that is free, else a random one.
    pub fn fresh_id(&self, key: Option<Key>, random: Random) -> String {
        let taken = |id: &str| self.entries.iter().any(|e| e.id == id);
        match key.map(|k| hex(&k[..16])) {
            Some(id) if !taken(&id) => id,
            _ => loop {
                let mut bytes = [0u8; 16];
                random(&mut bytes);
                let id = hex(&bytes);
                if !taken(&id) {
                    break id;
                }
            },
        }
    }

    /// An entry for a contact whose card came, under the name it chose
    /// for itself, unless one has its key already. Whether one was added.
    pub fn add_card(&mut self, key: Key, name: &str, random: Random) -> bool {
        if self.entries.iter().any(|e| e.key == Some(key)) {
            return false;
        }
        let id = self.fresh_id(Some(key), random);
        self.entries.push(Entry {
            uid: id.clone(),
            id,
            name: name.into(),
            key: Some(key),
            ..Entry::default()
        });
        self.sort();
        true
    }

    /// Keeps `entry` in place of the one with `id`, or else the one with
    /// its key, or else the one with its UID: so an import of a contact
    /// already here changes it rather than adding it twice. A new one gets
    /// an id, and that as its UID if it has none. The id it is kept under,
    /// or `None` for an entry with nothing in it. Its card is the caller's
    /// to check and keep; the book keeps none.
    pub fn put(&mut self, id: &str, mut entry: Entry, random: Random) -> Option<String> {
        entry.card = None;
        if entry.is_empty() {
            return None;
        }
        let at = self
            .entries
            .iter()
            .position(|e| !id.is_empty() && e.id == id)
            .or_else(|| {
                let key = entry.key?;
                self.entries.iter().position(|e| e.key == Some(key))
            })
            .or_else(|| {
                (!entry.uid.is_empty())
                    .then(|| self.entries.iter().position(|e| e.uid == entry.uid))
                    .flatten()
            });
        match at {
            Some(i) => {
                let old = &self.entries[i];
                entry.id = old.id.clone();
                if entry.uid.is_empty() {
                    entry.uid = old.uid.clone();
                }
                // A key the entry had and this one leaves out stays: an
                // address book that knows nothing of keys must not cut the
                // contact off by its edit.
                if entry.key.is_none() {
                    entry.key = old.key;
                }
            }
            None => {
                entry.id = self.fresh_id(entry.key, random);
                if entry.uid.is_empty() {
                    entry.uid = entry.id.clone();
                }
            }
        }
        let id = entry.id.clone();
        match at {
            Some(i) => self.entries[i] = entry,
            None => self.entries.push(entry),
        }
        self.sort();
        Some(id)
    }

    /// Takes the entry `id` out, and gives it back.
    pub fn remove(&mut self, id: &str) -> Option<Entry> {
        let i = self.entries.iter().position(|e| e.id == id)?;
        Some(self.entries.remove(i))
    }

    /// What the contact `key` is called in the book.
    pub fn name_of(&self, key: &Key) -> Option<&str> {
        self.entries
            .iter()
            .find(|e| e.key == Some(*key))
            .map(Entry::title)
    }
}