add: apps api

This commit is contained in:
trisua 2025-06-14 14:45:52 -04:00
parent 2a99d49c8a
commit ebded00fd3
33 changed files with 698 additions and 31 deletions

View file

@ -0,0 +1,150 @@
use oiseau::cache::Cache;
use crate::model::{
Error, Result,
auth::User,
permissions::FinePermission,
apps::{AppQuota, ThirdPartyApp},
};
use crate::{auto_method, DataManager};
#[cfg(feature = "sqlite")]
use oiseau::SqliteRow;
#[cfg(feature = "postgres")]
use oiseau::PostgresRow;
use oiseau::{execute, get, query_rows, params};
impl DataManager {
/// Get a [`ThirdPartyApp`] from an SQL row.
pub(crate) fn get_app_from_row(
#[cfg(feature = "sqlite")] x: &SqliteRow<'_>,
#[cfg(feature = "postgres")] x: &PostgresRow,
) -> ThirdPartyApp {
ThirdPartyApp {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
title: get!(x->3(String)),
homepage: get!(x->4(String)),
redirect: get!(x->5(String)),
quota_status: serde_json::from_str(&get!(x->6(String))).unwrap(),
banned: get!(x->7(i32)) as i8 == 1,
grants: get!(x->8(i32)) as usize,
}
}
auto_method!(get_app_by_id(usize as i64)@get_app_from_row -> "SELECT * FROM apps WHERE id = $1" --name="app" --returns=ThirdPartyApp --cache-key-tmpl="atto.app:{}");
/// Get all apps by user.
///
/// # Arguments
/// * `id` - the ID of the user to fetch apps for
pub async fn get_apps_by_owner(&self, id: usize) -> Result<Vec<ThirdPartyApp>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM apps WHERE owner = $1 ORDER BY created DESC",
&[&(id as i64)],
|x| { Self::get_app_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("app".to_string()));
}
Ok(res.unwrap())
}
const MAXIMUM_FREE_APPS: usize = 1;
/// Create a new app in the database.
///
/// # Arguments
/// * `data` - a mock [`ThirdPartyApp`] object to insert
pub async fn create_app(&self, data: ThirdPartyApp) -> Result<ThirdPartyApp> {
// check values
if data.title.len() < 2 {
return Err(Error::DataTooShort("title".to_string()));
} else if data.title.len() > 32 {
return Err(Error::DataTooLong("title".to_string()));
}
// check number of apps
let owner = self.get_user_by_id(data.owner).await?;
if !owner.permissions.check(FinePermission::SUPPORTER) {
let apps = self.get_apps_by_owner(data.owner).await?;
if apps.len() >= Self::MAXIMUM_FREE_APPS {
return Err(Error::MiscError(
"You already have the maximum number of apps you can have".to_string(),
));
}
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO apps VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&data.title,
&data.homepage,
&data.redirect,
&serde_json::to_string(&data.quota_status).unwrap(),
&{ if data.banned { 1 } else { 0 } },
&(data.grants as i32)
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
pub async fn delete_app(&self, id: usize, user: &User) -> Result<()> {
let app = self.get_app_by_id(id).await?;
// check user permission
if user.id != app.owner && !user.permissions.check(FinePermission::MANAGE_APPS) {
return Err(Error::NotAllowed);
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, "DELETE FROM apps WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.app:{}", id)).await;
Ok(())
}
auto_method!(update_app_title(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_homepage(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET homepage = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_redirect(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET redirect = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_quota_status(AppQuota) -> "UPDATE apps SET quota_status = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.app:{}");
auto_method!(incr_app_grants() -> "UPDATE apps SET grants = grants + 1 WHERE id = $2" --cache-key-tmpl="atto.app:{}" --incr);
auto_method!(decr_app_grants()@get_app_by_id -> "UPDATE apps SET grants = grants - 1 WHERE id = $2" --cache-key-tmpl="atto.app:{}" --decr=grants);
}

View file

@ -34,6 +34,7 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_DRAFTS).unwrap();
execute!(&conn, common::CREATE_TABLE_POLLS).unwrap();
execute!(&conn, common::CREATE_TABLE_POLLVOTES).unwrap();
execute!(&conn, common::CREATE_TABLE_APPS).unwrap();
self.0
.1
@ -456,7 +457,7 @@ macro_rules! auto_method {
let res = execute!(
&conn,
$query,
&[&serde_json::to_string(&x).unwrap(), &(id as i64)]
params![&serde_json::to_string(&x).unwrap(), &(id as i64)]
);
if let Err(e) = res {
@ -507,6 +508,31 @@ macro_rules! auto_method {
}
};
($name:ident()@$select_fn:ident -> $query:literal --cache-key-tmpl=$cache_key_tmpl:literal --decr=$field:ident) => {
pub async fn $name(&self, id: usize) -> Result<()> {
let y = self.$select_fn(id).await?;
if (y.$field as isize) - 1 < 0 {
return Ok(());
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, $query, &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!($cache_key_tmpl, id)).await;
Ok(())
}
};
($name:ident()@$select_fn:ident:$permission:ident -> $query:literal --cache-key-tmpl=$cache_key_tmpl:ident) => {
pub async fn $name(&self, id: usize, user: &User) -> Result<()> {
let y = self.$select_fn(id).await?;

View file

@ -21,3 +21,4 @@ pub const CREATE_TABLE_STACKS: &str = include_str!("./sql/create_stacks.sql");
pub const CREATE_TABLE_DRAFTS: &str = include_str!("./sql/create_drafts.sql");
pub const CREATE_TABLE_POLLS: &str = include_str!("./sql/create_polls.sql");
pub const CREATE_TABLE_POLLVOTES: &str = include_str!("./sql/create_pollvotes.sql");
pub const CREATE_TABLE_APPS: &str = include_str!("./sql/create_apps.sql");

View file

@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS apps (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
title TEXT NOT NULL,
homepage TEXT NOT NULL,
redirect TEXT NOT NULL,
quota_status TEXT NOT NULL,
banned INT NOT NULL,
grants INT NOT NULL
)

View file

@ -1,3 +1,4 @@
mod apps;
mod audit_log;
mod auth;
mod common;

View file

@ -1,11 +1,10 @@
use oiseau::cache::Cache;
use crate::model::communities::{Community, Poll, Post, Question};
use crate::model::stacks::{StackMode, StackSort};
use crate::model::{
Error, Result,
auth::User,
permissions::FinePermission,
stacks::{StackPrivacy, UserStack},
stacks::{StackPrivacy, UserStack, StackMode, StackSort},
communities::{Community, Poll, Post, Question},
};
use crate::{auto_method, DataManager};