dsh-reminder-notify 0.16.0 → 0.17.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.
package/README.md CHANGED
@@ -13,6 +13,15 @@ dsh plugin --profile desktop add link:<本目录绝对路径>
13
13
 
14
14
  装完新会话就有 `notify_user`。
15
15
 
16
+ ## 0.17 起多了什么
17
+
18
+ - **定时提醒**:`notify_user` 支持 `at: "22:00"`(今天已过就排到明天)或 `inMinutes: 25`,到点才弹,不进队列占位。
19
+ - **优先级**:`decide` 卡永远排在 `done`/`raw` 前面;`maxHoldSeconds` 可给任何卡设「最多挂多久」。
20
+ - **卡片上的链接**:传 `url` 会在卡上加「打开链接」按钮;键盘 `Enter` 知道了、`S` 稍后提醒、`Esc` 关掉。
21
+ - **历史导出**:面板「历史与统计」多了「导出 CSV / 导出 JSON」,文件落在桌面,统计里同时给近 30 天。
22
+ - **更多推送格式**:除企业微信/Server酱/JSON/纯文本,还支持 Telegram(填 chat_id)、飞书、钉钉。
23
+ - **服务契约第 2 版**:`ctx.get('reminder')` 现在带 `apiVersion`、`events()`(最近 20 条 shown/notified)和 `registerSource()`,别的插件也能挂自己的提醒来源。
24
+
16
25
  ## 用
17
26
 
18
27
  | 场景 | 调用 |
@@ -102,6 +111,19 @@ reminder.config() // 当前生效配置的只读副
102
111
 
103
112
  ## 出问题先自检(0.16 起)
104
113
 
114
+ 面板「高级:历史、余额与宿主」里的「工程与可靠性:自检」有三个按钮:**运行自检**(逐项打勾)、**弹样卡**、**测 GitHub**。
115
+ 其中「GitHub 连通性」一项会在 hosts 里发现「把 github.com 指到 127.0.0.1」的本机重定向时标红——那是 Steam++(Watt Toolkit)
116
+ 加速 GitHub 的做法:加速器在跑时正常,它没接管(只开了进程没点「一键加速」/被强杀)时浏览器和 git 都会连不上。
117
+
118
+ 推送时如果遇到这种情况,直接跑:
119
+
120
+ ```powershell
121
+ powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx
122
+ ```
123
+
124
+ 它会先测通不通;不通且发现本机重定向就临时注释 + 刷 DNS 再测,通了才 push,结束再按原样还原 hosts(`-KeepChanges` 保留改动、`-DryRun` 只探测不推送)。
125
+
126
+
105
127
  设置面板最下面的「工程与可靠性:自检」里有两个按钮:
106
128
 
107
129
  - **运行自检**:逐条检查系统 / PowerShell / 宿主脚本 / 提示音目录与文件 / 历史文件可写 / 面板路由 / `notify_user` / 配置可写 / 余额接口 / 宿主服务 API / 最近一次宿主退出码,✗ 会带上具体路径或原因。
package/client.js CHANGED
@@ -23,6 +23,7 @@ window.__ModuleLoader__.load({
23
23
  // 0.11 新增:提醒历史(GET 拿统计+最近记录,POST { mode: 'clear' } 清空)。
24
24
  const HISTORY_ROUTE = '/dsh-reminder-notify/history'
25
25
  const DOCTOR_ROUTE = '/dsh-reminder-notify/doctor'
26
+ const EXPORT_ROUTE = '/dsh-reminder-notify/export'
26
27
  const DIGEST_ROUTE = '/dsh-reminder-notify/digest'
27
28
  // 下拉按扩展名分组:wav 一组、mp3 一组……组内按文件名排序,一眼能看出格式。
28
29
  function groupAudioFiles(files) {
@@ -276,6 +277,10 @@ window.__ModuleLoader__.load({
276
277
  doctorProbe: '弹样卡',
277
278
  doctorProbeOk: '样卡已弹出,能看到就说明宿主正常。',
278
279
  doctorProbeFailed: '自检失败:',
280
+ doctorGithub: '测 GitHub',
281
+ doctorGithubOk: 'GitHub 能连上:HTTP ',
282
+ doctorGithubFailed: 'GitHub 连不上:',
283
+ check_github: 'GitHub 连通性',
279
284
  doctorLastExit: '最近退出码',
280
285
  doctorFailures: '最近失败次数',
281
286
  check_platform: '系统',
@@ -303,6 +308,18 @@ window.__ModuleLoader__.load({
303
308
  quietModeHold: '留到结束后补弹',
304
309
  quietModeSkip: '直接跳过',
305
310
  pushFormatWecom: '企业微信机器人',
311
+ pushFormatTelegram: 'Telegram',
312
+ pushFormatFeishu: '飞书',
313
+ pushFormatDingtalk: '钉钉',
314
+ pushChat: '会话 ID(telegram)',
315
+ pushChatHint: 'telegram 机器人要填 chat_id;其它格式留空即可。',
316
+ maxHoldSeconds: '单卡最长停留(秒)',
317
+ maxHoldSecondsHint: '0 = 不额外限制(最多 600 秒);填 30 就是任何卡最多挂 30 秒。',
318
+ exportCsv: '导出 CSV',
319
+ exportJson: '导出 JSON',
320
+ exportDone: '已导出到桌面:',
321
+ exportFailed: '导出失败:',
322
+ last30: '近 30 天:',
306
323
  pushFormatServerchan: 'Server 酱',
307
324
  pushFormatJson: '通用 JSON',
308
325
  pushFormatText: '纯文本',
@@ -412,6 +429,10 @@ window.__ModuleLoader__.load({
412
429
  doctorProbe: 'Probe a card',
413
430
  doctorProbeOk: 'A probe card is on screen; if you can see it, the host is fine.',
414
431
  doctorProbeFailed: 'Self-check failed: ',
432
+ doctorGithub: 'Test GitHub',
433
+ doctorGithubOk: 'GitHub reachable: HTTP ',
434
+ doctorGithubFailed: 'GitHub unreachable: ',
435
+ check_github: 'GitHub reachability',
415
436
  doctorLastExit: 'last exit code',
416
437
  doctorFailures: 'recent failures',
417
438
  check_platform: 'platform',
@@ -439,6 +460,18 @@ window.__ModuleLoader__.load({
439
460
  quietModeHold: 'Hold until it ends',
440
461
  quietModeSkip: 'Skip it',
441
462
  pushFormatWecom: 'WeCom bot',
463
+ pushFormatTelegram: 'Telegram',
464
+ pushFormatFeishu: 'Feishu',
465
+ pushFormatDingtalk: 'DingTalk',
466
+ pushChat: 'Chat ID (Telegram)',
467
+ pushChatHint: 'Telegram bots need a chat_id; leave empty for other formats.',
468
+ maxHoldSeconds: 'Max card lifetime (s)',
469
+ maxHoldSecondsHint: '0 = no extra cap (600 s max); 30 means no card stays longer than 30 s.',
470
+ exportCsv: 'Export CSV',
471
+ exportJson: 'Export JSON',
472
+ exportDone: 'Exported to Desktop: ',
473
+ exportFailed: 'Export failed: ',
474
+ last30: 'Last 30 days: ',
442
475
  pushFormatServerchan: 'ServerChan',
443
476
  pushFormatJson: 'Generic JSON',
444
477
  pushFormatText: 'Plain text',
@@ -601,6 +634,7 @@ window.__ModuleLoader__.load({
601
634
  { key: 'queueEnabled', group: 'queue', kind: 'boolean' },
602
635
  { key: 'queueMax', group: 'queue', kind: 'number' },
603
636
  { key: 'mergeWindowMs', group: 'queue', kind: 'number' },
637
+ { key: 'maxHoldSeconds', group: 'queue', kind: 'number' },
604
638
  { key: 'quietEnabled', group: 'queue', kind: 'boolean' },
605
639
  { key: 'quietStart', group: 'queue', kind: 'text' },
606
640
  { key: 'quietEnd', group: 'queue', kind: 'text' },
@@ -616,7 +650,8 @@ window.__ModuleLoader__.load({
616
650
  { key: 'digestAlertCount', group: 'digest', kind: 'number' },
617
651
  { key: 'pushEnabled', group: 'digest', kind: 'boolean' },
618
652
  { key: 'pushUrl', group: 'digest', kind: 'text' },
619
- { key: 'pushFormat', group: 'digest', kind: 'select', options: ['wecom', 'serverchan', 'json', 'text'], optionLabels: ['pushFormatWecom', 'pushFormatServerchan', 'pushFormatJson', 'pushFormatText'] },
653
+ { key: 'pushFormat', group: 'digest', kind: 'select', options: ['wecom', 'serverchan', 'telegram', 'feishu', 'dingtalk', 'json', 'text'], optionLabels: ['pushFormatWecom', 'pushFormatServerchan', 'pushFormatTelegram', 'pushFormatFeishu', 'pushFormatDingtalk', 'pushFormatJson', 'pushFormatText'] },
654
+ { key: 'pushChat', group: 'digest', kind: 'text' },
620
655
  { key: 'pushDecide', group: 'digest', kind: 'boolean' },
621
656
  { key: 'pushDigest', group: 'digest', kind: 'boolean' },
622
657
  { key: 'hostMode', group: 'host', kind: 'select', options: ['script', 'exe'], optionLabels: ['hostModeScript', 'hostModeExe'] },
@@ -629,6 +664,8 @@ window.__ModuleLoader__.load({
629
664
  seconds: 'secondsHint',
630
665
  sound: 'soundHint',
631
666
  cooldownMs: 'cooldownHint',
667
+ pushChat: 'pushChatHint',
668
+ maxHoldSeconds: 'maxHoldSecondsHint',
632
669
  retryHostOnce: 'retryHostOnceHint',
633
670
  doneAudio: 'audioHint',
634
671
  audioDir: 'audioDirHint',
@@ -943,11 +980,11 @@ window.__ModuleLoader__.load({
943
980
  setMessage(null)
944
981
  Promise.resolve()
945
982
  .then(() => {
946
- const init = mode === 'probe'
983
+ const init = mode === 'probe' || mode === 'github'
947
984
  ? {
948
985
  method: 'POST',
949
986
  headers: { 'content-type': 'application/json', accept: 'application/json' },
950
- body: JSON.stringify({ mode: 'probe' }),
987
+ body: JSON.stringify({ mode }),
951
988
  }
952
989
  : { headers: { accept: 'application/json' } }
953
990
  return fetch(DOCTOR_ROUTE, init)
@@ -967,6 +1004,15 @@ window.__ModuleLoader__.load({
967
1004
  setDoctorBusy(false)
968
1005
  if (data && data.report) setDoctor(data.report)
969
1006
  const label = typeof t === 'function' ? t : (key) => key
1007
+ if (mode === 'github') {
1008
+ const probe = data && data.github ? data.github : {}
1009
+ if (probe.ok === true) {
1010
+ setMessage({ ok: true, text: label('doctorGithubOk') + String(probe.statusCode || '') + ' · ' + String(probe.ms || 0) + 'ms' })
1011
+ } else {
1012
+ setMessage({ ok: false, text: label('doctorGithubFailed') + String(probe.error || ('HTTP ' + (probe.statusCode || 0))) })
1013
+ }
1014
+ return
1015
+ }
970
1016
  if (mode === 'probe') {
971
1017
  const card = data && data.card ? data.card : {}
972
1018
  if (card.ok === false) {
@@ -1193,6 +1239,21 @@ window.__ModuleLoader__.load({
1193
1239
  historyFetch({ method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ mode: 'clear' }) })
1194
1240
  }
1195
1241
 
1242
+ async function runExport(format) {
1243
+ const label = typeof t === 'function' ? t : (key) => key
1244
+ try {
1245
+ const response = await fetch(`${EXPORT_ROUTE}?format=${format}&days=30`)
1246
+ const data = await response.json()
1247
+ if (data && data.ok === true) {
1248
+ setMessage(`${label('exportDone')}${data.file}(${data.count} 条)`)
1249
+ } else {
1250
+ setMessage(`${label('exportFailed')}${(data && (data.detail || data.error)) || ''}`)
1251
+ }
1252
+ } catch (error) {
1253
+ setMessage(`${label('exportFailed')}${String(error && error.message ? error.message : error)}`)
1254
+ }
1255
+ }
1256
+
1196
1257
  function historyText() {
1197
1258
  const label = typeof t === 'function' ? t : (key) => key
1198
1259
  if (history === null) return label('historyLoading')
@@ -1357,6 +1418,16 @@ window.__ModuleLoader__.load({
1357
1418
  { type: 'button', className: 'drn-btn small', disabled: historyBusy, onClick: clearHistory },
1358
1419
  label('historyClear'),
1359
1420
  ),
1421
+ h(
1422
+ 'button',
1423
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: historyBusy, onClick: () => runExport('csv') },
1424
+ label('exportCsv'),
1425
+ ),
1426
+ h(
1427
+ 'button',
1428
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: historyBusy, onClick: () => runExport('json') },
1429
+ label('exportJson'),
1430
+ ),
1360
1431
  ),
1361
1432
  ),
1362
1433
  )
@@ -1505,6 +1576,11 @@ window.__ModuleLoader__.load({
1505
1576
  { type: 'button', className: 'drn-btn drn-digest-btn', disabled: doctorBusy, onClick: () => runDoctor('probe') },
1506
1577
  label('doctorProbe'),
1507
1578
  ),
1579
+ h(
1580
+ 'button',
1581
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: doctorBusy, onClick: () => runDoctor('github') },
1582
+ label(doctorBusy ? 'doctorRunning' : 'doctorGithub'),
1583
+ ),
1508
1584
  ),
1509
1585
  ),
1510
1586
  ]
package/cordis.patch.yml CHANGED
@@ -94,4 +94,6 @@
94
94
  pushDecide: true
95
95
  # 日报同时推到手机
96
96
  pushDigest: true
97
+ pushChat: ""
98
+ maxHoldSeconds: 0
97
99
  retryHostOnce: true
package/docs/PUBLISH.md CHANGED
@@ -12,7 +12,7 @@ DSH 的「插件市场 → 发现」页读的是**索引 URL**:一份 JSON(
12
12
  | 索引地址(他人添加这个) | `https://jiangshuaiye1203.github.io/dsh-reminder-notify/publish/index.json` |
13
13
  | 站点首页 | https://jiangshuaiye1203.github.io/dsh-reminder-notify/ |
14
14
  | npm 包 | https://www.npmjs.com/package/dsh-reminder-notify |
15
- | 当前版本 | **0.15.0**,装源为 **npm**(`dsh-reminder-notify@0.15.0`),不再是 git 固定提交 |
15
+ | 当前版本 | **0.17.0**,装源为 **npm**(`dsh-reminder-notify@0.17.0`),不再是 git 固定提交 |
16
16
  | Pages | Deploy from a branch,`main` / `(root)` |
17
17
 
18
18
  发新版(npm 源):改代码 → 升 `package.json` 版本 → `scripts\publish-npm.cmd` 发布到 npm →
package/docs/detail.en.md CHANGED
@@ -11,3 +11,5 @@ Cards are drawn by the bundled `host/ReminderHost.ps1` with the built-in PowerSh
11
11
  - **Want it on your phone**: open push under "Digest & push", pick the format, paste your own webhook URL (WeCom bot or Server Chan), then press "Send one now".
12
12
  - **Everything else**: folded into "How it works (expand to read)" inside the settings panel below, one topic at a time.
13
13
  - **For other plugins**: this plugin exposes a `reminder` service (`notify` / `digest` / `stats` / `config`); see the README.
14
+ - The self-check now has a **GitHub reachability** item (it flags hosts entries pointing github.com at 127.0.0.1, i.e. the Steam++ acceleration table) plus a **Test GitHub** button; `scripts/github-push.ps1` repairs that state around a push and restores hosts afterwards.
15
+ - 0.17 adds scheduled reminders (`at` / `inMinutes`), `decide` priority, a max card lifetime, an "Open link" button with Enter/S/Esc shortcuts, CSV/JSON history export, Telegram/Feishu/DingTalk push formats, and service contract v2.
package/docs/detail.zh.md CHANGED
@@ -11,3 +11,5 @@
11
11
  - **想推到手机**:在「日报与推送」里打开推送、选格式、填自己的 webhook 地址(企业微信机器人或 Server 酱),点「现在发一条」验证。
12
12
  - **其余说明**:全部收在下面设置面板的「使用说明(点开才看)」里,一次只展开一条。
13
13
  - **给别的插件用**:本插件对外提供 `reminder` 服务(`notify` / `digest` / `stats` / `config`),写法见 README。
14
+ - 自检里新增「GitHub 连通性」:hosts 里有指向 127.0.0.1 的 github 行(Steam++ 加速表)时标红,另有「测 GitHub」按钮现测一次;推送用 `scripts/github-push.ps1` 可自动处理并还原。
15
+ - 0.17 新增:定时提醒(`at` / `inMinutes`)、`decide` 优先、单卡最长停留、卡上「打开链接」按钮与 Enter/S/Esc 快捷键、历史导出 CSV/JSON、Telegram/飞书/钉钉推送格式、服务契约第 2 版。
@@ -35,7 +35,8 @@ param(
35
35
  [string]$Speak = '',
36
36
  [string]$ResultPath = '',
37
37
  [int]$SnoozeMinutes = 10,
38
- [switch]$NoButtons,
38
+ [switch]$NoButtons,
39
+ [string]$OpenUrl = '',
39
40
  [switch]$Compact,
40
41
  [switch]$AutoCompact,
41
42
  [int]$QueueLeft = 0,
@@ -238,7 +239,12 @@ if ($showButtons) {
238
239
  $snoozeRect = New-Object System.Drawing.Rectangle ($btnRight - $snoozeWidth), $btnTop, $snoozeWidth, $buttonHeight
239
240
  $okRect = New-Object System.Drawing.Rectangle ($snoozeRect.Left - $buttonGap - $okWidth), $btnTop, $okWidth, $buttonHeight
240
241
  $script:btnRects['snooze'] = $snoozeRect
241
- $script:btnRects['ok'] = $okRect
242
+ $script:btnRects['ok'] = $okRect
243
+ if ($OpenUrl -ne '') {
244
+ $openWidth = 78
245
+ $openRect = New-Object System.Drawing.Rectangle ($okRect.Left - $buttonGap - $openWidth), $btnTop, $openWidth, $buttonHeight
246
+ $script:btnRects['open'] = $openRect
247
+ }
242
248
  }
243
249
 
244
250
  # ---- 定位:光标所在屏幕的工作区 ---------------------------------------------
@@ -340,7 +346,7 @@ $form.Add_Paint({
340
346
 
341
347
  # 按钮
342
348
  if ($showButtons) {
343
- foreach ($key in @('ok', 'snooze')) {
349
+ foreach ($key in @('open', 'ok', 'snooze')) {
344
350
  $rect = $script:btnRects[$key]
345
351
  if ($rect -eq $null) { continue }
346
352
  $fill = if ($script:hover -eq $key) { $btnHoverColor } else { $btnColor }
@@ -355,7 +361,7 @@ $form.Add_Paint({
355
361
  $g.FillPath($btnBrush, $btnPath)
356
362
  $btnBrush.Dispose()
357
363
  $btnPath.Dispose()
358
- $label = if ($key -eq 'ok') { $okText } else { $snoozeText }
364
+ $label = if ($key -eq 'ok') { $okText } elseif ($key -eq 'open') { '打开链接' } else { $snoozeText }
359
365
  $fmt = New-Object System.Drawing.StringFormat
360
366
  $fmt.Alignment = [System.Drawing.StringAlignment]::Center
361
367
  $fmt.LineAlignment = [System.Drawing.StringAlignment]::Center
@@ -413,12 +419,25 @@ function Close-With([string]$action) {
413
419
  Write-Log ('action ' + $action)
414
420
  }
415
421
 
422
+ $form.KeyPreview = $true
423
+ $form.Add_KeyDown({
424
+ param($sender, $e)
425
+ if ($e.KeyCode -eq [System.Windows.Forms.Keys]::Enter) { Close-With 'ok' }
426
+ elseif ($e.KeyCode -eq [System.Windows.Forms.Keys]::S) { Close-With 'snooze' }
427
+ elseif ($e.KeyCode -eq [System.Windows.Forms.Keys]::Escape) { Close-With 'dismiss' }
428
+ })
429
+
416
430
  $form.Add_MouseDown({
417
431
  param($sender, $e)
418
432
  if ($script:phase -eq 'out') { return }
419
- foreach ($key in @('ok', 'snooze')) {
433
+ foreach ($key in @('open', 'ok', 'snooze')) {
420
434
  $rect = $script:btnRects[$key]
421
435
  if ($rect -ne $null -and $rect.Contains($e.X, $e.Y)) {
436
+ if ($key -eq 'open' -and $OpenUrl -ne '') {
437
+ try { Start-Process $OpenUrl | Out-Null } catch { }
438
+ Close-With 'ok'
439
+ return
440
+ }
422
441
  Close-With $key
423
442
  return
424
443
  }
package/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { spawn } from 'node:child_process'
13
13
  import fs from 'node:fs'
14
+ import https from 'node:https'
14
15
  import os from 'node:os'
15
16
  import path from 'node:path'
16
17
  import { fileURLToPath } from 'node:url'
@@ -98,7 +99,9 @@ export const Config = z === null ? undefined : z.object({
98
99
  digestAlertDate: z.string().default('').description('内部状态:上次弹条数预警的日期').volatile(),
99
100
  pushEnabled: z.boolean().default(false).description('把提醒同时推到手机(企业微信机器人 / Server酱 / 自定义 webhook)').volatile(),
100
101
  pushUrl: z.string().default('').description('推送地址,例如 https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…').volatile(),
101
- pushFormat: z.union(['wecom', 'serverchan', 'json', 'text']).default('wecom').description('推送格式:wecom 企业微信机器人、serverchan Server酱、json 通用 JSON、text 纯文本').volatile(),
102
+ pushFormat: z.union(['wecom', 'serverchan', 'json', 'text', 'telegram', 'feishu', 'dingtalk']).default('wecom').description('推送格式:wecom 企业微信机器人、serverchan Server酱、telegram、feishu 飞书、dingtalk 钉钉、json 通用 JSON、text 纯文本').volatile(),
103
+ pushChat: z.string().default('').description('telegram 用的 chat_id(只 telegram 格式需要)').volatile(),
104
+ maxHoldSeconds: z.number().min(0).max(3600).step(5).default(0).description('单张卡最长停留秒数(0 = 不额外限制,仍以 600 为上限)').volatile(),
102
105
  pushDecide: z.boolean().default(true).description('「需要你来决定」档位也推到手机').volatile(),
103
106
  pushDigest: z.boolean().default(true).description('日报同时推到手机').volatile(),
104
107
  retryHostOnce: z.boolean().default(true).description('宿主第一次没画出卡片时,自动静音重试一次').volatile(),
@@ -239,7 +242,9 @@ function settingsOf(config) {
239
242
  digestAlertDate: str(c.digestAlertDate, ''),
240
243
  pushEnabled: c.pushEnabled === true,
241
244
  pushUrl: typeof c.pushUrl === 'string' ? c.pushUrl.trim() : '',
242
- pushFormat: ['wecom', 'serverchan', 'json', 'text'].includes(c.pushFormat) ? c.pushFormat : 'wecom',
245
+ pushFormat: ['wecom', 'serverchan', 'json', 'text', 'telegram', 'feishu', 'dingtalk'].includes(c.pushFormat) ? c.pushFormat : 'wecom',
246
+ pushChat: typeof c.pushChat === 'string' ? c.pushChat.trim() : '',
247
+ maxHoldSeconds: Math.round(clamp(num(c.maxHoldSeconds, 0), 0, 3600)),
243
248
  pushDecide: c.pushDecide !== false,
244
249
  pushDigest: c.pushDigest !== false,
245
250
  retryHostOnce: c.retryHostOnce !== false,
@@ -365,6 +370,7 @@ function argvOfScriptHost(o) {
365
370
  if (o.compact) argv.push('-Compact')
366
371
  if (o.autoCompact) argv.push('-AutoCompact')
367
372
  if (o.queueLeft > 0) argv.push('-QueueLeft', String(o.queueLeft))
373
+ if (o.openUrl) argv.push('-OpenUrl', String(o.openUrl))
368
374
  return argv
369
375
  }
370
376
 
@@ -439,6 +445,30 @@ export function quietEndAt(settings, now = new Date()) {
439
445
  return at.getTime()
440
446
  }
441
447
 
448
+ function priorityOf(kind) {
449
+ // decide 是「要人来拍板」的,最优先;done 次之;raw 最低。
450
+ if (kind === 'decide') return 2
451
+ if (kind === 'done') return 1
452
+ return 0
453
+ }
454
+
455
+ // at="22:00"(今天已过则明天)或 inMinutes=N → 到点时间戳;都没给返回 0(立刻弹)。
456
+ function dueAtOf(args) {
457
+ const minutes = num(args.inMinutes, NaN)
458
+ if (Number.isFinite(minutes) && minutes > 0) {
459
+ return Date.now() + Math.min(minutes, 7 * 24 * 60) * 60 * 1000
460
+ }
461
+ const clock = str(args.at, '')
462
+ if (clock === '') return 0
463
+ const target = parseClock(clock)
464
+ if (target === null) return 0
465
+ const now = new Date()
466
+ const at = new Date(now.getTime())
467
+ at.setHours(Math.floor(target / 60), target % 60, 0, 0)
468
+ if (at.getTime() <= now.getTime()) at.setDate(at.getDate() + 1)
469
+ return at.getTime()
470
+ }
471
+
442
472
  function enqueue(item) {
443
473
  const settings = item.settings
444
474
  if (!settings.queueEnabled) {
@@ -451,7 +481,7 @@ function enqueue(item) {
451
481
  return { queued: false, position: 0 }
452
482
  }
453
483
  const now = Date.now()
454
- if (settings.mergeWindowMs > 0) {
484
+ if (settings.mergeWindowMs > 0 && !((item.dueAt ?? 0) > now)) {
455
485
  const pending = queue.find(
456
486
  (other) =>
457
487
  other.kind === item.kind &&
@@ -476,17 +506,27 @@ function enqueue(item) {
476
506
  function pump() {
477
507
  if (active !== null) return
478
508
  const now = Date.now()
479
- const index = queue.findIndex((item) => (item.holdUntil ?? 0) <= now)
480
- if (index < 0) {
481
- // 全都在免打扰时段里攒着:睡到最早那一条的放行时间再看
482
- const next = queue.reduce((min, item) => Math.min(min, item.holdUntil ?? Infinity), Infinity)
509
+ // 0.17:到点的(既不在免打扰里、也过了定时时间)才放;decide 永远排在前面。
510
+ const ready = queue.filter(
511
+ (item) => (item.holdUntil ?? 0) <= now && (item.dueAt ?? 0) <= now,
512
+ )
513
+ if (ready.length === 0) {
514
+ // 剩下的要么在免打扰时段里,要么是定时提醒:睡到最早那个时间点再看
515
+ const next = queue.reduce((min, item) => {
516
+ const when = Math.max(item.holdUntil ?? 0, item.dueAt ?? 0)
517
+ return when > now ? Math.min(min, when) : min
518
+ }, Infinity)
483
519
  if (Number.isFinite(next)) {
484
520
  const timer = setTimeout(() => pump(), Math.max(1000, Math.min(next - now, 60 * 60 * 1000)))
485
521
  if (typeof timer.unref === 'function') timer.unref()
486
522
  }
487
523
  return
488
524
  }
489
- const [item] = queue.splice(index, 1)
525
+ ready.sort(
526
+ (a, b) => (b.priority ?? 0) - (a.priority ?? 0) || (a.createdAt ?? 0) - (b.createdAt ?? 0),
527
+ )
528
+ const item = ready[0]
529
+ queue.splice(queue.indexOf(item), 1)
490
530
  active = item
491
531
  showItem(item)
492
532
  .catch(() => {})
@@ -519,6 +559,7 @@ async function showItem(item) {
519
559
  icon: extras.icon,
520
560
  speak: item.speak,
521
561
  resultPath: resultFile,
562
+ openUrl: str(item.url, ''),
522
563
  buttonsEnabled: settings.buttonsEnabled,
523
564
  snoozeMinutes: settings.snoozeMinutes,
524
565
  autoCompact: settings.compactOnFullscreen,
@@ -600,7 +641,10 @@ async function notify(kind, args, settings) {
600
641
  const kindMessageTemplate = str(settings[`${kind}MessageTemplate`], '')
601
642
  const title = renderTemplate(kindTitleTemplate !== '' ? kindTitleTemplate : settings.titleTemplate, '{title}', vars)
602
643
  const message = renderTemplate(kindMessageTemplate !== '' ? kindMessageTemplate : settings.messageTemplate, '{message}', vars)
603
- const seconds = Math.round(clamp(num(args.seconds, settings.seconds), 2, 600))
644
+ const secondsWanted = Math.round(clamp(num(args.seconds, settings.seconds), 2, 600))
645
+ // 0.17:单卡最长停留(maxHoldSeconds>0 时再压一道),避免 decide 卡一直挂在屏幕上。
646
+ const seconds =
647
+ settings.maxHoldSeconds > 0 ? Math.min(secondsWanted, settings.maxHoldSeconds) : secondsWanted
604
648
  const sound = args.sound === false ? false : settings.sound
605
649
  const audio = audioNameOf(kind, settings)
606
650
  const speak = str(args.speak, settings.speakEnabled ? message : '')
@@ -706,11 +750,16 @@ async function notify(kind, args, settings) {
706
750
  }
707
751
  const holdUntil = quiet ? quietEndAt(settings) : 0
708
752
 
753
+ const dueAt = dueAtOf(args)
754
+ const openUrl = str(args.url, '')
709
755
  const item = {
710
756
  kind,
711
757
  title,
712
758
  message,
713
759
  seconds,
760
+ url: openUrl,
761
+ dueAt,
762
+ priority: priorityOf(kind),
714
763
  sound: sound && audioPath !== '',
715
764
  audioPath,
716
765
  audioMissing,
@@ -723,6 +772,12 @@ async function notify(kind, args, settings) {
723
772
  holdUntil,
724
773
  }
725
774
  const placement = enqueue(item)
775
+ emitServiceEvent('notified', {
776
+ kind,
777
+ title,
778
+ queued: placement.queued === true || placement.merged === true,
779
+ scheduledAt: dueAt > 0 ? new Date(dueAt).toISOString() : '',
780
+ })
726
781
  return {
727
782
  ok: true,
728
783
  hostMode: 'script',
@@ -743,6 +798,8 @@ async function notify(kind, args, settings) {
743
798
  count: placement.count,
744
799
  quiet: quiet || undefined,
745
800
  holdUntil: holdUntil > 0 ? new Date(holdUntil).toISOString() : undefined,
801
+ url: openUrl !== '' ? openUrl : undefined,
802
+ scheduledAt: dueAt > 0 ? new Date(dueAt).toISOString() : undefined,
746
803
  }
747
804
  }
748
805
 
@@ -764,6 +821,19 @@ const parameters = {
764
821
  description:
765
822
  '用系统语音念出来的句子(不弹窗也能念)。不传时:插件里开了「语音朗读」就念正文,否则不念。',
766
823
  },
824
+ url: {
825
+ type: 'string',
826
+ description: '卡片上带一个「打开链接」按钮,点了会用默认浏览器打开这个地址(https 开头)。',
827
+ },
828
+ at: {
829
+ type: 'string',
830
+ description:
831
+ '定时提醒:HH:MM(24 小时制)。到点才弹;今天这个时间已经过了就排到明天,最多等到 24 小时内。',
832
+ },
833
+ inMinutes: {
834
+ type: 'number',
835
+ description: '定时提醒:多少分钟之后弹(1–10080)。和 at 同时给时以 inMinutes 为准。',
836
+ },
767
837
  },
768
838
  }
769
839
 
@@ -809,6 +879,7 @@ const CONFIG_ROUTE = '/dsh-reminder-notify/config'
809
879
  const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
810
880
  const BALANCE_ROUTE = '/dsh-reminder-notify/balance'
811
881
  const HISTORY_ROUTE = '/dsh-reminder-notify/history'
882
+ const EXPORT_ROUTE = '/dsh-reminder-notify/export'
812
883
  const DIGEST_ROUTE = '/dsh-reminder-notify/digest'
813
884
 
814
885
  // 面板要「把音频目录里的文件列成下拉」,但 Client 侧没有任何读文件能力,
@@ -1328,6 +1399,13 @@ export function historyStats(entries) {
1328
1399
  d.setDate(d.getDate() - i)
1329
1400
  buckets.set(dayKey(d.getTime()), 0)
1330
1401
  }
1402
+ // 0.17:再给一份 30 天桶,面板画趋势图用(前 7 天与上面完全一致)。
1403
+ const monthBuckets = new Map()
1404
+ for (let i = 29; i >= 0; i -= 1) {
1405
+ const d = new Date()
1406
+ d.setDate(d.getDate() - i)
1407
+ monthBuckets.set(dayKey(d.getTime()), 0)
1408
+ }
1331
1409
  const today = dayKey(Date.now())
1332
1410
  let todayCount = 0
1333
1411
  for (const entry of entries) {
@@ -1339,6 +1417,7 @@ export function historyStats(entries) {
1339
1417
  const key = dayKey(num(entry.at, 0))
1340
1418
  if (key === today) todayCount += 1
1341
1419
  if (buckets.has(key)) buckets.set(key, buckets.get(key) + 1)
1420
+ if (monthBuckets.has(key)) monthBuckets.set(key, monthBuckets.get(key) + 1)
1342
1421
  }
1343
1422
  return {
1344
1423
  total: entries.length,
@@ -1346,6 +1425,7 @@ export function historyStats(entries) {
1346
1425
  byKind,
1347
1426
  byAction,
1348
1427
  last7: [...buckets.entries()].map(([date, count]) => ({ date, count })),
1428
+ last30: [...monthBuckets.entries()].map(([date, count]) => ({ date, count })),
1349
1429
  }
1350
1430
  }
1351
1431
 
@@ -1406,6 +1486,21 @@ export function pushPayload(settings, title, message, extra = {}) {
1406
1486
  if (settings.pushFormat === 'text') {
1407
1487
  return { headers: { 'content-type': 'text/plain; charset=utf-8' }, body: `${title}\n${body}` }
1408
1488
  }
1489
+ if (settings.pushFormat === 'telegram') {
1490
+ return {
1491
+ headers: json,
1492
+ body: JSON.stringify({ chat_id: str(settings.pushChat, ''), text: `${title}\n${body}` }),
1493
+ }
1494
+ }
1495
+ if (settings.pushFormat === 'feishu') {
1496
+ return { headers: json, body: JSON.stringify({ msg_type: 'text', content: { text: `${title}\n${body}` } }) }
1497
+ }
1498
+ if (settings.pushFormat === 'dingtalk') {
1499
+ return {
1500
+ headers: json,
1501
+ body: JSON.stringify({ msgtype: 'markdown', markdown: { title, text: `### ${title}\n\n${body}` } }),
1502
+ }
1503
+ }
1409
1504
  if (settings.pushFormat === 'wecom') {
1410
1505
  return { headers: json, body: JSON.stringify({ msgtype: 'text', text: { content: `${title}\n${body}` } }) }
1411
1506
  }
@@ -1649,6 +1744,33 @@ export function doctorReport(ctx, getSettings) {
1649
1744
  add('account', service('deepseekAccount') !== undefined, service('deepseekAccount') === undefined ? '读不到余额(不影响卡片)' : '可读余额')
1650
1745
  add('service-api', typeof ctx.provide === 'function', typeof ctx.provide === 'function' ? "可 provide('reminder')" : '旧宿主没有 ctx.provide')
1651
1746
 
1747
+ // 0.16.1:GitHub 连通性。Steam++(Watt Toolkit)加速 GitHub 靠改 hosts 把 github.com
1748
+ // 指到 127.0.0.1,由它的本地代理接住;它没接管(只开了进程没点「一键加速」/被强杀)时,
1749
+ // 浏览器和 git 都会连不上。这里做静态判断:hosts 里有没有本机重定向。
1750
+ // 真正「能不能连」用 POST /doctor {mode:'github'} 现测。
1751
+ const hostsFile = process.platform === 'win32'
1752
+ ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'drivers', 'etc', 'hosts')
1753
+ : '/etc/hosts'
1754
+ let githubLines = []
1755
+ try {
1756
+ githubLines = fs.readFileSync(hostsFile, 'utf8')
1757
+ .split(/\r?\n/)
1758
+ .map((line) => line.trim())
1759
+ .filter((line) => line !== '' && !line.startsWith('#'))
1760
+ .filter((line) => /^\d{1,3}(\.\d{1,3}){3}\s/.test(line))
1761
+ .filter((line) => /github\.com|githubusercontent\.com/i.test(line))
1762
+ } catch {
1763
+ githubLines = []
1764
+ }
1765
+ const loopback = githubLines.filter((line) => /^127\.0\.0\.1\s/.test(line))
1766
+ if (githubLines.length === 0) {
1767
+ add('github', true, 'hosts 里没有 github 重定向(裸连)')
1768
+ } else if (loopback.length === 0) {
1769
+ add('github', true, 'hosts 指向 ' + githubLines[0].split(/\s+/)[0])
1770
+ } else {
1771
+ add('github', false, 'hosts 把 github 指到 127.0.0.1(Steam++ 加速表);加速器没接管就连不上,跑 scripts/github-push.ps1 会自动处理')
1772
+ }
1773
+
1652
1774
  const lastExit = hostHealth.lastExit
1653
1775
  const hostOk = lastExit === null || lastExit === 0
1654
1776
  add('host-exit', hostOk, lastExit === null ? '还没有弹过卡片' : `最近一次退出码 ${lastExit}`)
@@ -1673,6 +1795,37 @@ export function doctorReport(ctx, getSettings) {
1673
1795
 
1674
1796
  const DOCTOR_ROUTE = '/dsh-reminder-notify/doctor'
1675
1797
 
1798
+ /** 现测一次 https://github.com(HEAD,8 秒超时)。 */
1799
+ export function probeGithub(timeoutMs = 8000) {
1800
+ const started = Date.now()
1801
+ return new Promise((resolve) => {
1802
+ let settled = false
1803
+ const done = (payload) => {
1804
+ if (settled) return
1805
+ settled = true
1806
+ resolve({ ...payload, ms: Date.now() - started })
1807
+ }
1808
+ try {
1809
+ const req = https.request(
1810
+ { method: 'HEAD', host: 'github.com', path: '/', timeout: timeoutMs, headers: { 'user-agent': 'dsh-reminder-notify-doctor' } },
1811
+ (res) => {
1812
+ res.resume()
1813
+ const code = res.statusCode ?? 0
1814
+ done({ ok: code >= 200 && code < 500, statusCode: code })
1815
+ },
1816
+ )
1817
+ req.on('timeout', () => {
1818
+ req.destroy()
1819
+ done({ ok: false, error: `timeout ${timeoutMs}ms` })
1820
+ })
1821
+ req.on('error', (error) => done({ ok: false, error: String(error?.message ?? error) }))
1822
+ req.end()
1823
+ } catch (error) {
1824
+ done({ ok: false, error: String(error?.message ?? error) })
1825
+ }
1826
+ })
1827
+ }
1828
+
1676
1829
  function registerDoctorRoute(ctx, getSettings) {
1677
1830
  const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
1678
1831
  if (web === undefined || web === null || typeof web.register !== 'function') {
@@ -1695,6 +1848,10 @@ function registerDoctorRoute(ctx, getSettings) {
1695
1848
  const body = await readJsonBody(req)
1696
1849
  const mode = body !== null && typeof body === 'object' ? str(body.mode, 'check') : 'check'
1697
1850
  if (mode === 'check') return reply(res, 200, { ok: true, report: doctorReport(ctx, getSettings) })
1851
+ if (mode === 'github') {
1852
+ const probe = await probeGithub()
1853
+ return reply(res, 200, { ok: true, mode: 'github', github: probe })
1854
+ }
1698
1855
  if (mode === 'probe') {
1699
1856
  const card = await notify(
1700
1857
  'raw',
@@ -1717,6 +1874,67 @@ function registerDoctorRoute(ctx, getSettings) {
1717
1874
  }, 'dsh-reminder-notify: doctor route')
1718
1875
  }
1719
1876
 
1877
+ // 0.17:历史导出 —— 面板点一下,CSV/JSON 落到桌面,方便拿去算账或贴给别人。
1878
+ function exportHistoryFile(settings, entries, format, days) {
1879
+ const since = Date.now() - Math.max(1, days) * 24 * 60 * 60 * 1000
1880
+ const rows = entries.filter((entry) => num(entry?.at, 0) >= since)
1881
+ const stamp = new Date()
1882
+ const pad = (n) => String(n).padStart(2, '0')
1883
+ const name = `提醒历史-${stamp.getFullYear()}${pad(stamp.getMonth() + 1)}${pad(stamp.getDate())}-${pad(stamp.getHours())}${pad(stamp.getMinutes())}.${format}`
1884
+ const dir = path.join(os.homedir(), 'Desktop')
1885
+ const file = path.join(dir, name)
1886
+ if (format === 'json') {
1887
+ fs.writeFileSync(file, JSON.stringify(rows, null, 2), 'utf8')
1888
+ return { file, count: rows.length }
1889
+ }
1890
+ const cell = (value) => `"${String(value ?? '').replace(/"/g, '""').replace(/\r?\n/g, ' ')}"`
1891
+ const lines = ['时间,档位,标题,正文,处理方式,条数,稍后提醒,免打扰']
1892
+ for (const entry of rows) {
1893
+ lines.push(
1894
+ [
1895
+ new Date(num(entry.at, 0)).toISOString(),
1896
+ cell(entry.kind),
1897
+ cell(entry.title),
1898
+ cell(entry.message),
1899
+ cell(entry.action),
1900
+ num(entry.count, 1),
1901
+ entry.snoozed === true ? '是' : '否',
1902
+ entry.quiet === true ? '是' : '否',
1903
+ ].join(','),
1904
+ )
1905
+ }
1906
+ fs.mkdirSync(dir, { recursive: true })
1907
+ fs.writeFileSync(file, lines.join('\r\n'), 'utf8')
1908
+ return { file, count: rows.length }
1909
+ }
1910
+
1911
+ function registerExportRoute(ctx, getSettings) {
1912
+ const web = ctx.get('webServer')
1913
+ if (web === null || web === undefined || typeof web.register !== 'function') return
1914
+ const reply = (res, status, payload) => {
1915
+ res.statusCode = status
1916
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1917
+ res.end(JSON.stringify(payload))
1918
+ }
1919
+ const dispose = web.register({
1920
+ kind: 'exact',
1921
+ path: EXPORT_ROUTE,
1922
+ handler: (req, res) => {
1923
+ try {
1924
+ const settings = getSettings()
1925
+ const url = new URL(req.url ?? EXPORT_ROUTE, 'http://127.0.0.1')
1926
+ const format = url.searchParams.get('format') === 'json' ? 'json' : 'csv'
1927
+ const days = Math.round(clamp(num(url.searchParams.get('days'), 30), 1, 365))
1928
+ const result = exportHistoryFile(settings, readHistory(settings), format, days)
1929
+ reply(res, 200, { ok: true, format, days, file: result.file, count: result.count })
1930
+ } catch (error) {
1931
+ reply(res, 500, { ok: false, error: 'export-failed', detail: String(error?.message ?? error) })
1932
+ }
1933
+ },
1934
+ })
1935
+ ctx.effect(() => dispose, 'dsh-reminder-notify: history export route')
1936
+ }
1937
+
1720
1938
  function registerHistoryRoute(ctx, getSettings) {
1721
1939
  const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
1722
1940
  if (web === undefined || web === null || typeof web.register !== 'function') {
@@ -1779,10 +1997,36 @@ function packageVersion() {
1779
1997
  * 0.15 起对外提供的服务:让别的插件也能发提醒、发日报、读统计,而不用自己起宿主。
1780
1998
  * 全部方法是 fire-and-forget 语义(返回 Promise,失败只在返回值里体现),不会抛给调用方。
1781
1999
  */
2000
+ const serviceEvents = []
2001
+ const sourceHandlers = new Map()
2002
+
2003
+ // 0.17:服务契约升到 2 —— 版本号、事件流、以及「别的插件也能注册提醒来源」。
2004
+ export function emitServiceEvent(type, payload = {}) {
2005
+ const event = { type, at: Date.now(), payload }
2006
+ serviceEvents.push(event)
2007
+ if (serviceEvents.length > 60) serviceEvents.shift()
2008
+ for (const handler of sourceHandlers.values()) {
2009
+ try {
2010
+ handler(event)
2011
+ } catch {
2012
+ // 别人的 handler 崩了不该影响弹卡
2013
+ }
2014
+ }
2015
+ return event
2016
+ }
2017
+
1782
2018
  export function serviceOf(ctx, getSettings) {
1783
2019
  return {
1784
2020
  name: 'dsh-reminder-notify',
1785
2021
  version: packageVersion(),
2022
+ // 0.17:契约第 2 版 —— 多了事件流与「别的插件也能注册提醒来源」。
2023
+ apiVersion: 2,
2024
+ events: () => serviceEvents.slice(-20),
2025
+ registerSource: (name, handler) => {
2026
+ const key = String(name ?? '').trim() || `source-${sourceHandlers.size + 1}`
2027
+ sourceHandlers.set(key, typeof handler === 'function' ? handler : () => {})
2028
+ return () => sourceHandlers.delete(key)
2029
+ },
1786
2030
  /** 发一张提醒卡。kind: done | decide | raw;options 同 notify_user 的参数。 */
1787
2031
  notify: (kind, options = {}) => notify(nodeKind(kind), options || {}, getSettings()),
1788
2032
  /** 立刻发一条日报(force: true 时忽略「今天已经发过」和「日报未开启」)。 */
@@ -1811,6 +2055,7 @@ export function apply(ctx, config) {
1811
2055
  registerPreviewRoute(ctx, () => settingsOf(config))
1812
2056
  registerBalanceRoute(ctx, () => settingsOf(config), config)
1813
2057
  registerHistoryRoute(ctx, () => settingsOf(config))
2058
+ registerExportRoute(ctx, () => settingsOf(config))
1814
2059
  registerDigestRoute(ctx, () => settingsOf(config))
1815
2060
  registerDigestLoop(ctx, () => settingsOf(config))
1816
2061
  registerDoctorRoute(ctx, () => settingsOf(config))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-reminder-notify",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "DSH 桌面提醒插件:把「完成/需要决定」提醒变成 notify_user 工具(浮动卡片 + 提示音,不抢焦点,纯 PowerShell 源码宿主,仓库零 exe)",
5
5
  "author": "Jiangshuaiye1203",
6
6
  "type": "module",
@@ -48,8 +48,8 @@
48
48
  },
49
49
  "versions": [
50
50
  {
51
- "version": "0.15.0",
52
- "publishTimestamp": 1795192355,
51
+ "version": "0.16.1",
52
+ "publishTimestamp": 1795224202,
53
53
  "source": {
54
54
  "type": "npm"
55
55
  },
@@ -0,0 +1,170 @@
1
+ # github-push.ps1 —— 推送前自动处理「Steam++ 加速表把 github.com 指到 127.0.0.1」的情况。
2
+ #
3
+ # 背景:Steam++(Watt Toolkit)加速 GitHub 的原理是改 hosts,把 github.com 指到
4
+ # 127.0.0.1,由它自己的本地代理接住。加速器在跑时一切正常;它没接管(进程开了但
5
+ # 没点「一键加速」、被强杀、崩了)时,浏览器和 git 都会连不上,报
6
+ # ERR_CONNECTION_REFUSED / Empty reply from server。
7
+ #
8
+ # 这个脚本做的事:
9
+ # 1. 先测 https://github.com 通不通;
10
+ # 2. 不通且 hosts 里有 127.0.0.1 的 github 行 → 临时注释它们(加 [dsh-temp] 标记)+ 刷 DNS,再测一次;
11
+ # 3. 通了就 git push(用 -Token,或环境变量 GITHUB_TOKEN,走 extraHeader,不落盘);
12
+ # 4. 无论成功失败,默认结束后把临时注释还原(-KeepChanges 则保留改动,方便继续用裸连)。
13
+ #
14
+ # 用法:
15
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -DryRun
16
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx
17
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx -KeepChanges
18
+
19
+ param(
20
+ [string]$Remote = 'origin',
21
+ [string]$Branch = 'main',
22
+ [string]$Token = $env:GITHUB_TOKEN,
23
+ [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot),
24
+ [switch]$DryRun,
25
+ [switch]$KeepChanges
26
+ )
27
+
28
+ $ErrorActionPreference = 'Stop'
29
+ $HostsPath = Join-Path $env:SystemRoot 'System32\drivers\etc\hosts'
30
+ $Marker = '# [dsh-temp] '
31
+ $script:changed = $false
32
+ $script:restored = $false
33
+ $script:original = @()
34
+
35
+ function Test-GitHub {
36
+ # 用独立进程的 curl.exe 探测:不受 PowerShell 进程内 DNS / 连接池缓存影响,
37
+ # 注释 hosts 后重测能立刻反映真实结果。没有 curl 时退回 HttpWebRequest。
38
+ $curl = Join-Path $env:SystemRoot 'System32\curl.exe'
39
+ if (Test-Path $curl) {
40
+ try {
41
+ $raw = (& $curl -s -o NUL -w '%{http_code}' --max-time 8 --ssl-no-revoke -I https://github.com/ 2>$null | Out-String).Trim()
42
+ $code = 0
43
+ [void][int]::TryParse($raw, [ref]$code)
44
+ if ($code -gt 0) { return @{ ok = ($code -ge 200 -and $code -lt 500); code = $code; error = '' } }
45
+ return @{ ok = $false; code = 0; error = 'curl 无响应(连接超时)' }
46
+ } catch {
47
+ return @{ ok = $false; code = 0; error = $_.Exception.Message }
48
+ }
49
+ }
50
+ try {
51
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
52
+ $req = [System.Net.HttpWebRequest]::Create('https://github.com/')
53
+ $req.Method = 'HEAD'
54
+ $req.Timeout = 8000
55
+ $req.UserAgent = 'dsh-github-push'
56
+ $res = $req.GetResponse()
57
+ $code = [int]$res.StatusCode
58
+ $res.Close()
59
+ return @{ ok = ($code -ge 200 -and $code -lt 500); code = $code; error = '' }
60
+ } catch {
61
+ return @{ ok = $false; code = 0; error = $_.Exception.Message }
62
+ }
63
+ }
64
+
65
+ function Clear-Dns {
66
+ try { & "$env:SystemRoot\System32\ipconfig.exe" /flushdns 2>$null | Out-Null } catch { }
67
+ }
68
+
69
+ function Get-HostsBlockers {
70
+ if (-not (Test-Path $HostsPath)) { return @() }
71
+ $lines = [System.IO.File]::ReadAllLines($HostsPath)
72
+ $hits = New-Object System.Collections.ArrayList
73
+ for ($i = 0; $i -lt $lines.Length; $i++) {
74
+ $trim = $lines[$i].Trim()
75
+ if ($trim -eq '' -or $trim.StartsWith('#')) { continue }
76
+ if ($trim -match '^127\.0\.0\.1\s' -and $trim -match 'github') { [void]$hits.Add($i) }
77
+ }
78
+ return @($hits)
79
+ }
80
+
81
+ function Set-HostsLines([string[]]$Lines) {
82
+ [System.IO.File]::WriteAllLines($HostsPath, $Lines, (New-Object System.Text.UTF8Encoding($false)))
83
+ }
84
+
85
+ function Restore-Hosts {
86
+ if (-not $script:changed) { return }
87
+ if ($KeepChanges) {
88
+ Write-Host ' hosts 保持改动(Steam++ 的屏蔽行仍被注释,GitHub 走裸连)。'
89
+ } else {
90
+ try {
91
+ Set-HostsLines $script:original
92
+ Clear-Dns
93
+ Write-Host ' hosts 已还原成原样。'
94
+ $script:restored = $true
95
+ } catch {
96
+ Write-Host (" hosts 还原失败,请手动检查:{0}" -f $_.Exception.Message)
97
+ }
98
+ }
99
+ $script:changed = $false
100
+ }
101
+
102
+ try {
103
+ Write-Host '[1/4] 测试 https://github.com ...'
104
+ $probe = Test-GitHub
105
+ if ($probe.ok) {
106
+ Write-Host (" OK(HTTP {0})" -f $probe.code)
107
+ } else {
108
+ Write-Host (" 连不上:{0}" -f $probe.error)
109
+ $blockers = Get-HostsBlockers
110
+ if ($blockers.Count -eq 0) {
111
+ Write-Host ' hosts 里没有 127.0.0.1 的 github 行,问题不在 hosts(可能是代理 / 网络)。'
112
+ Write-Host ' 建议:打开 Steam++ → 网络加速 → 勾 GitHub → 一键加速,并保持它运行。'
113
+ if (-not $DryRun) { exit 2 }
114
+ } else {
115
+ Write-Host (" 发现 {0} 行本机重定向(Steam++ 加速表),临时注释后重试 ..." -f $blockers.Count)
116
+ $script:original = @([System.IO.File]::ReadAllLines($HostsPath))
117
+ $lines = @($script:original)
118
+ foreach ($i in $blockers) { $lines[$i] = $Marker + $lines[$i] }
119
+ Set-HostsLines $lines
120
+ $script:changed = $true
121
+ Clear-Dns
122
+ $probe = Test-GitHub
123
+ if ($probe.ok) {
124
+ Write-Host (" OK(HTTP {0})" -f $probe.code)
125
+ } else {
126
+ Write-Host (" 仍然连不上:{0}" -f $probe.error)
127
+ Write-Host ' 建议:打开 Steam++ → 网络加速 → 勾 GitHub → 一键加速,保持运行后重试。'
128
+ Restore-Hosts
129
+ if (-not $DryRun) { exit 2 }
130
+ }
131
+ }
132
+ }
133
+
134
+ Write-Host '[2/4] 检查仓库状态 ...'
135
+ Push-Location $RepoRoot
136
+ try {
137
+ $status = git status --porcelain
138
+ if ($status) {
139
+ Write-Host ' 工作树有未提交的改动(脚本不会替你提交):'
140
+ $status | ForEach-Object { Write-Host " $_" }
141
+ }
142
+ $ahead = (git rev-list --count "origin/$Branch..HEAD" 2>$null | Out-String).Trim()
143
+ Write-Host (" 待推送提交:{0} 个" -f $ahead)
144
+
145
+ Write-Host '[3/4] 推送 ...'
146
+ if ($DryRun) {
147
+ Write-Host ' -DryRun:跳过实际推送。'
148
+ } elseif ($ahead -eq '0') {
149
+ Write-Host ' 没有需要推送的提交。'
150
+ } elseif (-not $Token) {
151
+ Write-Host ' 没给令牌:请加 -Token ghp_xxx,或先设置环境变量 GITHUB_TOKEN。'
152
+ Write-Host ' 令牌在 https://github.com/settings/tokens/new 生成(勾 repo;要改 .github/workflows 还要勾 workflow)。'
153
+ } else {
154
+ $basic = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("x-access-token:$Token"))
155
+ & git -c credential.helper= -c "http.https://github.com/.extraHeader=Authorization: Basic $basic" push $Remote $Branch
156
+ if ($LASTEXITCODE -ne 0) { throw "git push 失败(退出码 $LASTEXITCODE)" }
157
+ Write-Host ' 推送完成。记得去 https://github.com/settings/tokens 删掉这个临时令牌。'
158
+ }
159
+ } finally {
160
+ Pop-Location
161
+ }
162
+ } catch {
163
+ Write-Host ("出错:{0}" -f $_.Exception.Message)
164
+ exit 1
165
+ } finally {
166
+ Write-Host '[4/4] 收尾 ...'
167
+ $wasChanged = $script:changed
168
+ Restore-Hosts
169
+ if (-not $wasChanged) { Write-Host ' hosts 未改动。' }
170
+ }