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
}
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 {
url: string
port: number
@ -428,20 +442,6 @@ export function isSafeUrl(url: string): boolean
export function latestVersion(): Promise<string>
export function toMastodonId(firefishId: 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.
*

View file

@ -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

View file

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

View file

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

View file

@ -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<Meta, DbErr> {
fetch_meta_impl(true).await
#[crate::export(js_name = "fetchMeta")]
pub async fn local_server_info() -> Result<Meta, DbErr> {
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<Meta, DbErr> {
async fn local_server_info_impl(use_cache: bool) -> Result<Meta, DbErr> {
// 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<bool>,
}
#[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

View file

@ -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;

View file

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

View file

@ -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<Nodeinfo21, Error> {
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(),

View file

@ -20,7 +20,7 @@
/// ```
#[crate::ts_export]
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?
.blocked_hosts
.iter()
@ -47,7 +47,7 @@ pub async fn is_blocked_server(host: &str) -> Result<bool, sea_orm::DbErr> {
/// ```
#[crate::ts_export]
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?
.silenced_hosts
.iter()
@ -75,7 +75,7 @@ pub async fn is_silenced_server(host: &str) -> Result<bool, sea_orm::DbErr> {
/// ```
#[crate::ts_export]
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) {
return Ok(true);

View file

@ -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;

View file

@ -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)]

View file

@ -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()
{