dsh-bark-push 0.1.6 → 0.2.1
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/CHANGELOG.md +29 -0
- package/README.md +72 -23
- package/cordis.patch.yml +6 -0
- package/lib/channels.js +528 -0
- package/lib/client.js +363 -60
- package/lib/config.js +106 -1
- package/lib/http.js +127 -30
- package/lib/index.js +20 -5
- package/lib/notifier.js +106 -32
- package/lib/ui.js +627 -155
- package/package.json +8 -2
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. */
|
|
@@ -114,19 +116,26 @@ function buildCatalog(ctx, snapshot) {
|
|
|
114
116
|
const mutedWorkspaces = new Set(snapshot.mutedWorkspaces);
|
|
115
117
|
const mutedSessions = new Set(snapshot.mutedSessions);
|
|
116
118
|
const workspaces = [];
|
|
119
|
+
/** Session id -> workspace id for every Session the registry knows. */
|
|
117
120
|
const workspaceBySession = new Map();
|
|
121
|
+
/** Workspace id -> root path, used as a fallback row detail. */
|
|
122
|
+
const workspacePathById = new Map();
|
|
118
123
|
try {
|
|
119
124
|
const registry = serviceOf(ctx, 'workspaceRegistry');
|
|
120
125
|
const list = typeof registry?.list === 'function' ? registry.list() : [];
|
|
121
126
|
for (const workspace of list) {
|
|
122
127
|
const id = String(workspace.id);
|
|
128
|
+
const path = typeof workspace.path === 'string' ? workspace.path : '';
|
|
123
129
|
workspaces.push({
|
|
124
130
|
id,
|
|
125
131
|
title: workspace.title,
|
|
126
|
-
path
|
|
132
|
+
path,
|
|
127
133
|
muted: mutedWorkspaces.has(id),
|
|
128
134
|
});
|
|
129
|
-
|
|
135
|
+
workspacePathById.set(id, path);
|
|
136
|
+
for (const sessionId of Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []) {
|
|
137
|
+
workspaceBySession.set(String(sessionId), id);
|
|
138
|
+
}
|
|
130
139
|
}
|
|
131
140
|
} catch {
|
|
132
141
|
// A missing or broken registry only means the page shows no projects.
|
|
@@ -134,45 +143,65 @@ function buildCatalog(ctx, snapshot) {
|
|
|
134
143
|
|
|
135
144
|
const sessions = [];
|
|
136
145
|
const seen = new Set();
|
|
146
|
+
const liveRows = [];
|
|
137
147
|
try {
|
|
138
148
|
const sessionsService = serviceOf(ctx, 'sessions');
|
|
139
149
|
const live = typeof sessionsService?.list === 'function' ? sessionsService.list() : [];
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
})
|
|
160
|
-
.filter((row) => row.id.length > 0)
|
|
161
|
-
.sort((left, right) => right.createdAt - left.createdAt)
|
|
162
|
-
.slice(0, 300);
|
|
163
|
-
for (const row of rows) {
|
|
164
|
-
sessions.push(row);
|
|
165
|
-
seen.add(row.id);
|
|
150
|
+
for (const session of live) {
|
|
151
|
+
const id = String(session.header?.id ?? session.id ?? '');
|
|
152
|
+
if (id.length === 0) continue;
|
|
153
|
+
let title = '';
|
|
154
|
+
try {
|
|
155
|
+
title = serviceOf(ctx, 'sessionTitle')?.get?.(session)?.title ?? '';
|
|
156
|
+
} catch {
|
|
157
|
+
title = '';
|
|
158
|
+
}
|
|
159
|
+
liveRows.push({
|
|
160
|
+
id,
|
|
161
|
+
title: typeof title === 'string' ? title : '',
|
|
162
|
+
cwd: typeof session.header?.cwd === 'string' ? session.header.cwd : '',
|
|
163
|
+
workspaceId: workspaceBySession.get(id) ?? null,
|
|
164
|
+
origin: session.header?.origin ?? null,
|
|
165
|
+
createdAt: Number.isFinite(session.header?.createdAt) ? session.header.createdAt : 0,
|
|
166
|
+
muted: mutedSessions.has(id),
|
|
167
|
+
offline: false,
|
|
168
|
+
});
|
|
166
169
|
}
|
|
167
170
|
} catch {
|
|
168
171
|
// Live Session enumeration is optional.
|
|
169
172
|
}
|
|
173
|
+
liveRows.sort((left, right) => right.createdAt - left.createdAt);
|
|
174
|
+
for (const row of liveRows.slice(0, 300)) {
|
|
175
|
+
sessions.push(row);
|
|
176
|
+
seen.add(row.id);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Persisted Sessions that are not loaded right now still belong to a
|
|
180
|
+
// workspace. Include them so the mute list is complete and the client can
|
|
181
|
+
// map every row to its workspace.
|
|
182
|
+
for (const [sessionId, workspaceId] of workspaceBySession) {
|
|
183
|
+
if (seen.has(sessionId)) continue;
|
|
184
|
+
sessions.push({
|
|
185
|
+
id: sessionId,
|
|
186
|
+
title: '',
|
|
187
|
+
cwd: workspacePathById.get(workspaceId) ?? '',
|
|
188
|
+
workspaceId,
|
|
189
|
+
origin: null,
|
|
190
|
+
createdAt: 0,
|
|
191
|
+
muted: mutedSessions.has(sessionId),
|
|
192
|
+
offline: true,
|
|
193
|
+
});
|
|
194
|
+
seen.add(sessionId);
|
|
195
|
+
if (sessions.length >= 500) break;
|
|
196
|
+
}
|
|
170
197
|
|
|
171
198
|
for (const id of mutedSessions) {
|
|
172
199
|
if (seen.has(id)) continue;
|
|
173
|
-
sessions.push({ id, title: '', cwd: '', workspaceId: null, origin: null, createdAt: 0, muted: true, offline: true });
|
|
200
|
+
sessions.push({ id, title: '', cwd: '', workspaceId: workspaceBySession.get(id) ?? null, origin: null, createdAt: 0, muted: true, offline: true });
|
|
201
|
+
seen.add(id);
|
|
202
|
+
if (sessions.length >= 500) break;
|
|
174
203
|
}
|
|
175
|
-
return { workspaces, sessions };
|
|
204
|
+
return { workspaces, sessions, sessionWorkspace: Object.fromEntries(workspaceBySession) };
|
|
176
205
|
}
|
|
177
206
|
|
|
178
207
|
/**
|
|
@@ -211,6 +240,7 @@ export function installHttpRoutes(ctx, runtime, host = ctx) {
|
|
|
211
240
|
ok: true,
|
|
212
241
|
version: runtime.version,
|
|
213
242
|
config: publicConfig(config),
|
|
243
|
+
channelTypes: channelTypeSummaries(),
|
|
214
244
|
mute: {
|
|
215
245
|
workspaces: snapshot.mutedWorkspaces,
|
|
216
246
|
sessions: snapshot.mutedSessions,
|
|
@@ -301,6 +331,28 @@ export function installHttpRoutes(ctx, runtime, host = ctx) {
|
|
|
301
331
|
}
|
|
302
332
|
});
|
|
303
333
|
|
|
334
|
+
register(ROUTES.testChannel, ['POST'], async (request) => {
|
|
335
|
+
if (!writeAllowed(request)) return json({ ok: false, error: 'forbidden' }, 403);
|
|
336
|
+
let body;
|
|
337
|
+
try {
|
|
338
|
+
body = await readJson(request);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
return json({ ok: false, error: error?.message ?? '无效请求' }, 400);
|
|
341
|
+
}
|
|
342
|
+
if (typeof body.id !== 'string' || body.id.trim().length === 0) {
|
|
343
|
+
return json({ ok: false, error: '缺少渠道 id' }, 400);
|
|
344
|
+
}
|
|
345
|
+
if (typeof runtime.testChannel !== 'function') {
|
|
346
|
+
return json({ ok: false, error: '当前运行时未启用渠道测试' }, 501);
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
const result = await runtime.testChannel(body.id.trim());
|
|
350
|
+
return json({ ok: result.ok, result, state: statePayload() });
|
|
351
|
+
} catch (error) {
|
|
352
|
+
return json({ ok: false, error: error?.message ?? '渠道测试失败' }, 500);
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
|
|
304
356
|
return () => {
|
|
305
357
|
for (const dispose of disposers) {
|
|
306
358
|
try {
|
|
@@ -336,5 +388,50 @@ export function nextConfigOverlay(currentOverlay, body, effective = {}) {
|
|
|
336
388
|
overlay.deviceKeys = normalizeDeviceKeys([...baseline, ...input.addDeviceKeys]);
|
|
337
389
|
}
|
|
338
390
|
if (input.clearDeviceKeys === true) overlay.deviceKeys = [];
|
|
391
|
+
if (Array.isArray(input.channels)) {
|
|
392
|
+
overlay.channels = resolveChannelSecrets(input.channels, effective.channels);
|
|
393
|
+
} else if (input.clearChannels === true) {
|
|
394
|
+
overlay.channels = [];
|
|
395
|
+
}
|
|
339
396
|
return { overlay, reset: false };
|
|
340
397
|
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Merge incoming channel edits with the stored secrets. A blank secret field
|
|
401
|
+
* keeps the previously stored value, because the browser is never shown it.
|
|
402
|
+
* @param {Array<unknown>} incoming - channels from the request body.
|
|
403
|
+
* @param {unknown} effective - current effective channels (with real secrets).
|
|
404
|
+
* @returns {Array<object>} resolved channels.
|
|
405
|
+
*/
|
|
406
|
+
export function resolveChannelSecrets(incoming, effective) {
|
|
407
|
+
const stored = new Map(
|
|
408
|
+
(Array.isArray(effective) ? effective : [])
|
|
409
|
+
.filter((channel) => channel && typeof channel.id === 'string')
|
|
410
|
+
.map((channel) => [channel.id, channel]),
|
|
411
|
+
);
|
|
412
|
+
const out = [];
|
|
413
|
+
for (const item of incoming) {
|
|
414
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue;
|
|
415
|
+
const provider = providerFor(item.type);
|
|
416
|
+
if (!provider) continue;
|
|
417
|
+
const baseConfig = stored.get(item.id)?.config ?? {};
|
|
418
|
+
const rawConfig = item.config !== null && typeof item.config === 'object' && !Array.isArray(item.config) ? item.config : {};
|
|
419
|
+
const config = {};
|
|
420
|
+
for (const field of provider.fields) {
|
|
421
|
+
if (field.kind === 'secret') {
|
|
422
|
+
const value = typeof rawConfig[field.key] === 'string' ? rawConfig[field.key].trim() : '';
|
|
423
|
+
config[field.key] = value.length > 0 ? value : typeof baseConfig[field.key] === 'string' ? baseConfig[field.key] : '';
|
|
424
|
+
} else {
|
|
425
|
+
config[field.key] = rawConfig[field.key];
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
out.push({
|
|
429
|
+
id: item.id,
|
|
430
|
+
type: item.type,
|
|
431
|
+
label: typeof item.label === 'string' ? item.label : '',
|
|
432
|
+
enabled: item.enabled !== false,
|
|
433
|
+
config,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
return out;
|
|
437
|
+
}
|
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
|
|
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
|
-
|
|
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
|
|
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;
|
|
@@ -105,17 +107,19 @@ export class Notifier {
|
|
|
105
107
|
if (cached !== undefined && now - cached.at < 60_000) return cached.key;
|
|
106
108
|
}
|
|
107
109
|
const registry = optionalService(this.ctx, 'workspaceRegistry');
|
|
108
|
-
let
|
|
110
|
+
let list = [];
|
|
109
111
|
try {
|
|
110
|
-
|
|
111
|
-
for (const workspace of list) {
|
|
112
|
-
if (Array.isArray(workspace?.sessionIds) && workspace.sessionIds.includes(sessionId)) {
|
|
113
|
-
key = String(workspace.id);
|
|
114
|
-
break;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
112
|
+
list = typeof registry?.list === 'function' ? registry.list() : [];
|
|
117
113
|
} catch {
|
|
118
|
-
|
|
114
|
+
list = [];
|
|
115
|
+
}
|
|
116
|
+
let key;
|
|
117
|
+
for (const workspace of list) {
|
|
118
|
+
const ids = Array.isArray(workspace?.sessionIds) ? workspace.sessionIds.map(String) : [];
|
|
119
|
+
if (ids.includes(sessionId)) {
|
|
120
|
+
key = String(workspace.id);
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
119
123
|
}
|
|
120
124
|
const cwd = session?.header?.cwd;
|
|
121
125
|
if (key === undefined && typeof cwd === 'string' && cwd.length > 0) {
|
|
@@ -125,6 +129,25 @@ export class Notifier {
|
|
|
125
129
|
} catch {
|
|
126
130
|
// Missing directories and unavailable registries fall through.
|
|
127
131
|
}
|
|
132
|
+
if (key === undefined) {
|
|
133
|
+
// A Session created inside a workspace subdirectory may not be listed in
|
|
134
|
+
// that workspace's sessionIds yet. Fall back to the longest containing
|
|
135
|
+
// workspace path so workspace-level mute still applies.
|
|
136
|
+
const target = cwd.replace(/[\\/]+$/, "");
|
|
137
|
+
let bestId;
|
|
138
|
+
let bestLength = -1;
|
|
139
|
+
for (const workspace of list) {
|
|
140
|
+
const root = typeof workspace?.path === "string" ? workspace.path.replace(/[\\/]+$/, "") : "";
|
|
141
|
+
if (root.length === 0) continue;
|
|
142
|
+
if (target === root || target.startsWith(root + "/") || target.startsWith(root + "\\")) {
|
|
143
|
+
if (root.length > bestLength) {
|
|
144
|
+
bestId = String(workspace.id);
|
|
145
|
+
bestLength = root.length;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (bestId !== undefined) key = bestId;
|
|
150
|
+
}
|
|
128
151
|
if (key === undefined) key = `cwd:${cwd}`;
|
|
129
152
|
}
|
|
130
153
|
if (key !== undefined) {
|
|
@@ -207,6 +230,10 @@ export class Notifier {
|
|
|
207
230
|
results: Array.isArray(record.results)
|
|
208
231
|
? record.results.slice(0, 20).map((entry) => ({
|
|
209
232
|
maskedKey: entry.maskedKey,
|
|
233
|
+
channelId: entry.channelId,
|
|
234
|
+
channelType: entry.channelType,
|
|
235
|
+
label: entry.label,
|
|
236
|
+
skipped: entry.skipped === true,
|
|
210
237
|
ok: entry.ok === true,
|
|
211
238
|
status: entry.status ?? null,
|
|
212
239
|
attempts: entry.attempts ?? null,
|
|
@@ -321,7 +348,9 @@ export class Notifier {
|
|
|
321
348
|
if (job.kind === 'reply' && config.notifyOnReply !== true) return;
|
|
322
349
|
if (job.kind === 'approval' && config.notifyOnApproval !== true) return;
|
|
323
350
|
if (job.kind === 'question' && config.notifyOnQuestion !== true) return;
|
|
324
|
-
|
|
351
|
+
const hasBark = Array.isArray(config.deviceKeys) && config.deviceKeys.length > 0;
|
|
352
|
+
const hasChannels = this.channels?.hasEnabled?.() === true;
|
|
353
|
+
if (!hasBark && !hasChannels) return;
|
|
325
354
|
|
|
326
355
|
// Re-read shared state and re-resolve the workspace immediately before
|
|
327
356
|
// sending: a mute applied while this job waited (including one written
|
|
@@ -364,11 +393,16 @@ export class Notifier {
|
|
|
364
393
|
});
|
|
365
394
|
if (url !== undefined) note.url = url;
|
|
366
395
|
}
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
396
|
+
const barkResult = hasBark
|
|
397
|
+
? await this.bark.send(note)
|
|
398
|
+
: { ok: true, skipped: true, reason: 'no-device-key', results: [] };
|
|
399
|
+
const channelResult = hasChannels ? await this.channels.send(note) : { ok: true, results: [] };
|
|
400
|
+
const results = [...(barkResult.results ?? []), ...(channelResult.results ?? [])];
|
|
401
|
+
const ok = (hasBark ? barkResult.ok === true : true) && (hasChannels ? channelResult.ok === true : true);
|
|
402
|
+
this.#record({ kind: job.kind, ok, skipped: !hasBark && !hasChannels, results });
|
|
403
|
+
if (ok) {
|
|
370
404
|
this.logger.debug?.(`bark-push: ${job.kind} 已推送`);
|
|
371
|
-
} else if (!
|
|
405
|
+
} else if (!(barkResult.skipped === true && channelResult.results.length === 0)) {
|
|
372
406
|
this.logger.warn?.(`bark-push: ${job.kind} 推送失败`);
|
|
373
407
|
}
|
|
374
408
|
}, job.kind);
|
|
@@ -379,35 +413,75 @@ export class Notifier {
|
|
|
379
413
|
|
|
380
414
|
/**
|
|
381
415
|
* Send one explicit test notification with the current effective config.
|
|
416
|
+
* Bark (when keys exist) and every enabled extra channel are exercised.
|
|
382
417
|
* @returns {Promise<object>} sanitized outcome.
|
|
383
418
|
*/
|
|
384
419
|
async test() {
|
|
385
420
|
const config = this.getConfig();
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
421
|
+
const hasBark = Array.isArray(config.deviceKeys) && config.deviceKeys.length > 0;
|
|
422
|
+
// The default "test push" button exercises only the built-in Bark channel.
|
|
423
|
+
// Extra channels are tested individually from their own card, so one test
|
|
424
|
+
// never blasts every configured channel at once.
|
|
425
|
+
const barkResult = hasBark
|
|
426
|
+
? await this.bark.send(formatTest(config), { force: true })
|
|
427
|
+
: { ok: false, skipped: true, reason: 'no-device-key', results: [] };
|
|
428
|
+
const ok = hasBark ? barkResult.ok === true : false;
|
|
429
|
+
const results = barkResult.results ?? [];
|
|
430
|
+
this.#record({ kind: 'test', ok, skipped: !hasBark, results });
|
|
389
431
|
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
|
-
});
|
|
432
|
+
await this.state.recordTest({ at: new Date().toISOString(), ok, results });
|
|
395
433
|
} catch (error) {
|
|
396
434
|
this.logger.warn?.(`bark-push: 测试结果无法写入状态文件:${error?.message ?? String(error)}`);
|
|
397
435
|
}
|
|
436
|
+
return {
|
|
437
|
+
ok,
|
|
438
|
+
skipped: !hasBark,
|
|
439
|
+
reason: hasBark ? barkResult.reason : 'no-device-key',
|
|
440
|
+
results: results.map((entry) => this.#publicResult(entry)),
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Test a single extra channel by id.
|
|
446
|
+
* @param {string} id - channel id.
|
|
447
|
+
* @returns {Promise<object>} sanitized outcome.
|
|
448
|
+
*/
|
|
449
|
+
async testChannel(id) {
|
|
450
|
+
if (!this.channels) return { ok: false, skipped: true, reason: 'no-channels', results: [] };
|
|
451
|
+
const result = await this.channels.testOne(id, this.#testNote());
|
|
398
452
|
return {
|
|
399
453
|
ok: result.ok === true,
|
|
400
454
|
skipped: result.skipped === true,
|
|
401
455
|
reason: result.reason,
|
|
402
|
-
results: Array.isArray(result.results)
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
456
|
+
results: Array.isArray(result.results) ? result.results.map((entry) => this.#publicResult(entry)) : [],
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* A channel-agnostic test note.
|
|
462
|
+
* @returns {{ title: string, body: string, kind: 'test' }} note.
|
|
463
|
+
*/
|
|
464
|
+
#testNote() {
|
|
465
|
+
const stamp = new Date().toLocaleString('zh-CN', { hour12: false });
|
|
466
|
+
return { title: 'DSH 推送测试', body: `配置有效:这是一条来自 DSH 的测试通知。\n时间:${stamp}`, kind: 'test' };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Reduce one delivery result to the shape the management page consumes.
|
|
471
|
+
* @param {object} entry - raw result.
|
|
472
|
+
* @returns {object} sanitized result.
|
|
473
|
+
*/
|
|
474
|
+
#publicResult(entry) {
|
|
475
|
+
return {
|
|
476
|
+
maskedKey: entry.maskedKey,
|
|
477
|
+
channelId: entry.channelId,
|
|
478
|
+
channelType: entry.channelType,
|
|
479
|
+
label: entry.label,
|
|
480
|
+
ok: entry.ok === true,
|
|
481
|
+
skipped: entry.skipped === true,
|
|
482
|
+
status: entry.status ?? null,
|
|
483
|
+
attempts: entry.attempts ?? null,
|
|
484
|
+
message: entry.message,
|
|
411
485
|
};
|
|
412
486
|
}
|
|
413
487
|
}
|