matrix-client.service.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import { effect, inject, Injectable, OnDestroy, signal } from '@angular/core';
  2. import type { MatrixClient, MatrixEvent, Room, RoomMember } from 'matrix-js-sdk';
  3. import { SessionService } from './session.service';
  4. /**
  5. * Matrix 客户端 —— `matrix-js-sdk` 的**唯一收敛点**
  6. *
  7. * 依据《数据访问层设计.md》§五(每域唯一 owner)与 SPEC FR-04。
  8. *
  9. * ## NFR-02:SDK 不得进主包
  10. *
  11. * `matrix-js-sdk` **只在首次真正需要时动态导入**(`await import()`),
  12. * 顶层仅 `import type`(编译期擦除,零运行时依赖)。
  13. * 验证:主包 chunk 中不得出现 `matrix-js-sdk` 字样。
  14. *
  15. * ## 身份规则(fmode-hub v4.2 P3 约定)
  16. *
  17. * - 用户 `mxid` = `@<用户 objectId 小写>:fmode.cn`
  18. * - Agent `mxid` = `@<FmodeAgent.objectId 小写>:fmode.cn`
  19. * - 凭据一律来自 provision 云函数(`RP5Ht55NeX`)**服务端签发**;
  20. * 本服务**不派生任何密码**(黄金规则 9:前端零密钥)。
  21. *
  22. * ## 不包含的能力
  23. *
  24. * 语音通话(`m.call.*` / WebRTC)按 SPEC FR-11 裁决**暂不实现**,
  25. * 故不引入 TURN 配置,也不依赖 `navigator.mediaDevices`。
  26. */
  27. /** 一条归一化后的文本消息(视图层只见此结构) */
  28. export interface MxMessage {
  29. /** 所属房间(未读计数需要知道消息来自哪个 Agent) */
  30. roomId: string;
  31. eventId: string;
  32. sender: string;
  33. body: string;
  34. ts: number;
  35. kind: 'text' | 'notice' | 'emote';
  36. /**
  37. * 是否**实时到达**的消息(`data.liveEvent === true`)。
  38. *
  39. * 🔴 `/sync` 初次同步会把**历史消息**逐条塞进 timeline,这些也会触发
  40. * `Room.timeline` 事件。若不加区分,未读计数会把整个历史都算成未读
  41. * (实测曾出现「刚连接就有 39 条未读」)。
  42. *
  43. * 未读计数**只计 `live === true`** 的消息;timeline 渲染两者都要。
  44. */
  45. live: boolean;
  46. }
  47. /** 同步连接状态(驱动 ChatService 的 ConnectionState) */
  48. export type MxSyncState = 'connecting' | 'connected' | 'disconnected';
  49. function kindOf(msgtype: string | undefined): MxMessage['kind'] {
  50. if (msgtype === 'm.notice') return 'notice';
  51. if (msgtype === 'm.emote') return 'emote';
  52. return 'text';
  53. }
  54. const TEXT_MSGTYPES = ['m.text', 'm.notice', 'm.emote'];
  55. @Injectable({ providedIn: 'root' })
  56. export class MatrixClientService implements OnDestroy {
  57. /** 懒加载的 SDK 模块(首次 `load()` 时填充) */
  58. private sdk: typeof import('matrix-js-sdk') | null = null;
  59. private client: MatrixClient | null = null;
  60. // ---------- 连接状态(供 chat 页徽标消费) ----------
  61. private readonly _syncState = signal<MxSyncState>('disconnected');
  62. readonly syncState = this._syncState.asReadonly();
  63. /**
  64. * 本地 store 版本号(每次 sync 完成 +1)。
  65. * 聊天页 `effect` 订阅它 → 重读 timeline,解决「同步晚于首读 → 历史空白」。
  66. */
  67. private readonly _storeVersion = signal(0);
  68. readonly storeVersion = this._storeVersion.asReadonly();
  69. private readonly _userId = signal<string>('');
  70. /** 当前登录的 Matrix 用户 id(`@xxx:fmode.cn`) */
  71. readonly userId = this._userId.asReadonly();
  72. private token = '';
  73. private deviceId = '';
  74. /** 显式停止标志:避免 disconnect() 后 sync 回调再改状态 */
  75. private stopped = false;
  76. /**
  77. * 初次同步是否已完成。
  78. *
  79. * 🔴 未读计数的**分界线**:初次 `/sync` 会把房间历史逐条回填(且按时间
  80. * 升序),若直接计数会把整个历史都算成未读。故此标志为 false 期间,
  81. * 未读只推进基线、不计数。
  82. */
  83. private initialSyncDone = false;
  84. /** 初次同步是否完成(未读计数用于区分历史与实时) */
  85. get hasInitialSync(): boolean {
  86. return this.initialSyncDone;
  87. }
  88. /**
  89. * 全局消息流 —— **全项目唯一一处** `Room.timeline` 订阅。
  90. *
  91. * 多路复用给:① 聊天页(当前房间)② 未读计数(所有房间)。
  92. * 这样 sync 常驻时也只有一个监听器,不会重复触发。
  93. */
  94. private readonly messageHandlers = new Set<(m: MxMessage) => void>();
  95. private globalBound = false;
  96. private readonly session = inject(SessionService);
  97. constructor() {
  98. // 🔴 登出即断连:不依赖页面记得调用 disconnect()。
  99. // 任一页面的 doLogout() 清掉 token 后,这里自动收敛。
  100. effect(() => {
  101. if (!this.session.token() && this.client) this.disconnect();
  102. });
  103. }
  104. ngOnDestroy(): void {
  105. this.disconnect();
  106. }
  107. // ---------- 生命周期(会话级常驻) ----------
  108. /**
  109. * 建立**会话级**连接(整个登录会话只调用一次,由 SessionService 持有者驱动)。
  110. *
  111. * 🔴 与旧实现的关键差异:这是**常驻**的 —— 不在聊天页 `close()` 时断开,
  112. * 否则离开会话后收不到消息,未读计数永远无法累加。
  113. * 断开只发生在**退出登录**时(`disconnect()`)。
  114. *
  115. * @param accessToken 云函数返回的 token(**不落 localStorage**,仅存内存)
  116. * @param userId 形如 `@sr2wipsdyq:fmode.cn`
  117. * @param deviceId 云函数返回的 deviceId(可空)
  118. */
  119. async connectSession(accessToken: string, userId: string, deviceId?: string): Promise<void> {
  120. if (!accessToken || !userId) {
  121. throw new Error('Matrix 凭据不完整(缺 accessToken 或 userId)');
  122. }
  123. // 同身份重复调用:幂等,不打断现有 sync
  124. if (this.client && this.token === accessToken && this._userId() === userId) {
  125. return;
  126. }
  127. this.disconnect();
  128. const sdk = await this.load();
  129. this.token = accessToken;
  130. this.deviceId = deviceId ?? '';
  131. this._userId.set(userId);
  132. this.stopped = false;
  133. this.initialSyncDone = false;
  134. this._syncState.set('connecting');
  135. this.client = sdk.createClient({
  136. baseUrl: MATRIX_HS,
  137. accessToken,
  138. userId,
  139. ...(deviceId ? { deviceId } : {}),
  140. });
  141. // sync 状态 → 连接状态(FR-04 AC-04.9:断线可自动重连)
  142. this.client.on(sdk.ClientEvent.Sync, (state: string) => {
  143. if (this.stopped) return;
  144. if (state === 'SYNCING' || state === 'PREPARED') this._syncState.set('connected');
  145. else if (state === 'ERROR') this._syncState.set('disconnected');
  146. else if (state === 'RECONNECTING') this._syncState.set('connecting');
  147. // 🔴 首个 SYNCING = 初次同步完成 → 之后的消息才算「实时」
  148. if (state === 'SYNCING') {
  149. this.initialSyncDone = true;
  150. /*
  151. * 🔴 通知「timeline 已就绪」。
  152. *
  153. * `startClient()` 是异步的:`openReal()` 里紧接着读 `timelineToMessages()`
  154. * 时,房间的历史事件**往往还没落到本地 store** → 拿到空数组;
  155. * 而后续只依赖 realtime 事件补消息,历史内容永远补不上
  156. * (表现为:刷新后会话空白、重开看不到之前的内容)。
  157. *
  158. * 每次 SYNCING 递增版本号,聊天页据此重读一次 timeline。
  159. */
  160. this._storeVersion.update((n) => n + 1);
  161. }
  162. });
  163. // 收到邀请自动接受(Agent 侧建房的场景)
  164. this.client.on(sdk.RoomMemberEvent.Membership, (_ev: MatrixEvent, member: RoomMember) => {
  165. if (this.stopped) return;
  166. if (member.membership === 'invite' && member.userId === userId) {
  167. void this.client?.joinRoom(member.roomId).catch(() => undefined);
  168. }
  169. });
  170. // 全局消息流(未读计数 + 聊天页复用)
  171. this.bindGlobalMessageStream();
  172. this.client.startClient({ initialSyncLimit: 50 });
  173. }
  174. /** 断开并清理(**仅退出登录时**调用) */
  175. disconnect(): void {
  176. this.stopped = true;
  177. this.initialSyncDone = false;
  178. this.messageHandlers.clear();
  179. this.globalBound = false;
  180. if (this.client) {
  181. try {
  182. this.client.stopClient();
  183. } catch {
  184. /* 忽略:销毁期异常不阻塞清理 */
  185. }
  186. try {
  187. this.client.removeAllListeners();
  188. } catch {
  189. /* 忽略 */
  190. }
  191. }
  192. this.client = null;
  193. this.token = '';
  194. this.deviceId = '';
  195. this._userId.set('');
  196. this._syncState.set('disconnected');
  197. }
  198. /** 是否已建立会话级连接 */
  199. get connected(): boolean {
  200. return !!this.client;
  201. }
  202. // ---------- 房间 ----------
  203. /**
  204. * 确保与目标 Agent 的 DM 房间可用。
  205. *
  206. * 优先用 provision 返回的 `roomId`(绑定表真相);未提供时按
  207. * `m.direct` accountData 查找,仍无则创建。
  208. */
  209. async ensureRoom(
  210. agentMxId: string,
  211. opts?: { roomId?: string | null; agentName?: string },
  212. ): Promise<string> {
  213. const c = this.requireClient();
  214. // ① 绑定表给的 roomId 优先(与容器侧同一房间)
  215. if (opts?.roomId) {
  216. const room = c.getRoom(opts.roomId);
  217. if (room && room.getMyMembership() === 'join') return opts.roomId;
  218. // 本地尚未 join → 尝试加入(可能是别的设备建的房)
  219. const joined = await c.joinRoom(opts.roomId).catch(() => null);
  220. if (joined) return opts.roomId;
  221. }
  222. // ② m.direct 里已有记录
  223. const directEv = c.getAccountData('m.direct' as never);
  224. const direct = directEv?.getContent() as Record<string, string[]> | undefined;
  225. for (const rid of direct?.[agentMxId] ?? []) {
  226. const room = c.getRoom(rid);
  227. if (room?.getMyMembership() === 'join') return rid;
  228. }
  229. // ③ 兜底:遍历已 join 房间找共同成员
  230. for (const room of c.getRooms()) {
  231. if (room.getMyMembership() !== 'join') continue;
  232. if (room.getMember(agentMxId)) return room.roomId;
  233. }
  234. // ④ 都没有 → 新建 DM
  235. const sdk = await this.load();
  236. const created = await c.createRoom({
  237. invite: [agentMxId],
  238. is_direct: true,
  239. preset: sdk.Preset.TrustedPrivateChat,
  240. name: opts?.agentName,
  241. });
  242. return created.room_id;
  243. }
  244. /** 该房间是否已是「已加入」状态 */
  245. isJoined(roomId: string): boolean {
  246. return !!this.client?.getRoom(roomId)?.getMyMembership?.();
  247. }
  248. // ---------- 消息收发 ----------
  249. /** 发文本(AC-04.2) */
  250. async sendText(roomId: string, text: string): Promise<{ event_id?: string }> {
  251. const c = this.requireClient();
  252. const sdk = await this.load();
  253. return c.sendEvent(roomId, sdk.EventType.RoomMessage, {
  254. msgtype: sdk.MsgType.Text,
  255. body: text,
  256. });
  257. }
  258. /** 发文件卡片(`m.text` + JSON body,与容器侧解析约定一致) */
  259. async sendFileCard(
  260. roomId: string,
  261. card: { name: string; size: number; mimeType: string; url: string },
  262. ): Promise<{ event_id?: string }> {
  263. const c = this.requireClient();
  264. const sdk = await this.load();
  265. return c.sendEvent(roomId, sdk.EventType.RoomMessage, {
  266. msgtype: sdk.MsgType.Text,
  267. body: JSON.stringify({ kind: 'file', ...card }),
  268. });
  269. }
  270. /** 当前 timeline → 归一消息(时间正序) */
  271. timelineToMessages(roomId: string): MxMessage[] {
  272. const room = this.client?.getRoom(roomId);
  273. if (!room) return [];
  274. return room
  275. .getLiveTimeline()
  276. .getEvents()
  277. .filter((e) => e.getType() === 'm.room.message')
  278. .filter((e) => TEXT_MSGTYPES.includes(String(e.getContent()['msgtype'] ?? '')))
  279. .map((e) => ({
  280. roomId,
  281. eventId: e.getId() ?? '',
  282. sender: e.getSender() ?? '',
  283. body: (e.getContent()['body'] as string) ?? '',
  284. ts: e.getTs(),
  285. kind: kindOf(String(e.getContent()['msgtype'] ?? '')),
  286. // 从 timeline 读出的都视为历史(未读不依赖此值)
  287. live: false,
  288. }));
  289. }
  290. /** 向上翻历史(AC-04.4) */
  291. async paginateBack(roomId: string, limit = 30): Promise<boolean> {
  292. const c = this.requireClient();
  293. let room = c.getRoom(roomId);
  294. if (!room) {
  295. await c.joinRoom(roomId).catch(() => null);
  296. room = c.getRoom(roomId);
  297. }
  298. if (!room) return false;
  299. return c.paginateEventTimeline(room.getLiveTimeline(), { backwards: true, limit });
  300. }
  301. /**
  302. * 是否还有更早历史(live timeline 的 pagination token 是否耗尽)。
  303. * 用于 UI 决定要不要显示「加载更早」入口,以及分页到顶后停止请求。
  304. */
  305. paginationToken(roomId: string): string | null {
  306. const room = this.client?.getRoom(roomId);
  307. if (!room || !this.sdk) return null;
  308. return room.getLiveTimeline().getPaginationToken(this.sdk.Direction.Backward) ?? null;
  309. }
  310. /** 已读回执 */
  311. async sendReceipt(roomId: string, eventId: string): Promise<void> {
  312. const c = this.requireClient();
  313. const ev = c
  314. .getRoom(roomId)
  315. ?.getLiveTimeline()
  316. .getEvents()
  317. .find((e) => e.getId() === eventId);
  318. if (!ev) return;
  319. await c.sendReadReceipt(ev);
  320. }
  321. /** 输入中通知(失败非致命) */
  322. async setTyping(roomId: string, typing: boolean, timeoutMs = 8000): Promise<void> {
  323. try {
  324. await this.requireClient().sendTyping(roomId, typing, timeoutMs);
  325. } catch {
  326. /* 非致命:typing 丢失不影响消息链路 */
  327. }
  328. }
  329. // ---------- 事件订阅 ----------
  330. /**
  331. * 订阅房间新消息;返回解绑函数。
  332. *
  333. * 不过滤 sender —— 自己发的消息也要接住(local echo 依赖 Timeline 事件)。
  334. */
  335. onMessage(roomId: string, cb: (m: MxMessage) => void): () => void {
  336. return this.onAnyMessage((m) => {
  337. if (m.roomId === roomId) cb(m);
  338. });
  339. }
  340. /**
  341. * 订阅**所有房间**的新消息(未读计数用);返回解绑函数。
  342. *
  343. * 与 `onMessage` 共用同一个底层订阅(`bindGlobalMessageStream`),
  344. * 因此无论多少订阅者,SDK 侧只有**一个** `Room.timeline` 监听器。
  345. */
  346. onAnyMessage(cb: (m: MxMessage) => void): () => void {
  347. this.messageHandlers.add(cb);
  348. return () => {
  349. this.messageHandlers.delete(cb);
  350. };
  351. }
  352. /** 订阅对方 typing 状态;返回解绑函数 */
  353. onTyping(roomId: string, cb: (typing: boolean, userId: string) => void): () => void {
  354. const c = this.requireClient();
  355. const handler = (ev: MatrixEvent, member: RoomMember) => {
  356. if (member?.roomId !== roomId || ev.getType() !== 'm.typing') return;
  357. cb(!!member.typing, member.userId ?? '');
  358. };
  359. c.on('RoomMember.typing' as never, handler as never);
  360. return () => {
  361. try {
  362. c.off('RoomMember.typing' as never, handler as never);
  363. } catch {
  364. /* 忽略 */
  365. }
  366. };
  367. }
  368. /** 绑定全局消息流(只绑一次,幂等) */
  369. private bindGlobalMessageStream(): void {
  370. const c = this.client;
  371. if (!c || this.globalBound) return;
  372. this.globalBound = true;
  373. c.on('Room.timeline' as never, ((ev: MatrixEvent, _room?: unknown, _toStart?: boolean, data?: { liveEvent?: boolean }) => {
  374. if (ev.getType() !== 'm.room.message') return;
  375. // 跳过本地未发送回执(echo 会再触发一次)
  376. const sending = (ev as unknown as { isSending?: () => boolean }).isSending;
  377. if (typeof sending === 'function' && sending.call(ev)) return;
  378. const msgtype = String(ev.getContent()['msgtype'] ?? '');
  379. if (!TEXT_MSGTYPES.includes(msgtype)) return;
  380. const msg: MxMessage = {
  381. roomId: ev.getRoomId() ?? '',
  382. eventId: ev.getId() ?? '',
  383. sender: ev.getSender() ?? '',
  384. body: (ev.getContent()['body'] as string) ?? '',
  385. ts: ev.getTs(),
  386. kind: kindOf(msgtype),
  387. // 仅真正的实时事件为 true;初次 /sync 的历史回填为 false
  388. live: !!data?.liveEvent,
  389. };
  390. for (const h of this.messageHandlers) {
  391. try {
  392. h(msg);
  393. } catch {
  394. /* 单个订阅者异常不影响其它订阅者 */
  395. }
  396. }
  397. }) as never);
  398. }
  399. // ---------- 工具 ----------
  400. /** `@<objectId 小写>:fmode.cn`(v4.2 P3 约定) */
  401. static agentMxId(objectId: string): string {
  402. return `@${objectId.toLowerCase()}:${MATRIX_SERVER_NAME}`;
  403. }
  404. /** 解析文件卡片 body;非卡片返回 null */
  405. static parseFileCard(
  406. body: string,
  407. ): { name: string; size: number; mimeType: string; url: string } | null {
  408. if (!body || body[0] !== '{') return null;
  409. try {
  410. const j = JSON.parse(body);
  411. if ((j.kind === 'file' || j.type === 'fcard') && j.url && j.name) {
  412. return {
  413. name: String(j.name),
  414. size: Number(j.size) || 0,
  415. mimeType: String(j.mimeType ?? j.mime ?? ''),
  416. url: String(j.url),
  417. };
  418. }
  419. return null;
  420. } catch {
  421. return null;
  422. }
  423. }
  424. private requireClient(): MatrixClient {
  425. if (!this.client) throw new Error('Matrix 客户端未连接');
  426. return this.client;
  427. }
  428. /** 动态导入 SDK(NFR-02:不进主包) */
  429. private async load(): Promise<typeof import('matrix-js-sdk')> {
  430. if (!this.sdk) {
  431. this.sdk = await import('matrix-js-sdk');
  432. /*
  433. * 🔴 SDK 日志降噪(否则控制台卡顿)。
  434. *
  435. * matrix-js-sdk 的 logger 默认输出 **warn 及以上**,且每条都带完整调用栈
  436. * (push rule 缺失的告警会在每次 startClient 时批量刷屏,
  437. * 叠加 zone.js 的调度栈,一次上百行)。
  438. * 这些告警不影响收发:push rule 是服务端推送规则,浏览器端本就不用。
  439. * 故收敛为只保留 error;取不到 logger 时静默跳过,绝不影响连接。
  440. */
  441. const sdkAny = this.sdk as { logger?: { setLevel?: (l: string) => void } };
  442. if (sdkAny.logger && typeof sdkAny.logger.setLevel === 'function') {
  443. sdkAny.logger.setLevel('error');
  444. }
  445. }
  446. return this.sdk;
  447. }
  448. }
  449. /** homeserver 常量(与《API-契约》§1.2 一致) */
  450. export const MATRIX_HS = 'https://matrix.fmode.cn';
  451. export const MATRIX_SERVER_NAME = 'fmode.cn';