chore: rename src/ to server/

This commit is contained in:
CrescentLeaf
2025-08-30 14:43:45 +08:00
parent 5e756636a9
commit 5666bcba24
16 changed files with 2 additions and 2 deletions

43
server/api/ApiManager.ts Normal file
View File

@@ -0,0 +1,43 @@
import HttpServerLike from '../types/HttpServerLike.ts'
import UserApi from "./UserApi.ts"
import SocketIo from "socket.io"
import ApiCallbackMessage from "../types/ApiCallbackMessage.ts"
import EventCallbackFunction from "../types/EventCallbackFunction.ts"
export default class ApiManager {
static httpServer: HttpServerLike
static socketIoServer: SocketIo.Server
static event_listeners: { [key: string] : EventCallbackFunction } = {}
static apis_instance: {}
static initServer(httpServer: HttpServerLike, socketIoServer: SocketIo.Server) {
this.httpServer = httpServer
this.socketIoServer = socketIoServer
}
static getHttpServer() {
return this.httpServer
}
static getSocketIoServer() {
return this.socketIoServer
}
static initAllApis() {
this.apis_instance = {
user: new UserApi()
}
}
static addEventListener(name: string, func: EventCallbackFunction) {
this.event_listeners[name] = func
}
static initEvents() {
const io = this.socketIoServer
io.on('connection', (socket) => {
socket.on("The_White_Silk", (name: string, args: {}, callback: (ret: ApiCallbackMessage) => void) => {
if (name == null || args == null) return callback({
msg: "Invalid request.",
code: 400
})
return callback(this.event_listeners[name]?.(args))
})
})
}
}

13
server/api/BaseApi.ts Normal file
View File

@@ -0,0 +1,13 @@
import EventCallbackFunction from "../types/EventCallbackFunction.ts"
import ApiManager from "./ApiManager.ts";
export default abstract class BaseApi {
abstract getName(): string
constructor() {
this.onInit()
}
abstract onInit(): void
registerEvent(name: string, func: EventCallbackFunction) {
ApiManager.addEventListener(this.getName() + "." + name, func)
}
}

18
server/api/UserApi.ts Normal file
View File

@@ -0,0 +1,18 @@
import BaseApi from "./BaseApi.ts";
export default class UserApi extends BaseApi {
override getName(): string {
return "User"
}
override onInit(): void {
this.registerEvent("", () => {
return {
msg: "",
code: 200,
data: {
}
}
})
}
}

39
server/config.ts Normal file
View File

@@ -0,0 +1,39 @@
import fs from 'node:fs/promises'
import chalk from 'chalk'
const default_data_path = "./thewhitesilk_data"
let config = {
data_path: default_data_path,
server: {
use: "http",
/**
* used in server.listen()
*/
listen: {
port: 3601,
host: "::",
/**
* setting ipv6Only to true will disable dual-stack support, i.e., binding to host :: won't make 0.0.0.0 be bound.
*/
ipv6Only: false,
},
/**
* used in https.createServer()
*/
https: {
key: default_data_path + '/key.pem',
cert: default_data_path + '/cert.pem',
},
},
}
try {
config = JSON.parse(await fs.readFile('thewhitesilk_config.json', 'utf-8'))
} catch (_e) {
console.log(chalk.yellow("配置文件貌似不存在, 正在创建..."))
await fs.writeFile('thewhitesilk_config.json', JSON.stringify(config))
}
await fs.mkdir(config.data_path, { recursive: true })
export default config

82
server/data/Chat.ts Normal file
View File

@@ -0,0 +1,82 @@
import { DatabaseSync } from "node:sqlite"
// import { Buffer } from "node:buffer"
import path from 'node:path'
import config from '../config.ts'
import ChatBean from './ChatBean.ts'
/**
* Chat.ts - Wrapper and manager
* Wrap with ChatBean to directly update database
* Manage the database by itself (static)
*/
export default class Chat {
static table_name: string = "Chat"
private static database: DatabaseSync = Chat.init()
private static init(): DatabaseSync {
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, 'Chats.db'))
db.exec(`
CREATE TABLE IF NOT EXISTS ${Chat.table_name} (
/* 序号 */ count INTEGER PRIMARY KEY AUTOINCREMENT,
/* Chat ID, 哈希 */ id TEXT,
/* 设置 */ settings TEXT NOT NULL
);
`)
return db
}
private static findAllByCondition(condition: string, ...args: unknown[]): ChatBean[] {
return database.prepare(`SELECT * FROM ${Chat.table_name} WHERE ${condition}`).all(...args)
}
static findById(id: string): Chat {
const beans = Chat.findAllBeansByCondition('id = ?', id)
if (beans.length == 0)
throw new Error(`找不到 id 为 ${id} 的 Chat`)
else if (beans.length > 1)
console.error(chalk.red(`警告: 查询 id = ${id} 时, 查询到多个相同 ID 的 Chat`))
return new Chat(beans[0])
}
declare bean: ChatBean
constructor(bean: ChatBean) {
this.bean = bean
}
private setAttr(key: string, value: unknown): void {
User.database.prepare(`UPDATE ${Chat.table_name} SET ${key} = ? WHERE id = ?`).run(value, this.bean.id)
this.bean[key] = value
}
getSettings(): Chat.Settings {
return new Chat.Settings(this, JSON.parse(this.bean.settings))
}
static Settings = class {
declare bean: Chat.SettingsBean
declare chat: Chat
constructor(chat: Chat, bean: Chat.SettingsBean) {
this.bean = bean
this.chat = chat
for (const i of [
]) {
this["set" + i.substring(0, 1).toUpperCase() + i.substring(1)] = (v: unknown) => {
this.set(i, v)
}
}
}
set(key: string, value: unknown) {
this.bean[key] = value
}
get(key: string) {
return this.bean[key]
}
apply() {
this.chat.setAttr("settings", JSON.stringify(this.bean))
}
}
static SettingsBean = class {
}
}

4
server/data/ChatBean.ts Normal file
View File

@@ -0,0 +1,4 @@
export default class ChatBean {
declare id: string
declare settings: string
}

139
server/data/FileManager.ts Normal file
View File

@@ -0,0 +1,139 @@
import { DatabaseSync, SQLInputValue } from "node:sqlite"
import { Buffer } from "node:buffer"
import path from 'node:path'
import crypto from 'node:crypto'
import fs_sync from 'node:fs'
import chalk from "chalk"
import { fileTypeFromBuffer } from 'file-type'
import config from "../config.ts"
class FileBean {
declare count: number
declare name: string
declare hash: string
declare mime: string
declare chatid?: string
declare upload_time: number
declare last_used_time: number
}
type FileBeanKey = keyof FileBean
class File {
declare bean: FileBean
constructor(bean: FileBean) {
this.bean = bean
}
private setAttr(key: FileBeanKey, value: SQLInputValue) {
FileManager.database.prepare(`UPDATE ${FileManager.table_name} SET ${key} = ? WHERE count = ?`).run(value, this.bean.count)
this.bean[key] = value as never
}
getMime() {
return this.bean.mime
}
getName() {
return this.bean.name
}
getFilePath() {
const hash = this.bean.hash
return path.join(
config.data_path,
"files",
hash.substring(0, 1),
hash.substring(2, 3),
hash.substring(3, 4),
this.bean.hash
)
}
getChatId() {
return this.bean.chatid
}
getUploadTime() {
return this.bean.upload_time
}
getLastUsedTime() {
return this.bean.last_used_time
}
readSync() {
this.setAttr("last_used_time", Date.now())
return fs_sync.readFileSync(this.getFilePath())
}
}
export default class FileManager {
static FileBean = FileBean
static File = File
static table_name: string = "FileReferences"
static database: DatabaseSync = FileManager.init()
private static init(): DatabaseSync {
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, FileManager.table_name + '.db'))
db.exec(`
CREATE TABLE IF NOT EXISTS ${FileManager.table_name} (
/* 序号 */ count INTEGER PRIMARY KEY AUTOINCREMENT,
/* 文件名称 */ name TEXT NOT NULL,
/* 文件哈希 */ hash TEXT NOT NULL,
/* MIME 类型 */ mime TEXT NOT NULL,
/* 来源 Chat, 可為空 */ chatid TEXT,
/* 上传时间 */ upload_time INT8 NOT NULL,
/* 最后使用时间 */ last_used_time INT8 NOT NULL
);
`)
return db
}
static async uploadFile(fileName: string, data: Buffer, chatId?: string) {
const hash = crypto.createHash('sha256').update(data).digest('hex')
try {
return FileManager.findByHash(hash)
} catch (_e) {
// Do nothing...
}
const mime = (await fileTypeFromBuffer(data))?.mime || 'application/octet-stream'
fs_sync.writeFileSync(
path.join(
config.data_path,
"files",
hash.substring(0, 1),
hash.substring(2, 3),
hash.substring(3, 4),
hash
),
data
)
return new FileManager.File(
FileManager.findAllBeansByCondition(
'count = ?',
FileManager.database.prepare(`INSERT INTO ${FileManager.table_name} (
name,
hash,
mime,
chatid,
upload_time,
last_used_time
) VALUES (?, ?, ?, ?, ?, ?);`).run(
fileName,
hash,
mime,
chatId || null,
Date.now(),
-1
).lastInsertRowid
)[0]
)
}
private static findAllBeansByCondition(condition: string, ...args: SQLInputValue[]): FileBean[] {
return FileManager.database.prepare(`SELECT * FROM ${FileManager.table_name} WHERE ${condition};`).all(...args) as unknown as FileBean[]
}
static findByHash(hash: string): File {
const beans = FileManager.findAllBeansByCondition('hash = ?', hash)
if (beans.length == 0)
throw new Error(`找不到 hash 为 ${hash} 的文件`)
else if (beans.length > 1)
console.error(chalk.red(`警告: 查询 hash = ${hash} 时, 查询到多个相同 Hash 的文件`))
return new FileManager.File(beans[0])
}
}

152
server/data/User.ts Normal file
View File

@@ -0,0 +1,152 @@
import { DatabaseSync } from "node:sqlite"
import { Buffer } from "node:buffer"
import path from 'node:path'
import crypto from 'node:crypto'
import chalk from 'chalk'
import config from '../config.ts'
import UserBean from './UserBean.ts'
import FileManager from './FileManager.ts'
/**
* User.ts - Wrapper and manager
* Wrap with UserBean to directly update database
* Manage the database by itself (static)
*/
export default class User {
static table_name: string = "Users"
private static database: DatabaseSync = User.init()
private static init(): DatabaseSync {
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, User.table_name + '.db'))
db.exec(`
CREATE TABLE IF NOT EXISTS ${User.table_name} (
/* 序号 */ count INTEGER PRIMARY KEY AUTOINCREMENT,
/* 用户 ID, 哈希 */ id TEXT,
/* 注册时间, 时间戳 */ registered_time INT8 NOT NULL,
/* 用戶名, 可選 */ username TEXT,
/* 昵称 */ nickname TEXT NOT NULL,
/* 头像, 可选 */ avatar_file_hash TEXT,
/* 设置 */ settings TEXT NOT NULL
);
`)
return db
}
static createWithUserNameChecked(userName: string | null, nickName: string, avatar: Buffer | null): User {
if (User.findAllBeansByCondition('username = ?', userName).length > 0)
throw new Error(`用户名 ${userName} 已存在`)
return User.create(
userName,
nickName,
avatar
)
}
static create(userName: string | null, nickName: string, avatar: Buffer | null): User {
const user = new User(
User.findAllBeansByCondition(
'count = ?',
User.database.prepare(`INSERT INTO ${User.table_name} (
id,
registered_time,
username,
nickname,
avatar_file_hash,
settings
) VALUES (?, ?, ?, ?, ?, ?);`).run(
crypto.randomUUID(),
Date.now(),
userName,
nickName,
null,
"{}"
).lastInsertRowid
)[0]
)
avatar && user.setAvatar(avatar)
return user
}
private static findAllBeansByCondition(condition: string, ...args: unknown[]): UserBean[] {
return User.database.prepare(`SELECT * FROM ${User.table_name} WHERE ${condition};`).all(...args)
}
static findById(id: string): User {
const beans = User.findAllBeansByCondition('id = ?', id)
if (beans.length == 0)
throw new Error(`找不到用户 ID 为 ${id} 的用户`)
else if (beans.length > 1)
console.error(chalk.red(`警告: 查询 id = ${id} 时, 查询到多个相同用户 ID 的用户`))
return new User(beans[0])
}
static findByUserName(userName: string): User {
const beans = User.findAllBeansByCondition('username = ?', userName)
if (beans.length == 0)
throw new Error(`找不到用户名为 ${userName} 的用户`)
else if (beans.length > 1)
console.error(chalk.red(`警告: 查询 username = ${userName} 时, 查询到多个相同用户名的用户`))
return new User(beans[0])
}
declare bean: UserBean
constructor(bean: UserBean) {
this.bean = bean
}
/* 一切的基础都是 count ID */
private setAttr(key: string, value: unknown): void {
User.database.prepare(`UPDATE ${User.table_name} SET ${key} = ? WHERE count = ?`).run(value, this.bean.count)
this.bean[key] = value
}
getUserName(): string | null {
return this.bean.username
}
setUserName(userName: string): void {
this.setAttr("username", userName)
}
getNickName(): string {
return this.bean.nickname
}
setNickName(nickName: string): void {
this.setAttr("nickname", nickName)
}
getAvatar(): Buffer | null {
return FileManager.findByHash(this.bean.avatar_file_hash)?.readSync()
}
setAvatar(avatar: Buffer): void {
this.setAttr("avatar_file_hash", FileManager.uploadFile(`avatar_user_${this.bean.count}`, avatar).getHash())
}
getSettings(): User.Settings {
return new User.Settings(this, JSON.parse(this.bean.settings))
}
static Settings = class {
declare bean: User.SettingsBean
declare user: User
constructor(user: User, bean: User.SettingsBean) {
this.bean = bean
this.user = user
for (const i of [
]) {
this["set" + i.substring(0, 1).toUpperCase() + i.substring(1)] = (v: unknown) => {
this.set(i, v)
}
}
}
set(key: string, value: unknown) {
this.bean[key] = value
}
get(key: string) {
return this.bean[key]
}
apply() {
this.user.setAttr("settings", JSON.stringify(this.bean))
}
}
static SettingsBean = class {
}
}

8
server/data/UserBean.ts Normal file
View File

@@ -0,0 +1,8 @@
export default class UserBean {
declare count: number
declare username: string | null
declare registered_time: number
declare nickname: string
declare avatar_file_hash: string | null
declare settings: string
}

23
server/main.ts Normal file
View File

@@ -0,0 +1,23 @@
import ApiManager from "./api/ApiManager.ts"
import express from 'express'
import SocketIo from 'socket.io'
import HttpServerLike from "./types/HttpServerLike.ts"
import config from './config.ts'
import http from 'node:http'
import https from 'node:https'
const app = express()
const httpServer: HttpServerLike = (
((config.server.use == 'http') && http.createServer(app)) ||
((config.server.use == 'https') && https.createServer(config.server.https, app)) ||
http.createServer(app)
)
const io = new SocketIo.Server(httpServer, {
})
ApiManager.initServer(httpServer, io)
ApiManager.initEvents()
ApiManager.initAllApis()
httpServer.listen(config.server.listen)

42
server/main_test.ts Normal file
View File

@@ -0,0 +1,42 @@
import { DatabaseSync } from "node:sqlite"
import fs from 'node:fs/promises'
await fs.mkdir('data', { recursive: true })
const db = new DatabaseSync("data/users.db")
const TABEL_NAME = "Users"
// 初始化表格
db.exec(
`
CREATE TABLE IF NOT EXISTS ${TABEL_NAME} (
/* 伺服器中 ID */ id INTEGER PRIMARY KEY AUTOINCREMENT,
/* 用戶名, 可選 */ username TEXT,
/* 姓名 */ nickname TEXT NOT NULL,
/* 头像, 可选 */ avatar BLOB
);
`,
)
// 插入测试数据
db.prepare(
`
INSERT INTO ${TABEL_NAME} (username, nickname, avatar) VALUES (?, ?, ?);
`,
).run("SisterWen", "文姐", null)
let rows = db.prepare(`SELECT id, username, nickname, avatar FROM ${TABEL_NAME}`).all();
for (const row of rows) {
console.log(row)
}
// 更新用户名
// 用户名要合规, 以免导致 SQL 注入!
db.prepare(`UPDATE ${TABEL_NAME} SET username = ? WHERE id = ?`).run("文姐", 1)
rows = db.prepare(`SELECT id, username, nickname, avatar FROM ${TABEL_NAME} WHERE username = ?`).all("文姐")
for (const row of rows) {
console.log(row)
}
db.close()

View File

@@ -0,0 +1,14 @@
type ApiCallbackMessage = {
msg: string,
/**
* 200: 成功
* 400: 伺服器端無法理解客戶端請求
* 401: 需要身份驗證
* 403: 伺服器端拒絕執行客戶端請求
* 404: Not Found
* 500: 伺服器端錯誤
* 501: 伺服器端不支持請求的功能
*/
code: 200 | 400 | 401 | 403 | 404 | 500 | 501,
}
export default ApiCallbackMessage

View File

@@ -0,0 +1,5 @@
import ApiCallbackMessage from "./ApiCallbackMessage.ts"
type EventCallbackFunction = (args: {}) => ApiCallbackMessage
export default EventCallbackFunction

View File

@@ -0,0 +1,6 @@
import http from 'node:http'
import https from 'node:https'
type HttpServerLike = http.Server | https.Server
export default HttpServerLike

View File

@@ -0,0 +1,3 @@
type UnknownFunction = (...args: unknown[]) => unknown
export default UnknownFunction