Lines
90.93 %
Functions
42.62 %
Branches
45.79 %
/*
* This file is part of mailpot
*
* Copyright 2020 - Manos Pitsidianakis
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! User subscriptions.
use log::trace;
use rusqlite::OptionalExtension;
use crate::{
errors::{ErrorKind::*, *},
models::{
changesets::{AccountChangeset, ListSubscriptionChangeset},
Account, ListCandidateSubscription, ListSubscription,
},
Connection, DbVal,
};
impl Connection {
/// Fetch all subscriptions of a mailing list.
pub fn list_subscriptions(&self, list_pk: i64) -> Result<Vec<DbVal<ListSubscription>>> {
let mut stmt = self
.connection
.prepare("SELECT * FROM subscription WHERE list = ?;")?;
let list_iter = stmt.query_map([&list_pk], |row| {
let pk = row.get("pk")?;
Ok(DbVal(
ListSubscription {
pk: row.get("pk")?,
list: row.get("list")?,
address: row.get("address")?,
account: row.get("account")?,
name: row.get("name")?,
digest: row.get("digest")?,
enabled: row.get("enabled")?,
verified: row.get("verified")?,
hide_address: row.get("hide_address")?,
receive_duplicates: row.get("receive_duplicates")?,
receive_own_posts: row.get("receive_own_posts")?,
receive_confirmation: row.get("receive_confirmation")?,
pk,
))
})?;
let mut ret = vec![];
for list in list_iter {
let list = list?;
ret.push(list);
}
Ok(ret)
/// Fetch mailing list subscription.
pub fn list_subscription(&self, list_pk: i64, pk: i64) -> Result<DbVal<ListSubscription>> {
.prepare("SELECT * FROM subscription WHERE list = ? AND pk = ?;")?;
let ret = stmt.query_row([&list_pk, &pk], |row| {
let _pk: i64 = row.get("pk")?;
debug_assert_eq!(pk, _pk);
/// Fetch mailing list subscription by their address.
pub fn list_subscription_by_address(
&self,
list_pk: i64,
address: &str,
) -> Result<DbVal<ListSubscription>> {
.prepare("SELECT * FROM subscription WHERE list = ? AND address = ?;")?;
let ret = stmt.query_row(rusqlite::params![&list_pk, &address], |row| {
let address_ = row.get("address")?;
debug_assert_eq!(address, &address_);
address: address_,
/// Add subscription to mailing list.
pub fn add_subscription(
mut new_val: ListSubscription,
new_val.list = list_pk;
.prepare(
"INSERT INTO subscription(list, address, account, name, enabled, digest, \
verified, hide_address, receive_duplicates, receive_own_posts, \
receive_confirmation) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *;",
)
.unwrap();
let val = stmt.query_row(
rusqlite::params![
&new_val.list,
&new_val.address,
&new_val.account,
&new_val.name,
&new_val.enabled,
&new_val.digest,
&new_val.verified,
&new_val.hide_address,
&new_val.receive_duplicates,
&new_val.receive_own_posts,
&new_val.receive_confirmation
],
|row| {
)?;
trace!("add_subscription {:?}.", &val);
// table entry might be modified by triggers, so don't rely on RETURNING value.
self.list_subscription(list_pk, val.pk())
/// Fetch all candidate subscriptions of a mailing list.
pub fn list_subscription_requests(
) -> Result<Vec<DbVal<ListCandidateSubscription>>> {
.prepare("SELECT * FROM candidate_subscription WHERE list = ?;")?;
ListCandidateSubscription {
accepted: row.get("accepted")?,
/// Create subscription candidate.
pub fn add_candidate_subscription(
) -> Result<DbVal<ListCandidateSubscription>> {
let mut stmt = self.connection.prepare(
"INSERT INTO candidate_subscription(list, address, name, accepted) VALUES(?, ?, ?, ?) \
RETURNING *;",
rusqlite::params![&new_val.list, &new_val.address, &new_val.name, None::<i64>,],
drop(stmt);
trace!("add_candidate_subscription {:?}.", &val);
self.candidate_subscription(val.pk())
/// Fetch subscription candidate by primary key.
pub fn candidate_subscription(&self, pk: i64) -> Result<DbVal<ListCandidateSubscription>> {
.prepare("SELECT * FROM candidate_subscription WHERE pk = ?;")?;
let val = stmt
.query_row(rusqlite::params![&pk], |row| {
})
.map_err(|err| {
if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
Error::from(err)
.chain_err(|| NotFound("Candidate subscription with this pk not found!"))
} else {
err.into()
Ok(val)
/// Accept subscription candidate.
pub fn accept_candidate_subscription(&self, pk: i64) -> Result<DbVal<ListSubscription>> {
let val = self.connection.query_row(
"INSERT INTO subscription(list, address, name, enabled, digest, verified, \
hide_address, receive_duplicates, receive_own_posts, receive_confirmation) SELECT \
list, address, name, 1, 0, 0, 0, 1, 1, 0 FROM candidate_subscription WHERE pk = ? \
rusqlite::params![&pk],
trace!("accept_candidate_subscription {:?}.", &val);
let ret = self.list_subscription(val.list, val.pk())?;
// assert that [ref:accept_candidate] trigger works.
debug_assert_eq!(Some(ret.pk), self.candidate_subscription(pk)?.accepted);
/// Remove a subscription by their address.
pub fn remove_subscription(&self, list_pk: i64, address: &str) -> Result<()> {
self.connection
.query_row(
"DELETE FROM subscription WHERE list = ? AND address = ? RETURNING *;",
rusqlite::params![&list_pk, &address],
|_| Ok(()),
Error::from(err).chain_err(|| NotFound("list or list owner not found!"))
Ok(())
/// Update a mailing list subscription.
pub fn update_subscription(&self, change_set: ListSubscriptionChangeset) -> Result<()> {
let pk = self
.list_subscription_by_address(change_set.list, &change_set.address)?
.pk;
if matches!(
change_set,
ListSubscriptionChangeset {
list: _,
address: _,
account: None,
name: None,
digest: None,
verified: None,
hide_address: None,
receive_duplicates: None,
receive_own_posts: None,
receive_confirmation: None,
enabled: None,
) {
return Ok(());
let ListSubscriptionChangeset {
list,
name,
account,
digest,
enabled,
verified,
hide_address,
receive_duplicates,
receive_own_posts,
receive_confirmation,
} = change_set;
let tx = self.savepoint(Some(stringify!(update_subscription)))?;
macro_rules! update {
($field:tt) => {{
if let Some($field) = $field {
tx.connection.execute(
concat!(
"UPDATE subscription SET ",
stringify!($field),
" = ? WHERE list = ? AND pk = ?;"
),
rusqlite::params![&$field, &list, &pk],
}};
update!(name);
update!(account);
update!(digest);
update!(enabled);
update!(verified);
update!(hide_address);
update!(receive_duplicates);
update!(receive_own_posts);
update!(receive_confirmation);
tx.commit()?;
/// Fetch account by pk.
pub fn account(&self, pk: i64) -> Result<Option<DbVal<Account>>> {
.prepare("SELECT * FROM account WHERE pk = ?;")?;
let ret = stmt
Account {
public_key: row.get("public_key")?,
password: row.get("password")?,
.optional()?;
/// Fetch account by address.
pub fn account_by_address(&self, address: &str) -> Result<Option<DbVal<Account>>> {
.prepare("SELECT * FROM account WHERE address = ?;")?;
.query_row(rusqlite::params![&address], |row| {
/// Fetch all subscriptions of an account by primary key.
pub fn account_subscriptions(&self, pk: i64) -> Result<Vec<DbVal<ListSubscription>>> {
.prepare("SELECT * FROM subscription WHERE account = ?;")?;
let list_iter = stmt.query_map([&pk], |row| {
/// Fetch all accounts.
pub fn accounts(&self) -> Result<Vec<DbVal<Account>>> {
.prepare("SELECT * FROM account ORDER BY pk ASC;")?;
let list_iter = stmt.query_map([], |row| {
/// Add account.
pub fn add_account(&self, new_val: Account) -> Result<DbVal<Account>> {
"INSERT INTO account(name, address, public_key, password, enabled) VALUES(?, ?, \
?, ?, ?) RETURNING *;",
let ret = stmt.query_row(
&new_val.public_key,
&new_val.password,
trace!("add_account {:?}.", &ret);
/// Remove an account by their address.
pub fn remove_account(&self, address: &str) -> Result<()> {
"DELETE FROM account WHERE address = ? RETURNING *;",
rusqlite::params![&address],
Error::from(err).chain_err(|| NotFound("account not found!"))
/// Update an account.
pub fn update_account(&self, change_set: AccountChangeset) -> Result<()> {
let Some(acc) = self.account_by_address(&change_set.address)? else {
return Err(NotFound("account with this address not found!").into());
let pk = acc.pk;
AccountChangeset {
public_key: None,
password: None,
let AccountChangeset {
public_key,
password,
let tx = self.savepoint(Some(stringify!(update_account)))?;
"UPDATE account SET ",
" = ? WHERE pk = ?;"
rusqlite::params![&$field, &pk],
update!(public_key);
update!(password);
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn test_subscription_ops() {
use tempfile::TempDir;
let tmp_dir = TempDir::new().unwrap();
let db_path = tmp_dir.path().join("mpot.db");
let config = Configuration {
send_mail: SendMail::ShellCommand("/usr/bin/false".to_string()),
db_path,
data_path: tmp_dir.path().to_path_buf(),
administrators: vec![],
let db = Connection::open_or_create_db(config).unwrap().trusted();
let list = db
.create_list(MailingList {
pk: -1,
name: "foobar chat".into(),
id: "foo-chat".into(),
address: "foo-chat@example.com".into(),
topics: vec![],
description: None,
archive_url: None,
let secondary_list = db
name: "foobar chat2".into(),
id: "foo-chat2".into(),
address: "foo-chat2@example.com".into(),
for i in 0..4 {
let sub = db
.add_subscription(
list.pk(),
list: list.pk(),
address: format!("{i}@example.com"),
name: Some(format!("User{i}")),
digest: false,
hide_address: false,
receive_duplicates: false,
receive_own_posts: false,
receive_confirmation: false,
enabled: true,
verified: false,
assert_eq!(db.list_subscription(list.pk(), sub.pk()).unwrap(), sub);
assert_eq!(
db.list_subscription_by_address(list.pk(), &sub.address)
.unwrap(),
sub
);
assert_eq!(db.accounts().unwrap(), vec![]);
db.remove_subscription(list.pk(), "nonexistent@example.com")
.map_err(|err| err.to_string())
.unwrap_err(),
NotFound("list or list owner not found!").to_string()
let cand = db
.add_candidate_subscription(
address: "4@example.com".into(),
name: Some("User4".into()),
let accepted = db.accept_candidate_subscription(cand.pk()).unwrap();
assert_eq!(db.account(5).unwrap(), None);
db.remove_account("4@example.com")
NotFound("account not found!").to_string()
let acc = db
.add_account(Account {
name: accepted.name.clone(),
address: accepted.address.clone(),
password: String::new(),
// Test [ref:add_account] SQL trigger (see schema.sql)
db.list_subscription(list.pk(), accepted.pk())
.unwrap()
.account,
Some(acc.pk())
// Test [ref:add_account_to_subscription] SQL trigger (see schema.sql)
secondary_list.pk(),
list: secondary_list.pk(),
verified: true,
assert_eq!(sub.account, Some(acc.pk()));
// Test [ref:verify_subscription_email] SQL trigger (see schema.sql)
assert!(!sub.verified);
assert_eq!(db.accounts().unwrap(), vec![acc.clone()]);
db.update_account(AccountChangeset {
address: "nonexistent@example.com".into(),
..AccountChangeset::default()
NotFound("account with this address not found!").to_string()
address: acc.address.clone(),
.map_err(|err| err.to_string()),
enabled: Some(Some(false)),
assert!(!db.account(acc.pk()).unwrap().unwrap().enabled);