add: full links api

This commit is contained in:
trisua 2025-06-24 16:34:55 -04:00
parent c2dbe2f114
commit ffdb767518
12 changed files with 532 additions and 4 deletions

View file

@ -40,6 +40,7 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_NOTES).unwrap();
execute!(&conn, common::CREATE_TABLE_MESSAGE_REACTIONS).unwrap();
execute!(&conn, common::CREATE_TABLE_INVITE_CODES).unwrap();
execute!(&conn, common::CREATE_TABLE_LINKS).unwrap();
self.0
.1

View file

@ -27,3 +27,4 @@ pub const CREATE_TABLE_JOURNALS: &str = include_str!("./sql/create_journals.sql"
pub const CREATE_TABLE_NOTES: &str = include_str!("./sql/create_notes.sql");
pub const CREATE_TABLE_MESSAGE_REACTIONS: &str = include_str!("./sql/create_message_reactions.sql");
pub const CREATE_TABLE_INVITE_CODES: &str = include_str!("./sql/create_invite_codes.sql");
pub const CREATE_TABLE_LINKS: &str = include_str!("./sql/create_links.sql");

View file

@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS links (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
label TEXT NOT NULL,
href TEXT NOT NULL,
upload_id BIGINT NOT NULL,
clicks INT NOT NULL,
position INT NOT NULL
)

View file

@ -0,0 +1,146 @@
use oiseau::{cache::Cache, query_row, query_rows};
use crate::model::{auth::User, links::Link, permissions::FinePermission, Error, Result};
use crate::{auto_method, DataManager};
use oiseau::{PostgresRow, execute, get, params};
impl DataManager {
/// Get a [`Link`] from an SQL row.
pub(crate) fn get_link_from_row(x: &PostgresRow) -> Link {
Link {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
label: get!(x->3(String)),
href: get!(x->4(String)),
upload_id: get!(x->5(i64)) as usize,
clicks: get!(x->6(i32)) as usize,
position: get!(x->7(i32)) as usize,
}
}
auto_method!(get_link_by_id()@get_link_from_row -> "SELECT * FROM links WHERE id = $1" --name="link" --returns=Link --cache-key-tmpl="atto.link:{}");
/// Get links by `owner`.
pub async fn get_links_by_owner(&self, owner: usize) -> Result<Vec<Link>> {
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 links WHERE owner = $1 ORDER BY position DESC",
&[&(owner as i64)],
|x| { Self::get_link_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("link".to_string()));
}
Ok(res.unwrap())
}
/// Get links by `owner`.
pub async fn get_links_by_owner_count(&self, owner: usize) -> Result<i32> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT COUNT(*)::int FROM links WHERE owner = $1",
&[&(owner as i64)],
|x| Ok(x.get::<usize, i32>(0))
);
if res.is_err() {
return Err(Error::GeneralNotFound("link".to_string()));
}
Ok(res.unwrap())
}
const MAXIMUM_FREE_LINKS: usize = 10;
const MAXIMUM_SUPPORTER_LINKS: usize = 20;
/// Create a new link in the database.
///
/// # Arguments
/// * `data` - a mock [`Link`] object to insert
pub async fn create_link(&self, data: Link, user: &User) -> Result<Link> {
if !user.permissions.check(FinePermission::SUPPORTER) {
if (self.get_links_by_owner_count(user.id).await? as usize) >= Self::MAXIMUM_FREE_LINKS
{
return Err(Error::MiscError(
"You already have the maximum number of links you can create".to_string(),
));
}
} else if !user.permissions.check(FinePermission::MANAGE_USERS) {
if (self.get_links_by_owner_count(user.id).await? as usize)
>= Self::MAXIMUM_SUPPORTER_LINKS
{
return Err(Error::MiscError(
"You already have the maximum number of links you can create".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 links VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&data.label,
&data.href,
&(data.upload_id as i64),
&(data.clicks as i32),
&(data.position as i32),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
pub async fn delete_link(&self, id: usize) -> Result<()> {
let y = self.get_link_by_id(id).await?;
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 links WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete upload
if y.upload_id != 0 {
self.delete_upload(id).await?;
}
// ...
self.0.1.remove(format!("atto.link:{}", id)).await;
Ok(())
}
auto_method!(update_link_label(&str) -> "UPDATE links SET label = $1 WHERE id = $2" --cache-key-tmpl="atto.link:{}");
auto_method!(update_link_href(&str) -> "UPDATE links SET href = $1 WHERE id = $2" --cache-key-tmpl="atto.link:{}");
auto_method!(update_link_upload_id(i64) -> "UPDATE links SET upload_id = $1 WHERE id = $2" --cache-key-tmpl="atto.link:{}");
auto_method!(update_link_clicks(i32) -> "UPDATE links SET clicks = $1 WHERE id = $2" --cache-key-tmpl="atto.link:{}");
auto_method!(update_link_position(i32) -> "UPDATE links SET position = $1 WHERE id = $2" --cache-key-tmpl="atto.link:{}");
}

View file

@ -12,6 +12,7 @@ mod invite_codes;
mod ipbans;
mod ipblocks;
mod journals;
mod links;
mod memberships;
mod message_reactions;
mod messages;

View file

@ -9,10 +9,7 @@ use crate::{
},
};
use crate::{auto_method, DataManager};
use oiseau::PostgresRow;
use oiseau::{execute, get, query_rows, params};
use oiseau::{PostgresRow, execute, get, query_rows, params};
impl DataManager {
/// Get a [`UserStack`] from an SQL row.

View file

@ -0,0 +1,41 @@
use serde::{Serialize, Deserialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Link {
pub id: usize,
pub created: usize,
/// Links should be selected by their owner, not their link list ID.
/// This is why we do not store link list ID.
pub owner: usize,
pub label: String,
pub href: String,
/// As link icons are optional, `upload_id` is allowed to be 0.
pub upload_id: usize,
/// Clicks are tracked for supporters only.
///
/// When a user clicks on a link through the UI, they'll be redirect to
/// `/links/{id}`. If the link's owner is a supporter, the link's clicks will
/// be incremented.
///
/// The page should just serve a simple HTML document with a meta tag to redirect.
/// We only really care about knowing they clicked it, so an automatic redirect will do.
pub clicks: usize,
pub position: usize,
}
impl Link {
/// Create a new [`Link`].
pub fn new(owner: usize, label: String, href: String, position: usize) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
owner,
label,
href,
upload_id: 0,
clicks: 0,
position,
}
}
}

View file

@ -6,6 +6,7 @@ pub mod channels;
pub mod communities;
pub mod communities_permissions;
pub mod journals;
pub mod links;
pub mod moderation;
pub mod oauth;
pub mod permissions;

View file

@ -68,6 +68,8 @@ pub enum AppScope {
UserReadJournals,
/// Read the user's notes.
UserReadNotes,
/// Read the user's links.
UserReadLinks,
/// Create posts as the user.
UserCreatePosts,
/// Create messages as the user.
@ -86,6 +88,8 @@ pub enum AppScope {
UserCreateJournals,
/// Create notes on behalf of the user.
UserCreateNotes,
/// Create links on behalf of the user.
UserCreateLinks,
/// Delete posts owned by the user.
UserDeletePosts,
/// Delete messages owned by the user.
@ -120,6 +124,8 @@ pub enum AppScope {
UserManageJournals,
/// Manage the user's notes.
UserManageNotes,
/// Manage the user's links.
UserManageLinks,
/// Edit posts created by the user.
UserEditPosts,
/// Edit drafts created by the user.