dsh-bark-push 0.1.6 → 0.2.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/lib/client.js CHANGED
@@ -28,24 +28,24 @@ window.__ModuleLoader__.load({
28
28
 
29
29
  const COPY = {
30
30
  zh: {
31
- nav: "Bark 推送",
32
- mute: "静音 Bark 通知",
33
- unmute: "取消静音 Bark 通知",
34
- muted: "Bark 通知已静音",
35
- unmuted: "Bark 通知已取消静音",
36
- settingsTitle: "Bark 推送",
37
- settingsIntro: "在下方配置 Bark Server、Device Key、通知类型与静音状态。",
31
+ nav: "推送通知",
32
+ mute: "静音推送通知",
33
+ unmute: "取消静音推送通知",
34
+ muted: "推送通知已静音",
35
+ unmuted: "推送通知已取消静音",
36
+ settingsTitle: "推送通知",
37
+ settingsIntro: "在下方管理推送渠道、通知规则与静音状态。",
38
38
  unavailable: "管理接口不可用;请确认 Web 运行时与 client-connection 已加载。",
39
39
  failed: "操作失败",
40
40
  },
41
41
  en: {
42
- nav: "Bark push",
43
- mute: "Mute Bark notifications",
44
- unmute: "Unmute Bark notifications",
45
- muted: "Bark notifications muted",
46
- unmuted: "Bark notifications unmuted",
47
- settingsTitle: "Bark push",
48
- settingsIntro: "Configure the Bark server, device keys, notification types, and mute state below.",
42
+ nav: "Push notifications",
43
+ mute: "Mute push notifications",
44
+ unmute: "Unmute push notifications",
45
+ muted: "Push notifications muted",
46
+ unmuted: "Push notifications unmuted",
47
+ settingsTitle: "Push notifications",
48
+ settingsIntro: "Manage push channels, notification rules, and mute state below.",
49
49
  unavailable: "Management API unavailable; check that the Web runtime and client-connection are mounted.",
50
50
  failed: "Action failed",
51
51
  },
@@ -74,6 +74,44 @@ window.__ModuleLoader__.load({
74
74
  listeners: new Set(),
75
75
  };
76
76
 
77
+ /**
78
+ * Transient notices raised by the iframe management page. The iframe cannot
79
+ * anchor a fixed toast (the host grows it to full content height), so it
80
+ * posts here and this top-document store feeds a `shell.overlay` entry.
81
+ */
82
+ const toastStore = (() => {
83
+ let current = null;
84
+ let seq = 0;
85
+ const listeners = new Set();
86
+ const emit = () => {
87
+ for (const listener of listeners) {
88
+ try {
89
+ listener();
90
+ } catch (_) {
91
+ // A broken subscriber must not stop the others.
92
+ }
93
+ }
94
+ };
95
+ return {
96
+ get: () => current,
97
+ subscribe(listener) {
98
+ listeners.add(listener);
99
+ return () => listeners.delete(listener);
100
+ },
101
+ show(message, kind) {
102
+ if (!message) return;
103
+ seq += 1;
104
+ current = { id: seq, message: String(message), kind: kind === 'bad' ? 'bad' : 'ok' };
105
+ emit();
106
+ },
107
+ dismiss() {
108
+ if (current === null) return;
109
+ current = null;
110
+ emit();
111
+ },
112
+ };
113
+ })();
114
+
77
115
  function emit() {
78
116
  for (const listener of store.listeners) {
79
117
  try {
@@ -181,6 +219,50 @@ window.__ModuleLoader__.load({
181
219
  );
182
220
  }
183
221
 
222
+ /**
223
+ * Frame-wide toast rendered into the host's `shell.overlay` seat. It lives
224
+ * in the top document (outside the Settings iframe), so it stays visible
225
+ * regardless of how far the Settings content is scrolled.
226
+ */
227
+ function BarkToast(props) {
228
+ const notify = props.store;
229
+ const [state, setState] = React.useState(notify.get());
230
+ React.useEffect(() => notify.subscribe(() => setState(notify.get())), [notify]);
231
+ React.useEffect(() => {
232
+ if (state === null) return undefined;
233
+ const timer = setTimeout(() => notify.dismiss(), 3200);
234
+ return () => clearTimeout(timer);
235
+ }, [state, notify]);
236
+ if (state === null) return null;
237
+ const tone = state.kind === 'bad'
238
+ ? { background: '#c0392b', color: '#ffffff' }
239
+ : { background: '#1c1d21', color: '#ffffff' };
240
+ return React.createElement(
241
+ 'div',
242
+ {
243
+ role: 'status',
244
+ 'aria-live': 'polite',
245
+ 'data-bark-toast': state.kind,
246
+ style: {
247
+ position: 'absolute',
248
+ left: '50%',
249
+ bottom: '24px',
250
+ transform: 'translateX(-50%)',
251
+ maxWidth: '80vw',
252
+ padding: '9px 16px',
253
+ borderRadius: '999px',
254
+ fontSize: '13px',
255
+ lineHeight: '1.5',
256
+ textAlign: 'center',
257
+ boxShadow: '0 6px 24px rgba(0, 0, 0, .18)',
258
+ pointerEvents: 'auto',
259
+ ...tone,
260
+ },
261
+ },
262
+ state.message,
263
+ );
264
+ }
265
+
184
266
  function SessionMuteAction(props) {
185
267
  const muted = useMuted("session", props.sessionId);
186
268
  const [busy, setBusy] = React.useState(false);
@@ -344,8 +426,38 @@ window.__ModuleLoader__.load({
344
426
  // Non-DOM test harnesses skip the refresh timer.
345
427
  }
346
428
 
429
+ // Bridge: the management iframe posts toast notices here for the
430
+ // frame-wide overlay, because a toast inside the auto-height iframe would
431
+ // be anchored to the whole (tall) document rather than the viewport.
432
+ try {
433
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
434
+ const onToast = (event) => {
435
+ if (event.origin !== window.location.origin) return;
436
+ const data = event.data;
437
+ if (!data || data.type !== "dsh-bark-push:toast") return;
438
+ toastStore.show(data.message, data.kind);
439
+ };
440
+ window.addEventListener("message", onToast);
441
+ ctx.effect(() => () => window.removeEventListener("message", onToast), "bark-push: toast bridge");
442
+ }
443
+ } catch (_) {
444
+ // No window (non-web composition): notices stay local to the iframe.
445
+ }
446
+
347
447
  if (!ctx.slots) return;
348
448
 
449
+ // Frame-wide overlay entry hosted by the layout shell (top document,
450
+ // above every column and outside their scroll containers).
451
+ try {
452
+ ctx.slots.inject("shell.overlay", () => ctx.slots.register({
453
+ name: "shell.overlay",
454
+ id: "dsh-bark-push.toast",
455
+ inject: () => ({ store: toastStore }),
456
+ }, BarkToast));
457
+ } catch (_) {
458
+ // Hosts without the overlay seat simply do not show host toasts.
459
+ }
460
+
349
461
  // Settings section: an authenticated iframe keeps the rich form out of
350
462
  // the client bundle and works in every web shell that declares the slot.
351
463
  try {
@@ -487,7 +599,7 @@ window.__ModuleLoader__.load({
487
599
 
488
600
  exports.apply = apply;
489
601
  exports.inject = inject;
490
- exports.__internals = { store, request, toggle, adopt, useMuted, COPY, NS, BELL_PATHS };
602
+ exports.__internals = { store, toastStore, request, toggle, adopt, useMuted, COPY, NS, BELL_PATHS };
491
603
  return module.exports;
492
604
  },
493
605
  });
package/lib/config.js CHANGED
@@ -10,6 +10,8 @@
10
10
  * @module dsh-bark-push/config
11
11
  */
12
12
 
13
+ import { generateChannelId, MAX_CHANNELS, providerFor } from './channels.js';
14
+
13
15
  /** Bark notification levels accepted by the official server and most forks. */
14
16
  export const LEVELS = Object.freeze(['active', 'timeSensitive', 'passive', 'critical']);
15
17
 
@@ -30,6 +32,7 @@ export const CONFIG_KEYS = Object.freeze([
30
32
  'enabled',
31
33
  'server',
32
34
  'deviceKeys',
35
+ 'channels',
33
36
  'group',
34
37
  'icon',
35
38
  'soundReply',
@@ -60,6 +63,7 @@ export const DEFAULTS = Object.freeze({
60
63
  enabled: true,
61
64
  server: 'https://api.day.app',
62
65
  deviceKeys: Object.freeze([]),
66
+ channels: Object.freeze([]),
63
67
  group: 'DSH',
64
68
  icon: '',
65
69
  soundReply: '',
@@ -253,6 +257,81 @@ function levelOf(value, legacy, fallback) {
253
257
  return LEVELS.includes(fallback) ? fallback : 'active';
254
258
  }
255
259
 
260
+ /**
261
+ * Normalize one field value for a channel descriptor.
262
+ * @param {object} field - descriptor field.
263
+ * @param {unknown} raw - incoming value.
264
+ * @param {unknown} stored - previously stored value, used for blank secrets.
265
+ * @returns {unknown} normalized value.
266
+ */
267
+ function normalizeChannelField(field, raw, stored) {
268
+ if (field.kind === 'checkbox') {
269
+ if (typeof raw === 'boolean') return raw;
270
+ if (typeof stored === 'boolean') return stored;
271
+ return field.default === true;
272
+ }
273
+ if (field.kind === 'number') {
274
+ const numeric = typeof raw === 'number' ? raw : Number(raw);
275
+ if (!Number.isFinite(numeric)) return field.default !== undefined ? String(field.default) : '';
276
+ return String(Math.round(numeric));
277
+ }
278
+ const limit = field.kind === 'textarea' ? 4000 : 1000;
279
+ let value = typeof raw === 'string' ? raw.trim() : typeof stored === 'string' ? stored : field.default !== undefined ? String(field.default) : '';
280
+ if (value.length > limit) value = value.slice(0, limit);
281
+ // A blank secret keeps the stored value so the browser never has to round-trip
282
+ // a token it was never shown.
283
+ if (field.kind === 'secret' && value.length === 0 && typeof stored === 'string') return stored;
284
+ return value;
285
+ }
286
+
287
+ /**
288
+ * Normalize the extra-channel list. Unknown types are dropped, ids are kept
289
+ * stable where valid, and every value is bounded. A missing `channels` field
290
+ * falls back to the previously normalized list so partial overlays never wipe
291
+ * configured channels.
292
+ * @param {unknown} value - raw channels array.
293
+ * @param {unknown} base - previously normalized channels array.
294
+ * @param {string[]} warnings - warning sink.
295
+ * @returns {Array<object>} normalized channels.
296
+ */
297
+ export function normalizeChannels(value, base = [], warnings = []) {
298
+ const source = Array.isArray(value) ? value : Array.isArray(base) ? base : [];
299
+ const baseById = new Map(
300
+ (Array.isArray(base) ? base : []).filter((item) => item && typeof item.id === 'string').map((item) => [item.id, item]),
301
+ );
302
+ const out = [];
303
+ const seen = new Set();
304
+ for (const item of source) {
305
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue;
306
+ const provider = providerFor(item.type);
307
+ if (!provider) {
308
+ if (typeof item.type === 'string' && item.type.length > 0) warnings.push(`未知渠道类型「${item.type}」,已忽略`);
309
+ continue;
310
+ }
311
+ let id = typeof item.id === 'string' && /^ch_[A-Za-z0-9]+$/.test(item.id) ? item.id : generateChannelId();
312
+ if (seen.has(id)) id = generateChannelId();
313
+ seen.add(id);
314
+ const storedConfig = baseById.get(id)?.config ?? {};
315
+ const rawConfig = item.config !== null && typeof item.config === 'object' && !Array.isArray(item.config) ? item.config : {};
316
+ const config = {};
317
+ for (const field of provider.fields) {
318
+ config[field.key] = normalizeChannelField(field, rawConfig[field.key], storedConfig[field.key]);
319
+ }
320
+ out.push({
321
+ id,
322
+ type: provider.type,
323
+ label: typeof item.label === 'string' ? item.label.trim().slice(0, 64) : '',
324
+ enabled: item.enabled !== false,
325
+ config,
326
+ });
327
+ if (out.length >= MAX_CHANNELS) {
328
+ if (source.length > MAX_CHANNELS) warnings.push(`渠道超过 ${MAX_CHANNELS} 个,仅保留前 ${MAX_CHANNELS} 个`);
329
+ break;
330
+ }
331
+ }
332
+ return out;
333
+ }
334
+
256
335
  /**
257
336
  * Normalize a complete field set against an already-normalized base. The base
258
337
  * is always one produced by this module or {@link DEFAULTS}, so every fallback
@@ -282,6 +361,7 @@ function normalizeFields(raw, base, warnings) {
282
361
  enabled: booleanOf(raw.enabled, base.enabled),
283
362
  server,
284
363
  deviceKeys: keys,
364
+ channels: normalizeChannels(raw.channels, base.channels, warnings),
285
365
  group: textOf(raw.group, base.group, 64),
286
366
  icon: typeof raw.icon === 'string' ? raw.icon.trim().slice(0, 512) : base.icon,
287
367
  soundReply: soundOf(raw.soundReply, raw.soundNormal, base.soundReply),
@@ -362,14 +442,39 @@ export function publicConfig(config) {
362
442
  const keys = normalizeDeviceKeys(source.deviceKeys);
363
443
  const out = {};
364
444
  for (const key of CONFIG_KEYS) {
365
- if (key === 'deviceKeys' || LEGACY_CONFIG_KEYS.includes(key)) continue;
445
+ if (key === 'deviceKeys' || key === 'channels' || LEGACY_CONFIG_KEYS.includes(key)) continue;
366
446
  out[key] = source[key];
367
447
  }
368
448
  out.deviceKeyCount = keys.length;
369
449
  out.deviceKeysMasked = keys.map((key) => maskDeviceKey(key));
450
+ out.channels = publicChannels(normalizeChannels(source.channels, [], []));
370
451
  return out;
371
452
  }
372
453
 
454
+ /**
455
+ * Project channels without leaking secrets. Secret fields become empty strings
456
+ * and a `secretsSet` map tells the page which ones are already stored.
457
+ * @param {Array<object>} channels - normalized channels.
458
+ * @returns {Array<object>} masked channels.
459
+ */
460
+ export function publicChannels(channels) {
461
+ return (Array.isArray(channels) ? channels : []).map((channel) => {
462
+ const provider = providerFor(channel.type);
463
+ const config = {};
464
+ const secretsSet = {};
465
+ for (const field of provider?.fields ?? []) {
466
+ if (field.kind === 'secret') {
467
+ const value = channel.config?.[field.key];
468
+ secretsSet[field.key] = typeof value === 'string' && value.length > 0;
469
+ config[field.key] = '';
470
+ } else {
471
+ config[field.key] = channel.config?.[field.key];
472
+ }
473
+ }
474
+ return { id: channel.id, type: channel.type, label: channel.label, enabled: channel.enabled, config, secretsSet };
475
+ });
476
+ }
477
+
373
478
  /**
374
479
  * Extract only the config keys the management API may write.
375
480
  * @param {unknown} input - raw request body.
package/lib/http.js CHANGED
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { normalizeDeviceKeys, publicConfig, writableConfigPatch } from './config.js';
14
+ import { channelTypeSummaries, providerFor } from './channels.js';
14
15
  import { renderUiPage } from './ui.js';
15
16
 
16
17
  /** Exact route paths, all below `/api`. */
@@ -21,6 +22,7 @@ export const ROUTES = Object.freeze({
21
22
  mute: '/api/bark-push/mute',
22
23
  toggle: '/api/bark-push/toggle',
23
24
  test: '/api/bark-push/test',
25
+ testChannel: '/api/bark-push/test-channel',
24
26
  });
25
27
 
26
28
  /** Maximum accepted JSON request body. */
@@ -211,6 +213,7 @@ export function installHttpRoutes(ctx, runtime, host = ctx) {
211
213
  ok: true,
212
214
  version: runtime.version,
213
215
  config: publicConfig(config),
216
+ channelTypes: channelTypeSummaries(),
214
217
  mute: {
215
218
  workspaces: snapshot.mutedWorkspaces,
216
219
  sessions: snapshot.mutedSessions,
@@ -301,6 +304,28 @@ export function installHttpRoutes(ctx, runtime, host = ctx) {
301
304
  }
302
305
  });
303
306
 
307
+ register(ROUTES.testChannel, ['POST'], async (request) => {
308
+ if (!writeAllowed(request)) return json({ ok: false, error: 'forbidden' }, 403);
309
+ let body;
310
+ try {
311
+ body = await readJson(request);
312
+ } catch (error) {
313
+ return json({ ok: false, error: error?.message ?? '无效请求' }, 400);
314
+ }
315
+ if (typeof body.id !== 'string' || body.id.trim().length === 0) {
316
+ return json({ ok: false, error: '缺少渠道 id' }, 400);
317
+ }
318
+ if (typeof runtime.testChannel !== 'function') {
319
+ return json({ ok: false, error: '当前运行时未启用渠道测试' }, 501);
320
+ }
321
+ try {
322
+ const result = await runtime.testChannel(body.id.trim());
323
+ return json({ ok: result.ok, result, state: statePayload() });
324
+ } catch (error) {
325
+ return json({ ok: false, error: error?.message ?? '渠道测试失败' }, 500);
326
+ }
327
+ });
328
+
304
329
  return () => {
305
330
  for (const dispose of disposers) {
306
331
  try {
@@ -336,5 +361,50 @@ export function nextConfigOverlay(currentOverlay, body, effective = {}) {
336
361
  overlay.deviceKeys = normalizeDeviceKeys([...baseline, ...input.addDeviceKeys]);
337
362
  }
338
363
  if (input.clearDeviceKeys === true) overlay.deviceKeys = [];
364
+ if (Array.isArray(input.channels)) {
365
+ overlay.channels = resolveChannelSecrets(input.channels, effective.channels);
366
+ } else if (input.clearChannels === true) {
367
+ overlay.channels = [];
368
+ }
339
369
  return { overlay, reset: false };
340
370
  }
371
+
372
+ /**
373
+ * Merge incoming channel edits with the stored secrets. A blank secret field
374
+ * keeps the previously stored value, because the browser is never shown it.
375
+ * @param {Array<unknown>} incoming - channels from the request body.
376
+ * @param {unknown} effective - current effective channels (with real secrets).
377
+ * @returns {Array<object>} resolved channels.
378
+ */
379
+ export function resolveChannelSecrets(incoming, effective) {
380
+ const stored = new Map(
381
+ (Array.isArray(effective) ? effective : [])
382
+ .filter((channel) => channel && typeof channel.id === 'string')
383
+ .map((channel) => [channel.id, channel]),
384
+ );
385
+ const out = [];
386
+ for (const item of incoming) {
387
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue;
388
+ const provider = providerFor(item.type);
389
+ if (!provider) continue;
390
+ const baseConfig = stored.get(item.id)?.config ?? {};
391
+ const rawConfig = item.config !== null && typeof item.config === 'object' && !Array.isArray(item.config) ? item.config : {};
392
+ const config = {};
393
+ for (const field of provider.fields) {
394
+ if (field.kind === 'secret') {
395
+ const value = typeof rawConfig[field.key] === 'string' ? rawConfig[field.key].trim() : '';
396
+ config[field.key] = value.length > 0 ? value : typeof baseConfig[field.key] === 'string' ? baseConfig[field.key] : '';
397
+ } else {
398
+ config[field.key] = rawConfig[field.key];
399
+ }
400
+ }
401
+ out.push({
402
+ id: item.id,
403
+ type: item.type,
404
+ label: typeof item.label === 'string' ? item.label : '',
405
+ enabled: item.enabled !== false,
406
+ config,
407
+ });
408
+ }
409
+ return out;
410
+ }
package/lib/index.js CHANGED
@@ -17,6 +17,7 @@ import { readFileSync } from 'node:fs';
17
17
 
18
18
  import { mergeConfig, normalizeConfig, objectOf, publicConfig } from './config.js';
19
19
  import { BarkClient } from './bark.js';
20
+ import { ChannelSender } from './channels.js';
20
21
  import { installSessionBridge, installQuestionBridge } from './events.js';
21
22
  import { installHttpRoutes, nextConfigOverlay } from './http.js';
22
23
  import { Notifier } from './notifier.js';
@@ -105,11 +106,13 @@ export function apply(ctx, config) {
105
106
 
106
107
  const queue = new SerialQueue({ concurrency: 1, limit: 100, logger });
107
108
  const bark = new BarkClient({ getConfig, logger, signal: abort.signal });
109
+ const channels = new ChannelSender({ getConfig, logger, signal: abort.signal });
108
110
  const notifier = new Notifier({
109
111
  ctx,
110
112
  getConfig,
111
113
  state,
112
114
  bark,
115
+ channels,
113
116
  queue,
114
117
  logger,
115
118
  version: packageVersion(),
@@ -142,9 +145,14 @@ export function apply(ctx, config) {
142
145
  const current = getConfig();
143
146
  if (body?.reset === true) {
144
147
  // Credentials are the one thing a "restore defaults" action must not
145
- // silently destroy: keep configured keys unless the caller clears them.
148
+ // silently destroy: keep configured keys and channels unless the caller
149
+ // clears them.
146
150
  const keys = Array.isArray(current.deviceKeys) ? current.deviceKeys : [];
147
- await state.setConfig(keys.length > 0 ? { deviceKeys: keys } : {});
151
+ const chans = Array.isArray(current.channels) ? current.channels : [];
152
+ const keep = {};
153
+ if (keys.length > 0) keep.deviceKeys = keys;
154
+ if (chans.length > 0) keep.channels = chans;
155
+ await state.setConfig(keep);
148
156
  } else {
149
157
  const next = nextConfigOverlay(snapshot.config, body, current);
150
158
  await state.setConfig(next.overlay);
@@ -174,6 +182,12 @@ export function apply(ctx, config) {
174
182
  },
175
183
  /** @returns {Promise<object>} sanitized test outcome. */
176
184
  test: () => notifier.test(),
185
+ /**
186
+ * Test a single extra channel.
187
+ * @param {string} id - channel id.
188
+ * @returns {Promise<object>} sanitized test outcome.
189
+ */
190
+ testChannel: (id) => notifier.testChannel(id),
177
191
  };
178
192
 
179
193
  // The management API is optional: headless compositions have no browser
@@ -201,13 +215,14 @@ export function apply(ctx, config) {
201
215
  );
202
216
 
203
217
  const configSummary = publicConfig(effective);
218
+ const channelCount = Array.isArray(configSummary.channels) ? configSummary.channels.length : 0;
204
219
  if (effective.enabled !== true) {
205
220
  logger.info('bark-push: 已加载,但总开关处于关闭状态');
206
- } else if (configSummary.deviceKeyCount === 0) {
207
- logger.warn('bark-push: 已加载,但尚未配置 Device Key;打开设置页或 cordis.patch.yml 配置后才会推送');
221
+ } else if (configSummary.deviceKeyCount === 0 && channelCount === 0) {
222
+ logger.warn('bark-push: 已加载,但尚未配置 Device Key 或任何推送渠道;打开设置页或 cordis.patch.yml 配置后才会推送');
208
223
  } else {
209
224
  logger.info(
210
- `bark-push: 已启用(group=${effective.group},设备 ${configSummary.deviceKeyCount} 个,状态文件 ${stateFile})`,
225
+ `bark-push: 已启用(group=${effective.group},设备 ${configSummary.deviceKeyCount} 个,额外渠道 ${channelCount} 个,状态文件 ${stateFile})`,
211
226
  );
212
227
  }
213
228
  }
package/lib/notifier.js CHANGED
@@ -70,15 +70,17 @@ export class Notifier {
70
70
  * @param {() => Record<string, unknown>} options.getConfig - current effective config.
71
71
  * @param {object} options.state - StateStore.
72
72
  * @param {object} options.bark - BarkClient.
73
+ * @param {object} [options.channels] - ChannelSender for the extra channels.
73
74
  * @param {object} options.queue - SerialQueue.
74
75
  * @param {{ info: Function, warn: Function, error: Function, debug: Function }} options.logger - logger.
75
76
  * @param {string} options.version - plugin version for diagnostics.
76
77
  */
77
- constructor({ ctx, getConfig, state, bark, queue, logger, version }) {
78
+ constructor({ ctx, getConfig, state, bark, channels, queue, logger, version }) {
78
79
  this.ctx = ctx;
79
80
  this.getConfig = getConfig;
80
81
  this.state = state;
81
82
  this.bark = bark;
83
+ this.channels = channels;
82
84
  this.queue = queue;
83
85
  this.logger = logger;
84
86
  this.version = version;
@@ -207,6 +209,10 @@ export class Notifier {
207
209
  results: Array.isArray(record.results)
208
210
  ? record.results.slice(0, 20).map((entry) => ({
209
211
  maskedKey: entry.maskedKey,
212
+ channelId: entry.channelId,
213
+ channelType: entry.channelType,
214
+ label: entry.label,
215
+ skipped: entry.skipped === true,
210
216
  ok: entry.ok === true,
211
217
  status: entry.status ?? null,
212
218
  attempts: entry.attempts ?? null,
@@ -321,7 +327,9 @@ export class Notifier {
321
327
  if (job.kind === 'reply' && config.notifyOnReply !== true) return;
322
328
  if (job.kind === 'approval' && config.notifyOnApproval !== true) return;
323
329
  if (job.kind === 'question' && config.notifyOnQuestion !== true) return;
324
- if (!Array.isArray(config.deviceKeys) || config.deviceKeys.length === 0) return;
330
+ const hasBark = Array.isArray(config.deviceKeys) && config.deviceKeys.length > 0;
331
+ const hasChannels = this.channels?.hasEnabled?.() === true;
332
+ if (!hasBark && !hasChannels) return;
325
333
 
326
334
  // Re-read shared state and re-resolve the workspace immediately before
327
335
  // sending: a mute applied while this job waited (including one written
@@ -364,11 +372,16 @@ export class Notifier {
364
372
  });
365
373
  if (url !== undefined) note.url = url;
366
374
  }
367
- const result = await this.bark.send(note);
368
- this.#record({ kind: job.kind, ...result });
369
- if (result.ok) {
375
+ const barkResult = hasBark
376
+ ? await this.bark.send(note)
377
+ : { ok: true, skipped: true, reason: 'no-device-key', results: [] };
378
+ const channelResult = hasChannels ? await this.channels.send(note) : { ok: true, results: [] };
379
+ const results = [...(barkResult.results ?? []), ...(channelResult.results ?? [])];
380
+ const ok = (hasBark ? barkResult.ok === true : true) && (hasChannels ? channelResult.ok === true : true);
381
+ this.#record({ kind: job.kind, ok, skipped: !hasBark && !hasChannels, results });
382
+ if (ok) {
370
383
  this.logger.debug?.(`bark-push: ${job.kind} 已推送`);
371
- } else if (!result.skipped) {
384
+ } else if (!(barkResult.skipped === true && channelResult.results.length === 0)) {
372
385
  this.logger.warn?.(`bark-push: ${job.kind} 推送失败`);
373
386
  }
374
387
  }, job.kind);
@@ -379,35 +392,75 @@ export class Notifier {
379
392
 
380
393
  /**
381
394
  * Send one explicit test notification with the current effective config.
395
+ * Bark (when keys exist) and every enabled extra channel are exercised.
382
396
  * @returns {Promise<object>} sanitized outcome.
383
397
  */
384
398
  async test() {
385
399
  const config = this.getConfig();
386
- const note = formatTest(config);
387
- const result = await this.bark.send(note, { force: true });
388
- this.#record({ kind: 'test', ...result });
400
+ const hasBark = Array.isArray(config.deviceKeys) && config.deviceKeys.length > 0;
401
+ // The default "test push" button exercises only the built-in Bark channel.
402
+ // Extra channels are tested individually from their own card, so one test
403
+ // never blasts every configured channel at once.
404
+ const barkResult = hasBark
405
+ ? await this.bark.send(formatTest(config), { force: true })
406
+ : { ok: false, skipped: true, reason: 'no-device-key', results: [] };
407
+ const ok = hasBark ? barkResult.ok === true : false;
408
+ const results = barkResult.results ?? [];
409
+ this.#record({ kind: 'test', ok, skipped: !hasBark, results });
389
410
  try {
390
- await this.state.recordTest({
391
- at: new Date().toISOString(),
392
- ok: result.ok === true,
393
- results: Array.isArray(result.results) ? result.results : [],
394
- });
411
+ await this.state.recordTest({ at: new Date().toISOString(), ok, results });
395
412
  } catch (error) {
396
413
  this.logger.warn?.(`bark-push: 测试结果无法写入状态文件:${error?.message ?? String(error)}`);
397
414
  }
415
+ return {
416
+ ok,
417
+ skipped: !hasBark,
418
+ reason: hasBark ? barkResult.reason : 'no-device-key',
419
+ results: results.map((entry) => this.#publicResult(entry)),
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Test a single extra channel by id.
425
+ * @param {string} id - channel id.
426
+ * @returns {Promise<object>} sanitized outcome.
427
+ */
428
+ async testChannel(id) {
429
+ if (!this.channels) return { ok: false, skipped: true, reason: 'no-channels', results: [] };
430
+ const result = await this.channels.testOne(id, this.#testNote());
398
431
  return {
399
432
  ok: result.ok === true,
400
433
  skipped: result.skipped === true,
401
434
  reason: result.reason,
402
- results: Array.isArray(result.results)
403
- ? result.results.map((entry) => ({
404
- maskedKey: entry.maskedKey,
405
- ok: entry.ok === true,
406
- status: entry.status ?? null,
407
- attempts: entry.attempts ?? null,
408
- message: entry.message,
409
- }))
410
- : [],
435
+ results: Array.isArray(result.results) ? result.results.map((entry) => this.#publicResult(entry)) : [],
436
+ };
437
+ }
438
+
439
+ /**
440
+ * A channel-agnostic test note.
441
+ * @returns {{ title: string, body: string, kind: 'test' }} note.
442
+ */
443
+ #testNote() {
444
+ const stamp = new Date().toLocaleString('zh-CN', { hour12: false });
445
+ return { title: 'DSH 推送测试', body: `配置有效:这是一条来自 DSH 的测试通知。\n时间:${stamp}`, kind: 'test' };
446
+ }
447
+
448
+ /**
449
+ * Reduce one delivery result to the shape the management page consumes.
450
+ * @param {object} entry - raw result.
451
+ * @returns {object} sanitized result.
452
+ */
453
+ #publicResult(entry) {
454
+ return {
455
+ maskedKey: entry.maskedKey,
456
+ channelId: entry.channelId,
457
+ channelType: entry.channelType,
458
+ label: entry.label,
459
+ ok: entry.ok === true,
460
+ skipped: entry.skipped === true,
461
+ status: entry.status ?? null,
462
+ attempts: entry.attempts ?? null,
463
+ message: entry.message,
411
464
  };
412
465
  }
413
466
  }