chore (backend-rs): fetch_meta -> local_server_info

This commit is contained in:
naskya 2024-06-06 03:29:28 +09:00
parent 050f4d554a
commit 95b860e820
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
12 changed files with 46 additions and 38 deletions

View file

@ -29,6 +29,20 @@ export interface EnvConfig {
slow: boolean slow: boolean
} }
export function loadEnv(): EnvConfig export function loadEnv(): EnvConfig
export function fetchMeta(): Promise<Meta>
export function updateMetaCache(): Promise<void>
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 { export interface ServerConfig {
url: string url: string
port: number port: number
@ -428,20 +442,6 @@ export function isSafeUrl(url: string): boolean
export function latestVersion(): Promise<string> export function latestVersion(): Promise<string>
export function toMastodonId(firefishId: string): string | null export function toMastodonId(firefishId: string): string | null
export function fromMastodonId(mastodonId: string): string | null export function fromMastodonId(mastodonId: string): string | null
export function fetchMeta(): Promise<Meta>
export function updateMetaCache(): Promise<void>
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. * Converts the given text into the cat language.
* *

View file

@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`) 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.SECOND = SECOND
module.exports.MINUTE = MINUTE 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.USER_ACTIVE_THRESHOLD = USER_ACTIVE_THRESHOLD
module.exports.FILE_TYPE_BROWSERSAFE = FILE_TYPE_BROWSERSAFE module.exports.FILE_TYPE_BROWSERSAFE = FILE_TYPE_BROWSERSAFE
module.exports.loadEnv = loadEnv module.exports.loadEnv = loadEnv
module.exports.fetchMeta = fetchMeta
module.exports.updateMetaCache = updateMetaCache
module.exports.metaToPugArgs = metaToPugArgs
module.exports.loadConfig = loadConfig module.exports.loadConfig = loadConfig
module.exports.stringToAcct = stringToAcct module.exports.stringToAcct = stringToAcct
module.exports.acctToString = acctToString module.exports.acctToString = acctToString
@ -352,9 +355,6 @@ module.exports.isSafeUrl = isSafeUrl
module.exports.latestVersion = latestVersion module.exports.latestVersion = latestVersion
module.exports.toMastodonId = toMastodonId module.exports.toMastodonId = toMastodonId
module.exports.fromMastodonId = fromMastodonId module.exports.fromMastodonId = fromMastodonId
module.exports.fetchMeta = fetchMeta
module.exports.updateMetaCache = updateMetaCache
module.exports.metaToPugArgs = metaToPugArgs
module.exports.nyaify = nyaify module.exports.nyaify = nyaify
module.exports.hashPassword = hashPassword module.exports.hashPassword = hashPassword
module.exports.verifyPassword = verifyPassword module.exports.verifyPassword = verifyPassword

View file

@ -1,3 +1,5 @@
//! This module is used in the TypeScript backend only.
#[crate::ts_export] #[crate::ts_export]
pub const SECOND: i32 = 1000; pub const SECOND: i32 = 1000;
#[crate::ts_export] #[crate::ts_export]

View file

@ -1,3 +1,5 @@
//! Environment options
// FIXME: Are these options used? // FIXME: Are these options used?
#[crate::export(object)] #[crate::export(object)]
pub struct EnvConfig { pub struct EnvConfig {

View file

@ -1,6 +1,7 @@
//! Server information
use crate::database::db_conn; use crate::database::db_conn;
use crate::model::entity::meta; use crate::model::entity::meta;
use rand::prelude::*;
use sea_orm::{prelude::*, ActiveValue}; use sea_orm::{prelude::*, ActiveValue};
use std::sync::Mutex; use std::sync::Mutex;
@ -11,18 +12,18 @@ fn set_cache(meta: &Meta) {
let _ = CACHE.lock().map(|mut cache| *cache = Some(meta.clone())); let _ = CACHE.lock().map(|mut cache| *cache = Some(meta.clone()));
} }
#[crate::export] #[crate::export(js_name = "fetchMeta")]
pub async fn fetch_meta() -> Result<Meta, DbErr> { pub async fn local_server_info() -> Result<Meta, DbErr> {
fetch_meta_impl(true).await local_server_info_impl(true).await
} }
#[crate::export] #[crate::export(js_name = "updateMetaCache")]
pub async fn update_meta_cache() -> Result<(), DbErr> { pub async fn update() -> Result<(), DbErr> {
fetch_meta_impl(false).await?; local_server_info_impl(false).await?;
Ok(()) Ok(())
} }
async fn fetch_meta_impl(use_cache: bool) -> Result<Meta, DbErr> { async fn local_server_info_impl(use_cache: bool) -> Result<Meta, DbErr> {
// try using cache // try using cache
if use_cache { if use_cache {
if let Some(cache) = CACHE.lock().ok().and_then(|cache| cache.clone()) { if let Some(cache) = CACHE.lock().ok().and_then(|cache| cache.clone()) {
@ -62,8 +63,9 @@ pub struct PugArgs {
pub private_mode: Option<bool>, pub private_mode: Option<bool>,
} }
#[crate::export] #[crate::ts_export]
pub fn meta_to_pug_args(meta: Meta) -> PugArgs { pub fn meta_to_pug_args(meta: Meta) -> PugArgs {
use rand::prelude::*;
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let splash_icon = meta let splash_icon = meta

View file

@ -1,7 +1,9 @@
//! Server configurations and environment variables //! Server configurations and environment variables
pub use meta::local_server_info;
pub use server::CONFIG; pub use server::CONFIG;
pub mod constant; pub mod constant;
pub mod environment; pub mod environment;
pub mod meta;
pub mod server; pub mod server;

View file

@ -1,3 +1,5 @@
//! Server configuration
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
use std::env; use std::env;

View file

@ -1,9 +1,8 @@
//! NodeInfo generator //! NodeInfo generator
use crate::config::CONFIG; use crate::config::{local_server_info, CONFIG};
use crate::database::{cache, db_conn}; use crate::database::{cache, db_conn};
use crate::federation::nodeinfo::schema::*; use crate::federation::nodeinfo::schema::*;
use crate::misc::meta::fetch_meta;
use crate::model::entity::{note, user}; use crate::model::entity::{note, user};
use sea_orm::{ColumnTrait, DbErr, EntityTrait, PaginatorTrait, QueryFilter}; use sea_orm::{ColumnTrait, DbErr, EntityTrait, PaginatorTrait, QueryFilter};
use serde_json::json; use serde_json::json;
@ -63,7 +62,7 @@ async fn statistics() -> Result<(u64, u64, u64, u64), DbErr> {
async fn generate_nodeinfo_2_1() -> Result<Nodeinfo21, Error> { async fn generate_nodeinfo_2_1() -> Result<Nodeinfo21, Error> {
let (local_users, local_active_halfyear, local_active_month, local_posts) = let (local_users, local_active_halfyear, local_active_month, local_posts) =
statistics().await?; statistics().await?;
let meta = fetch_meta().await?; let meta = local_server_info().await?;
let metadata = HashMap::from([ let metadata = HashMap::from([
( (
"nodeName".to_string(), "nodeName".to_string(),

View file

@ -20,7 +20,7 @@
/// ``` /// ```
#[crate::ts_export] #[crate::ts_export]
pub async fn is_blocked_server(host: &str) -> Result<bool, sea_orm::DbErr> { pub async fn is_blocked_server(host: &str) -> Result<bool, sea_orm::DbErr> {
Ok(crate::misc::meta::fetch_meta() Ok(crate::config::local_server_info()
.await? .await?
.blocked_hosts .blocked_hosts
.iter() .iter()
@ -47,7 +47,7 @@ pub async fn is_blocked_server(host: &str) -> Result<bool, sea_orm::DbErr> {
/// ``` /// ```
#[crate::ts_export] #[crate::ts_export]
pub async fn is_silenced_server(host: &str) -> Result<bool, sea_orm::DbErr> { pub async fn is_silenced_server(host: &str) -> Result<bool, sea_orm::DbErr> {
Ok(crate::misc::meta::fetch_meta() Ok(crate::config::local_server_info()
.await? .await?
.silenced_hosts .silenced_hosts
.iter() .iter()
@ -75,7 +75,7 @@ pub async fn is_silenced_server(host: &str) -> Result<bool, sea_orm::DbErr> {
/// ``` /// ```
#[crate::ts_export] #[crate::ts_export]
pub async fn is_allowed_server(host: &str) -> Result<bool, sea_orm::DbErr> { pub async fn is_allowed_server(host: &str) -> Result<bool, sea_orm::DbErr> {
let meta = crate::misc::meta::fetch_meta().await?; let meta = crate::config::local_server_info().await?;
if !meta.private_mode.unwrap_or(false) { if !meta.private_mode.unwrap_or(false) {
return Ok(true); return Ok(true);

View file

@ -13,7 +13,6 @@ pub mod is_quote;
pub mod is_safe_url; pub mod is_safe_url;
pub mod latest_version; pub mod latest_version;
pub mod mastodon_id; pub mod mastodon_id;
pub mod meta;
pub mod nyaify; pub mod nyaify;
pub mod password; pub mod password;
pub mod reaction; pub mod reaction;

View file

@ -1,5 +1,5 @@
use crate::config::local_server_info;
use crate::database::db_conn; use crate::database::db_conn;
use crate::misc::meta::fetch_meta;
use crate::model::entity::emoji; use crate::model::entity::emoji;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; 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)] #[cfg(test)]

View file

@ -1,6 +1,6 @@
use crate::config::local_server_info;
use crate::database::db_conn; use crate::database::db_conn;
use crate::misc::get_note_summary::{get_note_summary, PartialNoteToSummarize}; use crate::misc::get_note_summary::{get_note_summary, PartialNoteToSummarize};
use crate::misc::meta::fetch_meta;
use crate::model::entity::sw_subscription; use crate::model::entity::sw_subscription;
use crate::util::http_client; use crate::util::http_client;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
@ -140,7 +140,7 @@ pub async fn send_push_notification(
kind: PushNotificationKind, kind: PushNotificationKind,
content: &serde_json::Value, content: &serde_json::Value,
) -> Result<(), Error> { ) -> 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() if !meta.enable_service_worker || meta.sw_public_key.is_none() || meta.sw_private_key.is_none()
{ {