dsh-share-chat 0.37.2 → 0.40.0

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 (3) hide show
  1. package/client.js +143 -21
  2. package/index.js +103 -0
  3. package/package.json +1 -1
package/client.js CHANGED
@@ -17,7 +17,7 @@ window.__ModuleLoader__.load({
17
17
  const K_SERVER = 'dsh-share-chat.server'
18
18
  const K_DEV = 'dsh-share-chat.dev'
19
19
  const DEFAULT_SERVER = 'https://xdxy-pet.com/relay'
20
- const POLL_MS = 5000
20
+ const POLL_MS = 1500
21
21
  /** 内嵌小游戏(微信小游戏的浏览器移植版,和 /api/fish/ 同源) */
22
22
  const GAME_URL = 'https://xdxy-pet.com/game/'
23
23
 
@@ -286,6 +286,10 @@ window.__ModuleLoader__.load({
286
286
 
287
287
  .sc-avatar{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;font-weight:600;color:#fff;user-select:none;overflow:hidden}
288
288
  .sc-chip{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 8px;border-radius:99px;background:rgba(127,127,127,.18);color:var(--dsw-alias-label-secondary,#5b6570);font-size:11px;white-space:nowrap}
289
+ .sc-unread{flex:0 0 auto;min-width:18px;height:18px;padding:0 5px;border-radius:99px;background:#e8434f;color:#fff;font-size:11px;font-weight:600;line-height:18px;text-align:center}
290
+ .sc-update-bar{display:flex;align-items:center;gap:8px;padding:7px 12px;background:#fff6e8;border-bottom:1px solid #f0e0c8;color:#8a5b1f;font-size:12px;flex:0 0 auto}
291
+ .sc-update-bar code{font:600 11.5px ui-monospace,monospace;background:rgba(138,91,31,.10);padding:2px 6px;border-radius:5px}
292
+ .sc-update-x{margin-left:auto;border:none;background:transparent;color:#b08a52;cursor:pointer;font-size:12px;padding:2px 4px}
289
293
  .sc-err{color:var(--dsw-alias-label-error,#d9534f);font-size:12px}
290
294
 
291
295
  /* 登录 */
@@ -891,6 +895,10 @@ window.__ModuleLoader__.load({
891
895
  const [hiddenChats, setHiddenChats] = useState([])
892
896
  const [sideTab, setSideTab] = useState('chats')
893
897
  const [myAvatar, setMyAvatar] = useState('')
898
+ // 未读:会话 key → 条数。清空条件是这个会话被打开
899
+ const [unread, setUnread] = useState({})
900
+ // 有新版本时这里放 { current, latest },点掉后当天不再提示
901
+ const [updateInfo, setUpdateInfo] = useState(null)
894
902
  // Electron 里 window.prompt 不可用,所有需要输入的地方都走这个内联框
895
903
  const [inline, setInline] = useState(null)
896
904
  const [askMode, setAskMode] = useState(() => readJson('dsh-share-chat.ask') === true)
@@ -971,12 +979,72 @@ window.__ModuleLoader__.load({
971
979
  if (r.messages && r.messages.length) {
972
980
  cursorRef.current = r.cursor
973
981
  setMessages((prev) => prev.concat(r.messages))
982
+ noteUnread(r.messages)
974
983
  }
975
984
  }
976
985
 
977
- // 5 秒轮询:消息 + 好友列表(对方加了你这边才看得见)
986
+ /** 新消息里别人发的、且不在当前会话 → 记未读,并弹一条提示 */
987
+ const noteUnread = (batch) => {
988
+ const add = {}
989
+ let latest = null
990
+ for (const m of batch) {
991
+ if (!m || m.from === auth.id) continue
992
+ const key = String(m.to || '').indexOf('g:') === 0 ? m.to : m.from
993
+ if (!key) continue
994
+ if (key === activeRef.current) continue
995
+ add[key] = (add[key] || 0) + 1
996
+ latest = m
997
+ }
998
+ if (!Object.keys(add).length) return
999
+ setUnread((prev) => {
1000
+ const next = Object.assign({}, prev)
1001
+ for (const k of Object.keys(add)) next[k] = (next[k] || 0) + add[k]
1002
+ return next
1003
+ })
1004
+ if (latest && typeof props.onToast === 'function') {
1005
+ const who = (latest.from || '').toString()
1006
+ const b = latest.body || {}
1007
+ const txt =
1008
+ b.kind === 'image' ? '🖼 图片' : b.kind === 'file' ? '📎 ' + (b.name || '文件') : String(b.text || '').slice(0, 24)
1009
+ props.onToast(who + ':' + txt)
1010
+ }
1011
+ }
1012
+
1013
+ // 打开某个会话就把它的未读清掉
1014
+ useEffect(() => {
1015
+ if (!active) return
1016
+ setUnread((prev) => {
1017
+ if (!prev[active]) return prev
1018
+ const next = Object.assign({}, prev)
1019
+ delete next[active]
1020
+ return next
1021
+ })
1022
+ }, [active])
1023
+
1024
+ // 查一次版本:有新版本就顶一条提示,点掉后当天不再出现
978
1025
  useEffect(() => {
979
1026
  let alive = true
1027
+ const TODAY = new Date().toISOString().slice(0, 10)
1028
+ ;(async () => {
1029
+ try {
1030
+ const r = await fetch('/api/share-chat/version').then((x) => x.json())
1031
+ if (!alive || !r || !r.behind) return
1032
+ const dismissed = window.localStorage.getItem('dsh-share-chat.updateDismissed')
1033
+ if (dismissed === TODAY) return
1034
+ setUpdateInfo({ current: r.current, latest: r.latest })
1035
+ } catch (e) {
1036
+ /* 查不到就算了 */
1037
+ }
1038
+ })()
1039
+ return () => {
1040
+ alive = false
1041
+ }
1042
+ }, [])
1043
+
1044
+ // 1.5 秒轮询消息;好友列表每 4 拍(6 秒)才拉一次,省请求
1045
+ useEffect(() => {
1046
+ let alive = true
1047
+ let beat = 0
980
1048
  const tick = async () => {
981
1049
  try {
982
1050
  const r = await api(auth.server, '/api/messages?since=' + cursorRef.current, {
@@ -986,10 +1054,12 @@ window.__ModuleLoader__.load({
986
1054
  if (r.messages && r.messages.length) {
987
1055
  cursorRef.current = r.cursor
988
1056
  setMessages((prev) => prev.concat(r.messages))
1057
+ noteUnread(r.messages)
989
1058
  }
990
1059
  } catch (e) {
991
1060
  /* 消息拉取失败不打扰用户,下次再来 */
992
1061
  }
1062
+ if (beat++ % 4 !== 0) return
993
1063
  try {
994
1064
  const f = await api(auth.server, '/api/friends', { token: auth.token })
995
1065
  if (!alive) return
@@ -1501,6 +1571,9 @@ window.__ModuleLoader__.load({
1501
1571
 
1502
1572
  const thread = messages.filter((m) => m.from === active || m.to === active)
1503
1573
 
1574
+ /** 全部未读总数,顶栏按这个显示 */
1575
+ const totalUnread = Object.keys(unread).reduce((a, k) => a + (unread[k] || 0), 0)
1576
+
1504
1577
  /** 正在上传 / 上传失败的附件,先占位显示,避免「点了没反应」 */
1505
1578
  const renderPending = (p) => {
1506
1579
  const failed = p.status === 'failed'
@@ -1654,6 +1727,33 @@ window.__ModuleLoader__.load({
1654
1727
  return h(
1655
1728
  'div',
1656
1729
  { className: 'sc-chat', ref: chatRef },
1730
+ updateInfo
1731
+ ? h(
1732
+ 'div',
1733
+ { className: 'sc-update-bar' },
1734
+ h(
1735
+ 'span',
1736
+ null,
1737
+ '有新版本 ' + updateInfo.latest + '(当前 ' + updateInfo.current + ')· 更新:',
1738
+ h('code', { style: { marginLeft: '2px' } }, 'dsh plugin --profile web add dsh-share-chat'),
1739
+ ),
1740
+ h(
1741
+ 'button',
1742
+ {
1743
+ className: 'sc-update-x',
1744
+ title: '今天不再提示',
1745
+ onClick: () => {
1746
+ window.localStorage.setItem(
1747
+ 'dsh-share-chat.updateDismissed',
1748
+ new Date().toISOString().slice(0, 10),
1749
+ )
1750
+ setUpdateInfo(null)
1751
+ },
1752
+ },
1753
+ '✕',
1754
+ ),
1755
+ )
1756
+ : null,
1657
1757
  /* 顶栏 */
1658
1758
  h(
1659
1759
  'div',
@@ -1683,7 +1783,7 @@ window.__ModuleLoader__.load({
1683
1783
  onClick: () => setSideTab('chats'),
1684
1784
  title: '会话列表',
1685
1785
  },
1686
- '💬 会话',
1786
+ '💬 会话' + (totalUnread ? ' ' + (totalUnread > 99 ? '99+' : totalUnread) : ''),
1687
1787
  ),
1688
1788
  h(
1689
1789
  'button',
@@ -1877,6 +1977,16 @@ window.__ModuleLoader__.load({
1877
1977
  ),
1878
1978
  h('div', { className: 'sc-friend-last' }, previewOf(lastOf(c.key)) || '还没有消息'),
1879
1979
  ),
1980
+ unread[c.key]
1981
+ ? h(
1982
+ 'span',
1983
+ {
1984
+ className: 'sc-unread',
1985
+ title: unread[c.key] + ' 条未读',
1986
+ },
1987
+ unread[c.key] > 99 ? '99+' : String(unread[c.key]),
1988
+ )
1989
+ : null,
1880
1990
  ),
1881
1991
  ),
1882
1992
  ),
@@ -8096,24 +8206,36 @@ const seatAvatarEl = (s, size) => {
8096
8206
  selEl.appendChild(bar)
8097
8207
  }
8098
8208
 
8099
- api(auth.server, '/api/killer/today', { token: auth.token })
8100
- .then((r) => {
8101
- day = r.day || ''
8102
- curSource = r.source || ''
8103
- curStale = !!r.stale
8104
- myStars = Number(r.myStars) || 0
8105
- renderStars()
8106
- loadShop()
8107
- puzzles = Array.isArray(r.puzzles) ? r.puzzles : []
8108
- if (!puzzles.length) {
8109
- bodyEl.textContent = '今天没有题目'
8110
- return
8111
- }
8112
- applyPuzzle(0, true)
8113
- })
8114
- .catch((e) => {
8115
- bodyEl.textContent = '题目加载失败:' + friendly(e)
8116
- })
8209
+ // 打开时如果服务器上的题还是旧的,就在本机补跑一次抓取,过十秒再取一次
8210
+ let refreshTried = false
8211
+ const loadToday = () =>
8212
+ api(auth.server, '/api/killer/today', { token: auth.token })
8213
+ .then((r) => {
8214
+ day = r.day || ''
8215
+ curSource = r.source || ''
8216
+ curStale = !!r.stale
8217
+ myStars = Number(r.myStars) || 0
8218
+ renderStars()
8219
+ loadShop()
8220
+ puzzles = Array.isArray(r.puzzles) ? r.puzzles : []
8221
+ if (!puzzles.length) {
8222
+ bodyEl.textContent = '今天没有题目'
8223
+ return
8224
+ }
8225
+ applyPuzzle(0, true)
8226
+ if (r.stale && !refreshTried) {
8227
+ refreshTried = true
8228
+ onToast('今天的题还没更新,正在后台抓')
8229
+ fetch('/api/share-chat/killer-refresh', { method: 'POST' })
8230
+ .then(() => setTimeout(() => loadToday().catch(() => {}), 12000))
8231
+ .catch(() => {})
8232
+ }
8233
+ })
8234
+ .catch((e) => {
8235
+ bodyEl.textContent = '题目加载失败:' + friendly(e)
8236
+ })
8237
+
8238
+ loadToday()
8117
8239
  }
8118
8240
  function SocialView(props) {
8119
8241
  const [auth, setAuth] = useState(() => readJson(K_AUTH))
package/index.js CHANGED
@@ -13,9 +13,39 @@
13
13
  */
14
14
 
15
15
  import { randomBytes } from 'node:crypto'
16
+ import { existsSync, readFileSync } from 'node:fs'
17
+ import { spawn } from 'node:child_process'
16
18
 
17
19
  const PREFIX = '/api/share-chat'
18
20
 
21
+ /** 每日数独抓取脚本的位置;可用 DSH_KILLER_UPDATER 覆盖 */
22
+ const KILLER_UPDATER =
23
+ process.env.DSH_KILLER_UPDATER ||
24
+ 'D:\\HuaweiMoveData\\Users\\zhanghao\\Documents\\deepseek-harness\\default-workspace\\tools\\dks-daily-http.mjs'
25
+
26
+ /** 读自己的版本号,用来和 npm 上的最新版比对 */
27
+ let OWN_VERSION = ''
28
+ try {
29
+ const here = new URL('.', import.meta.url)
30
+ const pkgUrl = new URL('package.json', here)
31
+ OWN_VERSION = JSON.parse(readFileSync(pkgUrl, 'utf8')).version || ''
32
+ } catch {
33
+ OWN_VERSION = ''
34
+ }
35
+
36
+ /** 版本号比较:a 比 b 新返回 1,旧返回 -1,相同返回 0 */
37
+ function compareVersion(a, b) {
38
+ const pa = String(a).split('.').map((x) => parseInt(x, 10) || 0)
39
+ const pb = String(b).split('.').map((x) => parseInt(x, 10) || 0)
40
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
41
+ const x = pa[i] || 0
42
+ const y = pb[i] || 0
43
+ if (x > y) return 1
44
+ if (x < y) return -1
45
+ }
46
+ return 0
47
+ }
48
+
19
49
  function json(status, body) {
20
50
  return new Response(JSON.stringify(body), {
21
51
  status,
@@ -48,6 +78,79 @@ function pickTitle(snap) {
48
78
  }
49
79
 
50
80
  export function apply(ctx) {
81
+ // ── 版本检查:告诉前端 npm 上有没有更新的版本 ──
82
+ let versionCache = { at: 0, latest: '' }
83
+ ctx.inject(['webServer'], (scope) => {
84
+ scope.effect(() =>
85
+ scope.webServer.register({
86
+ path: PREFIX + '/version',
87
+ kind: 'exact',
88
+ resource: async () => {
89
+ const now = Date.now()
90
+ if (!versionCache.latest || now - versionCache.at > 3600000) {
91
+ try {
92
+ const r = await fetch('https://registry.npmjs.org/dsh-share-chat/latest', {
93
+ headers: { accept: 'application/json' },
94
+ })
95
+ if (r.ok) {
96
+ const j = await r.json()
97
+ versionCache = { at: now, latest: String(j.version || '') }
98
+ }
99
+ } catch {
100
+ /* 查不到就算了,不影响使用 */
101
+ }
102
+ }
103
+ const latest = versionCache.latest
104
+ return json(200, {
105
+ current: OWN_VERSION,
106
+ latest,
107
+ behind: latest ? compareVersion(latest, OWN_VERSION) > 0 : false,
108
+ })
109
+ },
110
+ }),
111
+ )
112
+ })
113
+
114
+ // ── 数独每日补跑 ──
115
+ // 打开数独时如果发现当天还没抓题,就在本机后台跑一次抓取脚本。
116
+ // 计划任务要用户登录才跑,这条兜底;只在 loopback 开放。
117
+ let lastRefresh = 0
118
+ ctx.inject(['webServer'], (scope) => {
119
+ scope.effect(() =>
120
+ scope.webServer.register({
121
+ path: PREFIX + '/killer-refresh',
122
+ kind: 'exact',
123
+ handler: (req, res) => {
124
+ const done = (status, body) => {
125
+ res.writeHead(status, {
126
+ 'content-type': 'application/json; charset=utf-8',
127
+ 'cache-control': 'no-store',
128
+ })
129
+ res.end(JSON.stringify(body))
130
+ }
131
+ if (!isLoopbackOrigin(scope)) return done(403, { error: 'not-loopback' })
132
+ if (req.method !== 'POST') return done(405, { error: 'method' })
133
+ // 一分钟内只跑一次,避免反复开窗口刷脚本
134
+ const now = Date.now()
135
+ if (now - lastRefresh < 60000) return done(200, { ok: false, reason: 'throttled' })
136
+ if (!existsSync(KILLER_UPDATER)) return done(200, { ok: false, reason: 'no-script' })
137
+ lastRefresh = now
138
+ try {
139
+ const child = spawn(process.execPath, [KILLER_UPDATER, '--deploy'], {
140
+ detached: true,
141
+ stdio: 'ignore',
142
+ windowsHide: true,
143
+ })
144
+ child.unref()
145
+ return done(200, { ok: true, started: true })
146
+ } catch (e) {
147
+ return done(200, { ok: false, reason: String(e && e.message).slice(0, 120) })
148
+ }
149
+ },
150
+ }),
151
+ )
152
+ })
153
+
51
154
  // ── 问模型:走 DSH 自己的 LLM 服务(消耗当前账号额度)──
52
155
  // 只在 loopback 下开放,公用部署直接 403。
53
156
  ctx.inject(['webServer', 'llm'], (scope) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-share-chat",
3
- "version": "0.37.2",
3
+ "version": "0.40.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "keywords": [