diff options
author | 2025-05-08 14:18:53 +0100 | |
---|---|---|
committer | 2025-05-08 14:33:32 +0100 | |
commit | 6d443f13fdeb78ea9dffab8762222572038d2ce3 (patch) | |
tree | 2344f741ee6969afcd5fffdeea0f03fd3454ecb7 | |
parent | 5f1bc4f2807614dca1ac84136a5c355fde65543a (diff) | |
download | luz-6d443f13fdeb78ea9dffab8762222572038d2ce3.tar.gz luz-6d443f13fdeb78ea9dffab8762222572038d2ce3.tar.bz2 luz-6d443f13fdeb78ea9dffab8762222572038d2ce3.zip |
feat(filamento): OPFS database
-rw-r--r-- | filamento/.cargo/config.toml | 19 | ||||
-rw-r--r-- | filamento/.gitignore | 2 | ||||
-rw-r--r-- | filamento/src/db.rs | 1956 | ||||
-rw-r--r-- | filamento/src/error.rs | 25 | ||||
-rw-r--r-- | filamento/src/files/opfs.rs | 110 | ||||
-rw-r--r-- | filamento/src/logic/online.rs | 2 | ||||
-rw-r--r-- | filamento/src/logic/process_stanza.rs | 4 |
7 files changed, 1124 insertions, 994 deletions
diff --git a/filamento/.cargo/config.toml b/filamento/.cargo/config.toml new file mode 100644 index 0000000..319101a --- /dev/null +++ b/filamento/.cargo/config.toml @@ -0,0 +1,19 @@ +[build] +rustflags = [ + # LLD (shipped with the Rust toolchain) is used as the default linker + # "-C", "link-arg=-Tlink.x", + + # if you run into problems with LLD switch to the GNU linker by commenting out + # this line + # "-C", "linker=arm-none-eabi-ld", + + # if you need to link to pre-compiled C libraries provided by a C toolchain + # use GCC as the linker by commenting out both lines above and then + # uncommenting the three lines below + "-C", + "target-feature=+atomics,+bulk-memory,+mutable-globals", +] + +[unstable] +build-std = ["std", "panic_abort"] + diff --git a/filamento/.gitignore b/filamento/.gitignore index 1ba9f2a..52acf71 100644 --- a/filamento/.gitignore +++ b/filamento/.gitignore @@ -1,3 +1,3 @@ filamento.db -files/ +./files/ .sqlx/ diff --git a/filamento/src/db.rs b/filamento/src/db.rs index e560443..b45e471 100644 --- a/filamento/src/db.rs +++ b/filamento/src/db.rs @@ -1,9 +1,14 @@ -use std::{collections::HashSet, path::Path, sync::Arc}; +use std::{collections::HashSet, ops::Deref, path::Path, sync::Arc}; use chrono::{DateTime, Utc}; use jid::JID; use rusqlite::{Connection, OptionalExtension}; use tokio::sync::{Mutex, MutexGuard}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::{spawn, spawn_blocking}; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; +use tracing::debug; use uuid::Uuid; use crate::{ @@ -16,17 +21,723 @@ use crate::{ #[derive(Clone, Debug)] pub struct Db { - db: Arc<Mutex<rusqlite::Connection>>, + sender: mpsc::Sender<DbCommand>, +} + +impl Deref for Db { + type Target = mpsc::Sender<DbCommand>; + + fn deref(&self) -> &Self::Target { + &self.sender + } +} + +#[derive(Debug)] +pub struct DbActor { + receiver: mpsc::Receiver<DbCommand>, + db: Connection, } -// TODO: turn into trait impl Db { #[cfg(not(target_arch = "wasm32"))] pub async fn create_connect_and_migrate( - path: impl AsRef<Path>, + path: impl AsRef<Path> + Send, + ) -> Result<Self, DatabaseOpenError> { + let (sender, receiver) = mpsc::channel(20); + let (result_send, result_recv) = oneshot::channel(); + spawn_blocking(move || { + let result = DbActor::new(path, receiver).await; + match result { + Ok(a) => { + result_send.send(Ok(())); + a.run() + } + Err(e) => { + result_send.send(Err(e)); + } + } + }); + match result_recv.await { + Ok(r) => match r { + Ok(o) => Ok(Self { sender }), + Err(e) => return Err(e), + }, + Err(e) => return Err(e.into()), + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> { + let (sender, receiver) = mpsc::channel(20); + let (result_send, result_recv) = oneshot::channel(); + spawn_blocking(move || { + let result = DbActor::new_memory(receiver).await; + match result { + Ok(a) => { + result_send.send(Ok(())); + // TODO: async run when not wasm + a.run() + } + Err(e) => { + result_send.send(Err(e)); + } + } + }); + match result_recv.await { + Ok(r) => match r { + Ok(o) => Ok(Self { sender }), + Err(e) => return Err(e), + }, + Err(e) => return Err(e.into()), + } + } + + /// `file_name` should be a file not in a directory + #[cfg(target_arch = "wasm32")] + pub async fn create_connect_and_migrate( + file_name: impl AsRef<str> + Send + 'static, ) -> Result<Self, DatabaseOpenError> { - use rusqlite::Connection; + use tokio_with_wasm::spawn_local; + + let (sender, receiver) = mpsc::channel(20); + let (result_send, result_recv) = oneshot::channel(); + spawn_blocking(move || { + spawn_local(async move { + debug!("installing opfs in spawn"); + rusqlite::ffi::install_opfs_sahpool( + Some(&rusqlite::ffi::OpfsSAHPoolCfg::default()), + false, + ) + .await + .unwrap(); + debug!("opfs installed"); + let file_name = format!("file:{}?vfs=opfs-sahpool", file_name.as_ref()); + let result = DbActor::new(file_name, receiver); + match result { + Ok(a) => { + result_send.send(Ok(())); + a.run() + } + Err(e) => { + result_send.send(Err(e)); + } + } + }); + }); + match result_recv.await { + Ok(r) => match r { + Ok(o) => Ok(Self { sender }), + Err(e) => return Err(e), + }, + Err(e) => return Err(e.into()), + } + } + + #[cfg(target_arch = "wasm32")] + pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> { + let (sender, receiver) = mpsc::channel(20); + let (result_send, result_recv) = oneshot::channel(); + spawn_blocking(move || { + let result = DbActor::new_memory(receiver); + match result { + Ok(a) => { + result_send.send(Ok(())); + a.run() + } + Err(e) => { + result_send.send(Err(e)); + } + } + }); + match result_recv.await { + Ok(r) => match r { + Ok(o) => Ok(Self { sender }), + Err(e) => return Err(e), + }, + Err(e) => return Err(e.into()), + } + } + + pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::CreateUser { user, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // TODO: this is not a 'read' user + pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadUser { user, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// returns whether or not the nickname was updated + pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteUserNick { jid, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// returns whether or not the nickname was updated + pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertUserNick { jid, nick, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar + pub(crate) async fn delete_user_avatar( + &self, + jid: JID, + ) -> Result<(bool, Option<String>), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteUserAvatar { jid, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar + pub(crate) async fn upsert_user_avatar( + &self, + jid: JID, + avatar: String, + ) -> Result<(bool, Option<String>), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertUserAvatar { + jid, + avatar, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // TODO: use references everywhere + pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpdateUser { user, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them. + // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {} + + /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately + pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::CreateContact { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadContact { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_contact_opt(&self, contact: JID) -> Result<Option<Contact>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadContactOpt { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// does not update the underlying user, to update user, update_user() must be called separately + pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpdateContact { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertContact { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteContact { contact, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReplaceCachedRoster { roster, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadCachedRoster { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_cached_roster_with_users( + &self, + ) -> Result<Vec<(Contact, User)>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadCachedRosterWithUsers { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::CreateChat { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster. + + pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadChat { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::MarkChatAsChatted { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn update_chat_correspondent( + &self, + old_chat: Chat, + new_correspondent: JID, + ) -> Result<Chat, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpdateChatCorrespondent { + old_chat, + new_correspondent, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // pub(crate) async fn update_chat + + pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteChat { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// TODO: sorting and filtering (for now there is no sorting) + pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadChats { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// chats ordered by date of last message + // greatest-n-per-group + pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadChatsOrdered { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// chats ordered by date of last message + // greatest-n-per-group + pub(crate) async fn read_chats_ordered_with_latest_messages( + &self, + ) -> Result<Vec<(Chat, Message)>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadChatsOrderedWithLatestMessages { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// chats ordered by date of last message + // greatest-n-per-group + pub(crate) async fn read_chats_ordered_with_latest_messages_and_users( + &self, + ) -> Result<Vec<((Chat, User), (Message, User))>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadChatsOrderedWithLatestMessagesAndUsers { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function. + #[tracing::instrument] + pub(crate) async fn create_message( + &self, + message: Message, + chat: JID, + from: JID, + ) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::CreateMessage { + message, + chat, + from, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn upsert_chat_and_user(&self, chat: JID) -> Result<bool, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertChatAndUser { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + /// create direct message from incoming. MUST upsert chat and user + #[tracing::instrument] + pub(crate) async fn create_message_with_user_resource( + &self, + message: Message, + // TODO: enforce two kinds of jid. bare and full + // must be bare jid + chat: JID, + // full jid + from: JID, + ) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::CreateMessageWithUserResource { + message, + chat, + from, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn update_message_delivery( + &self, + message: Uuid, + delivery: Delivery, + ) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpdateMessageDelivery { + message, + delivery, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> { + // Ok(Message { + // id: Uuid, + // from: todo!(), + // delivery: todo!(), + // timestamp: todo!(), + // body: todo!(), + // }) + // } + + // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {} + + pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteMessage { message, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadMessage { message, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + // TODO: paging + pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadMessageHistory { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_message_history_with_users( + &self, + chat: JID, + ) -> Result<Vec<(Message, User)>, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadMessageHistoryWithUsers { chat, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadCachedStatus { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertCachedStatus { status, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::DeleteCachedStatus { result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn read_capabilities(&self, node: String) -> Result<String, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::ReadCapabilities { node, result }; + self.sender.send(command).await?; + let result = recv.await?; + result + } + + pub(crate) async fn upsert_capabilities( + &self, + node: String, + capabilities: String, + ) -> Result<(), Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertCapabilities { + node, + capabilities, + result, + }; + self.sender.send(command).await?; + let result = recv.await?; + result + } +} + +// TODO: i should really just make an actor macro +pub enum DbCommand { + CreateUser { + user: User, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadUser { + user: JID, + result: oneshot::Sender<Result<User, Error>>, + }, + DeleteUserNick { + jid: JID, + result: oneshot::Sender<Result<bool, Error>>, + }, + UpsertUserNick { + jid: JID, + nick: String, + result: oneshot::Sender<Result<bool, Error>>, + }, + DeleteUserAvatar { + jid: JID, + result: oneshot::Sender<Result<(bool, Option<String>), Error>>, + }, + UpsertUserAvatar { + jid: JID, + avatar: String, + result: oneshot::Sender<Result<(bool, Option<String>), Error>>, + }, + UpdateUser { + user: User, + result: oneshot::Sender<Result<(), Error>>, + }, + CreateContact { + contact: Contact, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadContact { + contact: JID, + result: oneshot::Sender<Result<Contact, Error>>, + }, + ReadContactOpt { + contact: JID, + result: oneshot::Sender<Result<Option<Contact>, Error>>, + }, + UpdateContact { + contact: Contact, + result: oneshot::Sender<Result<(), Error>>, + }, + UpsertContact { + contact: Contact, + result: oneshot::Sender<Result<(), Error>>, + }, + DeleteContact { + contact: JID, + result: oneshot::Sender<Result<(), Error>>, + }, + ReplaceCachedRoster { + roster: Vec<Contact>, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadCachedRoster { + result: oneshot::Sender<Result<Vec<Contact>, Error>>, + }, + ReadCachedRosterWithUsers { + result: oneshot::Sender<Result<Vec<(Contact, User)>, Error>>, + }, + CreateChat { + chat: Chat, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadChat { + chat: JID, + result: oneshot::Sender<Result<Chat, Error>>, + }, + MarkChatAsChatted { + chat: JID, + result: oneshot::Sender<Result<(), Error>>, + }, + UpdateChatCorrespondent { + old_chat: Chat, + new_correspondent: JID, + result: oneshot::Sender<Result<Chat, Error>>, + }, + DeleteChat { + chat: JID, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadChats { + result: oneshot::Sender<Result<Vec<Chat>, Error>>, + }, + ReadChatsOrdered { + result: oneshot::Sender<Result<Vec<Chat>, Error>>, + }, + ReadChatsOrderedWithLatestMessages { + result: oneshot::Sender<Result<Vec<(Chat, Message)>, Error>>, + }, + ReadChatsOrderedWithLatestMessagesAndUsers { + result: oneshot::Sender<Result<Vec<((Chat, User), (Message, User))>, Error>>, + }, + // ReadChatID { + + // result: oneshot::Sender<Result<, Error>>, + // }, + // ReadChatIDOpt { + // chat: JID, + // result: oneshot::Sender<Result<Option<Uuid>, Error>>, + // }, + CreateMessage { + message: Message, + chat: JID, + from: JID, + result: oneshot::Sender<Result<(), Error>>, + }, + UpsertChatAndUser { + chat: JID, + result: oneshot::Sender<Result<bool, Error>>, + }, + CreateMessageWithUserResource { + message: Message, + chat: JID, + from: JID, + result: oneshot::Sender<Result<(), Error>>, + }, + UpdateMessageDelivery { + message: Uuid, + delivery: Delivery, + result: oneshot::Sender<Result<(), Error>>, + }, + DeleteMessage { + message: Uuid, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadMessage { + message: Uuid, + result: oneshot::Sender<Result<Message, Error>>, + }, + ReadMessageHistory { + chat: JID, + result: oneshot::Sender<Result<Vec<Message>, Error>>, + }, + ReadMessageHistoryWithUsers { + chat: JID, + result: oneshot::Sender<Result<Vec<(Message, User)>, Error>>, + }, + ReadCachedStatus { + result: oneshot::Sender<Result<Online, Error>>, + }, + UpsertCachedStatus { + status: Online, + result: oneshot::Sender<Result<(), Error>>, + }, + DeleteCachedStatus { + result: oneshot::Sender<Result<(), Error>>, + }, + ReadCapabilities { + node: String, + result: oneshot::Sender<Result<String, Error>>, + }, + UpsertCapabilities { + node: String, + capabilities: String, + result: oneshot::Sender<Result<(), Error>>, + }, +} + +impl DbActor { + /// must be run in blocking spawn + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new(path: impl AsRef<Path>, receiver: mpsc::Receiver<DbCommand>) -> Self { if let Some(dir) = path.as_ref().parent() { if dir.is_dir() { } else { @@ -49,46 +760,186 @@ impl Db { // Ok(Self { db }) let db = Connection::open(url)?; db.execute_batch(include_str!("../migrations/1.sql"))?; - Ok(Self { - db: Arc::new(Mutex::new(db)), - }) + Ok(Self { db, receiver }) + } + + /// must be run in blocking spawn + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new_memory(receiver: mpsc::Receiver<DbCommand>) -> Self { + let db = Connection::open_in_memory()?; + db.execute_batch(include_str!("../migrations/1.sql"))?; + Ok(Self { db, receiver }) } + /// must be run in blocking spawn #[cfg(target_arch = "wasm32")] - pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> { + pub fn new_memory(receiver: mpsc::Receiver<DbCommand>) -> Result<Self, DatabaseOpenError> { let db = Connection::open("mem.db")?; db.execute_batch(include_str!("../migrations/1.sql"))?; - Ok(Self { - db: Arc::new(Mutex::new(db)), - }) + Ok(Self { db, receiver }) } + /// must be run in blocking spawn #[cfg(target_arch = "wasm32")] - pub async fn create_connect_and_migrate( - path: impl AsRef<Path>, + pub fn new( + file_name: impl AsRef<Path>, + receiver: mpsc::Receiver<DbCommand>, ) -> Result<Self, DatabaseOpenError> { - // rusqlite::ffi::install_opfs_sahpool(Some(&rusqlite::ffi::OpfsSAHPoolCfg::default()), true) - // .await - // .unwrap(); - let db = Connection::open(path)?; + let db = Connection::open(file_name)?; db.execute_batch(include_str!("../migrations/1.sql"))?; - Ok(Self { - db: Arc::new(Mutex::new(db)), - }) + Ok(Self { db, receiver }) } - // pub(crate) fn new(db: SqlitePool) -> Self { - // // Self { db } - // Self {} - // } - // - pub async fn db(&self) -> MutexGuard<'_, Connection> { - self.db.lock().await + pub(crate) fn run(mut self) { + while let Some(cmd) = self.receiver.blocking_recv() { + match cmd { + DbCommand::CreateUser { user, result } => { + result.send(self.create_user(user)); + } + DbCommand::ReadUser { user, result } => { + result.send(self.read_user(user)); + } + DbCommand::DeleteUserNick { jid, result } => { + result.send(self.delete_user_nick(jid)); + } + DbCommand::UpsertUserNick { jid, nick, result } => { + result.send(self.upsert_user_nick(jid, nick)); + } + DbCommand::DeleteUserAvatar { jid, result } => { + result.send(self.delete_user_avatar(jid)); + } + DbCommand::UpsertUserAvatar { + jid, + avatar, + result, + } => { + result.send(self.upsert_user_avatar(jid, avatar)); + } + DbCommand::UpdateUser { user, result } => { + result.send(self.update_user(user)); + } + DbCommand::CreateContact { contact, result } => { + result.send(self.create_contact(contact)); + } + DbCommand::ReadContact { contact, result } => { + result.send(self.read_contact(contact)); + } + DbCommand::ReadContactOpt { contact, result } => { + result.send(self.read_contact_opt(&contact)); + } + DbCommand::UpdateContact { contact, result } => { + result.send(self.update_contact(contact)); + } + DbCommand::UpsertContact { contact, result } => { + result.send(self.upsert_contact(contact)); + } + DbCommand::DeleteContact { contact, result } => { + result.send(self.delete_contact(contact)); + } + DbCommand::ReplaceCachedRoster { roster, result } => { + result.send(self.replace_cached_roster(roster)); + } + DbCommand::ReadCachedRoster { result } => { + result.send(self.read_cached_roster()); + } + DbCommand::ReadCachedRosterWithUsers { result } => { + result.send(self.read_cached_roster_with_users()); + } + DbCommand::CreateChat { chat, result } => { + result.send(self.create_chat(chat)); + } + DbCommand::ReadChat { chat, result } => { + result.send(self.read_chat(chat)); + } + DbCommand::MarkChatAsChatted { chat, result } => { + result.send(self.mark_chat_as_chatted(chat)); + } + DbCommand::UpdateChatCorrespondent { + old_chat, + new_correspondent, + result, + } => { + result.send(self.update_chat_correspondent(old_chat, new_correspondent)); + } + DbCommand::DeleteChat { chat, result } => { + result.send(self.delete_chat(chat)); + } + DbCommand::ReadChats { result } => { + result.send(self.read_chats()); + } + DbCommand::ReadChatsOrdered { result } => { + result.send(self.read_chats_ordered()); + } + DbCommand::ReadChatsOrderedWithLatestMessages { result } => { + result.send(self.read_chats_ordered_with_latest_messages()); + } + DbCommand::ReadChatsOrderedWithLatestMessagesAndUsers { result } => { + result.send(self.read_chats_ordered_with_latest_messages_and_users()); + } + DbCommand::CreateMessage { + message, + chat, + from, + result, + } => { + result.send(self.create_message(message, chat, from)); + } + DbCommand::UpsertChatAndUser { chat, result } => { + result.send(self.upsert_chat_and_user(&chat)); + } + DbCommand::CreateMessageWithUserResource { + message, + chat, + from, + result, + } => { + result.send(self.create_message_with_user_resource(message, chat, from)); + } + DbCommand::UpdateMessageDelivery { + message, + delivery, + result, + } => { + result.send(self.update_message_delivery(message, delivery)); + } + DbCommand::DeleteMessage { message, result } => { + result.send(self.delete_message(message)); + } + DbCommand::ReadMessage { message, result } => { + result.send(self.read_message(message)); + } + DbCommand::ReadMessageHistory { chat, result } => { + result.send(self.read_message_history(chat)); + } + DbCommand::ReadMessageHistoryWithUsers { chat, result } => { + result.send(self.read_message_history_with_users(chat)); + } + DbCommand::ReadCachedStatus { result } => { + result.send(self.read_cached_status()); + } + DbCommand::UpsertCachedStatus { status, result } => { + result.send(self.upsert_cached_status(status)); + } + DbCommand::DeleteCachedStatus { result } => { + result.send(self.delete_cached_status()); + } + DbCommand::ReadCapabilities { node, result } => { + result.send(self.read_capabilities(node)); + } + DbCommand::UpsertCapabilities { + node, + capabilities, + result, + } => { + result.send(self.upsert_capabilities(node, capabilities)); + } + } + } } - pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> { + pub(crate) fn create_user(&self, user: User) -> Result<(), Error> { { - self.db().await.execute( + self.db.execute( "insert into users ( jid, nick, avatar ) values ( ?1, ?2, ?3 )", (user.jid, user.nick, user.avatar), )?; @@ -97,8 +948,8 @@ impl Db { } // TODO: this is not a 'read' user - pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> { - let db = self.db().await; + pub(crate) fn read_user(&self, user: JID) -> Result<User, Error> { + let db = &self.db; let user_opt = db .query_row( "select jid, nick, avatar from users where jid = ?1", @@ -126,10 +977,10 @@ impl Db { } /// returns whether or not the nickname was updated - pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { + pub(crate) fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { let rows_affected; { - rows_affected = self.db().await.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, None::<String>, None::<String>, None::<String>))?; + rows_affected = self.db.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, None::<String>, None::<String>, None::<String>))?; } if rows_affected > 0 { Ok(true) @@ -139,10 +990,10 @@ impl Db { } /// returns whether or not the nickname was updated - pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { + pub(crate) fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { let rows_affected; { - rows_affected = self.db().await.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, &nick, &nick, &nick))?; + rows_affected = self.db.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, &nick, &nick, &nick))?; } if rows_affected > 0 { Ok(true) @@ -152,13 +1003,10 @@ impl Db { } /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar - pub(crate) async fn delete_user_avatar( - &self, - jid: JID, - ) -> Result<(bool, Option<String>), Error> { + pub(crate) fn delete_user_avatar(&self, jid: JID) -> Result<(bool, Option<String>), Error> { let (old_avatar, rows_affected): (Option<String>, _); { - let db = self.db().await; + let db = &self.db; old_avatar = db .query_row("select avatar from users where jid = ?1", [&jid], |row| { Ok(row.get(0)?) @@ -174,14 +1022,14 @@ impl Db { } /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar - pub(crate) async fn upsert_user_avatar( + pub(crate) fn upsert_user_avatar( &self, jid: JID, avatar: String, ) -> Result<(bool, Option<String>), Error> { let (old_avatar, rows_affected): (Option<String>, _); { - let db = self.db().await; + let db = &self.db; old_avatar = db .query_row("select avatar from users where jid = ?1", [&jid], |row| { let avatar: Option<String> = row.get(0)?; @@ -199,8 +1047,8 @@ impl Db { } // TODO: use references everywhere - pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> { - self.db().await.execute( + pub(crate) fn update_user(&self, user: User) -> Result<(), Error> { + self.db.execute( "update users set nick = ?1, avatar = ?2 where user_jid = ?1", (&user.nick, &user.avatar, &user.jid), )?; @@ -208,11 +1056,11 @@ impl Db { } // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them. - // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {} + // pub(crate) fn delete_user(&self, user: JID) -> Result<(), Error> {} /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately - pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> { - let db = self.db().await; + pub(crate) fn create_contact(&self, contact: Contact) -> Result<(), Error> { + let db = &self.db; db.execute( "insert into roster ( user_jid, name, subscription ) values ( ?1, ?2, ?3 )", (&contact.user_jid, &contact.name, contact.subscription), @@ -230,8 +1078,8 @@ impl Db { Ok(()) } - pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> { - let db = self.db().await; + pub(crate) fn read_contact(&self, contact: JID) -> Result<Contact, Error> { + let db = &self.db; let mut contact_item = db.query_row( "select user_jid, name, subscription from roster where user_jid = ?1", [&contact], @@ -252,8 +1100,8 @@ impl Db { Ok(contact_item) } - pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> { - let db = self.db().await; + pub(crate) fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> { + let db = &self.db; let contact_item = db .query_row( "select user_jid, name, subscription from roster where user_jid = ?1", @@ -281,8 +1129,8 @@ impl Db { } /// does not update the underlying user, to update user, update_user() must be called separately - pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> { - let db = self.db().await; + pub(crate) fn update_contact(&self, contact: Contact) -> Result<(), Error> { + let db = &self.db; db.execute( "update roster set name = ?1, subscription = ?2 where user_jid = ?3", (&contact.name, &contact.subscription, &contact.user_jid), @@ -305,8 +1153,8 @@ impl Db { Ok(()) } - pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> { - let db = self.db().await; + pub(crate) fn upsert_contact(&self, contact: Contact) -> Result<(), Error> { + let db = &self.db; db.execute( "insert into users (jid) values (?1) on conflict do nothing", [&contact.user_jid], @@ -332,25 +1180,24 @@ impl Db { Ok(()) } - pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> { - self.db() - .await + pub(crate) fn delete_contact(&self, contact: JID) -> Result<(), Error> { + self.db .execute("delete from roster where user_jid = ?1", [&contact])?; Ok(()) } - pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> { + pub(crate) fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> { { - self.db().await.execute("delete from roster", [])?; + self.db.execute("delete from roster", [])?; } for contact in roster { - self.upsert_contact(contact).await?; + self.upsert_contact(contact)?; } Ok(()) } - pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> { - let db = self.db().await; + pub(crate) fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> { + let db = &self.db; let mut roster: Vec<_> = db .prepare("select user_jid, name, subscription from roster")? .query_map([], |row| { @@ -372,10 +1219,8 @@ impl Db { Ok(roster) } - pub(crate) async fn read_cached_roster_with_users( - &self, - ) -> Result<Vec<(Contact, User)>, Error> { - let db = self.db().await; + pub(crate) fn read_cached_roster_with_users(&self) -> Result<Vec<(Contact, User)>, Error> { + let db = &self.db; let mut roster: Vec<(Contact, User)> = db.prepare("select user_jid, name, subscription, jid, nick, avatar from roster join users on jid = user_jid")?.query_map([], |row| { Ok(( Contact { @@ -401,10 +1246,10 @@ impl Db { Ok(roster) } - pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> { + pub(crate) fn create_chat(&self, chat: Chat) -> Result<(), Error> { let id = Uuid::new_v4(); let jid = chat.correspondent(); - self.db().await.execute( + self.db.execute( "insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3)", (id, jid, chat.have_chatted), )?; @@ -413,8 +1258,8 @@ impl Db { // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster. - pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> { - let chat = self.db().await.query_row( + pub(crate) fn read_chat(&self, chat: JID) -> Result<Chat, Error> { + let chat = self.db.query_row( "select correspondent, have_chatted from chats where correspondent = ?1", [&chat], |row| { @@ -427,22 +1272,22 @@ impl Db { Ok(chat) } - pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { - self.db().await.execute( + pub(crate) fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { + self.db.execute( "update chats set have_chatted = true where correspondent = ?1", [chat], )?; Ok(()) } - pub(crate) async fn update_chat_correspondent( + pub(crate) fn update_chat_correspondent( &self, old_chat: Chat, new_correspondent: JID, ) -> Result<Chat, Error> { let new_jid = &new_correspondent; let old_jid = old_chat.correspondent(); - let chat = self.db().await.query_row( + let chat = self.db.query_row( "update chats set correspondent = ?1 where correspondent = ?2 returning correspondent, have_chatted", [new_jid, old_jid], |row| Ok(Chat { @@ -453,20 +1298,18 @@ impl Db { Ok(chat) } - // pub(crate) async fn update_chat + // pub(crate) fn update_chat - pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> { - self.db() - .await + pub(crate) fn delete_chat(&self, chat: JID) -> Result<(), Error> { + self.db .execute("delete from chats where correspondent = ?1", [chat])?; Ok(()) } /// TODO: sorting and filtering (for now there is no sorting) - pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> { + pub(crate) fn read_chats(&self) -> Result<Vec<Chat>, Error> { let chats = self - .db() - .await + .db .prepare("select correspondent, have_chatted from chats")? .query_map([], |row| { Ok(Chat { @@ -480,10 +1323,9 @@ impl Db { /// chats ordered by date of last message // greatest-n-per-group - pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> { + pub(crate) fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> { let chats = self - .db() - .await + .db .prepare("select c.correspondent, c.have_chatted, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")? .query_map([], |row| { Ok(Chat { @@ -497,12 +1339,11 @@ impl Db { /// chats ordered by date of last message // greatest-n-per-group - pub(crate) async fn read_chats_ordered_with_latest_messages( + pub(crate) fn read_chats_ordered_with_latest_messages( &self, ) -> Result<Vec<(Chat, Message)>, Error> { let chats = self - .db() - .await + .db .prepare("select c.correspondent, c.have_chatted, m.id, m.from_jid, m.delivery, m.timestamp, m.body from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")? .query_map([], |row| { Ok(( @@ -527,12 +1368,11 @@ impl Db { /// chats ordered by date of last message // greatest-n-per-group - pub(crate) async fn read_chats_ordered_with_latest_messages_and_users( + pub(crate) fn read_chats_ordered_with_latest_messages_and_users( &self, ) -> Result<Vec<((Chat, User), (Message, User))>, Error> { let chats = self - .db() - .await + .db .prepare("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc")? .query_map([], |row| { Ok(( @@ -570,8 +1410,8 @@ impl Db { } #[tracing::instrument] - async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> { - let chat_id = self.db().await.query_row( + fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> { + let chat_id = self.db.query_row( "select id from chats where correspondent = ?1", [chat], |row| Ok(row.get(0)?), @@ -579,10 +1419,9 @@ impl Db { Ok(chat_id) } - async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> { + fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> { let chat_id = self - .db() - .await + .db .query_row( "select id from chats where correspondent = ?1", [chat], @@ -594,22 +1433,22 @@ impl Db { /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function. #[tracing::instrument] - pub(crate) async fn create_message( + pub(crate) fn create_message( &self, message: Message, chat: JID, from: JID, ) -> Result<(), Error> { let from_jid = from.as_bare(); - let chat_id = self.read_chat_id(chat).await?; + let chat_id = self.read_chat_id(chat)?; tracing::debug!("creating message"); - self.db().await.execute("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp, delivery) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)", (&message.id, &message.body.body, &chat_id, &from_jid, &from.resourcepart, &message.timestamp, &message.delivery))?; + self.db.execute("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp, delivery) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)", (&message.id, &message.body.body, &chat_id, &from_jid, &from.resourcepart, &message.timestamp, &message.delivery))?; Ok(()) } - pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> { + pub(crate) fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> { let bare_chat = chat.as_bare(); - let db = self.db().await; + let db = &self.db; db.execute( "insert into users (jid) values (?1) on conflict do nothing", [&bare_chat], @@ -631,7 +1470,7 @@ impl Db { /// create direct message from incoming. MUST upsert chat and user #[tracing::instrument] - pub(crate) async fn create_message_with_user_resource( + pub(crate) fn create_message_with_user_resource( &self, message: Message, // TODO: enforce two kinds of jid. bare and full @@ -644,28 +1483,28 @@ impl Db { let chat = chat.as_bare(); tracing::debug!("creating resource"); if let Some(resource) = &from.resourcepart { - self.db().await.execute( + self.db.execute( "insert into resources (bare_jid, resource) values (?1, ?2) on conflict do nothing", (&from_jid, resource), )?; } - self.create_message(message, chat, from).await?; + self.create_message(message, chat, from)?; Ok(()) } - pub(crate) async fn update_message_delivery( + pub(crate) fn update_message_delivery( &self, message: Uuid, delivery: Delivery, ) -> Result<(), Error> { - self.db().await.execute( + self.db.execute( "update messages set delivery = ?1 where id = ?2", (delivery, message), )?; Ok(()) } - // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> { + // pub(crate) fn read_message(&self, message: Uuid) -> Result<Message, Error> { // Ok(Message { // id: Uuid, // from: todo!(), @@ -675,17 +1514,16 @@ impl Db { // }) // } - // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {} + // TODO: message updates/edits pub(crate) fn update_message(&self, message: Message) -> Result<(), Error> {} - pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> { - self.db() - .await + pub(crate) fn delete_message(&self, message: Uuid) -> Result<(), Error> { + self.db .execute("delete from messages where id = ?1", [message])?; Ok(()) } - pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> { - let message = self.db().await.query_row( + pub(crate) fn read_message(&self, message: Uuid) -> Result<Message, Error> { + let message = self.db.query_row( "select id, from_jid, delivery, timestamp, body from messages where id = ?1", [&message], |row| { @@ -703,11 +1541,10 @@ impl Db { } // TODO: paging - pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> { - let chat_id = self.read_chat_id(chat).await?; + pub(crate) fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> { + let chat_id = self.read_chat_id(chat)?; let messages = self - .db() - .await + .db .prepare( "select id, from_jid, delivery, timestamp, body from messages where chat_id = ?1", )? @@ -725,14 +1562,13 @@ impl Db { Ok(messages) } - pub(crate) async fn read_message_history_with_users( + pub(crate) fn read_message_history_with_users( &self, chat: JID, ) -> Result<Vec<(Message, User)>, Error> { - let chat_id = self.read_chat_id(chat).await?; + let chat_id = self.read_chat_id(chat)?; let messages = self - .db() - .await + .db .prepare( "select id, from_jid, delivery, timestamp, body, jid, nick, avatar from messages join users on jid = from_jid where chat_id = ? order by timestamp asc", )? @@ -757,8 +1593,8 @@ impl Db { Ok(messages) } - pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> { - let status = self.db().await.query_row( + pub(crate) fn read_cached_status(&self) -> Result<Online, Error> { + let status = self.db.query_row( "select show, message from cached_status where id = 0", [], |row| { @@ -772,21 +1608,21 @@ impl Db { Ok(status) } - pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> { - self.db().await.execute("insert into cached_status (id, show, message) values (0, ?1, ?2) on conflict do update set show = ?3, message = ?4", (status.show, &status.status, status.show, &status.status))?; + pub(crate) fn upsert_cached_status(&self, status: Online) -> Result<(), Error> { + self.db.execute("insert into cached_status (id, show, message) values (0, ?1, ?2) on conflict do update set show = ?3, message = ?4", (status.show, &status.status, status.show, &status.status))?; Ok(()) } - pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> { - self.db().await.execute( + pub(crate) fn delete_cached_status(&self) -> Result<(), Error> { + self.db.execute( "update cached_status set show = null, message = null where id = 0", [], )?; Ok(()) } - pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> { - let capabilities = self.db().await.query_row( + pub(crate) fn read_capabilities(&self, node: String) -> Result<String, Error> { + let capabilities = self.db.query_row( "select capabilities from capability_hash_nodes where node = ?1", [node], |row| Ok(row.get(0)?), @@ -794,865 +1630,13 @@ impl Db { Ok(capabilities) } - pub(crate) async fn upsert_capabilities( + pub(crate) fn upsert_capabilities( &self, - node: &str, - capabilities: &str, + node: String, + capabilities: String, ) -> Result<(), Error> { let now = Utc::now(); - self.db().await.execute("insert into capability_hash_nodes (node, timestamp, capabilities) values (?1, ?2, ?3) on conflict do update set timestamp = ?, capabilities = ?", (node, now, capabilities, now, capabilities))?; + self.db.execute("insert into capability_hash_nodes (node, timestamp, capabilities) values (?1, ?2, ?3) on conflict do update set timestamp = ?, capabilities = ?", (node, now, &capabilities, now, &capabilities))?; Ok(()) } - - // pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> { - // sqlx::query!( - // "insert into users ( jid, nick ) values ( ?, ? )", - // user.jid, - // user.nick, - // ) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> { - // sqlx::query!( - // "insert into users ( jid ) values ( ? ) on conflict do nothing", - // user - // ) - // .execute(&self.db) - // .await?; - // let user: User = sqlx::query_as("select * from users where jid = ?") - // .bind(user) - // .fetch_one(&self.db) - // .await?; - // Ok(user) - // } - - // /// returns whether or not the nickname was updated - // pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { - // if sqlx::query!( - // "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?", - // jid, - // None::<String>, - // None::<String>, - // None::<String>, - // ) - // .execute(&self.db) - // .await? - // .rows_affected() - // > 0 - // { - // Ok(true) - // } else { - // Ok(false) - // } - // } - - // /// returns whether or not the nickname was updated - // pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { - // let rows_affected = sqlx::query!( - // "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?", - // jid, - // nick, - // nick, - // nick - // ) - // .execute(&self.db) - // .await? - // .rows_affected(); - // tracing::debug!("rows affected: {}", rows_affected); - // if rows_affected > 0 { - // Ok(true) - // } else { - // Ok(false) - // } - // } - - // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar - // pub(crate) async fn delete_user_avatar( - // &self, - // jid: JID, - // ) -> Result<(bool, Option<String>), Error> { - // #[derive(sqlx::FromRow)] - // struct AvatarRow { - // avatar: Option<String>, - // } - // let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?") - // .bind(jid.clone()) - // .fetch_optional(&self.db) - // .await? - // .map(|row: AvatarRow| row.avatar) - // .unwrap_or(None); - // if sqlx::query!( - // "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?", - // jid, - // None::<String>, - // None::<String>, - // None::<String>, - // ) - // .execute(&self.db) - // .await? - // .rows_affected() - // > 0 - // { - // Ok((true, old_avatar)) - // } else { - // Ok((false, old_avatar)) - // } - // } - - // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar - // pub(crate) async fn upsert_user_avatar( - // &self, - // jid: JID, - // avatar: String, - // ) -> Result<(bool, Option<String>), Error> { - // #[derive(sqlx::FromRow)] - // struct AvatarRow { - // avatar: Option<String>, - // } - // let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?") - // .bind(jid.clone()) - // .fetch_optional(&self.db) - // .await? - // .map(|row: AvatarRow| row.avatar) - // .unwrap_or(None); - // if sqlx::query!( - // "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?", - // jid, - // avatar, - // avatar, - // avatar, - // ) - // .execute(&self.db) - // .await? - // .rows_affected() - // > 0 - // { - // Ok((true, old_avatar)) - // } else { - // Ok((false, old_avatar)) - // } - // } - - // pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> { - // sqlx::query!( - // "update users set nick = ? where jid = ?", - // user.nick, - // user.jid - // ) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them. - // // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {} - - // /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately - // pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> { - // sqlx::query!( - // "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? )", - // contact.user_jid, - // contact.name, - // contact.subscription - // ) - // .execute(&self.db) - // .await?; - // // TODO: abstract this out in to add_to_group() function ? - // for group in contact.groups { - // sqlx::query!( - // "insert into groups (group_name) values (?) on conflict do nothing", - // group - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "insert into groups_roster (group_name, contact_jid) values (?, ?)", - // group, - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // } - // Ok(()) - // } - - // pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> { - // let mut contact: Contact = sqlx::query_as("select * from roster where user_jid = ?") - // .bind(contact) - // .fetch_one(&self.db) - // .await?; - // #[derive(sqlx::FromRow)] - // struct Row { - // group_name: String, - // } - // let groups: Vec<Row> = - // sqlx::query_as("select group_name from groups_roster where contact_jid = ?") - // .bind(&contact.user_jid) - // .fetch_all(&self.db) - // .await?; - // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name)); - // Ok(contact) - // } - - // pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> { - // let contact: Option<Contact> = - // sqlx::query_as("select * from roster join users on jid = user_jid where jid = ?") - // .bind(contact) - // .fetch_optional(&self.db) - // .await?; - // if let Some(mut contact) = contact { - // #[derive(sqlx::FromRow)] - // struct Row { - // group_name: String, - // } - // let groups: Vec<Row> = - // sqlx::query_as("select group_name from groups_roster where contact_jid = ?") - // .bind(&contact.user_jid) - // .fetch_all(&self.db) - // .await?; - // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name)); - // Ok(Some(contact)) - // } else { - // Ok(None) - // } - // } - - // /// does not update the underlying user, to update user, update_user() must be called separately - // pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> { - // sqlx::query!( - // "update roster set name = ?, subscription = ? where user_jid = ?", - // contact.name, - // contact.subscription, - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "delete from groups_roster where contact_jid = ?", - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // // TODO: delete orphaned groups from groups table - // for group in contact.groups { - // sqlx::query!( - // "insert into groups (group_name) values (?) on conflict do nothing", - // group - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "insert into groups_roster (group_name, contact_jid) values (?, ?)", - // group, - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // } - // Ok(()) - // } - - // pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> { - // sqlx::query!( - // "insert into users ( jid ) values ( ? ) on conflict do nothing", - // contact.user_jid, - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? ) on conflict do update set name = ?, subscription = ?", - // contact.user_jid, - // contact.name, - // contact.subscription, - // contact.name, - // contact.subscription - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "delete from groups_roster where contact_jid = ?", - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // // TODO: delete orphaned groups from groups table - // for group in contact.groups { - // sqlx::query!( - // "insert into groups (group_name) values (?) on conflict do nothing", - // group - // ) - // .execute(&self.db) - // .await?; - // sqlx::query!( - // "insert into groups_roster (group_name, contact_jid) values (?, ?)", - // group, - // contact.user_jid - // ) - // .execute(&self.db) - // .await?; - // } - // Ok(()) - // } - - // pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> { - // sqlx::query!("delete from roster where user_jid = ?", contact) - // .execute(&self.db) - // .await?; - // // TODO: delete orphaned groups from groups table - // Ok(()) - // } - - // pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> { - // sqlx::query!("delete from roster").execute(&self.db).await?; - // for contact in roster { - // self.upsert_contact(contact).await?; - // } - // Ok(()) - // } - - // pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> { - // let mut roster: Vec<Contact> = sqlx::query_as("select * from roster") - // .fetch_all(&self.db) - // .await?; - // for contact in &mut roster { - // #[derive(sqlx::FromRow)] - // struct Row { - // group_name: String, - // } - // let groups: Vec<Row> = - // sqlx::query_as("select group_name from groups_roster where contact_jid = ?") - // .bind(&contact.user_jid) - // .fetch_all(&self.db) - // .await?; - // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name)); - // } - // Ok(roster) - // } - - // pub(crate) async fn read_cached_roster_with_users( - // &self, - // ) -> Result<Vec<(Contact, User)>, Error> { - // #[derive(sqlx::FromRow)] - // struct Row { - // #[sqlx(flatten)] - // contact: Contact, - // #[sqlx(flatten)] - // user: User, - // } - // let mut roster: Vec<Row> = - // sqlx::query_as("select * from roster join users on jid = user_jid") - // .fetch_all(&self.db) - // .await?; - // for row in &mut roster { - // #[derive(sqlx::FromRow)] - // struct Row { - // group_name: String, - // } - // let groups: Vec<Row> = - // sqlx::query_as("select group_name from groups_roster where contact_jid = ?") - // .bind(&row.contact.user_jid) - // .fetch_all(&self.db) - // .await?; - // row.contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name)); - // } - // let roster = roster - // .into_iter() - // .map(|row| (row.contact, row.user)) - // .collect(); - // Ok(roster) - // } - - // pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> { - // let id = Uuid::new_v4(); - // let jid = chat.correspondent(); - // sqlx::query!( - // "insert into chats (id, correspondent, have_chatted) values (?, ?, ?)", - // id, - // jid, - // chat.have_chatted, - // ) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster. - - // pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> { - // // check if the chat correponding with the jid exists - // let chat: Chat = sqlx::query_as("select correspondent from chats where correspondent = ?") - // .bind(chat) - // .fetch_one(&self.db) - // .await?; - // Ok(chat) - // } - - // pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { - // let jid = chat.as_bare(); - // sqlx::query!( - // "update chats set have_chatted = true where correspondent = ?", - // jid - // ) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // pub(crate) async fn update_chat_correspondent( - // &self, - // old_chat: Chat, - // new_correspondent: JID, - // ) -> Result<Chat, Error> { - // // TODO: update other chat data if it differs (for now there is only correspondent so doesn't matter) - // let new_jid = &new_correspondent; - // let old_jid = old_chat.correspondent(); - // sqlx::query!( - // "update chats set correspondent = ? where correspondent = ?", - // new_jid, - // old_jid, - // ) - // .execute(&self.db) - // .await?; - // let chat = self.read_chat(new_correspondent).await?; - // Ok(chat) - // } - - // // pub(crate) async fn update_chat - - // pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> { - // sqlx::query!("delete from chats where correspondent = ?", chat) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // /// TODO: sorting and filtering (for now there is no sorting) - // pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> { - // let chats: Vec<Chat> = sqlx::query_as("select * from chats") - // .fetch_all(&self.db) - // .await?; - // Ok(chats) - // } - - // /// chats ordered by date of last message - // // greatest-n-per-group - // pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> { - // let chats = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc") - // .fetch_all(&self.db) - // .await?; - // Ok(chats) - // } - - // /// chats ordered by date of last message - // // greatest-n-per-group - // pub(crate) async fn read_chats_ordered_with_latest_messages( - // &self, - // ) -> Result<Vec<(Chat, Message)>, Error> { - // #[derive(sqlx::FromRow)] - // pub struct RowChat { - // chat_correspondent: JID, - // chat_have_chatted: bool, - // } - // impl From<RowChat> for Chat { - // fn from(value: RowChat) -> Self { - // Self { - // correspondent: value.chat_correspondent, - // have_chatted: value.chat_have_chatted, - // } - // } - // } - // #[derive(sqlx::FromRow)] - // pub struct RowMessage { - // message_id: Uuid, - // message_body: String, - // message_delivery: Option<Delivery>, - // message_timestamp: DateTime<Utc>, - // message_from_jid: JID, - // } - // impl From<RowMessage> for Message { - // fn from(value: RowMessage) -> Self { - // Self { - // id: value.message_id, - // from: value.message_from_jid, - // delivery: value.message_delivery, - // timestamp: value.message_timestamp, - // body: Body { - // body: value.message_body, - // }, - // } - // } - // } - - // #[derive(sqlx::FromRow)] - // pub struct ChatWithMessageRow { - // #[sqlx(flatten)] - // pub chat: RowChat, - // #[sqlx(flatten)] - // pub message: RowMessage, - // } - - // pub struct ChatWithMessage { - // chat: Chat, - // message: Message, - // } - - // impl From<ChatWithMessageRow> for ChatWithMessage { - // fn from(value: ChatWithMessageRow) -> Self { - // Self { - // chat: value.chat.into(), - // message: value.message.into(), - // } - // } - // } - - // // TODO: sometimes chats have no messages. - // let chats: Vec<ChatWithMessageRow> = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc") - // .fetch_all(&self.db) - // .await?; - - // let chats = chats - // .into_iter() - // .map(|chat_with_message_row| { - // let chat_with_message: ChatWithMessage = chat_with_message_row.into(); - // (chat_with_message.chat, chat_with_message.message) - // }) - // .collect(); - - // Ok(chats) - // } - - // /// chats ordered by date of last message - // // greatest-n-per-group - // pub(crate) async fn read_chats_ordered_with_latest_messages_and_users( - // &self, - // ) -> Result<Vec<((Chat, User), (Message, User))>, Error> { - // #[derive(sqlx::FromRow)] - // pub struct RowChat { - // chat_correspondent: JID, - // chat_have_chatted: bool, - // } - // impl From<RowChat> for Chat { - // fn from(value: RowChat) -> Self { - // Self { - // correspondent: value.chat_correspondent, - // have_chatted: value.chat_have_chatted, - // } - // } - // } - // #[derive(sqlx::FromRow)] - // pub struct RowMessage { - // message_id: Uuid, - // message_body: String, - // message_delivery: Option<Delivery>, - // message_timestamp: DateTime<Utc>, - // message_from_jid: JID, - // } - // impl From<RowMessage> for Message { - // fn from(value: RowMessage) -> Self { - // Self { - // id: value.message_id, - // from: value.message_from_jid, - // delivery: value.message_delivery, - // timestamp: value.message_timestamp, - // body: Body { - // body: value.message_body, - // }, - // } - // } - // } - // #[derive(sqlx::FromRow)] - // pub struct RowChatUser { - // chat_user_jid: JID, - // chat_user_nick: Option<String>, - // chat_user_avatar: Option<String>, - // } - // impl From<RowChatUser> for User { - // fn from(value: RowChatUser) -> Self { - // Self { - // jid: value.chat_user_jid, - // nick: value.chat_user_nick, - // avatar: value.chat_user_avatar, - // } - // } - // } - // #[derive(sqlx::FromRow)] - // pub struct RowMessageUser { - // message_user_jid: JID, - // message_user_nick: Option<String>, - // message_user_avatar: Option<String>, - // } - // impl From<RowMessageUser> for User { - // fn from(value: RowMessageUser) -> Self { - // Self { - // jid: value.message_user_jid, - // nick: value.message_user_nick, - // avatar: value.message_user_avatar, - // } - // } - // } - // #[derive(sqlx::FromRow)] - // pub struct ChatWithMessageAndUsersRow { - // #[sqlx(flatten)] - // pub chat: RowChat, - // #[sqlx(flatten)] - // pub chat_user: RowChatUser, - // #[sqlx(flatten)] - // pub message: RowMessage, - // #[sqlx(flatten)] - // pub message_user: RowMessageUser, - // } - - // impl From<ChatWithMessageAndUsersRow> for ChatWithMessageAndUsers { - // fn from(value: ChatWithMessageAndUsersRow) -> Self { - // Self { - // chat: value.chat.into(), - // chat_user: value.chat_user.into(), - // message: value.message.into(), - // message_user: value.message_user.into(), - // } - // } - // } - - // pub struct ChatWithMessageAndUsers { - // chat: Chat, - // chat_user: User, - // message: Message, - // message_user: User, - // } - - // let chats: Vec<ChatWithMessageAndUsersRow> = sqlx::query_as("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc") - // .fetch_all(&self.db) - // .await?; - - // let chats = chats - // .into_iter() - // .map(|chat_with_message_and_users_row| { - // let chat_with_message_and_users: ChatWithMessageAndUsers = - // chat_with_message_and_users_row.into(); - // ( - // ( - // chat_with_message_and_users.chat, - // chat_with_message_and_users.chat_user, - // ), - // ( - // chat_with_message_and_users.message, - // chat_with_message_and_users.message_user, - // ), - // ) - // }) - // .collect(); - - // Ok(chats) - // } - - // async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> { - // #[derive(sqlx::FromRow)] - // struct Row { - // id: Uuid, - // } - // let chat = chat.as_bare(); - // let chat_id: Row = sqlx::query_as("select id from chats where correspondent = ?") - // .bind(chat) - // .fetch_one(&self.db) - // .await?; - // let chat_id = chat_id.id; - // Ok(chat_id) - // } - - // async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> { - // #[derive(sqlx::FromRow)] - // struct Row { - // id: Uuid, - // } - // let chat_id: Option<Row> = sqlx::query_as("select id from chats where correspondent = ?") - // .bind(chat) - // .fetch_optional(&self.db) - // .await?; - // let chat_id = chat_id.map(|row| row.id); - // Ok(chat_id) - // } - - // /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function. - // pub(crate) async fn create_message( - // &self, - // message: Message, - // chat: JID, - // from: JID, - // ) -> Result<(), Error> { - // // TODO: one query - // let from_jid = from.as_bare(); - // let chat_id = self.read_chat_id(chat).await?; - // sqlx::query!("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp) values (?, ?, ?, ?, ?, ?)", message.id, message.body.body, chat_id, from_jid, from.resourcepart, message.timestamp).execute(&self.db).await?; - // Ok(()) - // } - - // pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> { - // let bare_chat = chat.as_bare(); - // sqlx::query!( - // "insert into users (jid) values (?) on conflict do nothing", - // bare_chat, - // ) - // .execute(&self.db) - // .await?; - // let id = Uuid::new_v4(); - // let chat: Chat = sqlx::query_as("insert into chats (id, correspondent, have_chatted) values (?, ?, ?) on conflict do nothing; select * from chats where correspondent = ?") - // .bind(id) - // .bind(bare_chat.clone()) - // .bind(false) - // .bind(bare_chat) - // .fetch_one(&self.db) - // .await?; - // tracing::debug!("CHECKING chat: {:?}", chat); - // Ok(chat.have_chatted) - // } - - // /// MUST upsert chat beforehand - // pub(crate) async fn create_message_with_self_resource( - // &self, - // message: Message, - // chat: JID, - // // full jid - // from: JID, - // ) -> Result<(), Error> { - // let from_jid = from.as_bare(); - // if let Some(resource) = &from.resourcepart { - // sqlx::query!( - // "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing", - // from_jid, - // resource - // ) - // .execute(&self.db) - // .await?; - // } - // self.create_message(message, chat, from).await?; - // Ok(()) - // } - - // /// create direct message from incoming. MUST upsert chat and user - // pub(crate) async fn create_message_with_user_resource( - // &self, - // message: Message, - // chat: JID, - // // full jid - // from: JID, - // ) -> Result<(), Error> { - // let bare_chat = chat.as_bare(); - // let resource = &chat.resourcepart; - // if let Some(resource) = resource { - // sqlx::query!( - // "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing", - // bare_chat, - // resource - // ) - // .execute(&self.db) - // .await?; - // } - // self.create_message(message, chat, from).await?; - // Ok(()) - // } - - // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> { - // let message: Message = sqlx::query_as("select * from messages where id = ?") - // .bind(message) - // .fetch_one(&self.db) - // .await?; - // Ok(message) - // } - - // // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {} - - // pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> { - // sqlx::query!("delete from messages where id = ?", message) - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // // TODO: paging - // pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> { - // let chat_id = self.read_chat_id(chat).await?; - // let messages: Vec<Message> = - // sqlx::query_as("select * from messages where chat_id = ? order by timestamp asc") - // .bind(chat_id) - // .fetch_all(&self.db) - // .await?; - // Ok(messages) - // } - - // pub(crate) async fn read_message_history_with_users( - // &self, - // chat: JID, - // ) -> Result<Vec<(Message, User)>, Error> { - // let chat_id = self.read_chat_id(chat).await?; - // #[derive(sqlx::FromRow)] - // pub struct Row { - // #[sqlx(flatten)] - // user: User, - // #[sqlx(flatten)] - // message: Message, - // } - // let messages: Vec<Row> = - // sqlx::query_as("select * from messages join users on jid = from_jid where chat_id = ? order by timestamp asc") - // .bind(chat_id) - // .fetch_all(&self.db) - // .await?; - // let messages = messages - // .into_iter() - // .map(|row| (row.message, row.user)) - // .collect(); - // Ok(messages) - // } - - // pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> { - // let online: Online = sqlx::query_as("select * from cached_status where id = 0") - // .fetch_one(&self.db) - // .await?; - // Ok(online) - // } - - // pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> { - // sqlx::query!( - // "insert into cached_status (id, show, message) values (0, ?, ?) on conflict do update set show = ?, message = ?", - // status.show, - // status.status, - // status.show, - // status.status - // ).execute(&self.db).await?; - // Ok(()) - // } - - // pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> { - // sqlx::query!("update cached_status set show = null, message = null where id = 0") - // .execute(&self.db) - // .await?; - // Ok(()) - // } - - // pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> { - // #[derive(sqlx::FromRow)] - // struct Row { - // capabilities: String, - // } - // let row: Row = - // sqlx::query_as("select capabilities from capability_hash_nodes where node = ?") - // .bind(node) - // .fetch_one(&self.db) - // .await?; - // Ok(row.capabilities) - // } - - // pub(crate) async fn upsert_capabilities( - // &self, - // node: &str, - // capabilities: &str, - // ) -> Result<(), Error> { - // let now = Utc::now(); - // sqlx::query!( - // "insert into capability_hash_nodes (node, timestamp, capabilities) values (?, ?, ?) on conflict do update set timestamp = ?, capabilities = ?", node, now, capabilities, now, capabilities - // ).execute(&self.db).await?; - // Ok(()) - // } } diff --git a/filamento/src/error.rs b/filamento/src/error.rs index 02f54ee..9334793 100644 --- a/filamento/src/error.rs +++ b/filamento/src/error.rs @@ -9,7 +9,10 @@ use thiserror::Error; pub use lampada::error::CommandError; pub use lampada::error::ConnectionError; +use tokio::sync::mpsc::error::SendError; +use tokio::sync::oneshot::error::RecvError; +use crate::db::DbCommand; use crate::files::FileStore; // for the client logic impl @@ -166,8 +169,20 @@ pub enum ResponseError { } #[derive(Debug, Error, Clone)] -#[error("database error: {0}")] -pub struct DatabaseError(pub Serializeable<Arc<rusqlite::Error>>); +pub enum DatabaseError { + #[error("database error: {0}")] + Database(Serializeable<Arc<rusqlite::Error>>), + #[error("database command send: {0}")] + Send(Arc<SendError<DbCommand>>), + #[error("database result recv: {0}")] + Recv(#[from] RecvError), +} + +impl From<SendError<DbCommand>> for DatabaseError { + fn from(e: SendError<DbCommand>) -> Self { + Self::Send(Arc::new(e)) + } +} pub enum Serializeable<T> { String(String), @@ -227,7 +242,7 @@ impl<'de> serde::Deserialize<'de> for DatabaseError { D: serde::Deserializer<'de>, { let string = deserializer.deserialize_string(StringVisitor)?; - Ok(Self(Serializeable::String(string))) + Ok(Self::Database(Serializeable::String(string))) } } @@ -246,7 +261,7 @@ impl serde::Serialize for DatabaseError { impl From<rusqlite::Error> for DatabaseError { fn from(e: rusqlite::Error) -> Self { - Self(Serializeable::Unserialized(Arc::new(e))) + Self::Database(Serializeable::Unserialized(Arc::new(e))) } } @@ -285,6 +300,8 @@ pub enum DatabaseOpenError { Io(Arc<tokio::io::Error>), #[error("invalid path")] InvalidPath, + #[error("tokio oneshot recv error: {0}")] + Recv(#[from] tokio::sync::oneshot::error::RecvError), } // impl From<sqlx::migrate::MigrateError> for DatabaseOpenError { diff --git a/filamento/src/files/opfs.rs b/filamento/src/files/opfs.rs new file mode 100644 index 0000000..e040762 --- /dev/null +++ b/filamento/src/files/opfs.rs @@ -0,0 +1,110 @@ +use std::path::Path; + +use thiserror::Error; +use wasm_bindgen::JsValue; +use wasm_bindgen_futures::JsFuture; +use web_sys::{ + window, File, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, FileSystemWritableFileStream, Url +}; + +use crate::FileStore; + +#[derive(Clone)] +pub struct FilesOPFS { + directory: String, +} + +impl FilesOPFS { + pub async fn new(directory: impl AsRef<str>) -> Result<Self, OPFSError> { + let directory = directory.as_ref(); + let directory_string = directory.to_string(); + let promise = window().unwrap().navigator().storage().get_directory(); + let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into(); + let options = FileSystemGetDirectoryOptions::new(); + options.set_create(true); + let directory: FileSystemDirectoryHandle = + JsFuture::from(opfs_root.get_directory_handle_with_options(directory, &options)) + .await? + .into(); + Ok(Self { directory: directory_string }) + } + + pub async fn get_src(&self, file_name: impl AsRef<str>) -> Result<String, OPFSError> { + let promise = window().unwrap().navigator().storage().get_directory(); + let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into(); + let directory: FileSystemDirectoryHandle = + JsFuture::from(opfs_root.get_directory_handle(&self.directory)) + .await? + .into(); + let handle: FileSystemFileHandle = + JsFuture::from(directory.get_file_handle(file_name.as_ref())) + .await? + .into(); + let file: File = JsFuture::from(handle.get_file()).await?.into(); + let src = Url::create_object_url_with_blob(&file)?; + Ok(src) + } +} + +impl FileStore for FilesOPFS { + type Err = OPFSError; + + async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> { + let promise = window().unwrap().navigator().storage().get_directory(); + let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into(); + let directory: FileSystemDirectoryHandle = + JsFuture::from(opfs_root.get_directory_handle(&self.directory)) + .await? + .into(); + let stored = JsFuture::from(directory.get_file_handle(name)) + .await + .map(|_| true) + // TODO: distinguish between other errors and notfound + .unwrap_or(false); + Ok(stored) + } + + async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> { + let promise = window().unwrap().navigator().storage().get_directory(); + let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into(); + let directory: FileSystemDirectoryHandle = + JsFuture::from(opfs_root.get_directory_handle(&self.directory)) + .await? + .into(); + let options = FileSystemGetFileOptions::new(); + options.set_create(true); + let handle: FileSystemFileHandle = JsFuture::from(directory.get_file_handle_with_options(name, &options)) + .await? + .into(); + let write_handle: FileSystemWritableFileStream = + JsFuture::from(handle.create_writable()).await?.into(); + let write_promise = write_handle.write_with_u8_array(data)?; + let _ = JsFuture::from(write_promise).await?; + let _ = JsFuture::from(write_handle.close()).await?; + Ok(()) + } + + async fn delete(&self, name: &str) -> Result<(), Self::Err> { + let promise = window().unwrap().navigator().storage().get_directory(); + let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into(); + let directory: FileSystemDirectoryHandle = + JsFuture::from(opfs_root.get_directory_handle(&self.directory)) + .await? + .into(); + let _ = JsFuture::from(directory.remove_entry(name)).await?; + Ok(()) + } +} + +#[derive(Error, Clone, Debug)] +pub enum OPFSError { + #[error("not found")] + NotFound, +} + +// TODO: better errors +impl From<JsValue> for OPFSError { + fn from(value: JsValue) -> Self { + Self::NotFound + } +} diff --git a/filamento/src/logic/online.rs b/filamento/src/logic/online.rs index 3936584..969e08a 100644 --- a/filamento/src/logic/online.rs +++ b/filamento/src/logic/online.rs @@ -478,7 +478,7 @@ pub async fn handle_set_status<Fs: FileStore + Clone>( pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, connection: Connected, jid: JID, body: Body) { // upsert the chat and user the message will be delivered to. if there is a conflict, it will return whatever was there, otherwise it will return false by default. // let have_chatted = logic.db().upsert_chat_and_user(&jid).await.unwrap_or(false); - let have_chatted = match logic.db().upsert_chat_and_user(&jid).await { + let have_chatted = match logic.db().upsert_chat_and_user(jid.clone()).await { Ok(have_chatted) => { have_chatted }, diff --git a/filamento/src/logic/process_stanza.rs b/filamento/src/logic/process_stanza.rs index 81c3b1f..3bc4b8c 100644 --- a/filamento/src/logic/process_stanza.rs +++ b/filamento/src/logic/process_stanza.rs @@ -80,7 +80,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( // TODO: process message type="error" // save the message to the database - match logic.db().upsert_chat_and_user(&from).await { + match logic.db().upsert_chat_and_user(from.clone()).await { Ok(_) => { if let Err(e) = logic .db() @@ -590,7 +590,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } else { match logic .db() - .read_capabilities(&query.node.clone().unwrap()) + .read_capabilities(query.node.clone().unwrap()) .await { Ok(c) => match caps::decode_info_base64(c) { |