From 95b860e820658a6401ded577626c919c8320fbec Mon Sep 17 00:00:00 2001 From: naskya Date: Thu, 6 Jun 2024 03:29:28 +0900 Subject: [PATCH] chore (backend-rs): fetch_meta -> local_server_info --- packages/backend-rs/index.d.ts | 28 +++++++++---------- packages/backend-rs/index.js | 8 +++--- packages/backend-rs/src/config/constant.rs | 2 ++ packages/backend-rs/src/config/environment.rs | 2 ++ .../backend-rs/src/{misc => config}/meta.rs | 20 +++++++------ packages/backend-rs/src/config/mod.rs | 2 ++ packages/backend-rs/src/config/server.rs | 2 ++ .../src/federation/nodeinfo/generate.rs | 5 ++-- .../backend-rs/src/misc/check_server_block.rs | 6 ++-- packages/backend-rs/src/misc/mod.rs | 1 - packages/backend-rs/src/misc/reaction.rs | 4 +-- .../src/service/push_notification.rs | 4 +-- 12 files changed, 46 insertions(+), 38 deletions(-) rename packages/backend-rs/src/{misc => config}/meta.rs (83%) diff --git a/packages/backend-rs/index.d.ts b/packages/backend-rs/index.d.ts index dd52c4a7b5..f9cb459f27 100644 --- a/packages/backend-rs/index.d.ts +++ b/packages/backend-rs/index.d.ts @@ -29,6 +29,20 @@ export interface EnvConfig { slow: boolean } export function loadEnv(): EnvConfig +export function fetchMeta(): Promise +export function updateMetaCache(): Promise +export interface PugArgs { + img: string | null + title: string + instanceName: string + desc: string | null + icon: string | null + splashIcon: string | null + themeColor: string | null + randomMotd: string + privateMode: boolean | null +} +export function metaToPugArgs(meta: Meta): PugArgs export interface ServerConfig { url: string port: number @@ -428,20 +442,6 @@ export function isSafeUrl(url: string): boolean export function latestVersion(): Promise export function toMastodonId(firefishId: string): string | null export function fromMastodonId(mastodonId: string): string | null -export function fetchMeta(): Promise -export function updateMetaCache(): Promise -export interface PugArgs { - img: string | null - title: string - instanceName: string - desc: string | null - icon: string | null - splashIcon: string | null - themeColor: string | null - randomMotd: string - privateMode: boolean | null -} -export function metaToPugArgs(meta: Meta): PugArgs /** * Converts the given text into the cat language. * diff --git a/packages/backend-rs/index.js b/packages/backend-rs/index.js index 478f82ce7e..5f16e2febd 100644 --- a/packages/backend-rs/index.js +++ b/packages/backend-rs/index.js @@ -310,7 +310,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, loadConfig, stringToAcct, acctToString, fetchNodeinfo, nodeinfo_2_1, nodeinfo_2_0, Protocol, Inbound, Outbound, greet, initializeRustLogger, showServerInfo, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, isQuote, isSafeUrl, latestVersion, toMastodonId, fromMastodonId, fetchMeta, updateMetaCache, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, cpuInfo, cpuUsage, memoryUsage, storageUsage, AntennaSrc, DriveFileUsageHint, MutedNoteReason, NoteVisibility, NotificationType, PageVisibility, PollNoteVisibility, RelayStatus, UserEmojiModPerm, UserProfileFfvisibility, UserProfileMutingNotificationTypes, updateAntennasOnNewNote, watchNote, unwatchNote, PushNotificationKind, sendPushNotification, publishToChannelStream, ChatEvent, publishToChatStream, ChatIndexEvent, publishToChatIndexStream, publishToBroadcastStream, publishToGroupChatStream, publishToModerationStream, getTimestamp, genId, genIdAt, generateSecureRandomString, generateUserToken } = nativeBinding +const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, fetchMeta, updateMetaCache, metaToPugArgs, loadConfig, stringToAcct, acctToString, fetchNodeinfo, nodeinfo_2_1, nodeinfo_2_0, Protocol, Inbound, Outbound, greet, initializeRustLogger, showServerInfo, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, isQuote, isSafeUrl, latestVersion, toMastodonId, fromMastodonId, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, cpuInfo, cpuUsage, memoryUsage, storageUsage, AntennaSrc, DriveFileUsageHint, MutedNoteReason, NoteVisibility, NotificationType, PageVisibility, PollNoteVisibility, RelayStatus, UserEmojiModPerm, UserProfileFfvisibility, UserProfileMutingNotificationTypes, updateAntennasOnNewNote, watchNote, unwatchNote, PushNotificationKind, sendPushNotification, publishToChannelStream, ChatEvent, publishToChatStream, ChatIndexEvent, publishToChatIndexStream, publishToBroadcastStream, publishToGroupChatStream, publishToModerationStream, getTimestamp, genId, genIdAt, generateSecureRandomString, generateUserToken } = nativeBinding module.exports.SECOND = SECOND module.exports.MINUTE = MINUTE @@ -320,6 +320,9 @@ module.exports.USER_ONLINE_THRESHOLD = USER_ONLINE_THRESHOLD module.exports.USER_ACTIVE_THRESHOLD = USER_ACTIVE_THRESHOLD module.exports.FILE_TYPE_BROWSERSAFE = FILE_TYPE_BROWSERSAFE module.exports.loadEnv = loadEnv +module.exports.fetchMeta = fetchMeta +module.exports.updateMetaCache = updateMetaCache +module.exports.metaToPugArgs = metaToPugArgs module.exports.loadConfig = loadConfig module.exports.stringToAcct = stringToAcct module.exports.acctToString = acctToString @@ -352,9 +355,6 @@ module.exports.isSafeUrl = isSafeUrl module.exports.latestVersion = latestVersion module.exports.toMastodonId = toMastodonId module.exports.fromMastodonId = fromMastodonId -module.exports.fetchMeta = fetchMeta -module.exports.updateMetaCache = updateMetaCache -module.exports.metaToPugArgs = metaToPugArgs module.exports.nyaify = nyaify module.exports.hashPassword = hashPassword module.exports.verifyPassword = verifyPassword diff --git a/packages/backend-rs/src/config/constant.rs b/packages/backend-rs/src/config/constant.rs index db6e7bed00..f2340893cd 100644 --- a/packages/backend-rs/src/config/constant.rs +++ b/packages/backend-rs/src/config/constant.rs @@ -1,3 +1,5 @@ +//! This module is used in the TypeScript backend only. + #[crate::ts_export] pub const SECOND: i32 = 1000; #[crate::ts_export] diff --git a/packages/backend-rs/src/config/environment.rs b/packages/backend-rs/src/config/environment.rs index 1825af326a..8efe509c7e 100644 --- a/packages/backend-rs/src/config/environment.rs +++ b/packages/backend-rs/src/config/environment.rs @@ -1,3 +1,5 @@ +//! Environment options + // FIXME: Are these options used? #[crate::export(object)] pub struct EnvConfig { diff --git a/packages/backend-rs/src/misc/meta.rs b/packages/backend-rs/src/config/meta.rs similarity index 83% rename from packages/backend-rs/src/misc/meta.rs rename to packages/backend-rs/src/config/meta.rs index 3f13f7e510..9a81dc870c 100644 --- a/packages/backend-rs/src/misc/meta.rs +++ b/packages/backend-rs/src/config/meta.rs @@ -1,6 +1,7 @@ +//! Server information + use crate::database::db_conn; use crate::model::entity::meta; -use rand::prelude::*; use sea_orm::{prelude::*, ActiveValue}; use std::sync::Mutex; @@ -11,18 +12,18 @@ fn set_cache(meta: &Meta) { let _ = CACHE.lock().map(|mut cache| *cache = Some(meta.clone())); } -#[crate::export] -pub async fn fetch_meta() -> Result { - fetch_meta_impl(true).await +#[crate::export(js_name = "fetchMeta")] +pub async fn local_server_info() -> Result { + local_server_info_impl(true).await } -#[crate::export] -pub async fn update_meta_cache() -> Result<(), DbErr> { - fetch_meta_impl(false).await?; +#[crate::export(js_name = "updateMetaCache")] +pub async fn update() -> Result<(), DbErr> { + local_server_info_impl(false).await?; Ok(()) } -async fn fetch_meta_impl(use_cache: bool) -> Result { +async fn local_server_info_impl(use_cache: bool) -> Result { // try using cache if use_cache { if let Some(cache) = CACHE.lock().ok().and_then(|cache| cache.clone()) { @@ -62,8 +63,9 @@ pub struct PugArgs { pub private_mode: Option, } -#[crate::export] +#[crate::ts_export] pub fn meta_to_pug_args(meta: Meta) -> PugArgs { + use rand::prelude::*; let mut rng = rand::thread_rng(); let splash_icon = meta diff --git a/packages/backend-rs/src/config/mod.rs b/packages/backend-rs/src/config/mod.rs index 0e8056a894..483ca3ac6e 100644 --- a/packages/backend-rs/src/config/mod.rs +++ b/packages/backend-rs/src/config/mod.rs @@ -1,7 +1,9 @@ //! Server configurations and environment variables +pub use meta::local_server_info; pub use server::CONFIG; pub mod constant; pub mod environment; +pub mod meta; pub mod server; diff --git a/packages/backend-rs/src/config/server.rs b/packages/backend-rs/src/config/server.rs index 26babb4953..e8a7cf73ab 100644 --- a/packages/backend-rs/src/config/server.rs +++ b/packages/backend-rs/src/config/server.rs @@ -1,3 +1,5 @@ +//! Server configuration + use once_cell::sync::Lazy; use serde::Deserialize; use std::env; diff --git a/packages/backend-rs/src/federation/nodeinfo/generate.rs b/packages/backend-rs/src/federation/nodeinfo/generate.rs index e65449b46e..49c3f8f63f 100644 --- a/packages/backend-rs/src/federation/nodeinfo/generate.rs +++ b/packages/backend-rs/src/federation/nodeinfo/generate.rs @@ -1,9 +1,8 @@ //! NodeInfo generator -use crate::config::CONFIG; +use crate::config::{local_server_info, CONFIG}; use crate::database::{cache, db_conn}; use crate::federation::nodeinfo::schema::*; -use crate::misc::meta::fetch_meta; use crate::model::entity::{note, user}; use sea_orm::{ColumnTrait, DbErr, EntityTrait, PaginatorTrait, QueryFilter}; use serde_json::json; @@ -63,7 +62,7 @@ async fn statistics() -> Result<(u64, u64, u64, u64), DbErr> { async fn generate_nodeinfo_2_1() -> Result { let (local_users, local_active_halfyear, local_active_month, local_posts) = statistics().await?; - let meta = fetch_meta().await?; + let meta = local_server_info().await?; let metadata = HashMap::from([ ( "nodeName".to_string(), diff --git a/packages/backend-rs/src/misc/check_server_block.rs b/packages/backend-rs/src/misc/check_server_block.rs index 136c43e7c2..885507a9ae 100644 --- a/packages/backend-rs/src/misc/check_server_block.rs +++ b/packages/backend-rs/src/misc/check_server_block.rs @@ -20,7 +20,7 @@ /// ``` #[crate::ts_export] pub async fn is_blocked_server(host: &str) -> Result { - Ok(crate::misc::meta::fetch_meta() + Ok(crate::config::local_server_info() .await? .blocked_hosts .iter() @@ -47,7 +47,7 @@ pub async fn is_blocked_server(host: &str) -> Result { /// ``` #[crate::ts_export] pub async fn is_silenced_server(host: &str) -> Result { - Ok(crate::misc::meta::fetch_meta() + Ok(crate::config::local_server_info() .await? .silenced_hosts .iter() @@ -75,7 +75,7 @@ pub async fn is_silenced_server(host: &str) -> Result { /// ``` #[crate::ts_export] pub async fn is_allowed_server(host: &str) -> Result { - let meta = crate::misc::meta::fetch_meta().await?; + let meta = crate::config::local_server_info().await?; if !meta.private_mode.unwrap_or(false) { return Ok(true); diff --git a/packages/backend-rs/src/misc/mod.rs b/packages/backend-rs/src/misc/mod.rs index 23782b11a0..9d717ded7f 100644 --- a/packages/backend-rs/src/misc/mod.rs +++ b/packages/backend-rs/src/misc/mod.rs @@ -13,7 +13,6 @@ pub mod is_quote; pub mod is_safe_url; pub mod latest_version; pub mod mastodon_id; -pub mod meta; pub mod nyaify; pub mod password; pub mod reaction; diff --git a/packages/backend-rs/src/misc/reaction.rs b/packages/backend-rs/src/misc/reaction.rs index 423a732f88..8e9800a166 100644 --- a/packages/backend-rs/src/misc/reaction.rs +++ b/packages/backend-rs/src/misc/reaction.rs @@ -1,5 +1,5 @@ +use crate::config::local_server_info; use crate::database::db_conn; -use crate::misc::meta::fetch_meta; use crate::model::entity::emoji; use once_cell::sync::Lazy; use regex::Regex; @@ -118,7 +118,7 @@ pub async fn to_db_reaction(reaction: Option<&str>, host: Option<&str>) -> Resul }; }; - Ok(fetch_meta().await?.default_reaction) + Ok(local_server_info().await?.default_reaction) } #[cfg(test)] diff --git a/packages/backend-rs/src/service/push_notification.rs b/packages/backend-rs/src/service/push_notification.rs index 693a9c7f32..9d19aceab1 100644 --- a/packages/backend-rs/src/service/push_notification.rs +++ b/packages/backend-rs/src/service/push_notification.rs @@ -1,6 +1,6 @@ +use crate::config::local_server_info; use crate::database::db_conn; use crate::misc::get_note_summary::{get_note_summary, PartialNoteToSummarize}; -use crate::misc::meta::fetch_meta; use crate::model::entity::sw_subscription; use crate::util::http_client; use once_cell::sync::OnceCell; @@ -140,7 +140,7 @@ pub async fn send_push_notification( kind: PushNotificationKind, content: &serde_json::Value, ) -> Result<(), Error> { - let meta = fetch_meta().await?; + let meta = local_server_info().await?; if !meta.enable_service_worker || meta.sw_public_key.is_none() || meta.sw_private_key.is_none() {