mod database;
mod error;
mod memory;
use database::Database;
pub use error::Error;
use memory::Memory;
use sqlite::{Connection, Transaction};
use std::{rc::Rc, sync::RwLock};
pub struct Auth {
pub database: Rc<Database>,
pub memory: Rc<Memory>,
}
impl Auth {
pub fn new(connection: Rc<RwLock<Connection>>) -> Result<Self, Error> {
let this = Self {
database: Rc::new(Database::new(connection)),
memory: Rc::new(Memory::new()),
};
Self::index(&this)?;
Ok(this)
}
pub fn apply(&self, profile_identity_gemini_id: i64, url: &str) -> Result<i64, Error> {
self.remove(url)?;
let profile_identity_gemini_auth_id =
match self.database.add(profile_identity_gemini_id, url) {
Ok(id) => id,
Err(reason) => return Err(Error::Database(reason)),
};
self.index()?;
Ok(profile_identity_gemini_auth_id)
}
pub fn remove(&self, url: &str) -> Result<(), Error> {
match self.database.records(Some(url)) {
Ok(records) => {
for record in records {
if let Err(reason) = self.database.delete(record.id) {
return Err(Error::Database(reason));
}
}
}
Err(reason) => return Err(Error::Database(reason)),
}
self.index()?;
Ok(())
}
pub fn index(&self) -> Result<(), Error> {
if let Err(reason) = self.memory.clear() {
return Err(Error::Memory(reason));
}
match self.database.records(None) {
Ok(records) => {
for record in records {
if let Err(reason) = self
.memory
.add(record.url, record.profile_identity_gemini_id)
{
return Err(Error::Memory(reason));
}
}
}
Err(reason) => return Err(Error::Database(reason)),
}
Ok(())
}
}
pub fn migrate(tx: &Transaction) -> Result<(), String> {
if let Err(e) = database::init(tx) {
return Err(e.to_string());
}
Ok(())
}