Compare commits

...

8 Commits

Author SHA1 Message Date
CrescentLeaf
03f6f2743f chore: add "not impl" for not exists func 2025-09-20 00:33:22 +08:00
CrescentLeaf
13c42ddf38 chore: add UserBean for client 2025-09-20 00:32:55 +08:00
CrescentLeaf
c13913f08a feat(wip): 聯絡人 2025-09-20 00:32:37 +08:00
CrescentLeaf
b7ce12ff5e ui: 添加打開對話提示 2025-09-20 00:32:21 +08:00
CrescentLeaf
dd7c578534 fix: auth not check user is exists 2025-09-20 00:32:00 +08:00
CrescentLeaf
d473ff81bd feat(wip): 對話 2025-09-20 00:31:36 +08:00
CrescentLeaf
c6bfca0482 fix(typo): p->a<-ivate 2025-09-19 22:50:55 +08:00
CrescentLeaf
b1e7f3e485 fix(ui): 侧边联络人列表显示溢出 2025-09-19 20:04:56 +08:00
19 changed files with 335 additions and 64 deletions

View File

@@ -8,6 +8,7 @@ export type CallMethod =
"User.setAvatar" |
"User.getMyInfo" |
"Chat.getInfo" |
"Chat.sendMessage" |
"Chat.getMessageHistory"

View File

@@ -0,0 +1,10 @@
export default class Chat {
declare type: "paivate" | "group"
declare id: string
declare title?: string
declare avatar_file_hash?: string
declare user_a_id?: string
declare user_b_id?: string
[key: string]: unknown
}

View File

@@ -82,6 +82,10 @@ export default function App() {
const [myUserProfileCache, setMyUserProfileCache]: [User, React.Dispatch<React.SetStateAction<User>>] = React.useState(null as unknown as User)
const [isShowChatFragment, setIsShowChatFragment] = React.useState(false)
const [currentChatId, setCurrentChatId] = React.useState('')
React.useEffect(() => {
; (async () => {
Split(['#SideBar', '#ChatFragment'], {
@@ -144,12 +148,19 @@ export default function App() {
{
// 最近聊天
<RecentsList
openChatFragment={(id) => {
setIsShowChatFragment(true)
}}
display={navigationItemSelected == "Recents"}
recentsList={recentsList} />
}
{
// 联系人列表
<ContactsList
openChatFragment={(id) => {
setIsShowChatFragment(true)
}}
display={navigationItemSelected == "Contacts"}
contactsMap={contactsMap} />
}
@@ -157,7 +168,23 @@ export default function App() {
{
// 聊天页面
}
<ChatFragment id="ChatFragment" />
<div id="ChatFragment" style={{
display: "flex"
}}>
{
!isShowChatFragment && <div style={{
width: '100%',
textAlign: 'center',
alignSelf: 'center',
}}>
...
</div>
}
{
isShowChatFragment && <ChatFragment
target={currentChatId} />
}
</div>
</div>
)
}

View File

@@ -1,12 +1,24 @@
import { Tab } from "mdui"
import useEventListener from "../useEventListener.ts"
import Message from "./Message.jsx"
import Element_Message from "./Message.jsx"
import MessageContainer from "./MessageContainer.jsx"
import * as React from 'react'
import Client from "../../api/Client.ts"
import Message from "../../api/client_data/Message.ts"
import Chat from "../../api/client_data/Chat.ts"
import data from "../../Data.ts"
import { checkApiSuccessOrSncakbar } from "../snackbar.ts"
export default function ChatFragment({ ...props } = {}) {
const messageList = React.useState([])
interface Args extends React.HTMLAttributes<HTMLElement> {
target: string,
}
export default function ChatFragment({ target, ...props }: Args) {
const [messagesList, setMessagesList] = React.useState([] as Message[])
const [chatInfo, setChatInfo] = React.useState({
title: '加載中...'
} as Chat)
const [tabItemSelected, setTabItemSelected] = React.useState('Chat')
const tabRef: React.MutableRefObject<Tab | null> = React.useRef(null)
@@ -14,6 +26,18 @@ export default function ChatFragment({ ...props } = {}) {
setTabItemSelected((event.target as HTMLElement as Tab).value as string)
})
React.useEffect(() => {
;(async () => {
const re = await Client.invoke('Chat.getInfo', {
token: data.access_token,
target: target,
})
if (re.code != 200)
return checkApiSuccessOrSncakbar(re, "對話錯誤")
setChatInfo(re.data as Chat)
})()
}, [target])
return (
<div style={{
width: '100%',
@@ -28,7 +52,9 @@ export default function ChatFragment({ ...props } = {}) {
flexDirection: "column",
height: "100%",
}}>
<mdui-tab value="Chat">Title</mdui-tab>
<mdui-tab value="Chat">{
chatInfo.title
}</mdui-tab>
<mdui-tab value="Settings"></mdui-tab>
<mdui-tab-panel slot="panel" value="Chat" style={{

View File

@@ -1,25 +1,29 @@
import User from "../../api/client_data/User.ts"
import ContactsListItem from "./ContactsListItem.jsx"
import ContactsListItem from "./ContactsListItem.tsx"
interface Args extends React.HTMLAttributes<HTMLElement> {
contactsMap: { [key: string]: User[] }
display: boolean
openChatFragment: (id: string) => void
}
export default function ContactsList({
contactsMap,
display,
openChatFragment,
...props
}: Args) {
return <mdui-list style={{
overflowY: 'auto',
marginLeft: '10px',
marginRight: '10px',
width: '100%',
paddingLeft: '10px',
paddingRight: '10px',
display: display ? undefined : 'none'
}} {...props}>
<mdui-collapse accordion value={Object.keys(contactsMap)[0]}>
<mdui-list-item rounded style={{
width: '100%',
}} icon="person_add"></mdui-list-item>
{
Object.keys(contactsMap).map((v) =>
<mdui-collapse-item key={v} value={v}>
@@ -27,9 +31,9 @@ export default function ContactsList({
{
contactsMap[v].map((v2) =>
<ContactsListItem
openChatFragment={openChatFragment}
key={v2.id}
nickName={v2.nickname}
avatar={v2.avatar} />
contact={v2} />
)
}
</mdui-collapse-item>

View File

@@ -1,16 +0,0 @@
import Avatar from "../Avatar.tsx"
export default function ContactsListItem({ nickName, avatar }) {
return (
<mdui-list-item rounded style={{
marginTop: '3px',
marginBottom: '3px',
width: '100%',
}}>
<span style={{
width: "100%",
}}>{nickName}</span>
<Avatar src={avatar} text="title" slot="icon" />
</mdui-list-item>
)
}

View File

@@ -0,0 +1,23 @@
import User from "../../api/client_data/User.ts"
import Avatar from "../Avatar.tsx"
interface Args extends React.HTMLAttributes<HTMLElement> {
contact: User
openChatFragment: (id: string) => void
}
export default function ContactsListItem({ contact, openChatFragment }: Args) {
const { id, nickname, avatar } = contact
return (
<mdui-list-item rounded style={{
marginTop: '3px',
marginBottom: '3px',
width: '100%',
}} onClick={() => openChatFragment(id)}>
<span style={{
width: "100%",
}}>{nickname}</span>
<Avatar src={avatar} text="title" slot="icon" />
</mdui-list-item>
)
}

View File

@@ -1,30 +1,29 @@
import RecentChat from "../../api/client_data/RecentChat.ts"
import User from "../../api/client_data/User.ts"
import ContactsListItem from "./ContactsListItem.jsx"
import RecentsListItem from "./RecentsListItem.jsx"
import RecentsListItem from "./RecentsListItem.tsx"
interface Args extends React.HTMLAttributes<HTMLElement> {
recentsList: RecentChat[]
display: boolean
openChatFragment: (id: string) => void
}
export default function RecentsList({
recentsList,
display,
openChatFragment,
...props
}: Args) {
return <mdui-list style={{
overflowY: 'auto',
paddingRight: '10px',
display: display ? undefined : 'none'
}}>
}} {...props}>
{
recentsList.map((v) =>
<RecentsListItem
openChatFragment={openChatFragment}
key={v.id}
nickName={v.title}
avatar={v.avatar}
content={v.content} />
recentChat={v} />
)
}
</mdui-list>

View File

@@ -1,13 +1,20 @@
import RecentChat from "../../api/client_data/RecentChat.ts"
import Avatar from "../Avatar.tsx"
export default function RecentsListItem({ nickName, avatar, content }) {
interface Args extends React.HTMLAttributes<HTMLElement> {
recentChat: RecentChat
openChatFragment: (id: string) => void
}
export default function RecentsListItem({ recentChat, openChatFragment }: Args) {
const { id, title, avatar, content } = recentChat
return (
<mdui-list-item rounded style={{
marginTop: '3px',
marginBottom: '3px',
}}>
{nickName}
<Avatar src={avatar} text={nickName} slot="icon" />
}} onClick={() => openChatFragment(id)}>
{title}
<Avatar src={avatar} text={title} slot="icon" />
<span slot="description"
style={{
width: "100%",

View File

@@ -8,6 +8,9 @@ export type CallMethod =
"User.setAvatar" |
"User.getMyInfo" |
"User.getMyContactGroups" |
"User.setMyContactGroups" |
"Chat.getInfo" |
"Chat.sendMessage" |
"Chat.getMessageHistory"

View File

@@ -1,11 +1,12 @@
import HttpServerLike from '../typedef/HttpServerLike.ts'
import UserApi from "./UserApi.ts"
import ChatApi from "./ChatApi.ts"
import * as SocketIo from "socket.io"
import ApiCallbackMessage from "./ApiCallbackMessage.ts"
import EventCallbackFunction from "../typedef/EventCallbackFunction.ts"
import BaseApi from "./BaseApi.ts"
import DataWrongError from "./DataWrongError.ts";
import chalk from "chalk";
import DataWrongError from "./DataWrongError.ts"
import chalk from "chalk"
export default class ApiManager {
static httpServer: HttpServerLike
@@ -24,7 +25,8 @@ export default class ApiManager {
}
static initAllApis() {
this.apis_instance = {
user: new UserApi()
user: new UserApi(),
chat: new ChatApi(),
}
}
static addEventListener(name: string, func: EventCallbackFunction) {
@@ -45,7 +47,10 @@ export default class ApiManager {
})
console.log(chalk.red('[收]') + ` ${socket.request.socket.remoteAddress} -> ${chalk.yellow(name)} <args: ${JSON.stringify(args)}>`)
return callback(this.event_listeners[name]?.(args))
return callback(this.event_listeners[name]?.(args) || {
code: 501,
msg: "Not implmented",
})
} catch (e) {
const err = e as Error
console.log(chalk.yellow('[壞]') + ` ${err.message} (${err.stack})`)

View File

@@ -1,19 +1,68 @@
import Chat from "../data/Chat.ts";
import ChatPrivate from "../data/ChatPrivate.ts";
import User from "../data/User.ts"
import BaseApi from "./BaseApi.ts"
import TokenManager from "./TokenManager.ts"
export default class UserApi extends BaseApi {
export default class ChatApi extends BaseApi {
override getName(): string {
return "Chat"
}
override onInit(): void {
this.registerEvent("Chat.getInfo", (args) => {
if (this.checkArgsMissing(args, ['token', 'target'])) return {
msg: "參數缺失",
code: 400,
}
const token = TokenManager.decode(args.token as string)
if (!this.checkToken(token)) return {
code: 401,
msg: "令牌無效",
}
const chat = Chat.findById(args.target as string)
if (chat == null) return {
code: 404,
msg: "對話不存在",
}
// 私聊
if (chat!.bean.type == 'private') {
const targetId = args.target as string
const target = User.findById(targetId)
const mine = User.findById(token.author) as User
if (target == null) return {
code: 404,
msg: "找不到用户",
}
return {
code: 200,
msg: "成功",
data: {
type: chat.bean.type,
title: ChatPrivate.fromChat(chat).getTitleForPrivate(mine, target)
}
}
}
return {
code: 501,
msg: "未實現",
msg: "not implmented",
}
})
this.registerEvent("Chat.sendMessage", (args) => {
if (this.checkArgsMissing(args, ['token', 'target'])) return {
msg: "參數缺失",
code: 400,
}
const token = TokenManager.decode(args.token as string)
if (!this.checkToken(token)) return {
code: 401,
msg: "令牌無效",
}
return {
code: 501,
@@ -21,6 +70,16 @@ export default class UserApi extends BaseApi {
}
})
this.registerEvent("Chat.getMessageHistory", (args) => {
if (this.checkArgsMissing(args, ['token', 'target'])) return {
msg: "參數缺失",
code: 400,
}
const token = TokenManager.decode(args.token as string)
if (!this.checkToken(token)) return {
code: 401,
msg: "令牌無效",
}
return {
code: 501,

View File

@@ -22,6 +22,11 @@ export default class UserApi extends BaseApi {
code: 401,
}
if (!User.findById(access_token.author)) return {
msg: "賬號不存在",
code: 401,
}
return {
msg: "成功",
code: 200,
@@ -190,6 +195,50 @@ export default class UserApi extends BaseApi {
}
}
})
// 獲取聯絡人列表
this.registerEvent("User.getMyContactGroups", (args) => {
if (this.checkArgsMissing(args, ['token'])) return {
msg: "參數缺失",
code: 400,
}
const token = TokenManager.decode(args.token as string)
if (!this.checkToken(token)) return {
code: 401,
msg: "令牌無效",
}
const user = User.findById(token.author)
return {
msg: "成功",
code: 200,
data: {
contact_groups: user!.getContactGroups()
}
}
})
// 更新聯絡人列表
this.registerEvent("User.setMyContactGroups", (args) => {
if (this.checkArgsMissing(args, ['token', 'contact_groups'])) return {
msg: "參數缺失",
code: 400,
}
const token = TokenManager.decode(args.token as string)
if (!this.checkToken(token)) return {
code: 401,
msg: "令牌無效",
}
const user = User.findById(token.author)
user!.setContactGroups(args.contact_groups as { [key: string]: string[] })
return {
msg: "成功",
code: 200,
}
})
/*
* ================================================
* 公開資料

View File

@@ -1,5 +1,5 @@
export default class ChatBean {
declare type: "paivate" | "group"
declare type: "private" | "group"
declare id: string
declare title?: string
declare avatar_file_hash?: string

View File

@@ -1,7 +1,12 @@
import chalk from "chalk"
import Chat from "./Chat.ts"
import User from "./User.ts";
import User from "./User.ts"
export default class ChatPrivate extends Chat {
static fromChat(chat: Chat) {
return new ChatPrivate(chat.bean)
}
static getChatIdByUsersId(userIdA: string, userIdB: string) {
return [userIdA, userIdB].sort().join('-')
}
@@ -9,8 +14,16 @@ export default class ChatPrivate extends Chat {
static createForPrivate(userA: User, userB: User) {
return this.create(this.getChatIdByUsersId(userA.bean.id, userB.bean.id), 'private')
}
static findForPrivate() {
static findForPrivate(userA: User, userB: User) {
return this.fromChat(this.findById(this.getChatIdByUsersId(userA.bean.id, userB.bean.id)) as Chat)
}
static findOrCreateForPrivate(userA: User, userB: User) {
let a = this.findForPrivate(userA, userB)
if (a == null) {
this.createForPrivate(userA, userB)
a = this.findForPrivate(userA, userB) as ChatPrivate
}
return a
}
getTitleForPrivate(user: User, targetUser: User) {

View File

@@ -1,7 +1,7 @@
export default class Message {
export default class MessageBean {
declare id: number
declare text: string
declare user_id: string
declare user_id?: string
[key: string]: unknown
}

View File

@@ -5,22 +5,59 @@ import chalk from "chalk"
import config from "../config.ts"
import Chat from "./Chat.ts"
import MessageBean from "./MessageBean.ts"
export default class MessagesManager {
static table_name: string = "Messages"
static database: DatabaseSync = this.init()
private static init(): DatabaseSync {
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, this.table_name + '.db'))
const db: DatabaseSync = new DatabaseSync(path.join(config.data_path, 'Messages.db'))
return db
}
static getInstance(chat: Chat) {
static getInstanceForChat(chat: Chat) {
return new MessagesManager(chat)
}
declare chat: Chat
constructor(chat: Chat) {
this.chat = chat
MessagesManager.database.exec(`
CREATE TABLE IF NOT EXISTS ${this.getTableName()} (
/* 序号, MessageId */ id INTEGER PRIMARY KEY AUTOINCREMENT,
/* 消息文本 */ text TEXT NOT NULL,
/* 发送者 */ user_id TEXT NOT NULL,
);
`)
}
protected getTableName() {
return `messages_${this.chat.bean.id}`
}
addMessage({
text,
user_id
}: {
text: string,
user_id?: string
}) {
MessagesManager.database.prepare(`INSERT INTO ${this.getTableName()} (
text,
user_id
) VALUES (?, ?);`).run(
text,
user_id || null
)
}
addSystemMessage(text: string) {
this.addMessage({
text
})
}
getMessages(limit: number = 15, offset: number = 0) {
return MessagesManager.database.prepare(`SELECT * FROM ${this.getTableName()} ORDER BY id DESC LIMIT ? OFFSET ?;`).all(limit, offset) as unknown as MessageBean[]
}
getMessagesWithPage(limit: number = 15, page: number = 0) {
return this.getMessages(limit, limit * page)
}
}

View File

@@ -33,16 +33,17 @@ export default class User {
/* 用戶名, 可選 */ username TEXT,
/* 昵称 */ nickname TEXT NOT NULL,
/* 头像, 可选 */ avatar_file_hash TEXT,
/* 聯絡人組 */ contact_groups TEXT NOT NULL,
/* 设置 */ settings TEXT NOT NULL
);
`)
return db
return db
}
static createWithUserNameChecked(userName: string | null, password: string, nickName: string, avatar: Buffer | null) {
if (userName && User.findAllBeansByCondition('username = ?', userName).length > 0)
throw new DataWrongError(`用户名 ${userName} 已存在`)
return User.create(
return User.create(
userName,
password,
nickName,
@@ -61,19 +62,26 @@ export default class User {
username,
nickname,
avatar_file_hash,
contact_groups,
settings
) VALUES (?, ?, ?, ?, ?, ?, ?);`).run(
) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`).run(
crypto.randomUUID(),
password,
Date.now(),
userName,
nickName,
null,
'{}',
"{}"
).lastInsertRowid
)[0]
)
avatar && user.setAvatar(avatar)
user.setContactGroups({
: [
user.bean.id
]
})
return user
}
@@ -112,6 +120,21 @@ export default class User {
setUserName(userName: string) {
this.setAttr("username", userName)
}
getContactGroups() {
try {
return JSON.parse(this.bean.contact_groups)
} catch (e) {
console.log(chalk.yellow(`警告: 聯絡人組解析失敗: ${(e as Error).message}`))
return {
: [
this.bean.id
]
}
}
}
setContactGroups(contactGroups: { [key: string]: string[] }) {
this.setAttr("contact_groups", JSON.stringify(contactGroups))
}
getNickName(): string {
return this.bean.nickname
}

View File

@@ -6,6 +6,7 @@ export default class UserBean {
declare registered_time: number
declare nickname: string
declare avatar_file_hash?: string
declare contact_groups: string
declare settings: string
[key: string]: unknown