dsh-reminder-notify 0.8.2 → 0.9.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/client.js CHANGED
@@ -18,6 +18,20 @@ window.__ModuleLoader__.load({
18
18
  const AUDIO_ROUTE = '/dsh-reminder-notify/audio'
19
19
  const CONFIG_ROUTE = '/dsh-reminder-notify/config'
20
20
  const AUDIO_KEYS = ['doneAudio', 'decideAudio', 'rawAudio']
21
+ const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
22
+ // 下拉按扩展名分组:wav 一组、mp3 一组……组内按文件名排序,一眼能看出格式。
23
+ function groupAudioFiles(files) {
24
+ const byExt = new Map()
25
+ for (const name of files) {
26
+ const dot = name.lastIndexOf('.')
27
+ const ext = dot >= 0 ? name.slice(dot + 1).toLowerCase() : 'other'
28
+ if (!byExt.has(ext)) byExt.set(ext, [])
29
+ byExt.get(ext).push(name)
30
+ }
31
+ return [...byExt.entries()]
32
+ .sort((a, b) => a[0].localeCompare(b[0]))
33
+ .map(([ext, names]) => ({ ext, names: names.sort((a, b) => a.localeCompare(b, 'zh-Hans-CN')) }))
34
+ }
21
35
 
22
36
  const zh = {
23
37
  title: '桌面提醒设置',
@@ -75,6 +89,10 @@ window.__ModuleLoader__.load({
75
89
  audioScanning: '正在读取音频目录…',
76
90
  audioEmpty: '音频目录里没有可用的音频文件',
77
91
  audioFailed: '读取音频目录失败:',
92
+ preview: '试听',
93
+ previewing: '播放中…',
94
+ previewOk: '已播放:',
95
+ previewFailed: '试听失败:',
78
96
  hostMode: '宿主模式',
79
97
  hostModeScript: '包内脚本(推荐)',
80
98
  hostModeExe: '外部 exe 客户端',
@@ -153,6 +171,10 @@ window.__ModuleLoader__.load({
153
171
  audioScanning: 'Reading the sound directory…',
154
172
  audioEmpty: 'No audio files in the sound directory',
155
173
  audioFailed: 'Could not read the sound directory: ',
174
+ preview: 'Play',
175
+ previewing: 'Playing…',
176
+ previewOk: 'Played: ',
177
+ previewFailed: 'Preview failed: ',
156
178
  hostMode: 'Host mode',
157
179
  hostModeScript: 'Bundled script (recommended)',
158
180
  hostModeExe: 'External exe client',
@@ -281,6 +303,7 @@ window.__ModuleLoader__.load({
281
303
  const [draft, setDraft] = React.useState(null)
282
304
  const [busy, setBusy] = React.useState(false)
283
305
  const [picking, setPicking] = React.useState(false)
306
+ const [previewing, setPreviewing] = React.useState(null)
284
307
  const [message, setMessage] = React.useState(null)
285
308
  const [audio, setAudio] = React.useState({ dir: '', files: [], error: null })
286
309
 
@@ -440,6 +463,44 @@ window.__ModuleLoader__.load({
440
463
  })
441
464
  }
442
465
 
466
+ // 试听:面板没有本地文件访问能力,交给宿主按档位代播(POST /preview)。
467
+ // 先保存再用当前编辑值试听会更准,但这里刻意不落盘 —— 试听不该改动配置。
468
+ function previewAudio(key) {
469
+ if (previewing !== null) return
470
+ const kind = key === 'decideAudio' ? 'decide' : key === 'rawAudio' ? 'raw' : 'done'
471
+ setPreviewing(key)
472
+ setMessage(null)
473
+ Promise.resolve()
474
+ .then(() =>
475
+ fetch(PREVIEW_ROUTE, {
476
+ method: 'POST',
477
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
478
+ body: JSON.stringify({ kind }),
479
+ }),
480
+ )
481
+ .then((response) => {
482
+ const status = response ? response.status : 0
483
+ const body = response && typeof response.json === 'function' ? response.json() : Promise.resolve(null)
484
+ return Promise.resolve(body)
485
+ .catch(() => null)
486
+ .then((data) => {
487
+ if (response && response.ok && data && data.ok !== false) return data
488
+ const detail = data && (data.detail || data.error) ? (data.detail || data.error) : 'HTTP ' + status
489
+ throw new Error(detail)
490
+ })
491
+ })
492
+ .then((data) => {
493
+ setPreviewing(null)
494
+ const label = typeof t === 'function' ? t('previewOk') : 'Playing: '
495
+ setMessage({ ok: true, text: label + String((data && data.audio) || '') })
496
+ })
497
+ .catch((error) => {
498
+ setPreviewing(null)
499
+ const prefix = typeof t === 'function' ? t('previewFailed') : 'preview failed: '
500
+ setMessage({ ok: false, text: prefix + String((error && error.message) || error) })
501
+ })
502
+ }
503
+
443
504
  function control(field) {
444
505
  const value = effective[field.key]
445
506
  const disabled = !writable || busy
@@ -478,6 +539,12 @@ window.__ModuleLoader__.load({
478
539
  onChange: (e) => edit(field.key, e.target.value, field.kind),
479
540
  })
480
541
  if (AUDIO_KEYS.includes(field.key) && audio.files.length > 0) {
542
+ const groups = groupAudioFiles(audio.files)
543
+ const options = [h('option', { value: '', key: '__pick' }, typeof t === 'function' ? t('audioPick') : 'pick')]
544
+ for (const group of groups) {
545
+ const children = group.names.map((name) => h('option', { key: name, value: name }, name))
546
+ options.push(h('optgroup', { key: 'grp-' + group.ext, label: group.ext }, children))
547
+ }
481
548
  return h(
482
549
  'div',
483
550
  { className: 'drn-pick' },
@@ -493,9 +560,19 @@ window.__ModuleLoader__.load({
493
560
  if (picked !== '') edit(field.key, picked, 'text')
494
561
  },
495
562
  },
496
- [h('option', { value: '' }, typeof t === 'function' ? t('audioPick') : 'pick')].concat(
497
- audio.files.map((name) => h('option', { value: name }, name)),
498
- ),
563
+ options,
564
+ ),
565
+ h(
566
+ 'button',
567
+ {
568
+ type: 'button',
569
+ className: 'drn-btn small drn-preview',
570
+ disabled: disabled || previewing !== null,
571
+ onClick: () => previewAudio(field.key),
572
+ },
573
+ previewing === field.key
574
+ ? (typeof t === 'function' ? t('previewing') : 'Playing…')
575
+ : (typeof t === 'function' ? t('preview') : 'Play'),
499
576
  ),
500
577
  )
501
578
  }
@@ -25,6 +25,7 @@ param(
25
25
  [string]$Background = '',
26
26
  [string]$Icon = '',
27
27
  [switch]$NoSound,
28
+ [switch]$Preview,
28
29
  [string]$Log = ''
29
30
  )
30
31
 
@@ -316,6 +317,25 @@ if (-not $NoSound -and -not [string]::IsNullOrEmpty($Audio) -and (Test-Path -Lit
316
317
  }
317
318
  }
318
319
 
320
+ # ---- 试听:只放声音,不弹卡 ----------------------------------------------------
321
+ # 面板里的「试听」按钮走这条分支:播完(或最多 8 秒)就退出,不留窗口。
322
+ if ($Preview) {
323
+ if ($script:player -ne $null) {
324
+ $deadline = (Get-Date).AddSeconds(8)
325
+ while ((Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 200 }
326
+ try { $script:player.Stop() } catch { }
327
+ $script:player.Dispose()
328
+ }
329
+ if ($script:wmp -ne $null) {
330
+ $deadline = (Get-Date).AddSeconds(8)
331
+ while ((Get-Date) -lt $deadline -and $script:wmp.playState -ne 1) { Start-Sleep -Milliseconds 200 }
332
+ try { $script:wmp.controls.stop(); $script:wmp.close() } catch { }
333
+ try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:wmp) } catch { }
334
+ }
335
+ Write-Log 'preview exit'
336
+ exit 0
337
+ }
338
+
319
339
  # ---- 显示并进入消息循环 -----------------------------------------------------
320
340
  $form.Show()
321
341
  $form.RaiseWithoutActivating()
package/index.js CHANGED
@@ -435,6 +435,7 @@ function toolDefinition(getSettings) {
435
435
  const AUDIO_EXTENSIONS = ['.wav', '.mp3', '.ogg', '.m4a', '.flac', '.aac', '.wma']
436
436
  const AUDIO_ROUTE = '/dsh-reminder-notify/audio'
437
437
  const CONFIG_ROUTE = '/dsh-reminder-notify/config'
438
+ const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
438
439
 
439
440
  // 面板要「把音频目录里的文件列成下拉」,但 Client 侧没有任何读文件能力,
440
441
  // 所以由 Host 注册一条只读的 GET 路由,页面用同源 fetch 取这个 JSON。
@@ -488,6 +489,45 @@ function registerAudioRoute(ctx, getSettings) {
488
489
  }, 'dsh-reminder-notify: audio list route')
489
490
  }
490
491
 
492
+ // 试听:只按档位放一遍提示音,不弹卡。面板拿不到本地音频文件,所以由宿主代播。
493
+ export async function previewAudio(kind, settings) {
494
+ if (process.platform !== 'win32') {
495
+ return { ok: false, error: 'only-windows', detail: '试听只能在 Windows 上播放' }
496
+ }
497
+ const audio = audioNameOf(kind, settings)
498
+ if (audio === '') {
499
+ return { ok: false, error: 'no-audio', detail: '这个档位没有配置提示音(留空 = 静音)' }
500
+ }
501
+ const audioPath = path.join(path.resolve(settings.audioDir), audio)
502
+ if (!fs.existsSync(audioPath)) {
503
+ return { ok: false, error: 'audio-not-found', detail: `找不到音频文件:${audioPath}` }
504
+ }
505
+ const scriptPath = path.resolve(settings.scriptPath)
506
+ if (!fs.existsSync(scriptPath)) {
507
+ return { ok: false, error: 'host-script-not-found', detail: `找不到提醒脚本宿主:${scriptPath}` }
508
+ }
509
+ const argv = [
510
+ '-NoProfile',
511
+ '-NonInteractive',
512
+ '-ExecutionPolicy',
513
+ 'Bypass',
514
+ '-WindowStyle',
515
+ 'Hidden',
516
+ '-File',
517
+ scriptPath,
518
+ '-Preview',
519
+ '-Audio',
520
+ audioPath,
521
+ ]
522
+ try {
523
+ const { pid, exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
524
+ const early = await Promise.race([exited, new Promise((r) => setTimeout(() => r('running'), 900))])
525
+ return { ok: true, kind, audio: audioPath, pid, earlyExit: early === 'running' ? null : early }
526
+ } catch (error) {
527
+ return { ok: false, error: 'spawn-failed', detail: String((error && error.message) || error) }
528
+ }
529
+ }
530
+
491
531
  function readJsonBody(req, limit = 256 * 1024) {
492
532
  return new Promise((resolve, reject) => {
493
533
  let size = 0
@@ -564,9 +604,50 @@ function registerConfigRoute(ctx, getSettings) {
564
604
  }, 'dsh-reminder-notify: settings route')
565
605
  }
566
606
 
607
+ function registerPreviewRoute(ctx, getSettings) {
608
+ const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
609
+ if (web === undefined || web === null || typeof web.register !== 'function') {
610
+ ctx.logger?.warn?.('dsh-reminder-notify: webServer is unavailable, the preview buttons stay hidden')
611
+ return
612
+ }
613
+ const reply = (res, status, payload) => {
614
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
615
+ res.end(JSON.stringify(payload))
616
+ }
617
+ const route = {
618
+ kind: 'exact',
619
+ path: PREVIEW_ROUTE,
620
+ handler: async (req, res) => {
621
+ try {
622
+ if ((req.method ?? 'GET').toUpperCase() !== 'POST') {
623
+ return reply(res, 405, { ok: false, error: 'use POST' })
624
+ }
625
+ const body = await readJsonBody(req)
626
+ const kind = str(body?.kind, 'done')
627
+ if (!['done', 'decide', 'raw'].includes(kind)) {
628
+ return reply(res, 400, { ok: false, error: `unknown kind: ${kind}` })
629
+ }
630
+ const result = await previewAudio(kind, getSettings())
631
+ if (result.ok) return reply(res, 200, result)
632
+ const status = result.error === 'no-audio' || result.error === 'audio-not-found' ? 400 : 500
633
+ return reply(res, status, result)
634
+ } catch (error) {
635
+ return reply(res, 500, { ok: false, error: String(error?.message ?? error) })
636
+ }
637
+ },
638
+ }
639
+ ctx.effect(() => {
640
+ const dispose = web.register(route)
641
+ return () => {
642
+ if (typeof dispose === 'function') dispose()
643
+ }
644
+ }, 'dsh-reminder-notify: preview route')
645
+ }
646
+
567
647
  export function apply(ctx, config) {
568
648
  registerAudioRoute(ctx, () => settingsOf(config))
569
649
  registerConfigRoute(ctx, () => settingsOf(config))
650
+ registerPreviewRoute(ctx, () => settingsOf(config))
570
651
  const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools
571
652
  if (tools === undefined || tools === null || typeof tools.register !== 'function') {
572
653
  ctx.logger?.warn?.('dsh-reminder-notify: tools service is unavailable, notify_user was not registered')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-reminder-notify",
3
- "version": "0.8.2",
3
+ "version": "0.9.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.8.1",
52
- "publishTimestamp": 1795094364,
51
+ "version": "0.8.2",
52
+ "publishTimestamp": 1795096031,
53
53
  "source": {
54
54
  "type": "npm"
55
55
  },