dsh-share-chat 0.37.2 → 0.40.2

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 +203 -22
  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
  ),
@@ -6015,6 +6125,19 @@ const seatAvatarEl = (s, size) => {
6015
6125
  stt.style.cssText = 'font-size:11px;color:' + (st.ready || st.bot ? '#2f8f65' : '#a184b3')
6016
6126
  info.appendChild(stt)
6017
6127
  card.appendChild(info)
6128
+ // 空位可以直接点,坐下
6129
+ if (st.empty && !(meSeat && meSeat.id)) {
6130
+ card.style.cursor = 'pointer'
6131
+ card.title = '点这里坐下'
6132
+ card.addEventListener('click', async () => {
6133
+ try {
6134
+ await api2('POST', '/api/mj/rooms/' + roomId + '/join')
6135
+ await render()
6136
+ } catch (e) {
6137
+ onToast('坐下失败:' + friendly(e))
6138
+ }
6139
+ })
6140
+ }
6018
6141
  if (st.bot && iAmOwner) {
6019
6142
  card.appendChild(
6020
6143
  btn('移除', async () => {
@@ -6033,6 +6156,23 @@ const seatAvatarEl = (s, size) => {
6033
6156
 
6034
6157
  const acts = document.createElement('div')
6035
6158
  acts.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;align-items:center'
6159
+ // 还没坐下:给一个明确的「坐下」按钮,点空位也能坐
6160
+ if (!(meSeat && meSeat.id)) {
6161
+ acts.appendChild(
6162
+ btn(
6163
+ '坐下',
6164
+ async () => {
6165
+ try {
6166
+ await api2('POST', '/api/mj/rooms/' + roomId + '/join')
6167
+ await render()
6168
+ } catch (e) {
6169
+ onToast('坐下失败:' + friendly(e))
6170
+ }
6171
+ },
6172
+ true,
6173
+ ),
6174
+ )
6175
+ }
6036
6176
  if (meSeat && meSeat.id) {
6037
6177
  acts.appendChild(
6038
6178
  btn(
@@ -6139,7 +6279,22 @@ const seatAvatarEl = (s, size) => {
6139
6279
  wrap.remove()
6140
6280
  })
6141
6281
 
6142
- renderLobby()
6282
+ // 首次渲染如果抛错,把错误写在窗口里,而不是留一个空白窗口
6283
+ Promise.resolve()
6284
+ .then(() => renderLobby())
6285
+ .catch((e) => {
6286
+ bodyEl.textContent = ''
6287
+ const box = document.createElement('div')
6288
+ box.style.cssText = 'font-size:12px;color:#c0392b;padding:12px;line-height:1.7'
6289
+ box.textContent = '麻将加载失败:' + (e && e.message ? e.message : String(e))
6290
+ const retry = document.createElement('button')
6291
+ retry.textContent = '重试'
6292
+ retry.style.cssText =
6293
+ 'display:block;margin-top:10px;padding:6px 14px;border-radius:9px;border:1.5px solid #ffd3e6;background:#fff;cursor:pointer'
6294
+ retry.addEventListener('click', () => renderLobby().catch(() => {}))
6295
+ box.appendChild(retry)
6296
+ bodyEl.appendChild(box)
6297
+ })
6143
6298
  timer = window.setInterval(tick, 1300)
6144
6299
  return { close: () => wrap.remove() }
6145
6300
  }
@@ -6165,8 +6320,22 @@ const seatAvatarEl = (s, size) => {
6165
6320
  el.style.bottom = 'auto'
6166
6321
  }
6167
6322
  const saved = readJson(SK)
6323
+ const visible = () => {
6324
+ const r = el.getBoundingClientRect()
6325
+ const vw = window.innerWidth
6326
+ const vh = window.innerHeight
6327
+ return r.right > 40 && r.left < vw - 40 && r.bottom > 40 && r.top < vh - 40
6328
+ }
6168
6329
  if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
6169
6330
  place(saved.x, saved.y)
6331
+ // 上次保存的位置如果跑到屏幕外(换显示器 / 改了缩放),回到右下角默认位
6332
+ if (!visible()) {
6333
+ el.style.left = ''
6334
+ el.style.top = ''
6335
+ el.style.right = '18px'
6336
+ el.style.bottom = '18px'
6337
+ writeJson(SK, { x: el.offsetLeft, y: el.offsetTop })
6338
+ }
6170
6339
  } else {
6171
6340
  const r = el.getBoundingClientRect()
6172
6341
  const sc = el.__scale || 1
@@ -8096,24 +8265,36 @@ const seatAvatarEl = (s, size) => {
8096
8265
  selEl.appendChild(bar)
8097
8266
  }
8098
8267
 
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
- })
8268
+ // 打开时如果服务器上的题还是旧的,就在本机补跑一次抓取,过十秒再取一次
8269
+ let refreshTried = false
8270
+ const loadToday = () =>
8271
+ api(auth.server, '/api/killer/today', { token: auth.token })
8272
+ .then((r) => {
8273
+ day = r.day || ''
8274
+ curSource = r.source || ''
8275
+ curStale = !!r.stale
8276
+ myStars = Number(r.myStars) || 0
8277
+ renderStars()
8278
+ loadShop()
8279
+ puzzles = Array.isArray(r.puzzles) ? r.puzzles : []
8280
+ if (!puzzles.length) {
8281
+ bodyEl.textContent = '今天没有题目'
8282
+ return
8283
+ }
8284
+ applyPuzzle(0, true)
8285
+ if (r.stale && !refreshTried) {
8286
+ refreshTried = true
8287
+ onToast('今天的题还没更新,正在后台抓')
8288
+ fetch('/api/share-chat/killer-refresh', { method: 'POST' })
8289
+ .then(() => setTimeout(() => loadToday().catch(() => {}), 12000))
8290
+ .catch(() => {})
8291
+ }
8292
+ })
8293
+ .catch((e) => {
8294
+ bodyEl.textContent = '题目加载失败:' + friendly(e)
8295
+ })
8296
+
8297
+ loadToday()
8117
8298
  }
8118
8299
  function SocialView(props) {
8119
8300
  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.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "keywords": [