@yusho/server 0.0.0-stage → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +135 -2
  2. package/app/appguide.mjs +33 -0
  3. package/app/asr.mjs +82 -0
  4. package/app/assets/agents/claude-192.webp +0 -0
  5. package/app/assets/agents/claude-96.webp +0 -0
  6. package/app/assets/agents/codex-192.webp +0 -0
  7. package/app/assets/agents/codex-96.webp +0 -0
  8. package/app/assets/agents/default-192.webp +0 -0
  9. package/app/assets/agents/default-96.webp +0 -0
  10. package/app/assets/agents/dsh-192.webp +0 -0
  11. package/app/assets/agents/dsh-96.webp +0 -0
  12. package/app/assets/brand/logo.webp +0 -0
  13. package/app/assets/lib/THIRD-PARTY.txt +1 -0
  14. package/app/assets/lib/jsqr.js +10102 -0
  15. package/app/assets/linux/alpine-arm64.tar.gz +0 -0
  16. package/app/assets/linux/alpine-x64.tar.gz +0 -0
  17. package/app/assets/live/claude.livliv +0 -0
  18. package/app/assets/live/dafeiyu.livliv +0 -0
  19. package/app/assets/live/gpt.livliv +0 -0
  20. package/app/assets/live/sho.livliv +0 -0
  21. package/app/assets/live//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  22. package/app/assets/livliv/LICENSE +202 -0
  23. package/app/assets/livliv/NOTICE +7 -0
  24. package/app/assets/livliv/player.mjs +15 -0
  25. package/app/assets/looks/claude.webp +0 -0
  26. package/app/assets/looks/dafeiyu.webp +0 -0
  27. package/app/assets/looks/gpt.webp +0 -0
  28. package/app/assets/looks//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  29. package/app/assets/sho/avatar.webp +0 -0
  30. package/app/assets/sho/done.webp +0 -0
  31. package/app/assets/sho/eat.webp +0 -0
  32. package/app/assets/sho/idle-blink.webp +0 -0
  33. package/app/assets/sho/idle.webp +0 -0
  34. package/app/assets/sho/listen.webp +0 -0
  35. package/app/assets/sho/need.webp +0 -0
  36. package/app/assets/sho/work.webp +0 -0
  37. package/app/companion.mjs +519 -0
  38. package/app/diag.mjs +51 -0
  39. package/app/index.html +497 -0
  40. package/app/judge.mjs +103 -0
  41. package/app/lanxfer.mjs +157 -0
  42. package/app/launcher.mjs +2711 -0
  43. package/app/linux.mjs +97 -0
  44. package/app/livliv-pack.mjs +12 -0
  45. package/app/memory.mjs +53 -0
  46. package/app/net.mjs +717 -0
  47. package/app/office.mjs +172 -0
  48. package/app/p2plink.mjs +134 -0
  49. package/app/pcupdate.mjs +55 -0
  50. package/app/plans.mjs +126 -0
  51. package/app/plugins.mjs +79 -0
  52. package/app/realtime.mjs +67 -0
  53. package/app/skills/app-icon/SKILL.md +31 -0
  54. package/app/skills/daily-brief/SKILL.md +29 -0
  55. package/app/skills/expense-review/SKILL.md +28 -0
  56. package/app/skills/make-app/SKILL.md +92 -0
  57. package/app/skills/make-skin/SKILL.md +51 -0
  58. package/app/skills/meeting-notes/SKILL.md +23 -0
  59. package/app/skills/reading-notes/SKILL.md +25 -0
  60. package/app/skills/sho-stickers/SKILL.md +34 -0
  61. package/app/skills/sho-stickers/stickers/eat.webp +0 -0
  62. package/app/skills/sho-stickers/stickers/got-it.webp +0 -0
  63. package/app/skills/sho-stickers/stickers/hi.webp +0 -0
  64. package/app/skills/sho-stickers/stickers/huh.webp +0 -0
  65. package/app/skills/sho-stickers/stickers/on-it.webp +0 -0
  66. package/app/skills/sho-stickers/stickers/yay.webp +0 -0
  67. package/app/skills/sho-stickers/stickers.json +12 -0
  68. package/app/skills/study-plan/SKILL.md +30 -0
  69. package/app/skills/trip-planner/SKILL.md +29 -0
  70. package/app/skills/weekly-report/SKILL.md +30 -0
  71. package/app/skills/workout-plan/SKILL.md +30 -0
  72. package/app/skills/writing-polish/SKILL.md +33 -0
  73. package/app/skills.mjs +173 -0
  74. package/app/skins.mjs +40 -0
  75. package/app/social.mjs +1067 -0
  76. package/app/storage.mjs +143 -0
  77. package/app/tts.mjs +68 -0
  78. package/app/ttslocal.mjs +77 -0
  79. package/app/voices.mjs +102 -0
  80. package/backup.mjs +109 -0
  81. package/bin/yusho.mjs +141 -0
  82. package/connector/lib/api.mjs +14 -0
  83. package/connector/lib/autostart.mjs +40 -0
  84. package/connector/lib/client.js +165 -0
  85. package/connector/lib/connector.mjs +468 -0
  86. package/connector/lib/dsh-acp.mjs +129 -0
  87. package/connector/lib/dsh-headless.patch.yml +4 -0
  88. package/connector/lib/dsh-plugin.mjs +80 -0
  89. package/connector/lib/lanfile.mjs +151 -0
  90. package/connector/lib/nostr.mjs +53 -0
  91. package/connector/lib/page.html +121 -0
  92. package/connector/lib/qr.mjs +4 -0
  93. package/connector/lib/service.mjs +54 -0
  94. package/node_modules/@local/shoal-mobile/lib/index.js +485 -0
  95. package/node_modules/@local/shoal-mobile/lib/polyfill.js +82 -0
  96. package/node_modules/@local/shoal-mobile/lib/session-context.js +34 -0
  97. package/node_modules/@local/shoal-mobile/lib/shell.js +60 -0
  98. package/node_modules/@local/shoal-mobile/lib/web-startup.js +33 -0
  99. package/node_modules/@local/shoal-mobile/package.json +24 -0
  100. package/node_modules/@local/yusho-pc/lib/client.js +9100 -0
  101. package/node_modules/@local/yusho-pc/lib/index.js +3 -0
  102. package/node_modules/@local/yusho-pc/package.json +28 -0
  103. package/node_modules/@local/yusho-web-login/brand/icon-192.webp +0 -0
  104. package/node_modules/@local/yusho-web-login/brand/logo-dark.svg +25 -0
  105. package/node_modules/@local/yusho-web-login/brand.mjs +8 -0
  106. package/node_modules/@local/yusho-web-login/dsh-web-login.mjs +974 -0
  107. package/node_modules/@local/yusho-web-login/lib/client.js +607 -0
  108. package/node_modules/@local/yusho-web-login/login-page.mjs +609 -0
  109. package/node_modules/@local/yusho-web-login/login-store.mjs +708 -0
  110. package/node_modules/@local/yusho-web-login/package.json +25 -0
  111. package/node_modules/@local/yusho-web-login/whale-scene.mjs +509 -0
  112. package/node_modules/@local/yusho-web-login/yusho-scene.mjs +227 -0
  113. package/package.json +38 -4
  114. package/pc.patch.yml +83 -0
  115. package/run.mjs +136 -0
package/app/social.mjs ADDED
@@ -0,0 +1,1067 @@
1
+ // 鱼Sho 手机版:人和人。昵称、按鱼Sho号加好友、和好友加密聊天。
2
+ // 消息走 net.mjs 的同一条 NIP-17 加密私聊:
3
+ // 聊天 = 普通的 NIP-17 文本(别的 Nostr 软件也能和你聊);
4
+ // 加好友 = 结构化消息 {shoal:1, type:'friend.request' | 'friend.accept', name, number, note?};
5
+ // 昵称 = 公开的个人资料(kind 0,带 nip05 = 号码@yusho.chat)。
6
+ // 动态(圈子)= 结构化消息 {type:'moment.post' | 'moment.delete' | 'moment.like' | 'moment.comment'}:发一条动态就给每个好友各发一份加密私信,
7
+ // 服务器只看到密文;点赞、评论只发给动态的作者(像朋友圈:你看得到自己点的赞、写的评论,作者看得到全部)
8
+ // 群聊 = {type:'group.invite' | 'group.update' | 'group.msg' | 'group.leave', gid}:每条群消息给每个成员各发一份加密私信。
9
+ // 只有好友能把你拉进群(防骚扰);只收群成员发来的消息;成员名单、群名、简介、群头像只认群主改;群主退群时转给下一个人
10
+ // 群昵称 {type:'group.nick'}:每个人改自己的;群里的 Agent {type:'group.agents'}:每个人只能带自己电脑上的 Agent,
11
+ // 别人 @ 它时,由带它进来的那部手机交给自己的电脑去做,再把回答发回群里(消息上标 agent)
12
+ // 文件 = {type:'file', file}(和图片一样:加密上传到文件服务器,消息里只有钥匙和哈希)
13
+ // 兴趣圈 = 带 circle 的群:圈主在中继上发一张公开名片(kind 30078,d = yusho-circle:<群号>,只有名字、简介、分类、人数),别人能搜到;
14
+ // 想进的人给圈主发 {type:'circle.join'};直接加入的圈自动拉进来,要申请的圈主点同意才拉;群里的消息照样一人一份加密
15
+ // 动态的“谁能看”:好友(一人一份加密私信)/ 某个兴趣圈(发给圈里的人)/ 公开(文字另外发一条公开帖到中继,带 t=yusho 标签)
16
+ // 防骚扰:只有好友的消息进聊天;不是好友的人发来的(加好友或直接说话)都只进“想加你的人”,你点了“通过”才是好友。
17
+ import fs from 'node:fs'
18
+ import path from 'node:path'
19
+ import crypto from 'node:crypto'
20
+ const sha256hex = (b) => crypto.createHash('sha256').update(b).digest('hex')
21
+
22
+ const MAX_TEXT = 4000
23
+
24
+ export function createSocial({ media, dir, me, idService, sendText, sendJson, copySelf = () => {}, query, publishSigned, moderate = async () => null, modList = async () => null, notify, changed, log }) {
25
+ const F = (n) => path.join(dir, n)
26
+ const chatDir = F('chats'); fs.mkdirSync(chatDir, { recursive: true })
27
+ const readJ = (f, d) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')) } catch { return d } }
28
+ let st = readJ(F('social.json'), { name: '', published: 0, friends: [], requests: [], outgoing: [] })
29
+ st.hide ??= []; st.reports ??= []; st.joinPending ??= {}; st.peers ??= {}; st.sig ??= ''
30
+ const save = () => fs.writeFileSync(F('social.json'), JSON.stringify(st))
31
+ const chatFile = (pk) => path.join(chatDir, pk.replace(/[^0-9a-f]/g, '') + '.json')
32
+ const readChat = (pk) => readJ(chatFile(pk), [])
33
+ const appendChat = (pk, msg) => { const a = [...readChat(pk), msg].slice(-500); fs.writeFileSync(chatFile(pk), JSON.stringify(a)); return a }
34
+ const friend = (pk) => st.friends.find((f) => f.pk === pk)
35
+ const clean = (s, n) => String(s ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, n)
36
+ const cleanML = (s, n) => String(s ?? '').replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, ' ').replace(/\n{3,}/g, '\n\n').trim().slice(0, n) // 动态可以换行
37
+
38
+ // ── 图片:发的时候先存一份到本地 media/,收到的在后台下载解密存进去;界面按哈希取
39
+ const mediaDir = F('media'); fs.mkdirSync(mediaDir, { recursive: true })
40
+ const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif' }
41
+ const mediaPath = (sha, type) => path.join(mediaDir, sha + '.' + (EXT[type] ?? 'bin'))
42
+ const imgInfo = (r) => ({ sha: r.sha256, type: r.type, w: r.w, h: r.h })
43
+ async function sendImage(b64, type) {
44
+ if (!media) throw new Error('这一版不能发图片')
45
+ const buf = Buffer.from(String(b64 ?? ''), 'base64'); if (buf.length < 100) throw new Error('图片是空的')
46
+ if (buf.length > 8_000_000) throw new Error('图片太大(超过 8 MB)')
47
+ const t = EXT[type] ? type : 'image/jpeg', ref = await media.upload(buf, { name: 'image.' + EXT[t], type: t })
48
+ fs.writeFileSync(mediaPath(ref.sha256, t), buf)
49
+ return ref
50
+ }
51
+ // 昵称、个签审核:好友和群里看到的是加密发过去的那份,服务器看不到,所以在改的时候判定;违规的存成星号(几个字几个星号)
52
+ // 审核服务没开 / 连不上:先放过(和动态一样)
53
+ const stars = (t) => '*'.repeat([...String(t ?? '')].length)
54
+ async function reviewProfile(name, sig) {
55
+ if (!name && !sig) return { name: true, sig: true }
56
+ try {
57
+ const v = await moderate({ kind: 0, created_at: Math.floor(Date.now() / 1000), tags: [], content: JSON.stringify({ name: name ?? '', about: sig ?? '' }) }, 'profile')
58
+ if (!v || !v.profile) return { name: true, sig: true }
59
+ if (name && v.profile.name !== false) st.nameOk = name // 审过、能用的昵称记下来:还没领到号时改的昵称,领到号后要补审
60
+ return { name: v.profile.name !== false, sig: v.profile.about !== false, done: true }
61
+ } catch (e) { log('昵称审核没成,先放过:', e?.message); return { name: true, sig: true } }
62
+ }
63
+ /** 同一个身份的另一台设备(手机 / 电脑)改了资料:照着改,不再往外发(那边已经发过了) */
64
+ function applySelfProfile(m) {
65
+ const at = Number(m.pat) || 0; if (at <= (st.profileAt ?? 0)) return
66
+ st.profileAt = at
67
+ if (m.name !== undefined) st.name = clean(m.name, 32) || st.name
68
+ if (m.sig !== undefined) st.sig = clean(m.sig, 40)
69
+ if (m.avatar === null) { delete st.avatar; delete st.avatarRef }
70
+ else if (m.avatar && media?.ok(m.avatar)) { const i = fetchImage(m.avatar); if (i) { st.avatarRef = m.avatar; st.avatar = i } }
71
+ save(); changed(); log('另一台设备改了我的资料,这边也跟着改了')
72
+ }
73
+ const syncSelfProfile = () => { st.profileAt = Date.now(); save(); copySelf({ type: 'profile.self', name: st.name, sig: st.sig ?? '', avatar: st.avatarRef ?? null, pat: st.profileAt }) }
74
+ // 12-01:以前只在收到消息那一刻下一次,失败了就永远“图片下载中”(下载地址和钥匙也没存)。
75
+ // 现在把下载信息记在 media/refs.json(只在本机),界面来要时没有就再下;服务器 30 天后删掉的,标成“已过期”
76
+ const REFS_F = path.join(mediaDir, 'refs.json')
77
+ let mediaRefs = (() => { try { return JSON.parse(fs.readFileSync(REFS_F, 'utf8')) } catch { return {} } })()
78
+ const saveRefs = () => { const ks = Object.keys(mediaRefs); for (const k of ks.slice(0, Math.max(0, ks.length - 3000))) delete mediaRefs[k]; try { fs.writeFileSync(REFS_F, JSON.stringify(mediaRefs), { mode: 0o600 }) } catch {} }
79
+ const mediaSt = new Map() // sha → { s: 'loading' | 'failed' | 'expired', at }
80
+ function pullImage(ref) {
81
+ const sha = ref.sha256, p = mediaPath(sha, ref.type); mediaSt.set(sha, { s: 'loading', at: Date.now() })
82
+ media.fetch(ref).then((buf) => { fs.writeFileSync(p, buf); mediaSt.delete(sha); changed() })
83
+ .catch((e) => { const m = String(e?.message ?? e); mediaSt.set(sha, { s: /HTTP (404|410)/.test(m) ? 'expired' : 'failed', at: Date.now() }); log('图片没下载下来:', m); changed() })
84
+ }
85
+ function fetchImage(ref) {
86
+ if (!media || !media.ok(ref)) return null
87
+ const p = mediaPath(ref.sha256, ref.type); if (fs.existsSync(p)) return imgInfo(ref)
88
+ if (!mediaRefs[ref.sha256]) { mediaRefs[ref.sha256] = ref; saveRefs() }
89
+ pullImage(ref)
90
+ return imgInfo(ref)
91
+ }
92
+ /** 图片在不在:ok / loading(在下,没下过的这时再下一次)/ expired(服务器上已经删了)/ unknown(这台设备没收到过下载信息) */
93
+ function mediaStatus(sha) {
94
+ if (mediaFile(sha)) return 'ok'
95
+ const st0 = mediaSt.get(sha), ref = mediaRefs[sha] ?? (st.avatarRef?.sha256 === sha ? st.avatarRef : null) ?? Object.values(st.peers ?? {}).find((p) => p?.avatarRef?.sha256 === sha)?.avatarRef ?? gs.groups.find((g) => g.avatar?.ref?.sha256 === sha)?.avatar?.ref ?? null
96
+ if (st0?.s === 'expired') return 'expired'
97
+ if (!ref || !media) { if (media) askMedia(sha); return Date.now() - (mediaAsked.get(sha) ?? 0) < 60_000 ? 'loading' : 'unknown' }
98
+ if (!st0 || (st0.s === 'failed' && Date.now() - st0.at > 30_000)) pullImage(ref)
99
+ return 'loading'
100
+ }
101
+ const MAX_FILE = 20_000_000
102
+ // 分享的小应用:文件消息上附带一张卡片(名字、介绍、图标、要的权限)。旧版本只看到一个文件
103
+ const APP_PERMS = ['ai', 'storage', 'speak', 'card']
104
+ const appCard = (a) => (a && typeof a === 'object' ? { title: clean(a.title, 32) || '小应用', description: clean(a.description, 80), icon: clean(a.icon, 4) || null, glyph: /^[a-z0-9-]{2,30}$/.test(String(a.glyph ?? '')) ? a.glyph : null, tone: ['blue', 'coral', 'green', 'teal', 'amber', 'violet', 'pink', 'indigo', 'red'].includes(a.tone) ? a.tone : null, version: Math.max(1, Math.min(9999, Number(a.version) || 1)), permissions: (Array.isArray(a.permissions) ? a.permissions : []).filter((p) => APP_PERMS.includes(p)).slice(0, 8), by: clean(a.by, 32) } : null)
105
+ const fileInfo = (r, name) => ({ sha: r.sha256, name: clean(name ?? r.name, 120) || '文件', size: r.size ?? null, type: String(r.type ?? 'application/octet-stream').slice(0, 80) })
106
+ // 小文件(比如分享的小应用)直接放进加密消息里,不经过文件服务器。
107
+ // 中继单条上限 64 KB,私聊加密套两层后体积约 2.5 倍(20 KB → 约 52 KB),再大就走文件服务器
108
+ const INLINE_SEND = 20_000, INLINE_MAX = 48_000 // 收的时候照旧认到 48 KB(旧版本发来的)
109
+ function inlineFile(b64, name, type) {
110
+ const buf = Buffer.from(String(b64 ?? ''), 'base64'); if (!buf.length || buf.length > INLINE_MAX) return null
111
+ const sha = sha256hex(buf); fs.writeFileSync(path.join(mediaDir, sha + '.bin'), buf)
112
+ return fileInfo({ sha256: sha, size: buf.length, type }, name)
113
+ }
114
+ async function sendFileData(b64, name, type, opt = {}) {
115
+ const buf0 = Buffer.from(String(b64 ?? ''), 'base64')
116
+ if (opt.inline && buf0.length && buf0.length <= INLINE_SEND) { const info = inlineFile(b64, name, type); return { ref: null, inline: buf0.toString('base64'), info } }
117
+ if (!media) throw new Error('这一版不能发文件')
118
+ const buf = buf0; if (!buf.length) throw new Error('文件是空的')
119
+ if (buf.length > MAX_FILE) throw new Error('文件太大(超过 20 MB)')
120
+ const ref = await media.upload(buf, { name: clean(name, 120) || 'file', type: String(type || 'application/octet-stream') })
121
+ fs.writeFileSync(path.join(mediaDir, ref.sha256 + '.bin'), buf)
122
+ return { ref, info: fileInfo({ ...ref, size: buf.length }, name) }
123
+ }
124
+ function fetchFile(ref, name) {
125
+ if (!media || !media.ok(ref, 'file')) return null
126
+ const p = path.join(mediaDir, ref.sha256 + '.bin')
127
+ if (!fs.existsSync(p) && (ref.size ?? 0) <= MAX_FILE) media.fetch(ref).then((buf) => { fs.writeFileSync(p, buf); changed() }).catch((e) => log('文件没下载下来:', e?.message))
128
+ return fileInfo(ref, name)
129
+ }
130
+ function mediaFile(sha) {
131
+ if (/^[0-9a-f]{64}$/.test(String(sha))) { const p = path.join(mediaDir, sha + '.bin'); if (fs.existsSync(p)) return { path: p, type: 'application/octet-stream' } } if (!/^[0-9a-f]{64}$/.test(String(sha))) return null; for (const [t, e] of Object.entries(EXT)) { const p = path.join(mediaDir, sha + '.' + e); if (fs.existsSync(p)) return { path: p, type: t } } return null }
132
+
133
+ const idHost = () => { try { return new URL(idService).hostname } catch { return 'yusho.chat' } }
134
+ // ── 我的头像、个签;别人的(存在 st.peers)
135
+ const peerOf = (pk) => st.peers[pk] ?? null
136
+ const avatarSha = (pk) => (pk === me.pk ? st.avatar?.sha : st.peers[pk]?.avatar?.sha) ?? null
137
+ /** 我的状态:online / busy(带一句话)/ invisible(隐身:好友看不到状态,我的 Agent 显示“不在”、不接请求) */
138
+ const myPresence = () => { const p = globalThis.__shoalSettings?.().presence ?? {}; return p.mode === 'busy' ? { mode: 'busy', text: clean(p.text, 20) } : p.mode === 'invisible' ? { mode: 'invisible' } : { mode: 'online' } }
139
+ const agentPublic = () => { const a = globalThis.__shoalSettings?.().agentAccess ?? { mode: 'ask' }; return a.mode === 'off' ? null : { name: clean(globalThis.__shoalAgentName?.() ?? '我的 Agent', 20), mode: a.mode === 'on' ? 'on' : 'ask', ...(myPresence().mode === 'invisible' ? { away: true } : {}) } }
140
+ const presencePublic = () => { const p = myPresence(); return p.mode === 'busy' ? p : null }
141
+ const profileMsg = () => ({ type: 'profile.update', name: st.name, sig: st.sig ?? '', avatar: st.avatarRef ?? null, agent: agentPublic(), presence: presencePublic() })
142
+ const sendProfile = (pk) => sendJson(pk, profileMsg()).catch(() => {})
143
+ const profAsked = new Map()
144
+ // 头像只有 sha、没有下载信息(以前的版本第一次没下成就丢了)而且本地也没有图的好友:启动后问 TA 要一次资料(新版收到就回一份)
145
+ setTimeout(() => { for (const f of st.friends ?? []) { const p = st.peers?.[f.pk]; if (p?.avatar?.sha && !p.avatarRef && !mediaFile(p.avatar.sha)) sendJson(f.pk, { type: 'profile.ask' }).catch(() => {}) } }, 20_000)
146
+ function everyone() { const s = new Set(st.friends.map((f) => f.pk)); for (const g of gs.groups) for (const m of g.members) if (m.pk !== me.pk) s.add(m.pk); return [...s] }
147
+ function onProfile(from, m) {
148
+ const known = friend(from) || gs.groups.some((g) => g.members.some((x) => x.pk === from)); if (!known) return
149
+ const p = st.peers[from] ?? {}
150
+ p.name = clean(m.name, 32) || p.name; p.sig = clean(m.sig, 20)
151
+ if (m.avatar && media?.ok(m.avatar)) { const i = fetchImage(m.avatar); if (i) { p.avatar = i; p.avatarRef = m.avatar } } else if (m.avatar === null) { delete p.avatar; delete p.avatarRef }
152
+ p.agent = m.agent && typeof m.agent === 'object' ? { name: clean(m.agent.name, 20) || 'TA 的 Agent', mode: m.agent.mode === 'on' ? 'on' : 'ask', ...(m.agent.away ? { away: true } : {}) } : null
153
+ p.presence = m.presence?.mode === 'busy' ? { mode: 'busy', text: clean(m.presence.text, 20), at: Date.now() } : null
154
+ p.at = Date.now(); st.peers[from] = p
155
+ const f = friend(from); if (f && p.name) f.name = p.name
156
+ save(); changed()
157
+ }
158
+
159
+ // ── 动态
160
+ let mo = readJ(F('moments.json'), { items: [], unread: 0 })
161
+ const saveMo = () => fs.writeFileSync(F('moments.json'), JSON.stringify({ ...mo, items: mo.items.slice(-300) }))
162
+ // 动态带的东西:做完的活卡(标题、谁做的、用时、交回的文件名)、谁写的(助理起草的标出来)、做法(可以拿来用的计划)
163
+ const extrasIn = (m) => {
164
+ const w = m.work && typeof m.work === 'object' ? { title: clean(m.work.title, 60), agent: clean(m.work.agent, 24), seconds: Number(m.work.seconds) || null, files: (Array.isArray(m.work.files) ? m.work.files : []).map((x) => clean(x, 80)).filter(Boolean).slice(0, 10) } : null
165
+ const r = m.recipe && typeof m.recipe === 'object' ? { title: clean(m.recipe.title, 60), jobs: (Array.isArray(m.recipe.jobs) ? m.recipe.jobs : []).slice(0, 6).map((j) => ({ agent: clean(j.agent, 24).toLowerCase(), title: clean(j.title, 60), instruction: cleanML(j.instruction, 2000) })).filter((j) => j.instruction) } : null
166
+ return { ...(w?.title ? { work: w } : {}), ...(r?.jobs?.length ? { recipe: r } : {}), ...(m.by === 'assistant' ? { by: 'assistant' } : {}) }
167
+ }
168
+ const rid = () => Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) => b.toString(16).padStart(2, '0')).join('')
169
+ // ── 群聊
170
+ let gs = readJ(F('groups.json'), { groups: [] })
171
+ const saveG = () => fs.writeFileSync(F('groups.json'), JSON.stringify(gs))
172
+ const group = (gid) => gs.groups.find((g) => g.gid === gid)
173
+ const gFile = (gid) => path.join(chatDir, 'g-' + gid.replace(/[^0-9a-f]/g, '') + '.json')
174
+ const readG = (gid) => readJ(gFile(gid), [])
175
+ const appendG = (gid, msg) => { const a = [...readG(gid), msg].slice(-500); fs.writeFileSync(gFile(gid), JSON.stringify(a)) }
176
+ const members = (list) => (Array.isArray(list) ? list : []).filter((x) => x && /^[0-9a-f]{64}$/.test(String(x.pk ?? ''))).slice(0, 50).map((x) => ({ pk: x.pk, name: clean(x.name, 32), number: /^\d{6,15}$/.test(String(x.number ?? '')) ? String(x.number) : null }))
177
+ const meEntry = () => ({ pk: me.pk, name: st.name, number: me.number() })
178
+ const AGN = { codex: 'Codex', claude: 'Claude', dsh: 'DSH' }
179
+ // 谁能叫我带进群的 Agent:me 只有我;ask 别人叫要我先批(电脑上的 Agent 默认);members 群里谁都能叫(助理、工作秘书默认,它们在群里不碰你的记忆、文件、任务)
180
+ const POLICIES = ['me', 'ask', 'members']
181
+ const agentsIn = (list, by) => (Array.isArray(list) ? list : []).filter((a) => a && /^[a-z0-9_-]{1,32}$/i.test(String(a.agent ?? '')) && /^[0-9a-f]{64}$/.test(String(a.to ?? ''))).slice(0, 12)
182
+ .map((a) => { const agent = String(a.agent).toLowerCase(), phone = agent === 'life' || agent === 'work'; return { key: a.to + ':' + agent, to: a.to, agent, by: by ?? (/^[0-9a-f]{64}$/.test(String(a.by ?? '')) ? a.by : null), name: clean(a.name, 24) || AGN[agent] || (agent === 'life' ? '助理' : agent === 'work' ? '工作秘书' : a.agent), computer: phone ? '手机' : clean(a.computer, 32), ...(phone ? { phone: true } : {}), policy: POLICIES.includes(a.policy) ? a.policy : phone ? 'members' : 'ask' } })
183
+ const avatarIn = (a) => !a ? null : a.kind === 'color' ? { kind: 'color', c: Math.max(0, Math.min(7, Number(a.c) || 0)) } : a.kind === 'collage' ? { kind: 'collage' } : a.kind === 'img' && media?.ok(a.ref) ? { kind: 'img', ref: a.ref } : null
184
+ const metaOf = (g) => ({ name: g.name, members: g.members, intro: g.intro ?? '', avatar: g.avatar ?? null, agents: g.agents ?? [], owner: g.owner, circle: g.circle ?? null, admins: g.admins ?? [], silenced: g.silenced ?? [], searchable: listed(g), vis: visOf(g), number: g.number ?? null, category: g.category ?? null })
185
+ // 群主或管理员
186
+ const isMgr = (g, pk) => pk === g.owner || (g.admins ?? []).includes(pk)
187
+ // 能不能被公开搜到:兴趣圈默认能(可以关);普通群默认不能(可以开)
188
+ // 三档:private 不公开;number 搜群号能找到、“发现”里不出现;public “发现”里也公开。老数据只有 searchable:兴趣圈默认公开,普通群默认不公开
189
+ const VIS = ['private', 'number', 'public']
190
+ const visOf = (g) => (VIS.includes(g.vis) ? g.vis : (g.circle ? g.searchable !== false : !!g.searchable) ? 'public' : 'private')
191
+ const listed = (g) => visOf(g) === 'public'
192
+ const GNO = /^8\d{7,8}$/
193
+ const pkList = (a, g) => (Array.isArray(a) ? a : []).map(String).filter((x) => /^[0-9a-f]{64}$/.test(x) && g.members.some((m) => m.pk === x)).slice(0, 50)
194
+ const CATS = ['AI 产品', 'Agent', '大肥鱼', '二创', '学习', '工作', '编程', '设计', '生活', '运动', '游戏', '其他'] // AI 方向放前面
195
+ const circleIn = (c) => c && typeof c === 'object' ? { category: CATS.includes(c.category) ? c.category : '其他', open: !!c.open } : null
196
+ function takeMeta(g, m) {
197
+ g.name = clean(m.name, 32) || g.name; g.intro = clean(m.intro, 200)
198
+ const av = avatarIn(m.avatar); g.avatar = av; if (av?.kind === 'img') { const i = fetchImage(av.ref); if (i) g.avatarImg = i }
199
+ if (Array.isArray(m.agents)) g.agents = agentsIn(m.agents)
200
+ if (m.circle !== undefined) g.circle = circleIn(m.circle)
201
+ if (m.admins !== undefined) g.admins = pkList(m.admins, g).filter((x) => x !== g.owner)
202
+ if (m.silenced !== undefined) g.silenced = pkList(m.silenced, g).filter((x) => x !== g.owner)
203
+ if (m.searchable !== undefined) g.searchable = !!m.searchable
204
+ if (VIS.includes(m.vis)) g.vis = m.vis
205
+ if (GNO.test(String(m.number ?? ''))) g.number = String(m.number)
206
+ if (m.category !== undefined) g.category = CATS.includes(m.category) ? m.category : null
207
+ }
208
+ const sendAll = (g, obj) => Promise.allSettled(g.members.filter((x) => x.pk !== me.pk).map((x) => sendJson(x.pk, { ...obj, gid: g.gid })))
209
+ function onGroup(from, m, at) {
210
+ const gid = String(m.gid ?? ''); if (!/^[0-9a-f]{8,32}$/.test(gid)) return
211
+ let g = group(gid)
212
+ if (m.type === 'group.invite') {
213
+ // 只有好友能拉你进群;兴趣圈:我申请过的、而且邀请必须来自我申请时的那个圈主(以前只看申请过没有,别人知道群号就能冒充)
214
+ const jp = st.joinPending[gid], jpOwner = jp && typeof jp === 'object' ? jp.owner : null
215
+ if (!friend(from) && !(jp && jpOwner === from)) return
216
+ if (jp && jpOwner === from) { delete st.joinPending[gid]; save() }
217
+ const ms = members(m.members); if (!ms.some((x) => x.pk === me.pk)) return
218
+ if (!g) { g = { gid, name: clean(m.name, 32) || '群聊', owner: from, members: ms, unread: 0, last: null, joined: Date.now(), nicks: {} }; gs.groups.push(g) } else { if (!isMgr(g, from)) return; g.members = ms }
219
+ takeMeta(g, m)
220
+ saveG(); changed()
221
+ const f = friend(from); notify({ kind: 'chat', gid, title: g.circle ? '你加入了兴趣圈「' + g.name + '」' : (f?.remark || f?.name || '好友') + ' 拉你进了群「' + g.name + '」', body: g.members.length + ' 个人' })
222
+ return
223
+ }
224
+ if (!g || !g.members.some((x) => x.pk === from)) return // 不是这个群的成员:不收
225
+ if (m.type === 'group.update') { if (from !== g.owner) return; const ms = members(m.members); if (!ms.some((x) => x.pk === me.pk)) { gs.groups = gs.groups.filter((x) => x !== g); saveG(); changed(); return } g.members = ms; takeMeta(g, m); if (m.owner && m.owner !== g.owner && ms.some((x) => x.pk === m.owner)) { g.owner = m.owner; appendG(gid, { id: rid(), from: 'system', text: nameIn(g, m.owner) + ' 成了群主', at }) } saveG(); changed(); return }
226
+ if (m.type === 'group.kick' || m.type === 'group.mute') {
227
+ const pk = String(m.pk ?? ''), t = g.members.find((x) => x.pk === pk)
228
+ if (!t || !isMgr(g, from) || pk === g.owner || (from !== g.owner && (g.admins ?? []).includes(pk))) return // 管理员管不了群主和别的管理员
229
+ if (m.type === 'group.kick') {
230
+ if (pk === me.pk) { gs.groups = gs.groups.filter((x) => x !== g); saveG(); changed(); notify({ kind: 'chat', title: '你被移出了群「' + g.name + '」', body: nameIn(g, from) + ' 把你移出了群' }); return }
231
+ appendG(gid, { id: rid(), from: 'system', text: nameIn(g, from) + ' 把 ' + nameIn(g, pk) + ' 移出了群', at })
232
+ g.members = g.members.filter((x) => x.pk !== pk); g.agents = (g.agents ?? []).filter((a) => a.by !== pk); g.admins = (g.admins ?? []).filter((x) => x !== pk); g.silenced = (g.silenced ?? []).filter((x) => x !== pk)
233
+ } else {
234
+ const on = !!m.on; g.silenced = [...new Set([...(g.silenced ?? []).filter((x) => x !== pk), ...(on ? [pk] : [])])]
235
+ appendG(gid, { id: rid(), from: 'system', text: nameIn(g, from) + (on ? ' 禁言了 ' : ' 解除了 ') + (pk === me.pk ? '你' : nameIn(g, pk)) + (on ? '' : ' 的禁言'), at })
236
+ }
237
+ saveG(); changed(); if (g.owner === me.pk) publishCard(g); return
238
+ }
239
+ if (m.type === 'group.nick') { g.nicks = { ...(g.nicks ?? {}), [from]: clean(m.nick, 20) }; saveG(); changed(); return }
240
+ if (m.type === 'group.agents') { g.agents = [...(g.agents ?? []).filter((a) => a.by !== from), ...agentsIn(m.agents, from)]; saveG(); changed(); return }
241
+ if (m.type === 'group.leave') { g.members = g.members.filter((x) => x.pk !== from); g.agents = (g.agents ?? []).filter((a) => a.by !== from); appendG(gid, { id: rid(), from: 'system', text: nameIn(g, from) + ' 退出了群聊', at }); saveG(); changed(); return }
242
+ if (m.type === 'group.recall') {
243
+ const a = readG(gid), i = a.findIndex((x) => x.id === String(m.mid ?? ''))
244
+ if (i < 0) return
245
+ const x = a[i], own = x.from === from, mgr = isMgr(g, from)
246
+ if (!(own && Date.now() - x.at < 24 * 3600_000) && !mgr) return
247
+ a[i] = { id: x.id, from: x.from, at: x.at, recalled: true, by: from, text: '' }; fs.writeFileSync(gFile(gid), JSON.stringify(a))
248
+ if (g.last && g.last.at === x.at) g.last = { ...g.last, text: '撤回了一条消息' }
249
+ saveG(); changed(); return
250
+ }
251
+ if (m.type === 'group.notice') {
252
+ if (!isMgr(g, from)) return
253
+ const text = clean(m.text, 1000); g.notice = text ? { text, at, by: from } : null
254
+ if (text) appendG(gid, { id: rid(), from, sys: true, text: '群公告:' + text, at })
255
+ saveG(); changed(); if (text && !g.muted) notify({ kind: 'chat', gid, title: g.name + ':新公告', body: text.slice(0, 160) }); return
256
+ }
257
+ if (m.type === 'group.msg') {
258
+ if (g.blocked || (g.silenced ?? []).includes(from)) return // 被禁言的人发的:大家都不收
259
+ if (g.hidden) g.hidden = false
260
+ const img = m.img ? fetchImage(m.img) : null, file = img ? null : m.inline ? inlineFile(m.inline, m.fileName, m.ftype) : m.file ? fetchFile(m.file, m.fileName) : null
261
+ const app = file ? appCard(m.app) : null
262
+ const text = img ? (m.sticker ? '[表情]' : '[图片]') : app ? '[小应用] ' + app.title : file ? '[文件] ' + file.name : clean(m.text, MAX_TEXT); if (!text) return
263
+ const agent = m.agent ? clean(m.agent, 24) : null, mentions = (Array.isArray(m.mentions) ? m.mentions : []).map(String).slice(0, 20)
264
+ const msg = { id: String(m.mid ?? rid()).slice(0, 32), from, text, ...(img ? { img } : {}), ...(img && m.sticker ? { sticker: true } : {}), ...(file ? { file } : {}), ...(app ? { app } : {}), ...(agent ? { agent } : {}), ...(mentions.length ? { mentions } : {}), hop: Math.min(9, Number(m.hop) || 0), at }
265
+ appendG(gid, msg); g.unread = (g.unread ?? 0) + 1; g.last = { text, at, from: agent ? agent : nameIn(g, from) }; saveG(); changed()
266
+ const atMe = mentions.includes(me.pk)
267
+ if (!g.muted || atMe) notify({ kind: 'chat', gid, title: atMe ? g.name + ':有人@你' : g.name, body: ((agent ? agent + '(' + nameIn(g, from) + ' 的)' : nameIn(g, from)) + ':' + text).slice(0, 160) })
268
+ callAgents(g, { ...msg, otherAgent: !!agent })
269
+ if (g.agentMode === 'active' && !(msg.agent && myWork(g)?.name === msg.agent)) watchGroup(g)
270
+ if (g.agentMgr?.on && g.agentMgr.auto && isMgr(g, me.pk) && !agent && !isMgr(g, from) && typeof globalThis.__shoalGroupPatrol === 'function') patrol(g, msg)
271
+ }
272
+ }
273
+ function onCircle(from, m, at) {
274
+ const gid = String(m.gid ?? ''), g = group(gid)
275
+ if (m.type === 'circle.reject') { if (st.joinPending[gid]) { delete st.joinPending[gid]; save(); changed(); notify({ kind: 'friend', title: '没能加入兴趣圈', body: clean(m.reason, 100) || '圈主没有同意' }) } return }
276
+ if (m.type !== 'circle.join' || !g || g.owner !== me.pk || g.members.some((x) => x.pk === from)) return
277
+ const who = { pk: from, name: clean(m.name, 32), number: /^\d{6,15}$/.test(String(m.number ?? '')) ? String(m.number) : null }
278
+ if (g.circle?.open && visOf(g) !== 'private') { api.addMembers(gid, [who]).catch((e) => log('拉人进圈失败', e?.message)); return }
279
+ g.joinReqs = [...(g.joinReqs ?? []).filter((x) => x.pk !== from), { ...who, note: clean(m.note, 100), at }].slice(-50); saveG(); changed()
280
+ notify({ kind: 'chat', gid, title: (who.name || '有人') + ' 想加入' + (g.circle ? '兴趣圈' : '群') + '「' + g.name + '」', body: clean(m.note, 100) || '打开圈资料看看要不要同意' })
281
+ }
282
+ // 兴趣圈的公开名片:圈主建圈、改资料、人数变了都重发一次(同一个 d,中继只留最新的)
283
+ // 群号:群主向号码服务领(同一个群永远同一个号),顺带告诉它公开范围;领到了发给群成员
284
+ const numTried = new Set()
285
+ async function syncNumber(g, extra = {}) {
286
+ if (g.owner !== me.pk || !me.auth) return
287
+ try {
288
+ const url = idService + '/api/id/group'
289
+ const r = await fetch(url, { method: 'POST', headers: { authorization: me.auth(url, 'POST'), 'content-type': 'application/json' }, body: JSON.stringify({ gid: g.gid, vis: visOf(g), ...extra }), signal: AbortSignal.timeout(10000) })
290
+ const j = await r.json().catch(() => ({}))
291
+ if (!r.ok) { log('群号没领到:', j.error ?? r.status); return }
292
+ if (j.number && j.number !== g.number) { g.number = j.number; saveG(); changed(); sendAll(g, { type: 'group.update', ...metaOf(g) }).catch(() => {}) }
293
+ } catch (e) { log('群号没领到:', e?.message) }
294
+ }
295
+ async function publishCard(g) {
296
+ if (g.owner !== me.pk) return
297
+ await syncNumber(g)
298
+ if (visOf(g) === 'private') { if (g.cardOut) unpublishCard(g); return }
299
+ const cat = g.circle?.category ?? (CATS.includes(g.category) ? g.category : '群聊') // 普通群也能选分类
300
+ try {
301
+ const cardT = { kind: 30078, created_at: cardTs(g), tags: [['d', 'yusho-circle:' + g.gid], ['t', listed(g) ? 'yusho-circle' : 'yusho-circle-unlisted'], ['c', cat]], content: JSON.stringify({ gno: g.number ?? null, name: g.name, intro: g.intro ?? '', category: cat, kind: g.circle ? 'circle' : 'group', open: !!g.circle?.open, count: g.members.length + (g.agents ?? []).length, number: me.number(), color: g.avatar?.kind === 'color' ? g.avatar.c : null, img: g.avatar?.kind === 'img' ? g.avatar.ref : null, faces: g.members.slice(0, 4).map((x) => nameIn(g, x.pk)) }) }
302
+ const v = await moderate(cardT, 'card').catch(() => null)
303
+ if (v && v.verdict !== 'public') { g.cardNote = v.note || '名片没通过审核'; saveG(); changed(); log('公开名片没通过审核'); return }
304
+ g.cardNote = null; await publishSigned(v?.ev ?? cardT)
305
+ if (!g.cardOut) { g.cardOut = true; saveG() }
306
+ } catch (e) { log('公开名片没发出去:', e?.message) }
307
+ }
308
+ // 名片的时间一定比上一张新(同一秒里开了又关,中继和别人只认新的那张)
309
+ const cardTs = (g) => { const t = Math.max(Math.floor(Date.now() / 1000), (g.cardAt ?? 0) + 1); g.cardAt = t; return t }
310
+ // 撤下公开名片:先发一张“已撤下”的空名片顶掉旧的,再发删除请求
311
+ async function unpublishCard(g) {
312
+ try {
313
+ await publishSigned({ kind: 30078, created_at: cardTs(g), tags: [['d', 'yusho-circle:' + g.gid], ['t', 'yusho-circle']], content: JSON.stringify({ hidden: true }) })
314
+ await publishSigned({ kind: 5, created_at: Math.floor(Date.now() / 1000), tags: [['a', '30078:' + me.pk + ':yusho-circle:' + g.gid]], content: '' }).catch(() => {})
315
+ g.cardOut = false; saveG()
316
+ } catch (e) { log('公开名片没撤下来:', e?.message) }
317
+ }
318
+ function nameIn(g, pk) { if (pk === me.pk) return g.nicks?.[me.pk] || st.name || '我'; const f = friend(pk); return f?.remark || g.nicks?.[pk] || f?.name || g.members.find((x) => x.pk === pk)?.name || '群成员' }
319
+ // 群里有人 @ 了我带进来的 Agent:交给我电脑上的它(带上最近的群聊),回答发回群里。Agent 的回答里再 @ 别的 Agent 就是接力(最多接 3 棒)
320
+ const busyAgents = new Map() // key -> 开始时间
321
+ // 别人叫我的 Agent:每个 Agent 每小时最多 20 次;要我批的先排着(10 分钟没批就算了)
322
+ const othersCalls = new Map(), groupAsks = []
323
+ const SECRET = [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, /\bnsec1[02-9ac-hj-np-z]{20,}/g, /\b(sk|rk|pk)-[A-Za-z0-9_-]{16,}/g, /\bAKIA[0-9A-Z]{16}\b/g, /\bgh[pousr]_[A-Za-z0-9]{30,}/g, /\bxox[abposr]-[A-Za-z0-9-]{10,}/g, /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, /((?:password|passwd|pwd|secret|token|api[_-]?key|密码|口令|密钥)\s*[:=:]\s*)\S{4,}/gi]
324
+ /** 发进群之前遮住像密钥、密码、令牌的东西(就算 Agent 说漏了嘴也不会出去) */
325
+ const redact = (s) => SECRET.reduce((t, re) => t.replace(re, (x, p1) => (typeof p1 === 'string' && /[:=:]\s*$/.test(p1) ? p1 : '') + '[已遮住]'), String(s ?? ''))
326
+ function callAgents(g, msg) {
327
+ if ((msg.hop ?? 0) >= 3) return
328
+ for (const a of (g.agents ?? []).filter((x) => x.by === me.pk)) {
329
+ if (!msg.text.includes('@' + a.name) || busyAgents.has(a.key) || (msg.agent && msg.agent === a.name)) continue
330
+ const byMe = (msg.from === me.pk || msg.from === 'me') && !msg.otherAgent
331
+ if (!byMe) {
332
+ let pol = a.policy ?? (a.phone ? 'members' : 'ask'); if (!a.phone && visOf(g) !== 'private' && pol === 'members') pol = 'ask' // 公开的群:电脑上的 Agent 别人叫一律要我批
333
+ if (pol === 'me') { api.sendGroup(g.gid, '(' + a.name + ' 在这个群里只听主人的。)', null, null, { agent: a.name, hop: 9 }).catch(() => {}); continue }
334
+ const k = a.key + '@' + g.gid, ts = (othersCalls.get(k) ?? []).filter((t) => Date.now() - t < 3600_000)
335
+ if (ts.length >= 20) { if (ts.length === 20) api.sendGroup(g.gid, '(' + a.name + ' 这一小时被叫得太多了,歇一会儿。)', null, null, { agent: a.name, hop: 9 }).catch(() => {}); ts.push(Date.now()); othersCalls.set(k, ts); continue }
336
+ ts.push(Date.now()); othersCalls.set(k, ts)
337
+ if (pol === 'ask') {
338
+ const caller = msg.agent ? msg.agent : nameIn(g, msg.from), q = { id: rid(), gid: g.gid, group: g.name, key: a.key, agent: a.agent, name: a.name, caller, text: msg.text.slice(0, 500), at: Date.now(), msg }
339
+ groupAsks.push(q); changed()
340
+ notify({ kind: 'ask', title: caller + ' 在群「' + g.name + '」里叫你的 ' + a.name, body: msg.text.slice(0, 120) + '(要你同意才会做)' })
341
+ setTimeout(() => { const i = groupAsks.indexOf(q); if (i >= 0) { groupAsks.splice(i, 1); changed(); api.sendGroup(g.gid, '(' + a.name + ' 的主人没有及时同意,这次没做。)', null, null, { agent: a.name, hop: 9 }).catch(() => {}) } }, 10 * 60_000)
342
+ continue
343
+ }
344
+ }
345
+ runAgent(g, a, msg, byMe)
346
+ }
347
+ }
348
+ // 工作秘书管群:回答里的 [撤回:编号]、[公告:内容] 换成真的操作(只在开了“管群”、我是群主 / 管理员时)
349
+ async function doManage(g, t) {
350
+ const done = []
351
+ for (const m of [...t.matchAll(/\[撤回[::]\s*([0-9a-z]{4,32})\s*\]/gi)]) { try { await api.recallGroup(g.gid, m[1]); done.push('撤回了 1 条') } catch (e) { done.push('撤回没成:' + e.message) } }
352
+ const n = /\[公告[::]\s*([^\]]{1,500})\]/.exec(t); if (n) { try { await api.setGroupNotice(g.gid, n[1].trim()); done.push('发了公告') } catch (e) { done.push('公告没发成:' + e.message) } }
353
+ t = t.replace(/\[撤回[::][^\]]*\]/g, '').replace(/\[公告[::][^\]]*\]/g, '').trim()
354
+ return done.length ? (t ? t + '\n' : '') + '(' + done.join(',') + ')' : t
355
+ }
356
+ // 自动巡查:一条一条看,违规(广告、辱骂、色情、诈骗、刷屏)就撤回并说一声
357
+ const patrolBusy = new Set()
358
+ async function patrol(g, msg) {
359
+ if (patrolBusy.has(msg.id)) return; patrolBusy.add(msg.id)
360
+ try {
361
+ const v = await globalThis.__shoalGroupPatrol({ group: g.name, text: msg.text, who: nameIn(g, msg.from) })
362
+ if (v?.recall) { await api.recallGroup(g.gid, msg.id); await api.sendGroup(g.gid, '撤回了 ' + nameIn(g, msg.from) + ' 的一条消息:' + String(v.why || '不合适').slice(0, 40), null, null, { agent: (g.agents ?? []).find((x) => x.phone && x.agent === 'work' && x.mine)?.name ?? '工作秘书', hop: 9 }) }
363
+ } catch (e) { log('巡查没成:', e?.message) } finally { setTimeout(() => patrolBusy.delete(msg.id), 60_000) }
364
+ }
365
+ // ── 群里的工作秘书“主动看群消息”(12-01 用户:不 @ 它也能看、需要时回复、帮你管群、记下要紧的事)。
366
+ // 为了省钱:一个群最多每 2 分钟看一次,攒着这段时间的新消息一起看;它觉得不用说话就不出声
367
+ const myWork = (g) => (g.agents ?? []).find((x) => x.by === me.pk && x.phone && x.agent === 'work') ?? null
368
+ const watchT = new Map(), watchAt = new Map(), WATCH_GAP = 2 * 60_000
369
+ function watchGroup(g) {
370
+ if (watchT.has(g.gid) || typeof globalThis.__shoalGroupWatch !== 'function' || !myWork(g)) return
371
+ const wait = Math.max(5_000, (watchAt.get(g.gid) ?? 0) + WATCH_GAP - Date.now())
372
+ watchT.set(g.gid, setTimeout(() => { watchT.delete(g.gid); watchAt.set(g.gid, Date.now()); runWatch(g.gid).catch((e) => log('主动看群没成:', e?.message)) }, wait))
373
+ }
374
+ async function runWatch(gid) {
375
+ const g = group(gid), a = g && myWork(g); if (!a || g.agentMode !== 'active' || busyAgents.has(a.key)) return
376
+ const manage = !!(g.agentMgr?.on && isMgr(g, me.pk))
377
+ const ctx = readG(gid).slice(-20).filter((x) => !x.recalled).map((x) => (manage ? '[' + x.id + '] ' : '') + (x.from === 'system' ? '(' + x.text + ')' : (x.agent ? x.agent : x.from === 'me' ? nameIn(g, me.pk) + '(主人)' : nameIn(g, x.from)) + ':' + x.text)).join('\n')
378
+ busyAgents.set(a.key, Date.now()); changed()
379
+ try {
380
+ let t = String(await globalThis.__shoalGroupWatch({ name: a.name, group: g.name, context: ctx, notes: (g.notes ?? []).map((x) => x.text), manage, public: visOf(g) !== 'private' }) ?? '').trim()
381
+ // [记住:…] 记进这个群的小本子(最多 30 条),下次看群时一起给她
382
+ const keep = [...t.matchAll(/\[记住[::]\s*([^\]]{1,200})\]/g)].map((m) => m[1].trim()).filter(Boolean)
383
+ if (keep.length) { g.notes = [...(g.notes ?? []), ...keep.map((text) => ({ text, at: Date.now() }))].slice(-30); saveG() }
384
+ t = t.replace(/\[记住[::][^\]]*\]/g, '').trim()
385
+ if (!t || /^PASS\b/i.test(t)) return
386
+ if (manage) t = await doManage(g, t)
387
+ if (t) await api.sendGroup(gid, redact(t).slice(0, MAX_TEXT), null, null, { agent: a.name, hop: 1 })
388
+ } finally { busyAgents.delete(a.key); changed() }
389
+ }
390
+ function runAgent(g, a, msg, byMe) {
391
+ const ask = a.phone ? globalThis.__shoalPhoneAgent : globalThis.__shoalGroupAgent; if (typeof ask !== 'function') return
392
+ {
393
+ busyAgents.set(a.key, Date.now()); changed()
394
+ const manage = !!(a.phone && a.agent === 'work' && g.agentMgr?.on && isMgr(g, me.pk) && (byMe || msg.from === 'me' || msg.from === me.pk || isMgr(g, msg.from)))
395
+ const ctx = readG(g.gid).slice(-12).filter((x) => !x.recalled).map((x) => (manage ? '[' + x.id + '] ' : '') + (x.from === 'system' ? '(' + x.text + ')' : (x.agent ? x.agent : x.from === 'me' ? nameIn(g, me.pk) : nameIn(g, x.from)) + ':' + x.text)).join('\n')
396
+ const others = (g.agents ?? []).filter((x) => x.key !== a.key).map((x) => '@' + x.name)
397
+ ask({ to: a.to, agent: a.agent, name: a.name, group: g.name, text: msg.text, context: ctx, others, byMe, manage, public: visOf(g) !== 'private', caller: msg.agent ? msg.agent : msg.from === me.pk || msg.from === 'me' ? nameIn(g, me.pk) : nameIn(g, msg.from) })
398
+ .then(async (r) => { let t = String(r || ''); if (manage) t = await doManage(g, t)
399
+ return api.sendGroup(g.gid, redact(t.trim() || '(做完了)').slice(0, MAX_TEXT), null, null, { agent: a.name, hop: (msg.hop ?? 0) + 1 }) })
400
+ .catch((e) => api.sendGroup(g.gid, '没做成:' + redact(String(e?.message ?? e)).slice(0, 300), null, null, { agent: a.name, hop: 9 }).catch(() => {}))
401
+ .finally(() => { busyAgents.delete(a.key); changed() })
402
+ }
403
+ }
404
+
405
+ function onMoment(from, m, at) {
406
+ const f = friend(from), cg = m.circle ? group(String(m.circle)) : null
407
+ const id = String(m.id ?? '').slice(0, 32); if (!/^[0-9a-f]{8,32}$/.test(id)) return
408
+ const post = mo.items.find((x) => x.id === id)
409
+ // 我发到兴趣圈的动态:圈里的人(不一定是好友)能赞、评论
410
+ const pg = post?.author === 'me' && String(post.to ?? '').startsWith('circle:') ? group(post.to.slice(7)) : null
411
+ if (!f && !(cg?.circle && cg.members.some((x) => x.pk === from)) && !pg?.members.some((x) => x.pk === from)) return // 只收好友的,或者同一个兴趣圈里的人
412
+ if (st.hide.includes(from) && m.type === 'moment.post') return // 不看 TA 的动态
413
+ if (m.type === 'moment.post') { if (post) return; const imgs = (Array.isArray(m.imgs) ? m.imgs : m.img ? [m.img] : []).slice(0, 9).map(fetchImage).filter(Boolean), text = cleanML(m.text, 2000), img = imgs[0] ?? null, file = m.file ? fetchFile(m.file, m.fileName) : null; if (!text && !img && !file) return; mo.items.push({ id, author: from, authorName: clean(m.name, 32), text, img, imgs, file, at, likes: [], comments: [], to: cg ? 'circle:' + cg.gid : m.to === 'public' ? 'public' : 'friends', ...extrasIn(m) }); mo.unread++; saveMo(); changed(); return }
414
+ if (m.type === 'moment.delete') { if (post && post.author === from) { mo.items = mo.items.filter((x) => x !== post); saveMo(); changed() } return }
415
+ // 点赞、评论:只认发给我自己的动态
416
+ if (!post || post.author !== 'me') return
417
+ if (m.type === 'moment.like') { post.likes = post.likes.filter((p) => p !== from); if (m.on !== false) { post.likes.push(from); if (post.author === 'me') addNotice({ kind: 'like', from, who: f ? f.remark || f.name || '好友' : pg ? nameIn(pg, from) : '有人', postId: post.id, text: String(post.text ?? '').slice(0, 60) }) } mo.unread++; saveMo(); changed(); return }
418
+ if (m.type === 'moment.uncomment') { post.comments = post.comments.filter((c) => !(c.id === String(m.cid) && c.from === from)); saveMo(); changed(); return }
419
+ if (m.type === 'moment.comment') {
420
+ const text = clean(m.text, 300); if (!text) return
421
+ post.comments.push({ id: String(m.cid ?? rid()).slice(0, 32), from, text, at, ...(m.replyTo ? { replyTo: clean(m.replyTo, 32) } : {}) }); mo.unread++; saveMo(); changed()
422
+ if (post.author === 'me') addNotice({ kind: 'comment', from, who: f ? f.remark || f.name || '好友' : pg ? nameIn(pg, from) : '有人', postId: post.id, text, post: String(post.text ?? '').slice(0, 60) })
423
+ notify({ kind: 'chat', open: { to: 'circle' }, title: (f ? f.remark || f.name || '好友' : pg ? nameIn(pg, from) : '有人') + ' 评论了你的动态', body: text.slice(0, 120) })
424
+ }
425
+ }
426
+
427
+ // ── 收到“人”发来的消息(不是连着的电脑)
428
+ // ── 鱼讯:通知列表(notices.json,最多 300 条)
429
+ const OFFICIAL = '424504a0b5c3d23c12406b766a016da602729044f7f084940e6a7d295f12e309' // 鱼Sho 小助手(100000)
430
+ let notices = readJ(F('notices.json'), { items: [], officialSince: 0 })
431
+ const saveN = () => fs.writeFileSync(F('notices.json'), JSON.stringify(notices))
432
+ function addNotice(n) {
433
+ if (n.nid && notices.items.some((x) => x.nid === n.nid)) { notices.items = notices.items.map((x) => (x.nid === n.nid ? { ...x, ...n, read: x.read } : x)) }
434
+ else notices.items = [{ id: rid(), at: Date.now(), read: false, ...n }, ...notices.items].slice(0, 300)
435
+ saveN(); changed()
436
+ }
437
+ const officialIn = (c) => ({ nid: clean(c.nid, 40), okind: ['notice', 'update', 'beta', 'event', 'survey'].includes(c.kind) ? c.kind : 'notice', title: clean(c.title, 60), body: clean(c.body, 2000), link: /^https:\/\/[^\s]{1,300}$/.test(String(c.link ?? '')) ? String(c.link) : null, version: /^\d+\.\d+\.\d+$/.test(String(c.version ?? '')) ? String(c.version) : null })
438
+ // 12-02 用户:电脑收到了手机的更新通知。更新 / 内测通知带 platform(android / pc / all),不是这台设备的不收;
439
+ // 以前发的没写 platform,都是手机包,当成 android
440
+ const MY_PLATFORM = process.env.SHOAL_PLATFORM === 'pc' ? 'pc' : 'android'
441
+ const notMine = (c) => ['update', 'beta'].includes(c.kind) && (c.platform ?? 'android') !== 'all' && (c.platform ?? 'android') !== MY_PLATFORM
442
+ if (MY_PLATFORM === 'pc' && notices.items.some((x) => x.kind === 'official' && ['update', 'beta'].includes(x.okind) && (x.platform ?? 'android') !== 'pc' && (x.platform ?? 'android') !== 'all')) { notices.items = notices.items.filter((x) => !(x.kind === 'official' && ['update', 'beta'].includes(x.okind) && (x.platform ?? 'android') !== 'pc' && (x.platform ?? 'android') !== 'all')); saveN() }
443
+ function onOfficial(m, at) {
444
+ if (m.type === 'official.recall') { notices.items = notices.items.filter((x) => x.nid !== clean(m.nid, 40)); saveN(); changed(); return }
445
+ if (m.type !== 'official.notice') return
446
+ if (notMine(m)) return
447
+ const o = officialIn(m); if (!o.nid || !o.title) return
448
+ addNotice({ kind: 'official', ...o, at, to: 'me' })
449
+ const upd = o.okind === 'update' || o.okind === 'beta'
450
+ notify({ kind: 'friend', open: { to: upd ? 'update' : 'notices' }, ...(upd ? { actions: [{ label: '立即更新', open: { to: 'update', auto: 1 } }] } : {}), title: '鱼Sho 小助手:' + o.title, body: o.body.slice(0, 120) })
451
+ }
452
+ // 全体公告:小助手在中继上发的公开事件(kind 30078,d = yusho-official:<编号>,带 t = yusho-official);撤回 = 同一个 d 再发一张 hidden 的
453
+ async function pullOfficial() {
454
+ try {
455
+ const evs = await query([{ kinds: [30078], authors: [OFFICIAL], '#t': ['yusho-official'], limit: 50 }], 8000)
456
+ const best = new Map(); for (const ev of evs) { const d = (ev.tags.find((t) => t[0] === 'd') ?? [])[1] ?? ''; if (d.startsWith('yusho-official:') && (!best.has(d) || best.get(d).created_at < ev.created_at)) best.set(d, ev) }
457
+ for (const ev of best.values()) {
458
+ let c; try { c = JSON.parse(ev.content) } catch { continue }
459
+ if (notMine(c)) continue
460
+ const nid = ((ev.tags.find((t) => t[0] === 'd') ?? [])[1] ?? '').slice('yusho-official:'.length)
461
+ if (c.hidden) { if (notices.items.some((x) => x.nid === nid)) { notices.items = notices.items.filter((x) => x.nid !== nid); saveN(); changed() } continue }
462
+ if (!notices.items.some((x) => x.nid === nid) && ev.created_at * 1000 > (notices.officialSince || 0) - 30 * 864e5) { const o = officialIn({ ...c, nid }); if (o.title) addNotice({ kind: 'official', ...o, at: ev.created_at * 1000, to: 'all' }) }
463
+ }
464
+ if (!notices.officialSince) { notices.officialSince = Date.now(); saveN() }
465
+ } catch {}
466
+ }
467
+ setTimeout(pullOfficial, 20_000); setInterval(pullOfficial, 15 * 60_000)
468
+
469
+ // ── 和好友的 Agent 聊:我问 TA 的 Agent 的记录(agentout-),TA 问我的 Agent 的记录(agentin-)
470
+ const aoFile = (pk) => path.join(chatDir, 'agentout-' + pk.replace(/[^0-9a-f]/g, '') + '.json'), aiFile = (pk) => path.join(chatDir, 'agentin-' + pk.replace(/[^0-9a-f]/g, '') + '.json')
471
+ const appendAO = (pk, x) => fs.writeFileSync(aoFile(pk), JSON.stringify([...readJ(aoFile(pk), []), x].slice(-300)))
472
+ const appendAI = (pk, x) => fs.writeFileSync(aiFile(pk), JSON.stringify([...readJ(aiFile(pk), []), x].slice(-200)))
473
+ st.agentAsks ??= []; st.agentAllow ??= {}
474
+ const agentHits = new Map()
475
+ function onAgentAsk(from, m, at) {
476
+ const f = friend(from); if (!f) return // 只有好友能问
477
+ const qid = clean(m.qid, 32), text = clean(m.text, 2000); if (!qid || !text) return
478
+ const mode = globalThis.__shoalSettings?.().agentAccess?.mode ?? 'ask', per = st.agentAllow[from]
479
+ const reply = (o) => sendJson(from, { type: 'agent.reply', qid, name: globalThis.__shoalAgentName?.() ?? '', ...o }).catch(() => {})
480
+ if (mode === 'off' || per === 'off') return reply({ error: 'TA 没开放和 TA 的 Agent 聊天' })
481
+ if (myPresence().mode === 'invisible') return reply({ error: 'TA 的 Agent 现在不在,晚点再来问' })
482
+ if (mode === 'ask' && per !== 'on') {
483
+ if (!st.agentAsks.some((x) => x.from === from && x.qid === qid)) { st.agentAsks.push({ id: rid(), from, qid, text, at }); st.agentAsks = st.agentAsks.slice(-50); save(); changed() }
484
+ notify({ kind: 'need', title: (f.remark || f.name || '好友') + ' 想和你的 Agent 聊', body: text.slice(0, 120) })
485
+ return reply({ pending: true, text: '已经告诉 TA 了,TA 同意后我再回答你。' })
486
+ }
487
+ answerAgent(from, qid, text)
488
+ }
489
+ // 隔离回答:单独的对话记录,看不到主人的记忆、日程、文件,不用任何工具;每个好友每小时最多 30 次
490
+ async function answerAgent(from, qid, text) {
491
+ const f = friend(from); if (!f) return
492
+ const now = Date.now(), hits = (agentHits.get(from) ?? []).filter((t) => now - t < 3600_000); hits.push(now); agentHits.set(from, hits)
493
+ const send = (o) => sendJson(from, { type: 'agent.reply', qid, name: globalThis.__shoalAgentName?.() ?? '', ...o }).catch(() => {})
494
+ if (hits.length > 30) return send({ error: '这一小时问得太多了,过一会儿再来' })
495
+ const hist = readJ(aiFile(from), []).slice(-12)
496
+ appendAI(from, { q: text, at: now })
497
+ try {
498
+ const a = String(await globalThis.__shoalFriendAgent({ friend: f.remark || f.name || '好友', text, history: hist }) ?? '').slice(0, MAX_TEXT)
499
+ const h2 = readJ(aiFile(from), []); if (h2.length) { h2[h2.length - 1].a = a; fs.writeFileSync(aiFile(from), JSON.stringify(h2)) }
500
+ send({ text: a || '(没想好怎么回答)' })
501
+ } catch (e) { send({ error: '没回答成:' + String(e?.message ?? e).slice(0, 80) }) }
502
+ }
503
+
504
+ // ── 12-02:以前的图(动态、聊天、头像)只记了指纹(sha),没记下载信息;第一次没下成,这台设备就再也拿不到了(服务器上是加密的,钥匙在发的人那里)。
505
+ // 现在找不到又没有下载信息的图:问可能有这张图的人(发帖的好友、聊天里发图的人;自己发的问自己的另一台设备)——
506
+ // 对方本地有这个文件,就重新加密上传一份,把新的下载信息发回来(media.refs),这边照常下载。
507
+ // 对方只回答“这个人本来就看得到”的图:TA 自己的帖子 / 和我的私聊 / TA 在的群里的图;自己的另一台设备什么都回答
508
+ const mediaAsked = new Map() // sha → 上次问的时间(10 分钟内不重复问)
509
+ function shaOwners(sha) {
510
+ const out = new Set(), has = (x) => x && (x.sha === sha || (Array.isArray(x) && x.some((i) => i?.sha === sha)))
511
+ for (const p of mo.items ?? []) if (has(p.img) || has(p.imgs)) out.add(p.author === 'me' ? 'self' : p.author)
512
+ for (const f of st.friends ?? []) { try { for (const m of readChat(f.pk)) if (has(m.img)) out.add(m.from === 'me' ? 'self' : f.pk) } catch {} }
513
+ for (const g of gs.groups ?? []) { try { for (const m of readG(g.gid)) if (has(m.img)) out.add(m.from === 'me' || m.from === me.pk ? 'self' : m.from) } catch {} }
514
+ return [...out].filter((x) => x === 'self' || /^[0-9a-f]{64}$/.test(x))
515
+ }
516
+ function askMedia(sha) {
517
+ if (Date.now() - (mediaAsked.get(sha) ?? 0) < 10 * 60_000) return; mediaAsked.set(sha, Date.now())
518
+ for (const o of shaOwners(sha).slice(0, 3)) { if (o === 'self') copySelf({ type: 'media.ask', shas: [sha] }); else sendJson(o, { type: 'media.ask', shas: [sha] }).catch(() => {}) }
519
+ }
520
+ // 别人(或自己的另一台设备)来要:本地有、对方看得到的,重新加密上传,回下载信息。一次最多 9 张、每人每小时最多 30 张
521
+ const mediaAnswered = new Map()
522
+ async function answerMedia(from, shas, self) {
523
+ const ok = (sha) => self || shaOwners(sha).length && (() => {
524
+ for (const p of mo.items ?? []) if (p.author === 'me' && [p.img, ...(p.imgs ?? [])].some((i) => i?.sha === sha)) return true
525
+ try { if (readChat(from).some((m) => m.img?.sha === sha)) return true } catch {}
526
+ for (const g of gs.groups ?? []) if (g.members?.some((x) => x.pk === from)) { try { if (readG(g.gid).some((m) => m.img?.sha === sha)) return true } catch {} }
527
+ return false
528
+ })()
529
+ const k = self ? 'self' : from, used = (mediaAnswered.get(k) ?? []).filter((t) => Date.now() - t < 3600_000)
530
+ const refs = []
531
+ for (const sha of (Array.isArray(shas) ? shas : []).map(String).filter((x) => /^[0-9a-f]{64}$/.test(x)).slice(0, 9)) {
532
+ if (used.length >= 30) break
533
+ const f = mediaFile(sha); if (!f || !media || !ok(sha)) continue
534
+ try { const t = EXT[f.type] ? f.type : 'image/jpeg'; refs.push(await media.upload(fs.readFileSync(f.path), { name: 'image.' + (EXT[t] ?? 'jpg'), type: t })); used.push(Date.now()) } catch (e) { log('重新上传图片没成:', e?.message) }
535
+ }
536
+ mediaAnswered.set(k, used)
537
+ if (!refs.length) return
538
+ if (self) copySelf({ type: 'media.refs', refs }); else sendJson(from, { type: 'media.refs', refs }).catch(() => {})
539
+ }
540
+ // 收到别人发回来的下载信息:是我在等的图才收,记下来、马上下
541
+ function takeMediaRefs(refs) {
542
+ for (const r of (Array.isArray(refs) ? refs : []).slice(0, 9)) {
543
+ if (!r || !media?.ok(r) || !mediaAsked.has(r.sha256) || mediaFile(r.sha256)) continue
544
+ mediaRefs[r.sha256] = r; saveRefs(); pullImage(r)
545
+ }
546
+ }
547
+ function onMessage(from, m, rumor) {
548
+ if (m?.type === 'media.ask') { if (friend(from) || gs.groups.some((g) => g.members?.some((x) => x.pk === from))) answerMedia(from, m.shas, false).catch(() => {}); return }
549
+ if (m?.type === 'media.refs') { takeMediaRefs(m.refs); return }
550
+ const at = (rumor?.created_at ?? Math.floor(Date.now() / 1000)) * 1000
551
+ if (from === OFFICIAL && String(m.type ?? '').startsWith('official.')) return onOfficial(m, at)
552
+ if (String(m.type ?? '').startsWith('moment.')) return onMoment(from, m, at)
553
+ if (String(m.type ?? '').startsWith('group.')) return onGroup(from, m, at)
554
+ if (String(m.type ?? '').startsWith('circle.')) return onCircle(from, m, at)
555
+ if (m.type === 'profile.update') return onProfile(from, m)
556
+ if (m.type === 'profile.ask') { if (friend(from) && Date.now() - (profAsked.get(from) ?? 0) > 3600_000) { profAsked.set(from, Date.now()); sendProfile(from) } return }
557
+ if (friend(from)?.blocked) return // 屏蔽了:什么都不收
558
+ if (m.type === 'agent.ask') return onAgentAsk(from, m, at)
559
+ if (m.type === 'agent.reply') {
560
+ if (!friend(from)) return
561
+ const text = clean(m.text, MAX_TEXT), err = m.error ? clean(m.error, 200) : null
562
+ appendAO(from, { id: rid(), from: 'agent', text: text || null, error: err, pending: !!m.pending, name: clean(m.name, 20), qid: clean(m.qid, 32), at }); changed()
563
+ if (text && !m.pending) notify({ kind: 'chat', peer: from, title: (clean(m.name, 20) || 'TA 的 Agent') + '(' + (friend(from).remark || friend(from).name || '好友') + ' 的)', body: text.slice(0, 120) })
564
+ return
565
+ }
566
+ const name = clean(m.name, 32), number = /^\d{6,15}$/.test(String(m.number ?? '')) ? String(m.number) : null
567
+ const f = friend(from)
568
+ if (m.type === 'friend.accept') {
569
+ // 只认我们发过申请的人;对方通过了,就成为好友
570
+ const o = st.outgoing.find((x) => x.pk === from)
571
+ if (!o && !f) return
572
+ if (!f) st.friends.push({ pk: from, name: name || o?.name || '', number: number ?? o?.number ?? null, added: Date.now(), unread: 0 })
573
+ st.outgoing = st.outgoing.filter((x) => x.pk !== from); save(); changed(); sendProfile(from)
574
+ notify({ kind: 'friend', title: `${name || '对方'} 通过了你的好友申请`, body: '现在可以聊天了' })
575
+ return
576
+ }
577
+ if (m.type === 'friend.request') {
578
+ if (f) { sendJson(from, { type: 'friend.accept', name: st.name, number: me.number() }).catch(() => {}); return } // 已经是好友:再回一次通过
579
+ // 我们也向对方发过申请:双方都想加,直接成为好友
580
+ if (st.outgoing.some((x) => x.pk === from)) { acceptRequest(from, { name, number }); return }
581
+ if (globalThis.__shoalSettings?.().allowAdd === false) return // 设置里关了“允许别人加我”
582
+ upsertRequest(from, { name, number, text: clean(m.note, 200), at }); return
583
+ }
584
+ if (m.type === 'image') {
585
+ if (!f) return
586
+ const img = fetchImage(m.img); if (!img) return
587
+ appendChat(from, { id: rumor?.id, from: 'them', text: m.sticker ? '[表情]' : '[图片]', img, ...(m.sticker ? { sticker: true } : {}), at }); f.hidden = false; f.unread = (f.unread ?? 0) + 1; f.last = { text: '[图片]', at, from: 'them' }; save(); changed()
588
+ if (!f.muted) notify({ kind: 'chat', peer: from, title: f.remark || f.name || f.number || '好友', body: '[图片]' }); return
589
+ }
590
+ if (m.type === 'file') {
591
+ if (!f) return
592
+ const file = m.inline ? inlineFile(m.inline, m.name, m.ftype) : fetchFile(m.file, m.name); if (!file) return
593
+ const app = appCard(m.app), label = app ? '[小应用] ' + app.title : '[文件] ' + file.name
594
+ appendChat(from, { id: rumor?.id, from: 'them', text: label, file, ...(app ? { app } : {}), at }); f.unread = (f.unread ?? 0) + 1; f.last = { text: label, at, from: 'them' }; save(); changed()
595
+ if (!f.muted) notify({ kind: 'chat', peer: from, title: f.remark || f.name || f.number || '好友', body: label }); return
596
+ }
597
+ if (m.type !== 'text' && f && !['friend.accept', 'friend.request', 'image', 'file', 'profile.update'].includes(m.type) && !String(m.type ?? '').includes('.')) {
598
+ appendChat(from, { id: rumor?.id, from: 'them', text: '[对方用了新版本的功能,升级鱼Sho 后就能看到]', newer: true, at }); f.unread = (f.unread ?? 0) + 1; f.last = { text: '[新版本的消息]', at, from: 'them' }; save(); changed(); return
599
+ }
600
+ if (m.type === 'text') {
601
+ const text = clean(m.text, MAX_TEXT); if (!text) return
602
+ if (f) {
603
+ appendChat(from, { id: rumor?.id, from: 'them', text, at }); f.hidden = false
604
+ f.unread = (f.unread ?? 0) + 1; f.last = { text, at, from: 'them' }; save(); changed()
605
+ if (!f.muted) notify({ kind: 'chat', peer: from, title: f.remark || f.name || f.number || '好友', body: text.slice(0, 160) })
606
+ } else upsertRequest(from, { name: '', number: null, text: text.slice(0, 200), at }) // 陌生人直接说话:不进聊天,只当作申请
607
+ }
608
+ }
609
+ function upsertRequest(pk, r) {
610
+ const old = st.requests.find((x) => x.pk === pk)
611
+ if (old) Object.assign(old, { ...Object.fromEntries(Object.entries(r).filter(([, v]) => v)), at: r.at })
612
+ else { st.requests.push({ pk, ...r }); if (st.requests.length > 50) st.requests.shift() }
613
+ save(); changed()
614
+ notify({ kind: 'friend', title: `${r.name || (r.number ? '鱼Sho号 ' + r.number : '有人')} 想加你为好友`, body: r.text || '打开 App 看看要不要通过' })
615
+ }
616
+ function acceptRequest(pk, extra = {}) {
617
+ const r = st.requests.find((x) => x.pk === pk) ?? {}
618
+ if (!friend(pk)) st.friends.push({ pk, name: extra.name || r.name || '', number: extra.number ?? r.number ?? null, added: Date.now(), unread: 0 })
619
+ st.requests = st.requests.filter((x) => x.pk !== pk); st.outgoing = st.outgoing.filter((x) => x.pk !== pk); save(); changed()
620
+ sendJson(pk, { type: 'friend.accept', name: st.name, number: me.number() }).then(() => sendProfile(pk)).catch((e) => log('通过好友的消息没发出去', e?.message))
621
+ }
622
+
623
+ // ── 查号:号码 → 公钥(号码服务,NIP-05)→ 昵称(中继上的个人资料)
624
+ async function lookup(number) {
625
+ number = String(number ?? '').replace(/\D/g, '')
626
+ if (!/^\d{6,15}$/.test(number)) throw new Error('鱼Sho号是 6 到 15 位数字')
627
+ const j = await (await fetch(`${idService}/.well-known/nostr.json?name=${number}`, { signal: AbortSignal.timeout(10000) })).json()
628
+ const pk = j?.names?.[number]
629
+ if (!pk) throw new Error('没有这个鱼Sho号')
630
+ let name = ''
631
+ try { const evs = await query([{ kinds: [0], authors: [pk], limit: 1 }], 5000); const ev = evs.sort((a, b) => b.created_at - a.created_at)[0]; if (ev) name = clean(JSON.parse(ev.content).name, 32) } catch {}
632
+ return { pk, number, name, self: pk === me.pk, friend: !!friend(pk), pending: st.outgoing.some((x) => x.pk === pk) }
633
+ }
634
+
635
+ const api = {
636
+ onMessage,
637
+ lookup,
638
+ view: () => ({ name: st.name, me: { name: st.name, sig: st.sig ?? '', avatar: st.avatar?.sha ?? null, presence: myPresence() }, friends: st.friends.map(({ pk, name, number, unread, last, added, remark, muted, pinned, hidden, blocked, starred, tags }) => ({ starred: !!starred, tags: tags ?? [], pk, name, number, remark: remark ?? '', unread: unread ?? 0, last: last ?? null, added, muted: !!muted, pinned: !!pinned, hidden: !!hidden, blocked: !!blocked, sig: st.peers[pk]?.sig ?? '', avatar: avatarSha(pk), agent: st.peers[pk]?.agent ?? null, presence: st.peers[pk]?.presence ?? null })).sort((a, b) => (b.pinned - a.pinned) || ((b.last?.at ?? b.added) - (a.last?.at ?? a.added))), requests: [...st.requests].reverse(), outgoing: st.outgoing, agentAsks: (st.agentAsks ?? []).map((x) => ({ ...x, who: friend(x.from) ? friend(x.from).remark || friend(x.from).name || '好友' : '有人' })), noticesUnread: notices.items.filter((x) => !x.read).length, momentsUnread: mo.unread, momentsRev: mo.items.length + ':' + (mo.items.at(-1)?.at ?? 0) + ':' + mo.items.reduce((s, x) => s + x.comments.length + x.likes.length, 0),
639
+ joinPending: Object.keys(st.joinPending), groups: gs.groups.map((g) => ({ gid: g.gid, circle: g.circle ?? null, joinReqs: g.owner === me.pk ? (g.joinReqs ?? []).length : 0, name: g.name, count: g.members.length, agents: (g.agents ?? []).length, agentPol: Object.fromEntries((g.agents ?? []).map((a) => [a.key, a.policy])), unread: g.unread ?? 0, last: g.last, owner: g.owner === me.pk, joined: g.joined, muted: !!g.muted, pinned: !!g.pinned, hidden: !!g.hidden, blocked: !!g.blocked, avatar: g.avatar?.kind === 'img' ? { kind: 'img', sha: g.avatarImg?.sha } : g.avatar ?? null, faces: g.members.slice(0, 4).map((x) => nameIn(g, x.pk)) })).sort((a, b) => (b.pinned - a.pinned) || ((b.last?.at ?? b.joined) - (a.last?.at ?? a.joined))) }),
640
+ // ── 群聊
641
+ async createGroup(name, pks, opt = {}) {
642
+ const picked = [...new Set(pks ?? [])].map(friend).filter(Boolean), ags = agentsIn(opt.agents, me.pk), circle = circleIn(opt.circle)
643
+ if (!picked.length && !ags.length && !circle) throw new Error('至少选一个好友,或者带上你的 Agent')
644
+ if (circle && !clean(name, 32)) throw new Error('兴趣圈要起个名字')
645
+ const g = { gid: rid(), name: clean(name, 32) || [st.name || '我', ...picked.map((f) => f.remark || f.name)].slice(0, 3).join('、'), owner: me.pk, members: [meEntry(), ...picked.map((f) => ({ pk: f.pk, name: f.name, number: f.number }))], unread: 0, last: null, joined: Date.now(), nicks: {}, agents: ags, intro: clean(opt.intro, 200), ...(circle ? { circle } : {}), ...(opt.searchable !== undefined ? { searchable: !!opt.searchable } : {}), ...(VIS.includes(opt.vis) ? { vis: opt.vis } : {}) }
646
+ if (!clean(name, 32) && !picked.length) g.name = '我的 Agent 群'
647
+ g.avatar = opt.avatar?.kind === 'img' && opt.avatar.data ? { kind: 'img', ref: (await sendImage(opt.avatar.data, opt.avatar.type)) } : avatarIn(opt.avatar) ?? { kind: 'collage' }
648
+ if (g.avatar.kind === 'img') g.avatarImg = imgInfo(g.avatar.ref)
649
+ gs.groups.push(g); saveG(); changed()
650
+ appendG(g.gid, { id: rid(), from: 'system', text: '你创建了群聊' + (picked.length ? ',拉了 ' + picked.map((f) => f.remark || f.name || f.number).join('、') : '') + (ags.length ? (picked.length ? ',' : ',') + '带上了 ' + ags.map((a) => a.name).join('、') + '(在群里 @ 它就会干活)' : ''), at: Date.now() })
651
+ await sendAll(g, { type: 'group.invite', ...metaOf(g) })
652
+ publishCard(g)
653
+ return { gid: g.gid }
654
+ },
655
+ groupChat(gid) { const g = group(gid); if (!g) throw new Error('没有这个群'); if (g.unread) { g.unread = 0; saveG(); changed() } const avOf = (x) => (x.from === 'me' ? st.avatar?.sha ?? null : avatarSha(x.from))
656
+ return { group: { gid, agentMgr: { on: false, auto: false, ...(g.agentMgr ?? {}), mode: g.agentMode ?? 'mention' }, notes: g.notes ?? [], circle: g.circle ?? null, category: g.category ?? null, categories: CATS, notice: g.notice ?? null, joinReqs: g.owner === me.pk ? g.joinReqs ?? [] : [], name: g.name, intro: g.intro ?? '', owner: g.owner === me.pk, ownerPk: g.owner, ownerName: nameIn(g, g.owner), number: g.number ?? null, vis: visOf(g), muted: !!g.muted, pinned: !!g.pinned, myNick: g.nicks?.[me.pk] ?? '', avatar: g.avatar?.kind === 'img' ? { kind: 'img', sha: g.avatarImg?.sha } : g.avatar ?? null, searchable: listed(g), role: g.owner === me.pk ? 'owner' : (g.admins ?? []).includes(me.pk) ? 'admin' : 'member', silencedMe: (g.silenced ?? []).includes(me.pk), members: g.members.map((x) => ({ pk: x.pk, name: nameIn(g, x.pk), me: x.pk === me.pk, friend: !!friend(x.pk), owner: x.pk === g.owner, admin: (g.admins ?? []).includes(x.pk), silenced: (g.silenced ?? []).includes(x.pk), avatar: avatarSha(x.pk), sig: x.pk === me.pk ? st.sig : st.peers[x.pk]?.sig ?? '' })), agents: (g.agents ?? []).map((a) => ({ ...a, mine: a.by === me.pk, byName: a.by ? nameIn(g, a.by) : '', busy: busyAgents.has(a.key) })) }, messages: readG(gid).slice(-200).map((x) => ({ ...x, av: avOf(x), mine: x.from === 'me', who: x.from === 'system' ? null : x.from === 'me' ? '我' : nameIn(g, x.from) })) } },
657
+ async sendGroup(gid, text, image, imageType, extra = {}) {
658
+ const g = group(gid); if (!g) throw new Error('没有这个群')
659
+ if (!extra.agent && (g.silenced ?? []).includes(me.pk)) throw new Error('你在这个群里被禁言了')
660
+ const ref = image ? await sendImage(image, imageType) : null
661
+ const fl = !ref && extra.file ? await sendFileData(extra.file.data, extra.file.name, extra.file.type, { inline: !!extra.app }) : null
662
+ const app = fl ? appCard(extra.app) : null
663
+ text = ref ? (extra.sticker ? '[表情]' : '[图片]') : app ? '[小应用] ' + app.title : fl ? '[文件] ' + fl.info.name : clean(text, MAX_TEXT); if (!text) throw new Error('没有内容')
664
+ const mentions = (Array.isArray(extra.mentions) ? extra.mentions : []).filter((x) => /^[0-9a-f]{64}$/.test(String(x))).slice(0, 20)
665
+ const agent = extra.agent ? clean(extra.agent, 24) : null, hop = Math.min(9, Number(extra.hop) || 0)
666
+ const mid = rid(), msg = { id: mid, from: 'me', text, ...(ref ? { img: imgInfo(ref) } : {}), ...(ref && extra.sticker ? { sticker: true } : {}), ...(fl ? { file: fl.info } : {}), ...(app ? { app } : {}), ...(agent ? { agent } : {}), ...(mentions.length ? { mentions } : {}), hop, at: Date.now() }
667
+ appendG(gid, msg); g.last = { text, at: msg.at, from: agent ?? '我' }; saveG(); changed()
668
+ const gm = { type: 'group.msg', text, mid, hop, ...(ref ? { img: ref } : {}), ...(ref && extra.sticker ? { sticker: true } : {}), ...(fl ? (fl.ref ? { file: fl.ref, fileName: fl.info.name } : { inline: fl.inline, ftype: fl.info.type, fileName: fl.info.name }) : {}), ...(app ? { app } : {}), ...(agent ? { agent } : {}), ...(mentions.length ? { mentions } : {}) }
669
+ copySelf({ ...gm, gid }) // 同一个身份的另一台设备也记下这条(群里只有自己时也抄)
670
+ const sent = await sendAll(g, gm)
671
+ { const bad = sent.filter((r) => r.status === 'rejected').length; if (sent.length && bad === sent.length) { const a = readG(gid), k = a.findIndex((x) => x.id === mid); if (k >= 0) { a[k] = { ...a[k], failed: true }; fs.writeFileSync(gFile(gid), JSON.stringify(a)); changed() } const why = sent.find((r) => r.status === 'rejected')?.reason; if (why?.refused) throw new Error('没发出去:' + why.message); throw new Error('没发出去:连不上中继,过一会儿长按这条消息点“重发”') } if (bad) { const a = readG(gid), k = a.findIndex((x) => x.id === mid); if (k >= 0) { a[k] = { ...a[k], partial: bad }; fs.writeFileSync(gFile(gid), JSON.stringify(a)) } } }
672
+ callAgents(g, { ...msg, from: me.pk }) // 自己 @ 了自己带进来的 Agent;或者 Agent 的回答里 @ 了别的 Agent(接力)
673
+ return msg
674
+ },
675
+ /** 撤回群里的一条:自己发的 24 小时内;群主、管理员可以撤回任何人的 */
676
+ async recallGroup(gid, mid) {
677
+ const g = group(gid); if (!g) throw new Error('没有这个群')
678
+ const a = readG(gid), i = a.findIndex((x) => x.id === String(mid)); if (i < 0) throw new Error('没有这条消息')
679
+ const x = a[i], own = x.from === 'me' || x.from === me.pk
680
+ if (x.recalled) return { ok: true }
681
+ if (!(own && Date.now() - x.at < 24 * 3600_000) && !isMgr(g, me.pk)) throw new Error(own ? '超过 24 小时,撤回不了了' : '只有群主和管理员能撤回别人的消息')
682
+ a[i] = { id: x.id, from: x.from, at: x.at, recalled: true, by: me.pk, text: '' }; fs.writeFileSync(gFile(gid), JSON.stringify(a)); saveG(); changed()
683
+ await sendAll(g, { type: 'group.recall', mid: x.id })
684
+ return { ok: true }
685
+ },
686
+ /** 群公告:群主、管理员发;空字符串 = 撤掉公告 */
687
+ async setGroupNotice(gid, text) {
688
+ const g = group(gid); if (!g) throw new Error('没有这个群'); if (!isMgr(g, me.pk)) throw new Error('只有群主和管理员能发公告')
689
+ text = clean(text, 1000); g.notice = text ? { text, at: Date.now(), by: me.pk } : null
690
+ if (text) appendG(gid, { id: rid(), from: 'me', sys: true, text: '群公告:' + text, at: Date.now() })
691
+ saveG(); changed(); await sendAll(g, { type: 'group.notice', text }); return { ok: true, notice: g.notice }
692
+ },
693
+ /** 只在这部手机上删掉一条(私聊或群聊) */
694
+ deleteLocalMsg(kind, id, mid) {
695
+ if (kind === 'group') { const a = readG(id).filter((x) => x.id !== String(mid)); fs.writeFileSync(gFile(id), JSON.stringify(a)); saveG(); changed(); return { ok: true } }
696
+ const a = readChat(id).filter((x) => String(x.id) !== String(mid) && !(x.id == null && String(x.at) === String(mid))); fs.writeFileSync(chatFile(id), JSON.stringify(a)); changed(); return { ok: true }
697
+ },
698
+ async addToGroup(gid, pks) {
699
+ const g = group(gid); if (!g) throw new Error('没有这个群'); if (!isMgr(g, me.pk)) throw new Error('只有群主和管理员能拉人')
700
+ const add = [...new Set(pks ?? [])].map(friend).filter((f) => f && !g.members.some((x) => x.pk === f.pk))
701
+ if (!add.length) throw new Error('没有可以拉的好友')
702
+ g.members.push(...add.map((f) => ({ pk: f.pk, name: f.name, number: f.number }))); saveG(); changed()
703
+ appendG(gid, { id: rid(), from: 'system', text: '你拉了 ' + add.map((f) => f.remark || f.name || f.number).join('、') + ' 进群', at: Date.now() })
704
+ await sendAll(g, { type: 'group.invite', ...metaOf(g) }); publishCard(g)
705
+ return { ok: true }
706
+ },
707
+ /** 设 / 取消管理员(只有群主;不限人数) */
708
+ async setAdmin(gid, pk, on) {
709
+ const g = group(gid); if (!g) throw new Error('没有这个群'); if (g.owner !== me.pk) throw new Error('只有群主能设管理员')
710
+ if (!g.members.some((x) => x.pk === pk) || pk === me.pk) throw new Error('不是群成员')
711
+ g.admins = [...new Set([...(g.admins ?? []).filter((x) => x !== pk), ...(on ? [pk] : [])])]
712
+ appendG(gid, { id: rid(), from: 'system', text: (on ? '你把 ' + nameIn(g, pk) + ' 设为管理员' : '你取消了 ' + nameIn(g, pk) + ' 的管理员'), at: Date.now() })
713
+ saveG(); changed(); await sendAll(g, { type: 'group.update', ...metaOf(g) }); return { ok: true }
714
+ },
715
+ /** 踢人 / 禁言(群主、管理员;管理员管不了群主和别的管理员) */
716
+ async manageMember(gid, pk, what, on) {
717
+ const g = group(gid); if (!g) throw new Error('没有这个群'); if (!isMgr(g, me.pk)) throw new Error('只有群主和管理员能管')
718
+ if (pk === me.pk || pk === g.owner || !g.members.some((x) => x.pk === pk)) throw new Error('管不了这个人')
719
+ if (g.owner !== me.pk && (g.admins ?? []).includes(pk)) throw new Error('管理员管不了别的管理员')
720
+ if (what === 'kick') {
721
+ await sendAll(g, { type: 'group.kick', pk }) // 被踢的人也收到,好让他那边把群去掉
722
+ appendG(gid, { id: rid(), from: 'system', text: '你把 ' + nameIn(g, pk) + ' 移出了群', at: Date.now() })
723
+ g.members = g.members.filter((x) => x.pk !== pk); g.agents = (g.agents ?? []).filter((a) => a.by !== pk); g.admins = (g.admins ?? []).filter((x) => x !== pk); g.silenced = (g.silenced ?? []).filter((x) => x !== pk)
724
+ } else {
725
+ g.silenced = [...new Set([...(g.silenced ?? []).filter((x) => x !== pk), ...(on ? [pk] : [])])]
726
+ appendG(gid, { id: rid(), from: 'system', text: (on ? '你禁言了 ' : '你解除了 ') + nameIn(g, pk) + (on ? '' : ' 的禁言'), at: Date.now() })
727
+ await sendAll(g, { type: 'group.mute', pk, on: !!on })
728
+ }
729
+ saveG(); changed(); publishCard(g); return { ok: true }
730
+ },
731
+ /** 别人在群里叫我的 Agent、等我批的 */
732
+ groupAsks: () => groupAsks.map(({ msg, ...q }) => q),
733
+ groupsOf: (pk) => gs.groups.filter((g) => g.members.some((m) => m.pk === pk)).map((g) => g.name),
734
+ iAskedFirst: (pk) => st.outgoing.some((x) => x.pk === pk),
735
+ answerGroupAsk(id, ok) {
736
+ const i = groupAsks.findIndex((q) => q.id === id); if (i < 0) throw new Error('这个请求已经处理过了(可能超时了)')
737
+ const [q] = groupAsks.splice(i, 1); changed(); const g = group(q.gid), a = (g?.agents ?? []).find((x) => x.key === q.key && x.by === me.pk)
738
+ if (!g || !a) throw new Error('这个 Agent 已经不在群里了')
739
+ if (ok) runAgent(g, a, q.msg, false); else api.sendGroup(g.gid, '(' + a.name + ' 的主人没有同意这次请求。)', null, null, { agent: a.name, hop: 9 }).catch(() => {})
740
+ return { ok: true }
741
+ },
742
+ async leaveGroup(gid) {
743
+ const g = group(gid); if (!g) throw new Error('没有这个群')
744
+ const next = g.members.find((x) => x.pk !== me.pk)
745
+ if (g.owner === me.pk && next) { if (g.number) await syncNumber(g, { transfer: next.pk }); g.owner = next.pk; g.members = g.members.filter((x) => x.pk !== me.pk); g.agents = (g.agents ?? []).filter((a) => a.by !== me.pk); await sendAll(g, { type: 'group.update', ...metaOf(g), members: [...g.members, meEntry()], owner: next.pk }) }
746
+ await sendAll({ ...g, members: [...g.members, meEntry()] }, { type: 'group.leave' })
747
+ gs.groups = gs.groups.filter((x) => x !== g); saveG(); changed(); return { ok: true }
748
+ },
749
+ /** 群资料(只有群主能改):名字、简介、头像(颜色 / 成员拼图 / 照片) */
750
+ async setGroupInfo(gid, b) {
751
+ const g = group(gid); if (!g) throw new Error('没有这个群'); if (g.owner !== me.pk) throw new Error('只有群主能改群资料')
752
+ if (b.name !== undefined) g.name = clean(b.name, 32) || g.name
753
+ if (b.intro !== undefined) g.intro = clean(b.intro, 200)
754
+ if (b.avatar) { if (b.avatar.kind === 'img' && b.avatar.data) { const ref = await sendImage(b.avatar.data, b.avatar.type); g.avatar = { kind: 'img', ref }; g.avatarImg = imgInfo(ref) } else g.avatar = avatarIn(b.avatar) ?? g.avatar }
755
+ if (b.circle !== undefined && g.circle) g.circle = circleIn({ ...g.circle, ...b.circle })
756
+ if (b.searchable !== undefined) { g.searchable = !!b.searchable; g.vis = b.searchable ? 'public' : 'private' }
757
+ if (VIS.includes(b.vis)) g.vis = b.vis
758
+ if (b.category !== undefined) g.category = CATS.includes(b.category) ? b.category : null
759
+ saveG(); changed(); await sendAll(g, { type: 'group.update', ...metaOf(g) }); publishCard(g); return { ok: true }
760
+ },
761
+ /** 拉人进圈(兴趣圈用:不要求是好友;只有圈主) */
762
+ async addMembers(gid, list) {
763
+ const g = group(gid); if (!g || g.owner !== me.pk) throw new Error('只有圈主能拉人')
764
+ const add = members(list).filter((x) => !g.members.some((y) => y.pk === x.pk)); if (!add.length) return { ok: true }
765
+ g.members.push(...add); g.joinReqs = (g.joinReqs ?? []).filter((x) => !add.some((y) => y.pk === x.pk)); saveG(); changed()
766
+ appendG(gid, { id: rid(), from: 'system', text: add.map((x) => x.name || '新成员').join('、') + ' 加入了', at: Date.now() })
767
+ await sendAll(g, { type: 'group.invite', ...metaOf(g) }); publishCard(g); return { ok: true }
768
+ },
769
+ async answerJoin(gid, pk, ok) {
770
+ const g = group(gid); if (!g || g.owner !== me.pk) throw new Error('只有圈主能审批')
771
+ const r = (g.joinReqs ?? []).find((x) => x.pk === pk); if (!r) throw new Error('这个申请已经处理过了')
772
+ if (ok) return api.addMembers(gid, [r])
773
+ g.joinReqs = g.joinReqs.filter((x) => x.pk !== pk); saveG(); changed(); await sendJson(pk, { type: 'circle.reject', gid, reason: '圈主没有同意' }).catch(() => {}); return { ok: true }
774
+ },
775
+ /** 发现兴趣圈:从中继上读公开名片(只看鱼Sho 的),按分类、关键字筛 */
776
+ async discover(q, category) {
777
+ const qs = String(q ?? '').trim()
778
+ if (GNO.test(qs)) {
779
+ const r = await fetch(idService + '/api/id/group?n=' + qs, { signal: AbortSignal.timeout(8000) }).catch(() => null), j = r ? await r.json().catch(() => ({})) : {}
780
+ if (!r?.ok) return { categories: [...CATS, '群聊'], items: [], mine: [], byNumber: { number: qs, error: j.error ?? '没有这个群号,或者这个群没公开' } }
781
+ const c = await api.groupCard(j.gid, j.owner)
782
+ const x = c.card ? { gid: j.gid, owner: j.owner, name: c.card.name, intro: c.card.intro, category: c.card.category || '群聊', open: c.card.open, count: c.card.count, gno: qs, color: null, img: c.card.img, faces: [] } : { gid: j.gid, owner: j.owner, name: '群 ' + qs, intro: '', category: '群聊', open: false, count: 1, gno: qs, color: null, img: null, faces: [] }
783
+ return { categories: [...CATS, '群聊'], items: [x], mine: [], byNumber: { number: qs, gid: j.gid, owner: j.owner, joined: c.joined, pending: c.pending } }
784
+ }
785
+ // 排序服务给的(审核过、排好序)在前;中继上的公开名片一律也读,补上排序服务还没收录的(新建的小群不会因为没人气就消失)
786
+ const [ranked, relay] = await Promise.all([modList('discover', { q: q ?? '', cat: category && category !== '全部' ? category : '' }).catch(() => null), query([{ kinds: [30078], '#t': ['yusho-circle'], limit: 300 }], 6000).catch(() => [])])
787
+ const rankIdx = new Map((ranked ?? []).map((ev, i) => [ev.id, i])), evs = [...(ranked ?? []), ...(relay ?? [])]
788
+ const best = new Map()
789
+ for (const ev of evs) { const d = (ev.tags.find((t) => t[0] === 'd') ?? [])[1] ?? ''; if (!d.startsWith('yusho-circle:')) continue; const k = ev.pubkey + d; if (!best.has(k) || best.get(k).created_at < ev.created_at) best.set(k, ev) }
790
+ const out = []
791
+ for (const ev of best.values()) {
792
+ let c; try { c = JSON.parse(ev.content) } catch { continue }
793
+ if (c.hidden || ev.tags.some((t) => t[0] === 't' && t[1] === 'yusho-circle-unlisted')) continue
794
+ const gid = ev.tags.find((t) => t[0] === 'd')[1].slice('yusho-circle:'.length); if (!/^[0-9a-f]{8,32}$/.test(gid)) continue
795
+ const x = { gid, owner: ev.pubkey, name: clean(c.name, 32), intro: clean(c.intro, 200), category: CATS.includes(c.category) || c.category === '群聊' ? c.category : '其他', open: !!c.open, count: Math.max(1, Number(c.count) || 1), gno: GNO.test(String(c.gno ?? '')) ? String(c.gno) : null, number: /^\d{6,15}$/.test(String(c.number ?? '')) ? String(c.number) : null, color: Number.isInteger(c.color) ? c.color : null, img: c.img && media?.ok(c.img) ? fetchImage(c.img)?.sha ?? null : null, faces: (Array.isArray(c.faces) ? c.faces : []).slice(0, 4).map((x) => clean(x, 16)), kind: c.kind === 'group' ? 'group' : 'circle', updated: ev.created_at * 1000, joined: !!group(gid), pending: !!st.joinPending[gid], mine: ev.pubkey === me.pk }
796
+ if (!x.name || (category && category !== '全部' && x.category !== category)) continue
797
+ if (q && !(x.name + x.intro).toLowerCase().includes(String(q).toLowerCase())) continue
798
+ if (rankIdx.has(ev.id)) x.rank = rankIdx.get(ev.id)
799
+ out.push(x)
800
+ }
801
+ // 展示策略:排序服务排过的按它的顺序;其余的按 人数(对数,防大群霸榜)+ 新鲜度(7 天减半)+ 当天固定的随机数
802
+ // 同一天里顺序稳定(不乱跳),每天换一批露脸的机会;新建的小群也排得上
803
+ const day = new Date().toISOString().slice(0, 10), rnd = (id) => { let x = 2166136261; for (const ch of id + day) x = Math.imul(x ^ ch.charCodeAt(0), 16777619); return (x >>> 0) / 4294967296 }
804
+ const score = (x) => 0.35 * Math.min(1, Math.log10(1 + x.count) / 1.5) + 0.35 * Math.pow(0.5, (Date.now() - x.updated) / (7 * 864e5)) + 0.3 * rnd(x.gid)
805
+ out.sort((a, b) => (a.rank ?? 1e9) - (b.rank ?? 1e9) || score(b) - score(a))
806
+ // 我建的群、圈:没公开的告诉用户(以为被屏蔽了,其实是没打开“能被公开搜到”)
807
+ const shown = new Set(out.map((x) => x.gid)), mine = gs.groups.filter((g) => g.owner === me.pk && !shown.has(g.gid)).map((g) => ({ gid: g.gid, name: g.name, circle: !!g.circle, listed: listed(g), vis: visOf(g), number: g.number ?? null, note: g.cardNote ?? null }))
808
+ return { categories: [...CATS, '群聊'], items: out.slice(0, 100), mine: q || (category && category !== '全部') ? [] : mine }
809
+ },
810
+ /** 群二维码扫进来:按群号 + 群主从中继上读它的公开名片(没公开就只回群号,照样能申请,群主同意才进) */
811
+ async groupCard(gid, owner) {
812
+ if (!/^[0-9a-f]{16,32}$/.test(String(gid)) || !/^[0-9a-f]{64}$/.test(String(owner))) throw new Error('二维码不对')
813
+ const joined = !!group(gid), pending = !!st.joinPending[gid]
814
+ const evs = await query([{ kinds: [30078], authors: [owner], '#d': ['yusho-circle:' + gid], limit: 5 }], 6000).catch(() => [])
815
+ const ev = evs.sort((a, b) => b.created_at - a.created_at)[0]
816
+ let c = null; try { c = ev ? JSON.parse(ev.content) : null } catch {}
817
+ if (!c || c.hidden) return { gid, owner, card: null, joined, pending }
818
+ return { gid, owner, joined, pending, card: { gno: GNO.test(String(c.gno ?? '')) ? String(c.gno) : null, name: clean(c.name, 32), intro: clean(c.intro, 200), count: Math.max(1, Number(c.count) || 1), category: clean(c.category, 12), open: !!c.open, kind: c.kind === 'circle' ? 'circle' : 'group', img: c.img && media?.ok(c.img) ? fetchImage(c.img)?.sha ?? null : null } }
819
+ },
820
+ notices() { return { items: notices.items, unread: notices.items.filter((x) => !x.read).length } },
821
+ readNotices(ids) { const set = ids ? new Set(ids) : null; notices.items = notices.items.map((x) => (!set || set.has(x.id) ? { ...x, read: true } : x)); saveN(); changed(); return { ok: true } },
822
+ deleteNotice(id) { notices.items = notices.items.filter((x) => x.id !== id); saveN(); changed(); return { ok: true } },
823
+ noticesUnread() { return notices.items.filter((x) => !x.read).length },
824
+ setAgentMgr(gid, b) { const g = group(gid); if (!g) throw new Error('没有这个群'); /* 主动看群消息只管自己带进群的秘书:谁都能开;让秘书管群(撤回、公告)要群主或管理员 */ if (b.mode === 'active' || b.mode === 'mention') { g.agentMode = b.mode; if (b.on === undefined) { saveG(); changed(); return { ok: true, agentMgr: { ...(g.agentMgr ?? {}), mode: g.agentMode } } } } if (!isMgr(g, me.pk)) throw new Error('只有群主和管理员能让秘书管群'); g.agentMgr = { on: !!b.on, auto: !!b.on && !!b.auto }; saveG(); changed(); return { ok: true, agentMgr: { ...g.agentMgr, mode: g.agentMode ?? 'mention' } } },
825
+ /** 问好友的 Agent */
826
+ async askFriendAgent(pk, text) {
827
+ const f = friend(pk); if (!f) throw new Error('不是好友'); if (!st.peers[pk]?.agent) throw new Error('TA 没开放和 TA 的 Agent 聊天')
828
+ text = clean(text, 2000); if (!text) throw new Error('没有内容')
829
+ const qid = rid(); appendAO(pk, { id: qid, from: 'me', text, qid, at: Date.now() }); changed()
830
+ await sendJson(pk, { type: 'agent.ask', qid, text }); return { ok: true }
831
+ },
832
+ clearFriendAgentChat(pk) { if (!friend(pk)) throw new Error('不是好友'); fs.writeFileSync(aoFile(pk), '[]'); return { ok: true } }, // 清空和好友 Agent 的聊天(只清这部手机上的)
833
+ friendAgentChat(pk) { const f = friend(pk); if (!f) throw new Error('不是好友'); return { agent: st.peers[pk]?.agent ?? null, name: f.remark || f.name || '好友', messages: readJ(aoFile(pk), []).slice(-200) } },
834
+ /** 好友想和我的 Agent 聊:这次允许 / 总是允许 TA / 拒绝 */
835
+ answerAgentRequest(id, how) {
836
+ const x = (st.agentAsks ?? []).find((y) => y.id === id); if (!x) throw new Error('这个请求已经处理过了')
837
+ st.agentAsks = st.agentAsks.filter((y) => y.id !== id)
838
+ if (how === 'always') st.agentAllow[x.from] = 'on'
839
+ if (how === 'deny') { sendJson(x.from, { type: 'agent.reply', qid: x.qid, error: 'TA 这次没同意', name: globalThis.__shoalAgentName?.() ?? '' }).catch(() => {}) } else answerAgent(x.from, x.qid, x.text)
840
+ save(); changed(); return { ok: true }
841
+ },
842
+ setAgentAllow(pk, v) { if (!friend(pk)) throw new Error('不是好友'); if (v === 'on' || v === 'off') st.agentAllow[pk] = v; else delete st.agentAllow[pk]; save(); changed(); return { ok: true, allow: st.agentAllow[pk] ?? null } },
843
+ agentAllowOf(pk) { return st.agentAllow?.[pk] ?? null },
844
+ /** 设置里改了“我的 Agent 开不开放”:重新告诉所有好友 */
845
+ republishProfile() { return Promise.allSettled(st.friends.map((f) => sendJson(f.pk, profileMsg()))) },
846
+ async joinCircle(gid, owner, note) {
847
+ if (group(gid)) throw new Error('已经在圈里了'); if (!/^[0-9a-f]{64}$/.test(String(owner))) throw new Error('找不到圈主')
848
+ st.joinPending[gid] = { at: Date.now(), owner }; save(); changed()
849
+ await sendJson(owner, { type: 'circle.join', gid, name: st.name, number: me.number(), note: clean(note, 100) }); return { ok: true }
850
+ },
851
+ /** 最近的公开动态(中继上鱼Sho 用户发的公开帖) */
852
+ async publicFeed() {
853
+ const ranked = await modList('feed'), evs = ranked ?? await query([{ kinds: [1], '#t': ['yusho'], limit: 60 }], 6000)
854
+ const tag = (ev, k) => ev.tags.filter((t) => t[0] === k).map((t) => t[1])
855
+ const ref = (s) => { try { const r = JSON.parse(s); return media?.ok(r) ? r : null } catch { return null } }
856
+ return { items: evs.filter((ev) => !st.hide.includes(ev.pubkey) && !st.reports.some((r) => r.ev === ev.id)).sort((a, b) => (ranked ? 0 : b.created_at - a.created_at)).slice(0, 40).map((ev) => {
857
+ const mine = ev.pubkey === me.pk, f = friend(ev.pubkey), av = tag(ev, 'yav')[0]
858
+ return { id: ev.id, pk: ev.pubkey, text: cleanML(ev.content, 2000), at: ev.created_at * 1000, mine, friend: !!f,
859
+ name: mine ? st.name || '我' : f ? f.remark || f.name : clean(tag(ev, 'name')[0], 32) || null,
860
+ avatar: mine ? st.avatar?.sha ?? null : f ? avatarSha(ev.pubkey) : av && ref(av) ? fetchImage(ref(av))?.sha ?? null : null,
861
+ imgs: tag(ev, 'yimg').slice(0, 9).map(ref).filter(Boolean).map(fetchImage).filter(Boolean) }
862
+ }) }
863
+ },
864
+ async setGroupNick(gid, nick) { const g = group(gid); if (!g) throw new Error('没有这个群'); g.nicks = { ...(g.nicks ?? {}), [me.pk]: clean(nick, 20) }; saveG(); changed(); await sendAll(g, { type: 'group.nick', nick: g.nicks[me.pk] }); return { ok: true } },
865
+ /** 我带进群的 Agent(只能是自己电脑上的) */
866
+ async setGroupAgents(gid, list) { const g = group(gid); if (!g) throw new Error('没有这个群'); const mine = agentsIn(list, me.pk); g.agents = [...(g.agents ?? []).filter((a) => a.by !== me.pk), ...mine]; saveG(); changed(); await sendAll(g, { type: 'group.agents', agents: mine }); publishCard(g); return { ok: true } },
867
+ applySelfProfile,
868
+ /** 我的资料:昵称、个签(20 字以内)、头像(加密发给好友和群里的人)。昵称、个签先审核,违规的存成星号;改完抄一份给自己的另一台设备 */
869
+ async setProfile(b) {
870
+ let nm, sg; const masked = []
871
+ if (b.name !== undefined) { nm = clean(b.name, 32); if (!nm) throw new Error('昵称不能是空的') }
872
+ if (b.sig !== undefined) { sg = clean(b.sig, 40); if ([...sg].length > 20) throw new Error('个签最多 20 个字') }
873
+ const rv = await reviewProfile(nm !== undefined && nm !== st.name ? nm : '', sg !== undefined && sg !== (st.sig ?? '') && sg ? sg : '')
874
+ if (nm !== undefined) { if (nm !== st.name && !rv.name) { nm = stars(nm); masked.push('name') } st.name = nm }
875
+ if (sg !== undefined) { if (sg && sg !== (st.sig ?? '') && !rv.sig) { sg = stars(sg); masked.push('sig') } st.sig = sg }
876
+ if (b.avatar === null) { delete st.avatar; delete st.avatarRef }
877
+ else if (b.avatar?.data) { const ref = await sendImage(b.avatar.data, b.avatar.type); st.avatarRef = ref; st.avatar = imgInfo(ref) }
878
+ save(); changed()
879
+ if (me.number()) publishSigned({ kind: 0, created_at: Math.floor(Date.now() / 1000), tags: [], content: JSON.stringify({ name: st.name, about: st.sig ?? '', nip05: me.number() + '@' + idHost() }) }).then(() => { st.published = Date.now(); save() }).catch(() => {})
880
+ await Promise.allSettled(everyone().map((pk) => sendJson(pk, profileMsg())))
881
+ syncSelfProfile()
882
+ return { name: st.name, sig: st.sig, avatar: st.avatar?.sha ?? null, masked }
883
+ },
884
+ /** 删掉和某人 / 某个群的聊天记录(只删自己手机上的) */
885
+ clearChat(kind, id) { if (kind === 'group') { const g = group(id); if (!g) throw new Error('没有这个群'); fs.writeFileSync(gFile(id), '[]'); g.last = null; g.unread = 0; saveG() } else { const f = friend(id); if (!f) throw new Error('不是好友'); fs.writeFileSync(chatFile(id), '[]'); f.last = null; f.unread = 0; save() } changed(); return { ok: true } },
886
+ /** 免打扰、置顶、隐藏(有新消息会重新出现)、屏蔽(不收这个人 / 这个群的任何消息):只存在自己手机上 */
887
+ setFlags(kind, id, b) { const x = kind === 'group' ? group(id) : friend(id); if (!x) throw new Error(kind === 'group' ? '没有这个群' : '不是好友'); if (b.muted !== undefined) x.muted = !!b.muted; if (b.pinned !== undefined) x.pinned = !!b.pinned; if (b.hidden !== undefined) x.hidden = !!b.hidden; if (b.blocked !== undefined) { x.blocked = !!b.blocked; if (x.blocked) x.hidden = true }; if (kind === 'friend' && b.starred !== undefined) x.starred = !!b.starred; if (kind === 'friend' && Array.isArray(b.tags)) x.tags = [...new Set(b.tags.map((t) => clean(t, 12)).filter(Boolean))].slice(0, 8); kind === 'group' ? saveG() : save(); changed(); return { muted: !!x.muted, pinned: !!x.pinned, hidden: !!x.hidden, blocked: !!x.blocked, starred: !!x.starred, tags: x.tags ?? [] } },
888
+ async sendChatFile(pk, data, name, type, app0) {
889
+ const f = friend(pk); if (!f) throw new Error('不是好友,不能发')
890
+ const app = appCard(app0), fl = await sendFileData(data, name, type, { inline: !!app }); await sendJson(pk, { type: 'file', ...(fl.ref ? { file: fl.ref } : { inline: fl.inline, ftype: fl.info.type }), name: fl.info.name, ...(app ? { app } : {}) })
891
+ const msg = { id: rid(), from: 'me', text: app ? '[小应用] ' + app.title : '[文件] ' + fl.info.name, file: fl.info, ...(app ? { app } : {}), at: Date.now() }
892
+ appendChat(pk, msg); f.last = { text: msg.text, at: msg.at, from: 'me' }; save(); changed(); return msg
893
+ },
894
+ /** 改昵称:存本地,再发一份公开的个人资料(别人查你的号能看到) */
895
+ async setName(name) {
896
+ name = clean(name, 32); if (!name) throw new Error('昵称不能是空的')
897
+ let masked = false; if (name !== st.name && !(await reviewProfile(name, '')).name) { name = stars(name); masked = true }
898
+ if (name !== st.name) Promise.allSettled(everyone().map((pk) => sendJson(pk, { ...profileMsg(), name })))
899
+ const was = st.name; st.name = name; save(); changed(); if (was !== name) syncSelfProfile()
900
+ if (!me.number()) throw new Error('还没领到鱼Sho号,昵称先存在手机上,领到后会自动发出去')
901
+ await publishSigned({ kind: 0, created_at: Math.floor(Date.now() / 1000), tags: [], content: JSON.stringify({ name, about: st.sig ?? '', nip05: `${me.number()}@${new URL(idService).hostname}` }) })
902
+ st.published = Date.now(); save(); return { name, masked }
903
+ },
904
+ /** 有昵称但还没发出去(比如当时还没号):联网后补发 */
905
+ async publishIfNeeded() {
906
+ if (st.name && !st.published && me.number()) {
907
+ // 没号时起的昵称没审过:先审,违规的换成星号再发
908
+ if (st.nameOk !== st.name && !/^\*+$/.test(st.name)) { const r = await reviewProfile(st.name, ''); if (r.done && !r.name) { st.name = stars(st.name); save(); changed(); syncSelfProfile(); log('昵称没通过审核,换成了星号') } }
909
+ try { await this.setName(st.name) } catch {}
910
+ }
911
+ // 以前建的群还没有群号:我是群主就补领一个(顺带重发名片,名片里带上群号)。每次启动每个群最多试一次
912
+ for (const g of gs.groups) if (g.owner === me.pk && !g.number && !numTried.has(g.gid)) { numTried.add(g.gid); await publishCard(g).catch(() => {}) }
913
+ },
914
+ async addFriend(number, note) {
915
+ const t = await lookup(number)
916
+ if (t.self) throw new Error('这是你自己的号')
917
+ if (t.friend) throw new Error('已经是好友了')
918
+ await sendJson(t.pk, { type: 'friend.request', name: st.name, number: me.number(), note: clean(note, 200) })
919
+ st.outgoing = [...st.outgoing.filter((x) => x.pk !== t.pk), { pk: t.pk, name: t.name, number: t.number, at: Date.now() }]; save(); changed()
920
+ return t
921
+ },
922
+ acceptRequest: (pk) => acceptRequest(pk),
923
+ ignoreRequest(pk) { st.requests = st.requests.filter((x) => x.pk !== pk); save(); changed() },
924
+ // ── 动态
925
+ moments() {
926
+ const who = (pk, fallback) => (pk === 'me' ? { me: true, name: st.name || '我' } : (() => { const f = friend(pk); return { pk, friend: !!f, name: f ? f.remark || f.name || '鱼Sho号 ' + f.number : fallback || '圈里的人' } })())
927
+ return { unread: mo.unread, circles: gs.groups.filter((g) => g.circle).map((g) => ({ gid: g.gid, name: g.name })), items: [...mo.items].filter((x) => x.author === 'me' || !st.hide.includes(x.author)).sort((a, b) => b.at - a.at).map((x) => ({ id: x.id, author: who(x.author, String(x.to ?? '').startsWith('circle:') && group(x.to.slice(7)) ? nameIn(group(x.to.slice(7)), x.author) : x.authorName), mine: x.author === 'me', modNote: x.author === 'me' ? x.modNote ?? null : null, text: x.text, img: x.img ?? null, imgs: x.imgs?.length ? x.imgs : x.img ? [x.img] : [], state: x.state ?? 'sent', file: x.file ?? null, work: x.work ?? null, authorAvatar: x.author === 'me' ? st.avatar?.sha ?? null : avatarSha(x.author), recipe: x.recipe ?? null, by: x.by ?? null, to: x.to ?? 'friends', toName: String(x.to ?? '').startsWith('circle:') ? group(x.to.slice(7))?.name ?? '兴趣圈' : null, at: x.at, likes: x.likes.map((p) => who(p).name), liked: x.likes.includes('me'), comments: x.comments.map((c) => ({ id: c.id, who: c.from !== 'me' && !friend(c.from) && String(x.to ?? '').startsWith('circle:') && group(x.to.slice(7)) ? nameIn(group(x.to.slice(7)), c.from) : who(c.from).name, from: c.from === 'me' ? 'me' : c.from, mine: c.from === 'me', text: c.text, at: c.at, replyTo: c.replyTo ?? null })) })) }
928
+ },
929
+ seenMoments() { if (mo.unread) { mo.unread = 0; saveMo(); changed() } },
930
+ async postMoment(text, image, imageType, opt = {}) {
931
+ const images = [...(image ? [{ data: image, type: imageType }] : []), ...(Array.isArray(opt.images) ? opt.images : [])].slice(0, 9)
932
+ text = cleanML(text, 2000); if (!text && !images.length && !opt.file && !opt.work) throw new Error('写点什么再发')
933
+ const wait = 60_000 - (Date.now() - (st.lastPostAt ?? 0)); if (wait > 0 && !opt.again) throw new Error('一分钟只能发一条动态,' + Math.ceil(wait / 1000) + ' 秒后再发')
934
+ let to = opt.to === 'public' ? 'public' : String(opt.to ?? '').startsWith('circle:') ? opt.to : 'friends', downgraded = null
935
+ // 公开的、发到兴趣圈的:先让助理看一眼(违法、色情、暴力、骚扰、广告、隐私),不合适就只发给好友
936
+ let approved = null
937
+ if (to !== 'friends' && (text || images.length)) {
938
+ const v = await moderate({ kind: 1, created_at: Math.floor(Date.now() / 1000), tags: [['t', 'yusho'], ['name', String(st.name ?? '').slice(0, 32)], ...images.map(() => ['yimg', '?'])], content: text }, to === 'public' ? 'public' : 'circle').catch(() => null)
939
+ if (v) { if (v.verdict === 'friends') { downgraded = v.note || '这条暂时只给好友看'; to = 'friends' } else if (v.verdict === 'self') { downgraded = v.note || '这条只有你自己能看到'; to = 'self' } else if (to === 'public') approved = true }
940
+ else if (text && typeof globalThis.__shoalModerate === 'function') { try { const v2 = await globalThis.__shoalModerate(text); if (v2 && !v2.ok) { downgraded = v2.reason || '不太适合公开'; to = 'friends' } } catch {} } // 审核服务没开:App 里先简单看一眼
941
+ }
942
+ const cg = to.startsWith('circle:') ? group(to.slice(7)) : null; if (to.startsWith('circle:') && !cg?.circle) throw new Error('没有这个兴趣圈')
943
+ const refs = []; for (const im of images) refs.push(await sendImage(im.data, im.type))
944
+ const ref = refs[0] ?? null
945
+ const fl = !ref && opt.file ? await sendFileData(opt.file.data, opt.file.name, opt.file.type) : null
946
+ const ex = extrasIn(opt)
947
+ const id = rid(), at = Date.now(); st.lastPostAt = at; save()
948
+ mo.items.push({ id, author: 'me', text, img: ref ? imgInfo(ref) : null, imgs: refs.map(imgInfo), file: fl?.info ?? null, at, likes: [], comments: [], to, state: 'sending', ...ex }); saveMo(); changed()
949
+ const msg = { type: 'moment.post', id, text, name: st.name, to: to === 'public' ? 'public' : undefined, ...(cg ? { circle: cg.gid } : {}), ...(ref ? { img: ref, imgs: refs } : {}), ...(fl ? { file: fl.ref, fileName: fl.info.name } : {}), ...ex }
950
+ const targets = to === 'self' ? [] : cg ? cg.members.filter((x) => x.pk !== me.pk).map((x) => x.pk) : st.friends.map((f) => f.pk)
951
+ const r = await Promise.allSettled(targets.map((pk) => sendJson(pk, msg)))
952
+ let pub = null
953
+ if (to === 'public' && (text || refs?.length)) { try { const tmpl = { kind: 1, created_at: Math.floor(at / 1000), tags: [['t', 'yusho'], ['yusho-moment', id], ['name', String(st.name ?? '').slice(0, 32)], ...(st.avatarRef ? [['yav', JSON.stringify(st.avatarRef)]] : []), ...(refs ?? []).slice(0, 9).map((r) => ['yimg', JSON.stringify(r)])], content: text }; const v = approved ? await moderate(tmpl, 'public').catch(() => null) : null; if (v && v.verdict !== 'public') { pub = 'failed:' + (v.note || '没通过审核'); const p1 = mo.items.find((x) => x.id === id); if (p1) p1.to = v.verdict === 'self' ? 'self' : 'friends' } else pub = (await publishSigned(v?.ev ?? tmpl)).id } catch (e) { pub = 'failed:' + (e?.message ?? e) } }
954
+ const p0 = mo.items.find((x) => x.id === id); if (p0) { if (pub && !pub.startsWith('failed')) p0.pub = pub; p0.state = targets.length && !r.some((x) => x.status === 'fulfilled') ? 'failed' : 'sent'; if (downgraded) p0.modNote = downgraded; saveMo(); changed() }
955
+ return { downgraded, id, sent: r.filter((x) => x.status === 'fulfilled').length, to: targets.length, public: pub ? !pub.startsWith('failed') : null, publicError: pub?.startsWith('failed') ? pub.slice(7) : null }
956
+ },
957
+ async deleteMoment(id) {
958
+ const p = mo.items.find((x) => x.id === id && x.author === 'me'); if (!p) throw new Error('只能删自己的动态')
959
+ mo.items = mo.items.filter((x) => x !== p); saveMo(); changed()
960
+ const cg = String(p.to ?? '').startsWith('circle:') ? group(p.to.slice(7)) : null
961
+ if (p.state === 'failed' || p.state === 'sending') return { ok: true } // 没发出去的:本机删掉就行
962
+ Promise.allSettled((cg ? cg.members.filter((x) => x.pk !== me.pk).map((x) => x.pk) : st.friends.map((f) => f.pk)).map((pk) => sendJson(pk, { type: 'moment.delete', id })))
963
+ if (p.pub) publishSigned({ kind: 5, created_at: Math.floor(Date.now() / 1000), tags: [['e', p.pub]], content: '' }).catch(() => {})
964
+ return { ok: true }
965
+ },
966
+ async likeMoment(id, on) {
967
+ const p = mo.items.find((x) => x.id === id); if (!p) throw new Error('这条动态不见了')
968
+ p.likes = p.likes.filter((x) => x !== 'me'); if (on) p.likes.push('me'); saveMo(); changed()
969
+ if (p.author !== 'me') await sendJson(p.author, { type: 'moment.like', id, on: !!on })
970
+ return { ok: true }
971
+ },
972
+ async commentMoment(id, text, replyTo) {
973
+ const p = mo.items.find((x) => x.id === id); if (!p) throw new Error('这条动态不见了')
974
+ text = clean(text, 300); if (!text) throw new Error('写点什么再发')
975
+ const rt = replyTo ? clean(replyTo, 32) : null
976
+ const cid = rid(); p.comments.push({ id: cid, from: 'me', text, at: Date.now(), ...(rt ? { replyTo: rt } : {}) }); saveMo(); changed()
977
+ if (p.author !== 'me') await sendJson(p.author, { type: 'moment.comment', id, cid, text, ...(rt ? { replyTo: rt } : {}) })
978
+ return { ok: true }
979
+ },
980
+ async uncommentMoment(id, cid) {
981
+ const p = mo.items.find((x) => x.id === id); if (!p) throw new Error('这条动态不见了')
982
+ const c = p.comments.find((x) => x.id === cid); if (!c) return { ok: true }
983
+ if (c.from !== 'me' && p.author !== 'me') throw new Error('只能删自己的评论')
984
+ p.comments = p.comments.filter((x) => x !== c); saveMo(); changed()
985
+ if (c.from === 'me' && p.author !== 'me') await sendJson(p.author, { type: 'moment.uncomment', id, cid }).catch(() => {})
986
+ return { ok: true }
987
+ },
988
+ /** 不看 TA 的动态(只在自己手机上);恢复 */
989
+ hideAuthor(pk, on) { st.hide = st.hide.filter((x) => x !== pk); if (on) st.hide.push(pk); save(); changed(); return { hidden: on } },
990
+ /** 举报:先从自己这里藏起来,记一笔(以后交给服务器审核) */
991
+ /** 审核服务判定违规、全局屏蔽的动态:自己收到的同一条也藏起来 */
992
+ hideBlocked(ids) { const set = new Set(ids); const n = mo.items.length; mo.items = mo.items.filter((x) => !set.has(x.evId) && !set.has(x.id)); if (mo.items.length !== n) { saveMo(); changed() } return n - mo.items.length },
993
+ /** 举报要交给审核服务的东西:那条动态的文字和作者(在藏起来之前取) */
994
+ reportInfo(id) { const p = mo.items.find((x) => x.id === id); return p ? { target: p.evId ?? p.id, author: p.authorPk ?? (/^[0-9a-f]{64}$/.test(p.author ?? '') ? p.author : null), content: p.text ?? '' } : null },
995
+ report(id, reason) { const p = mo.items.find((x) => x.id === id); st.reports.push({ id: p ? id : null, ev: p ? null : String(id), author: p?.author ?? null, reason: clean(reason, 100), at: Date.now() }); if (p) { mo.items = mo.items.filter((x) => x !== p); saveMo() } save(); changed(); return { ok: true } },
996
+ /** 改谁能看:先从原来能看的人那里删掉,再发给新的人 */
997
+ async moveMoment(id, to) {
998
+ const p = mo.items.find((x) => x.id === id && x.author === 'me'); if (!p) throw new Error('只能改自己的动态')
999
+ const keep = { text: p.text, img: p.img, work: p.work, recipe: p.recipe, by: p.by }
1000
+ if (p.img || p.file) throw new Error('带图片或附件的动态改不了谁能看:删掉重发吧')
1001
+ await api.deleteMoment(id)
1002
+ return api.postMoment(keep.text, null, null, { to, work: keep.work, recipe: keep.recipe, by: keep.by })
1003
+ },
1004
+ /** 备注:只存在自己手机上,对方看不到 */
1005
+ setRemark(pk, remark) { const f = friend(pk); if (!f) throw new Error('不是好友'); f.remark = clean(remark, 32); save(); changed(); return { remark: f.remark } },
1006
+ removeFriend(pk) { st.friends = st.friends.filter((x) => x.pk !== pk); save(); changed() },
1007
+ /** 只看不动(不清未读):最近 n 条聊天,给有权限的助理、工作秘书看 */
1008
+ peek(kind, id, n = 30) { const file = kind === 'group' ? gFile(id) : chatFile(id); if (kind === 'group' ? !group(id) : !friend(id)) throw new Error(kind === 'group' ? '没有这个群' : '不是好友'); try { return JSON.parse(fs.readFileSync(file, 'utf8')).slice(-Math.max(1, Math.min(100, n))) } catch { return [] } },
1009
+ chat(pk) { const f = friend(pk); if (!f) throw new Error('不是好友'); if (f.unread) { f.unread = 0; save(); changed() } return { friend: { pk, name: f.name, number: f.number, muted: !!f.muted, pinned: !!f.pinned }, messages: readChat(pk).slice(-200) } },
1010
+ async sendChatImage(pk, image, type, sticker) {
1011
+ const f = friend(pk); if (!f) throw new Error('不是好友,不能发')
1012
+ const ref = await sendImage(image, type); await sendJson(pk, { type: 'image', img: ref, ...(sticker ? { sticker: true } : {}) })
1013
+ const msg = { id: rid(), from: 'me', text: sticker ? '[表情]' : '[图片]', img: imgInfo(ref), ...(sticker ? { sticker: true } : {}), at: Date.now() }
1014
+ appendChat(pk, msg); f.last = { text: '[图片]', at: msg.at, from: 'me' }; save(); changed(); return msg
1015
+ },
1016
+ mediaFile,
1017
+ mediaStatus,
1018
+ /** 自己的另一台设备来要图 / 发回下载信息(net.mjs 的 self.copy) */
1019
+ onSelfMedia(c) { if (c?.type === 'media.ask') answerMedia(null, c.shas, true).catch(() => {}); else if (c?.type === 'media.refs') takeMediaRefs(c.refs) },
1020
+ async sendChat(pk, text) {
1021
+ const f = friend(pk); if (!f) throw new Error('不是好友,不能发')
1022
+ text = clean(text, MAX_TEXT); if (!text) throw new Error('没有内容')
1023
+ const ev = await sendText(pk, text)
1024
+ const msg = { id: ev?.id ?? null, from: 'me', text, at: Date.now() }
1025
+ appendChat(pk, msg); f.last = { text, at: msg.at, from: 'me' }; save(); changed()
1026
+ return msg
1027
+ },
1028
+ /** 扫码登录电脑时交过去的:资料、好友、群、动态、鱼讯,每个对话最近 200 条 */
1029
+ exportState() {
1030
+ const chats = {}
1031
+ for (const f of fs.readdirSync(chatDir).filter((x) => /^[\w-]+\.json$/.test(x))) chats[f] = readJ(path.join(chatDir, f), []).slice(-200)
1032
+ return { st, groups: gs, moments: { ...mo, items: mo.items.slice(-100) }, notices, chats }
1033
+ },
1034
+ /** 同一个身份的另一台设备发出去的(self.copy):照着记进对话,标成“我发的”。不提醒、不叫 Agent、不再转发 */
1035
+ mirror(to, c, id, at) {
1036
+ if (c.type === 'friend.accept') { if (!friend(to)) { const r = st.requests.find((x) => x.pk === to) ?? {}; st.friends.push({ pk: to, name: r.name || '', number: r.number ?? null, added: Date.now(), unread: 0 }); st.requests = st.requests.filter((x) => x.pk !== to); save(); changed() } return }
1037
+ if (c.type === 'group.msg') {
1038
+ const g = group(String(c.gid ?? '')); if (!g) return
1039
+ const mid = String(c.mid ?? '').slice(0, 32); if (!mid || readG(g.gid).some((x) => x.id === mid)) return
1040
+ const img = c.img ? fetchImage(c.img) : null, file = img ? null : c.inline ? inlineFile(c.inline, c.fileName, c.ftype) : c.file ? fetchFile(c.file, c.fileName) : null
1041
+ const text = img ? (c.sticker ? '[表情]' : '[图片]') : file ? '[文件] ' + file.name : clean(c.text, MAX_TEXT); if (!text) return
1042
+ appendG(g.gid, { id: mid, from: 'me', text, ...(img ? { img } : {}), ...(file ? { file } : {}), ...(c.agent ? { agent: clean(c.agent, 24) } : {}), hop: Math.min(9, Number(c.hop) || 0), at })
1043
+ g.last = { text, at, from: c.agent ? clean(c.agent, 24) : '我' }; saveG(); changed(); return
1044
+ }
1045
+ const f = friend(to); if (!f) return
1046
+ if (id && readChat(to).some((x) => x.id === id)) return
1047
+ let msg = null
1048
+ if (c.type === 'text') { const text = clean(c.text, MAX_TEXT); if (text) msg = { id, from: 'me', text, at } }
1049
+ else if (c.type === 'image') { const img = fetchImage(c.img); if (img) msg = { id, from: 'me', text: c.sticker ? '[表情]' : '[图片]', img, ...(c.sticker ? { sticker: true } : {}), at } }
1050
+ else if (c.type === 'file') { const file = c.inline ? inlineFile(c.inline, c.name, c.ftype) : fetchFile(c.file, c.name); if (file) msg = { id, from: 'me', text: '[文件] ' + file.name, file, at } }
1051
+ if (!msg) return
1052
+ appendChat(to, msg); f.last = { text: msg.text, at, from: 'me' }; save(); changed()
1053
+ },
1054
+ }
1055
+ return api
1056
+ }
1057
+
1058
+ /** 扫码登录到电脑上时:把手机交来的聊天数据写进这台电脑的目录(文件名只认安全的) */
1059
+ export function writeSocialState(dir, s) {
1060
+ const chatDir = path.join(dir, 'chats'); fs.mkdirSync(chatDir, { recursive: true })
1061
+ const w = (f, v) => fs.writeFileSync(f, JSON.stringify(v))
1062
+ if (s?.st && typeof s.st === 'object') w(path.join(dir, 'social.json'), s.st)
1063
+ if (s?.groups && Array.isArray(s.groups.groups)) w(path.join(dir, 'groups.json'), s.groups)
1064
+ if (s?.moments && Array.isArray(s.moments.items)) w(path.join(dir, 'moments.json'), s.moments)
1065
+ if (s?.notices && Array.isArray(s.notices.items)) w(path.join(dir, 'notices.json'), s.notices)
1066
+ for (const [f, a] of Object.entries(s?.chats ?? {})) if (/^[\w-]{1,80}\.json$/.test(f) && Array.isArray(a)) w(path.join(chatDir, f), a)
1067
+ }