From c4a7cd602991235896b1dbf027b5ab626b90b5ff Mon Sep 17 00:00:00 2001 From: sup39 Date: Sat, 18 May 2024 17:13:19 +0800 Subject: [PATCH] refactor (backend): port greet to backend-rs Co-authored-by: naskya --- packages/backend-rs/index.d.ts | 1 + packages/backend-rs/index.js | 3 +- packages/backend-rs/src/config/server.rs | 4 +- packages/backend-rs/src/init/greet.rs | 20 +++++++ packages/backend-rs/src/init/mod.rs | 1 + packages/backend/package.json | 1 - packages/backend/src/boot/master.ts | 71 +----------------------- packages/client/vite.config.ts | 8 --- pnpm-lock.yaml | 11 ---- scripts/copy-assets.mjs | 6 +- 10 files changed, 30 insertions(+), 96 deletions(-) create mode 100644 packages/backend-rs/src/init/greet.rs diff --git a/packages/backend-rs/index.d.ts b/packages/backend-rs/index.d.ts index 5fadb517e4..37392c2796 100644 --- a/packages/backend-rs/index.d.ts +++ b/packages/backend-rs/index.d.ts @@ -199,6 +199,7 @@ export interface Acct { } export function stringToAcct(acct: string): Acct export function acctToString(acct: Acct): string +export function greet(): void export function initializeRustLogger(): void export function showServerInfo(): void /** diff --git a/packages/backend-rs/index.js b/packages/backend-rs/index.js index 64b4e0d9d6..0dc930ed2c 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, initializeRustLogger, showServerInfo, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, isQuote, isSafeUrl, latestVersion, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, cpuInfo, cpuUsage, memoryUsage, storageUsage, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, updateAntennasOnNewNote, fetchNodeinfo, nodeinfo_2_1, nodeinfo_2_0, Protocol, Inbound, Outbound, 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, loadConfig, stringToAcct, acctToString, greet, initializeRustLogger, showServerInfo, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, isQuote, isSafeUrl, latestVersion, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, cpuInfo, cpuUsage, memoryUsage, storageUsage, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, updateAntennasOnNewNote, fetchNodeinfo, nodeinfo_2_1, nodeinfo_2_0, Protocol, Inbound, Outbound, 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 @@ -323,6 +323,7 @@ module.exports.loadEnv = loadEnv module.exports.loadConfig = loadConfig module.exports.stringToAcct = stringToAcct module.exports.acctToString = acctToString +module.exports.greet = greet module.exports.initializeRustLogger = initializeRustLogger module.exports.showServerInfo = showServerInfo module.exports.isBlockedServer = isBlockedServer diff --git a/packages/backend-rs/src/config/server.rs b/packages/backend-rs/src/config/server.rs index 5c77a46363..838516af04 100644 --- a/packages/backend-rs/src/config/server.rs +++ b/packages/backend-rs/src/config/server.rs @@ -3,6 +3,8 @@ use serde::Deserialize; use std::env; use std::fs; +pub const VERSION: &str = macro_rs::read_version_from_package_json!(); + #[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(rename_all = "camelCase")] #[crate::export(object, use_nullable = false)] @@ -252,8 +254,6 @@ fn read_config_file() -> ServerConfig { data } -const VERSION: &str = macro_rs::read_version_from_package_json!(); - #[crate::export] pub fn load_config() -> Config { let server_config = read_config_file(); diff --git a/packages/backend-rs/src/init/greet.rs b/packages/backend-rs/src/init/greet.rs new file mode 100644 index 0000000000..95cc019318 --- /dev/null +++ b/packages/backend-rs/src/init/greet.rs @@ -0,0 +1,20 @@ +use crate::config::server::VERSION; + +const GREETING_MESSAGE: &str = "\ +███████╗██╗██████╗ ███████╗███████╗██╗███████╗██╗ ██╗ ○ ▄ ▄ +██╔════╝██║██╔══██╗██╔════╝██╔════╝██║██╔════╝██║ ██║ ⚬ █▄▄ █▄▄ +█████╗ ██║██████╔╝█████╗ █████╗ ██║███████╗███████║ ▄▄▄▄▄▄ ▄ +██╔══╝ ██║██╔══██╗██╔══╝ ██╔══╝ ██║╚════██║██╔══██║ █ █ █▄▄ +██║ ██║██║ ██║███████╗██║ ██║███████║██║ ██║ █ ● ● █ +╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ▀▄▄▄▄▄▄▀ + Firefish is an open-source decentralized microblogging platform. + If you like Firefish, please consider contributing to the repo. https://firefish.dev/firefish/firefish +"; + +#[macro_rs::export] +pub fn greet() { + println!("{}", GREETING_MESSAGE); + + tracing::info!("Welcome to Firefish!"); + tracing::info!("Firefish {VERSION}"); +} diff --git a/packages/backend-rs/src/init/mod.rs b/packages/backend-rs/src/init/mod.rs index 252339d8fd..e76c732184 100644 --- a/packages/backend-rs/src/init/mod.rs +++ b/packages/backend-rs/src/init/mod.rs @@ -1,2 +1,3 @@ +pub mod greet; pub mod log; pub mod system_info; diff --git a/packages/backend/package.json b/packages/backend/package.json index d3a88d07bb..b4ef0eebd7 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -44,7 +44,6 @@ "cacheable-lookup": "TheEssem/cacheable-lookup", "cbor-x": "1.5.9", "chalk": "5.3.0", - "chalk-template": "1.1.0", "cli-highlight": "2.1.11", "color-convert": "2.0.1", "content-disposition": "0.5.4", diff --git a/packages/backend/src/boot/master.ts b/packages/backend/src/boot/master.ts index 68e7863628..b331eb898d 100644 --- a/packages/backend/src/boot/master.ts +++ b/packages/backend/src/boot/master.ts @@ -1,15 +1,11 @@ -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; import * as os from "node:os"; import cluster from "node:cluster"; -import chalk from "chalk"; -import chalkTemplate from "chalk-template"; import semver from "semver"; import Logger from "@/services/logger.js"; import { fetchMeta, + greet, initializeRustLogger, removeOldAttestationChallenges, showServerInfo, @@ -19,74 +15,9 @@ import { config, envOption } from "@/config.js"; import { db, initDb } from "@/db/postgre.js"; import { inspect } from "node:util"; -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const meta = JSON.parse( - fs.readFileSync(`${_dirname}/../../../../built/meta.json`, "utf-8"), -); - const logger = new Logger("core", "cyan"); const bootLogger = logger.createSubLogger("boot", "magenta", false); -const themeColor = chalk.hex("#31748f"); - -function greet() { - //#region Firefish logo - console.log( - themeColor( - "██████╗ ██╗██████╗ ███████╗███████╗██╗███████╗██╗ ██╗ ○ ▄ ▄ ", - ), - ); - console.log( - themeColor( - "██╔════╝██║██╔══██╗██╔════╝██╔════╝██║██╔════╝██║ ██║ ⚬ █▄▄ █▄▄ ", - ), - ); - console.log( - themeColor( - "█████╗ ██║██████╔╝█████╗ █████╗ ██║███████╗███████║ ▄▄▄▄▄▄ ▄ ", - ), - ); - console.log( - themeColor( - "██╔══╝ ██║██╔══██╗██╔══╝ ██╔══╝ ██║╚════██║██╔══██║ █ █ █▄▄ ", - ), - ); - console.log( - themeColor( - "██║ ██║██║ ██║███████╗██║ ██║███████║██║ ██║ █ ● ● █ ", - ), - ); - console.log( - themeColor( - "╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ▀▄▄▄▄▄▄▀ ", - ), - ); - //#endregion - - console.log( - " Firefish is an open-source decentralized microblogging platform.", - ); - console.log( - chalk.rgb( - 255, - 136, - 0, - )( - " If you like Firefish, please consider contributing to the repo. https://firefish.dev/firefish/firefish", - ), - ); - - console.log(""); - console.log( - chalkTemplate`--- ${os.hostname()} {gray (PID: ${process.pid.toString()})} ---`, - ); - - bootLogger.info("Welcome to Firefish!"); - bootLogger.info(`Firefish v${meta.version}`, null, true); -} - /** * Init master process */ diff --git a/packages/client/vite.config.ts b/packages/client/vite.config.ts index 14bbc44661..aa9d1a9186 100644 --- a/packages/client/vite.config.ts +++ b/packages/client/vite.config.ts @@ -1,4 +1,3 @@ -import * as fs from "fs"; import pluginVue from "@vitejs/plugin-vue"; import { defineConfig } from "vite"; @@ -23,13 +22,6 @@ const extensions = [ ]; export default defineConfig(({ command, mode }) => { - fs.mkdirSync(`${__dirname}/../../built`, { recursive: true }); - fs.writeFileSync( - `${__dirname}/../../built/meta.json`, - JSON.stringify({ version: meta.version }), - "utf-8", - ); - return { base: "/assets/", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 01646a3ee4..7d75eb7aec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -108,9 +108,6 @@ importers: chalk: specifier: 5.3.0 version: 5.3.0 - chalk-template: - specifier: 1.1.0 - version: 1.1.0 cli-highlight: specifier: 2.1.11 version: 2.1.11 @@ -3261,10 +3258,6 @@ packages: cbor-x@1.5.9: resolution: {integrity: sha512-OEI5rEu3MeR0WWNUXuIGkxmbXVhABP+VtgAXzm48c9ulkrsvxshjjk94XSOGphyAKeNGLPfAxxzEtgQ6rEVpYQ==} - chalk-template@1.1.0: - resolution: {integrity: sha512-T2VJbcDuZQ0Tb2EWwSotMPJjgpy1/tGee1BTpUNsGZ/qgNjV2t7Mvu+d4600U564nbLesN1x2dPL+xii174Ekg==} - engines: {node: '>=14.16'} - chalk@2.4.2: resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} engines: {node: '>=4'} @@ -10781,10 +10774,6 @@ snapshots: optionalDependencies: cbor-extract: 2.2.0 - chalk-template@1.1.0: - dependencies: - chalk: 5.3.0 - chalk@2.4.2: dependencies: ansi-styles: 3.2.1 diff --git a/scripts/copy-assets.mjs b/scripts/copy-assets.mjs index 9f667315de..1bfc08d3f2 100644 --- a/scripts/copy-assets.mjs +++ b/scripts/copy-assets.mjs @@ -14,12 +14,12 @@ await (async () => { ]); const locales = (await import("../locales/index.mjs")).default; - const meta = JSON.parse(await fs.readFile(file("built/meta.json"))); + const { version } = JSON.parse(await fs.readFile(file("package.json"))); for await (const [lang, locale] of Object.entries(locales)) { await fs.writeFile( - file(`built/_client_dist_/locales/${lang}.${meta.version}.json`), - JSON.stringify({ ...locale, _version_: meta.version }), + file(`built/_client_dist_/locales/${lang}.${version}.json`), + JSON.stringify({ ...locale, _version_: version }), "utf-8", ); }