Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ThreadMetadata store #189

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
62 changes: 61 additions & 1 deletion presage-store-sled/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sled::{Batch, IVec};

use presage::{GroupMasterKeyBytes, Registered, Store, Thread};
use presage::{GroupMasterKeyBytes, Registered, Store, Thread, ThreadMetadata};

mod error;
mod protobuf;
Expand All @@ -47,6 +47,7 @@ const SLED_TREE_SIGNED_PRE_KEYS: &str = "signed_pre_keys";
const SLED_TREE_KYBER_PRE_KEYS: &str = "kyber_pre_keys";
const SLED_TREE_STATE: &str = "state";
const SLED_TREE_THREADS_PREFIX: &str = "threads";
const SLED_TREE_THREADS_METADATA: &str = "threads_metadata";
const SLED_TREE_PROFILES: &str = "profiles";
const SLED_TREE_PROFILE_KEYS: &str = "profile_keys";

Expand Down Expand Up @@ -252,6 +253,13 @@ impl SledStore {
hasher.update(key.collect::<Vec<_>>());
format!("{:x}", hasher.finalize())
}

fn thread_metadata_key(&self, thread: &Thread) -> Vec<u8> {
match thread {
Thread::Contact(contact) => contact.to_string().into_bytes(),
Thread::Group(group) => group.to_vec(),
}
}
}

fn migrate(
Expand Down Expand Up @@ -335,6 +343,7 @@ impl Store for SledStore {
type ContactsIter = SledContactsIter;
type GroupsIter = SledGroupsIter;
type MessagesIter = SledMessagesIter;
type ThreadMetadataIter = SledThreadMetadataIter;

/// State

Expand Down Expand Up @@ -442,6 +451,12 @@ impl Store for SledStore {
Ok(())
}

fn save_contact(&mut self, contact: Contact) -> Result<(), Self::Error> {
self.insert(SLED_TREE_CONTACTS, contact.uuid, contact)?;
debug!("saved contact");
Ok(())
}

fn contacts(&self) -> Result<Self::ContactsIter, SledStoreError> {
Ok(SledContactsIter {
iter: self.read().open_tree(SLED_TREE_CONTACTS)?.iter(),
Expand Down Expand Up @@ -606,6 +621,29 @@ impl Store for SledStore {
let key = self.profile_key_for_uuid(uuid, key);
self.get(SLED_TREE_PROFILES, key)
}
/// Thread metadata

fn save_thread_metadata(&mut self, metadata: ThreadMetadata) -> Result<(), Self::Error> {
let key = self.thread_metadata_key(&metadata.thread);
self.insert(SLED_TREE_THREADS_METADATA, key, metadata)?;
Ok(())
}

fn thread_metadata(&self, thread: &Thread) -> Result<Option<ThreadMetadata>, Self::Error> {
let key = self.thread_metadata_key(thread);
self.get(SLED_TREE_THREADS_METADATA, key)
}

fn thread_metadatas(
&self,
) -> Result<<Self as presage::Store>::ThreadMetadataIter, <Self as presage::Store>::Error> {
let tree = self.read().open_tree(SLED_TREE_THREADS_METADATA)?;
let iter = tree.iter();
Ok(SledThreadMetadataIter {
cipher: self.cipher.clone(),
iter,
})
}
}

pub struct SledContactsIter {
Expand Down Expand Up @@ -1018,6 +1056,28 @@ impl DoubleEndedIterator for SledMessagesIter {
}
}

pub struct SledThreadMetadataIter {
cipher: Option<Arc<StoreCipher>>,
iter: sled::Iter,
}

impl Iterator for SledThreadMetadataIter {
type Item = Result<ThreadMetadata, SledStoreError>;

fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()?
.map_err(SledStoreError::from)
.and_then(|(_key, value)| {
self.cipher.as_ref().map_or_else(
|| serde_json::from_slice(&value).map_err(SledStoreError::from),
|c| c.decrypt_value(&value).map_err(SledStoreError::from),
)
})
.into()
}
}

#[cfg(test)]
mod tests {
use core::fmt;
Expand Down
2 changes: 1 addition & 1 deletion presage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ base64 = "0.12"
futures = "0.3"
log = "0.4.8"
rand = "0.8"
serde = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"
url = "2.2"
Expand Down
2 changes: 2 additions & 0 deletions presage/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ pub enum Error<S: std::error::Error> {
AttachmentCipherError(#[from] libsignal_service::attachment_cipher::AttachmentCipherError),
#[error("unknown group")]
UnknownGroup,
#[error("unknown contact")]
UnknownContact,
#[error("unknown recipient")]
UnknownRecipient,
#[error("timeout: {0}")]
Expand Down
21 changes: 20 additions & 1 deletion presage/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
mod cache;
mod errors;
mod manager;
mod serde;
mod serializers;
use serde::{Deserialize, Serialize};
mod store;

pub use errors::Error;
Expand Down Expand Up @@ -34,3 +35,21 @@ const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "-rs-", env!("CARGO_PKG

// TODO: open a PR in libsignal and make sure the bytes can be read from `GroupMasterKey` instead of using this type
pub type GroupMasterKeyBytes = [u8; 32];

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ThreadMetadata {
pub thread: Thread,
pub last_message: Option<ThreadMetadataMessageContent>,
pub unread_messages_count: usize,
pub title: Option<String>,
pub archived: bool,
pub muted: bool,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ThreadMetadataMessageContent {
pub sender: prelude::Uuid,
pub timestamp: u64,
pub message: Option<String>,

}
Loading