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

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
}