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

@ -121,6 +121,8 @@ pub const FORGE_BASE: &str = include_str!("./public/html/forge/base.lisp");
pub const FORGE_INFO: &str = include_str!("./public/html/forge/info.lisp");
pub const FORGE_TICKETS: &str = include_str!("./public/html/forge/tickets.lisp");
pub const DEVELOPER_HOME: &str = include_str!("./public/html/developer/home.lisp");
// langs
pub const LANG_EN_US: &str = include_str!("./langs/en-US.toml");
@ -129,6 +131,8 @@ pub const LANG_EN_US: &str = include_str!("./langs/en-US.toml");
pub const VENDOR_SPOTIFY_ICON: &str = include_str!("./public/images/vendor/spotify.svg");
pub const VENDOR_LAST_FM_ICON: &str = include_str!("./public/images/vendor/last-fm.svg");
pub const TETRATTO_BUNNY: &[u8] = include_bytes!("./public/images/tetratto_bunny.webp");
pub(crate) static HTML_FOOTER: LazyLock<RwLock<String>> =
LazyLock::new(|| RwLock::new(String::new()));
@ -174,6 +178,13 @@ macro_rules! vendor_icon {
}};
}
macro_rules! bin_icon {
($name:literal, $icon:ident, $icons_dir:expr) => {{
let file_path = PathBufD::current().extend(&[$icons_dir.clone(), $name.to_string()]);
std::fs::write(file_path, $icon).unwrap();
}};
}
/// Read a string and replace all custom blocks with the corresponding correct HTML.
///
/// # Replaces
@ -315,6 +326,7 @@ pub(crate) fn lisp_plugins() -> HashMap<String, Box<dyn FnMut(Element) -> Elemen
pub(crate) async fn write_assets(config: &Config) -> PathBufD {
vendor_icon!("spotify", VENDOR_SPOTIFY_ICON, config.dirs.icons);
vendor_icon!("last_fm", VENDOR_LAST_FM_ICON, config.dirs.icons);
bin_icon!("tetratto_bunny.webp", TETRATTO_BUNNY, config.dirs.assets);
// ...
let mut plugins = lisp_plugins();
@ -395,6 +407,8 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
write_template!(html_path->"forge/info.html"(crate::assets::FORGE_INFO) --config=config --lisp plugins);
write_template!(html_path->"forge/tickets.html"(crate::assets::FORGE_TICKETS) --config=config --lisp plugins);
write_template!(html_path->"developer/home.html"(crate::assets::DEVELOPER_HOME) -d "developer" --config=config --lisp plugins);
html_path
}
@ -402,6 +416,8 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
pub(crate) async fn init_dirs(config: &Config) {
create_dir_if_not_exists!(&config.dirs.templates);
create_dir_if_not_exists!(&config.dirs.docs);
create_dir_if_not_exists!(&config.dirs.rustdoc);
create_dir_if_not_exists!(&config.dirs.assets);
// images
create_dir_if_not_exists!(&config.dirs.media);

View file

@ -28,6 +28,7 @@ version = "1.0.0"
"general:action.view" = "View"
"general:action.copy_link" = "Copy link"
"general:action.post" = "Post"
"general:label.account" = "Account"
"general:label.safety" = "Safety"
"general:label.share" = "Share"
"general:action.add_account" = "Add account"
@ -210,3 +211,8 @@ version = "1.0.0"
"forge:tab.tickets" = "Tickets"
"forge:action.reopen" = "Reopen"
"forge:action.close" = "Close"
"developer:label.my_apps" = "My apps"
"developer:label.create_new" = "Create new app"
"developer:label.homepage" = "Homepage"
"developer:label.redirect" = "Redirect URL"

View file

@ -1,3 +1,6 @@
#![doc = include_str!("../../../README.md")]
#![doc(html_favicon_url = "/public/favicon.svg")]
#![doc(html_logo_url = "/public/tetratto_bunny.webp")]
mod assets;
mod image;
mod macros;

View file

@ -94,6 +94,7 @@
]);
if (res.ok) {
e.target.reset();
setTimeout(() => {
window.location.href = `/community/${res.payload}`;
}, 100);

View file

@ -595,7 +595,7 @@
("style" "display: none;")
(text "{{ self::theme_color(color=user.settings.theme_color_surface, css=\"color-surface\") }} {{ self::theme_color(color=user.settings.theme_color_text, css=\"color-text\") }} {{ self::theme_color(color=user.settings.theme_color_text_link, css=\"color-link\") }} {{ self::theme_color(color=user.settings.theme_color_lowered, css=\"color-lowered\") }} {{ self::theme_color(color=user.settings.theme_color_text_lowered, css=\"color-text-lowered\") }} {{ self::theme_color(color=user.settings.theme_color_super_lowered, css=\"color-super-lowered\") }} {{ self::theme_color(color=user.settings.theme_color_raised, css=\"color-raised\") }} {{ self::theme_color(color=user.settings.theme_color_text_raised, css=\"color-text-raised\") }} {{ self::theme_color(color=user.settings.theme_color_super_raised, css=\"color-super-raised\") }} {{ self::theme_color(color=user.settings.theme_color_primary, css=\"color-primary\") }} {{ self::theme_color(color=user.settings.theme_color_text_primary, css=\"color-text-primary\") }} {{ self::theme_color(color=user.settings.theme_color_primary_lowered, css=\"color-primary-lowered\") }} {{ self::theme_color(color=user.settings.theme_color_secondary, css=\"color-secondary\") }} {{ self::theme_color(color=user.settings.theme_color_text_secondary, css=\"color-text-secondary\") }} {{ self::theme_color(color=user.settings.theme_color_secondary_lowered, css=\"color-secondary-lowered\") }} {% if user.permissions|has_supporter -%}")
(style
(text "{{ user.settings.theme_custom_css|safe|remove_script_tags }}"))
(text "{{ user.settings.theme_custom_css|remove_script_tags|safe }}"))
(text "{%- endif %}"))
(text "{%- endif %} {%- endmacro %} {% macro theme_color(color, css) -%} {% if color -%}")
@ -1001,20 +1001,20 @@
(span
(text "{{ text \"general:link.stats\" }}")))
(text "{%- endif %}")
(b
("class" "title")
(text "{{ config.name }}"))
(b ("class" "title") (text "{{ config.name }}"))
(a
("href" "https://trisua.com/t/tetratto")
(text "{{ icon \"code\" }}")
(span
(text "{{ text \"general:link.source_code\" }}")))
; <a href="https://trisuaso.github.io/tetratto">
; {{ icon "book" }}
; <span>{{ text "general:link.reference" }}</span>
; </a>
(div
("class" "title"))
("class" "button")
(icon (text "code"))
(str (text "general:link.source_code")))
(a
("href" "/reference/tetratto/index.html")
("class" "button")
("data-turbo" "false")
(icon (text "rabbit"))
(str (text "general:link.reference")))
(b ("class" "title") (str (text "general:label.account")))
(button
("onclick" "trigger('me::switch_account')")
(text "{{ icon \"ellipsis\" }}")

View file

@ -0,0 +1,121 @@
(text "{% extends \"root.html\" %} {% block head %}")
(title
(text "Developer panel - {{ config.name }}"))
(text "{% endblock %} {% block body %} {{ macros::nav(selected=\"\") }}")
(main
("class" "flex flex-col gap-2")
; create new
(text "{{ components::supporter_ad(body=\"Become a supporter to create multiple apps!\") }}")
(div
("class" "card-nest")
(div
("class" "card small")
(b
(text "{{ text \"developer:label.create_new\" }}")))
(form
("class" "card flex flex-col gap-2")
("onsubmit" "create_app_from_form(event)")
(div
("class" "flex flex-col gap-1")
(label
("for" "title")
(text "{{ text \"communities:label.name\" }}"))
(input
("type" "text")
("name" "title")
("id" "title")
("placeholder" "name")
("required" "")
("minlength" "2")
("maxlength" "32")))
(div
("class" "flex flex-col gap-1")
(label
("for" "title")
(text "{{ text \"developer:label.homepage\" }}"))
(input
("type" "url")
("name" "homepage")
("id" "homepage")
("placeholder" "homepage")
("required" "")
("minlength" "2")
("maxlength" "32")))
(div
("class" "flex flex-col gap-1")
(label
("for" "title")
(text "{{ text \"developer:label.redirect\" }}"))
(input
("type" "url")
("name" "redirect")
("id" "redirect")
("placeholder" "redirect URL")
("required" "")
("minlength" "2")
("maxlength" "32")))
(button
("class" "primary")
(text "{{ text \"communities:action.create\" }}"))))
; app listing
(div
("class" "card-nest")
(div
("class" "card small flex items-center gap-2")
(icon (text "bot"))
(str (text "developer:label.my_apps")))
(div
("class" "card flex flex-col gap-2")
(text "{% for item in list %}")
(a
("href" "/developer/app/{{ item.id }}")
("class" "card secondary flex flex-col gap-2")
(div
("class" "flex items-center gap-2")
(text "{{ icon \"code\" }}")
(b
(text "{{ item.title }}")))
(span
(text "Created ")
(span
("class" "date")
(text "{{ item.created }}"))
(text "; {{ item.quota_status }} mode; {{ item.grants }} users")))
(text "{% endfor %}"))))
(script
(text "async function create_app_from_form(e) {
e.preventDefault();
await trigger(\"atto::debounce\", [\"apps::create\"]);
fetch(\"/api/v1/apps\", {
method: \"POST\",
headers: {
\"Content-Type\": \"application/json\",
},
body: JSON.stringify({
title: e.target.title.value,
homepage: e.target.homepage.value,
redirect: e.target.redirect.value,
}),
})
.then((res) => res.json())
.then((res) => {
trigger(\"atto::toast\", [
res.ok ? \"success\" : \"error\",
res.message,
]);
if (res.ok) {
e.target.reset();
setTimeout(() => {
window.location.href = `/developer/app/${res.payload}`;
}, 100);
}
});
}"))
(text "{% endblock %}")

View file

@ -71,6 +71,7 @@
]);
if (res.ok) {
e.target.reset();
setTimeout(() => {
window.location.href = `/forge/${res.payload}`;
}, 100);

View file

@ -100,12 +100,19 @@
(icon (text "user-plus"))
(str (text "auth:action.register")))
(div ("class" "title"))
(b ("class" "title") (text "{{ config.name }}"))
(a
("href" "https://trisua.com/t/tetratto")
("class" "button")
(icon (text "code"))
(text "View source")))))
(str (text "general:link.source_code")))
(a
("href" "/reference/tetratto/index.html")
("class" "button")
("data-turbo" "false")
(icon (text "rabbit"))
(str (text "general:link.reference"))))))
(text "{%- endif %}")))
(text "{%- endmacro %}")

View file

@ -561,7 +561,9 @@
(li
(text "Ability to search through all posts"))
(li
(text "Ability to create forges")))
(text "Ability to create forges"))
(li
(text "Ability to create more than 1 app")))
(a
("href" "{{ config.stripe.payment_link }}?client_reference_id={{ user.id }}")
("class" "button")

View file

@ -57,8 +57,7 @@
(span
("class" "date")
(text "{{ item.created }}"))
(text "; {{
item.privacy }}; {{ item.users|length }} users")))
(text "; {{ item.privacy }}; {{ item.users|length }} users")))
(text "{% endfor %}"))))
(script

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

View file

@ -0,0 +1,151 @@
use crate::{
get_user_from_token,
routes::api::v1::{UpdateAppHomepage, UpdateAppQuotaStatus, UpdateAppRedirect, UpdateAppTitle},
State,
};
use axum::{Extension, Json, extract::Path, response::IntoResponse};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{apps::ThirdPartyApp, permissions::FinePermission, ApiReturn, Error};
use super::CreateApp;
pub async fn create_request(
jar: CookieJar,
Extension(data): Extension<State>,
Json(req): Json<CreateApp>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data
.create_app(ThirdPartyApp::new(
req.title,
user.id,
req.homepage,
req.redirect,
))
.await
{
Ok(s) => Json(ApiReturn {
ok: true,
message: "App created".to_string(),
payload: s.id.to_string(),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_title_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateAppTitle>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data.update_app_title(id, &user, &req.title).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "App updated".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_homepage_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateAppHomepage>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data.update_app_homepage(id, &user, &req.homepage).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "App updated".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_redirect_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateAppRedirect>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data.update_app_redirect(id, &user, &req.redirect).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "App updated".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_quota_status_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateAppQuotaStatus>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
if !user.permissions.check(FinePermission::MANAGE_APPS) {
return Json(Error::NotAllowed.into());
}
match data.update_app_quota_status(id, req.quota_status).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "App updated".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn delete_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data.delete_app(id, &user).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "App deleted".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}

View file

@ -164,8 +164,8 @@ pub async fn banner_request(
))
}
pub static MAXIMUM_FILE_SIZE: usize = 8388608;
pub static MAXIMUM_GIF_FILE_SIZE: usize = 2097152;
pub const MAXIMUM_FILE_SIZE: usize = 8388608;
pub const MAXIMUM_GIF_FILE_SIZE: usize = 2097152;
/// Upload avatar
pub async fn upload_avatar_request(

View file

@ -1,3 +1,4 @@
pub mod apps;
pub mod auth;
pub mod communities;
pub mod notifications;
@ -17,6 +18,7 @@ use axum::{
};
use serde::Deserialize;
use tetratto_core::model::{
apps::AppQuota,
communities::{
CommunityContext, CommunityJoinAccess, CommunityReadAccess, CommunityWriteAccess,
PollOption, PostContext,
@ -321,6 +323,10 @@ pub fn routes() -> Router {
"/auth/user/find_by_ip/{ip}",
get(auth::profile::redirect_from_ip),
)
.route(
"/auth/user/find_by_stripe_id/{id}",
get(auth::profile::redirect_from_stripe_id),
)
.route("/auth/ip/{ip}/block", post(auth::social::ip_block_request))
.route(
"/auth/user/{id}/gpa",
@ -342,6 +348,16 @@ pub fn routes() -> Router {
"/auth/user/{id}/followers",
get(auth::social::followers_request),
)
// apps
.route("/apps", post(apps::create_request))
.route("/apps/{id}/title", post(apps::update_title_request))
.route("/apps/{id}/homepage", post(apps::update_homepage_request))
.route("/apps/{id}/redirect", post(apps::update_redirect_request))
.route(
"/apps/{id}/quota_status",
post(apps::update_quota_status_request),
)
.route("/apps/{id}", delete(apps::delete_request))
// warnings
.route("/warnings/{id}", get(auth::user_warnings::get_request))
.route("/warnings/{id}", post(auth::user_warnings::create_request))
@ -773,3 +789,30 @@ pub struct AppendAssociations {
pub struct UpdatePostIsOpen {
pub open: bool,
}
#[derive(Deserialize)]
pub struct CreateApp {
pub title: String,
pub homepage: String,
pub redirect: String,
}
#[derive(Deserialize)]
pub struct UpdateAppTitle {
pub title: String,
}
#[derive(Deserialize)]
pub struct UpdateAppHomepage {
pub homepage: String,
}
#[derive(Deserialize)]
pub struct UpdateAppRedirect {
pub redirect: String,
}
#[derive(Deserialize)]
pub struct UpdateAppQuotaStatus {
pub quota_status: AppQuota,
}

View file

@ -22,6 +22,10 @@ pub fn routes(config: &Config) -> Router {
"/public",
get_service(tower_http::services::ServeDir::new(&config.dirs.assets)),
)
.nest_service(
"/reference",
get_service(tower_http::services::ServeDir::new(&config.dirs.rustdoc)),
)
.route("/public/favicon.svg", get(assets::favicon_request))
.route_service(
"/robots.txt",

View file

@ -0,0 +1,35 @@
use super::render_error;
use crate::{assets::initial_context, get_lang, get_user_from_token, State};
use axum::{
response::{Html, IntoResponse},
Extension,
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::Error;
/// `/developer`
pub async fn home_request(jar: CookieJar, Extension(data): Extension<State>) -> impl IntoResponse {
let data = data.read().await;
let user = match get_user_from_token!(jar, data.0) {
Some(ua) => ua,
None => {
return Err(Html(
render_error(Error::NotAllowed, &jar, &data, &None).await,
));
}
};
let list = match data.0.get_apps_by_owner(user.id).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
};
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0.0, lang, &Some(user)).await;
context.insert("list", &list);
// return
Ok(Html(
data.1.render("developer/home.html", &context).unwrap(),
))
}

View file

@ -1,5 +1,6 @@
pub mod auth;
pub mod communities;
pub mod developer;
pub mod forge;
pub mod misc;
pub mod mod_panel;
@ -116,6 +117,8 @@ pub fn routes() -> Router {
.route("/forge/{title}", get(forge::info_request))
.route("/forge/{title}/tickets", get(forge::tickets_request))
.route("/forge/{title}/members", get(communities::members_request))
// developer
.route("/developer", get(developer::home_request))
// stacks
.route("/stacks", get(stacks::list_request))
.route("/stacks/{id}", get(stacks::posts_request))