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/channels.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-channel push registry and generic sender.
|
|
3
|
+
*
|
|
4
|
+
* Bark remains the primary, first-class channel (see `bark.js` and the flat
|
|
5
|
+
* `server` / `deviceKeys` config). Everything here adds *additional* channels
|
|
6
|
+
* that receive the same formatted note (`{ title, body, kind, url }`):
|
|
7
|
+
*
|
|
8
|
+
* - Self-hosted push: Gotify, ntfy.
|
|
9
|
+
* - Chinese push services: PushDeer, Server酱 ServerChan, PushPlus.
|
|
10
|
+
* - An extra Bark server and a fully generic Webhook.
|
|
11
|
+
*
|
|
12
|
+
* Every provider is a small descriptor: `fields` drive the management UI and
|
|
13
|
+
* normalization, `build` turns a note into an HTTP request, and `check` reads
|
|
14
|
+
* the provider's own success convention. Adding a channel is one entry in
|
|
15
|
+
* {@link PROVIDERS}; nothing else needs to change.
|
|
16
|
+
*
|
|
17
|
+
* This module intentionally imports no other project file, so it stays a
|
|
18
|
+
* dependency-free leaf that both `config.js` (for field descriptors) and the
|
|
19
|
+
* runtime (for delivery) can share without a cycle.
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-bark-push/channels
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Hard bound on configured extra channels. */
|
|
25
|
+
export const MAX_CHANNELS = 20;
|
|
26
|
+
|
|
27
|
+
/** Marker shown by the UI when a secret is already stored (never the value). */
|
|
28
|
+
export const MASKED_SECRET = '••••••••';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* JSON.parse that never throws.
|
|
32
|
+
* @param {string} text - raw response body.
|
|
33
|
+
* @returns {any} parsed value or null.
|
|
34
|
+
*/
|
|
35
|
+
function parseJson(text) {
|
|
36
|
+
try {
|
|
37
|
+
return String(text ?? '').length > 0 ? JSON.parse(text) : null;
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Join a base URL and one path fragment without doubling or dropping slashes.
|
|
45
|
+
* @param {string} base - server root.
|
|
46
|
+
* @param {string} path - path fragment.
|
|
47
|
+
* @returns {string} joined URL.
|
|
48
|
+
*/
|
|
49
|
+
function joinUrl(base, path) {
|
|
50
|
+
return `${String(base ?? '').replace(/\/+$/, '')}/${String(path ?? '').replace(/^\/+/, '')}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Truncate a string by code points.
|
|
55
|
+
* @param {string} value - source.
|
|
56
|
+
* @param {number} limit - maximum code points.
|
|
57
|
+
* @returns {string} bounded string.
|
|
58
|
+
*/
|
|
59
|
+
function clamp(value, limit) {
|
|
60
|
+
const chars = Array.from(String(value ?? ''));
|
|
61
|
+
return chars.length > limit ? chars.slice(0, limit).join('') : String(value ?? '');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A short human title for a channel instance.
|
|
66
|
+
* @param {object} channel - channel instance.
|
|
67
|
+
* @param {string} [fallback] - fallback name.
|
|
68
|
+
* @returns {string} label.
|
|
69
|
+
*/
|
|
70
|
+
export function channelLabel(channel, fallback = '渠道') {
|
|
71
|
+
if (channel && typeof channel.label === 'string' && channel.label.trim().length > 0) return channel.label.trim();
|
|
72
|
+
const provider = PROVIDERS.find((entry) => entry.type === channel?.type);
|
|
73
|
+
return provider ? provider.name : fallback;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Build a fresh channel id. The pattern matches the ones the UI generates.
|
|
78
|
+
* @returns {string} channel id.
|
|
79
|
+
*/
|
|
80
|
+
export function generateChannelId() {
|
|
81
|
+
return `ch_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Provider descriptors.
|
|
86
|
+
*
|
|
87
|
+
* Field shape:
|
|
88
|
+
* { key, label, kind, required?, placeholder?, options?, default?, help? }
|
|
89
|
+
* `kind` is one of text | secret | url | textarea | select | checkbox | number.
|
|
90
|
+
* `secret` values are never returned to the browser; an empty value on save
|
|
91
|
+
* keeps the stored one.
|
|
92
|
+
*/
|
|
93
|
+
const PROVIDERS = [
|
|
94
|
+
{
|
|
95
|
+
type: 'gotify',
|
|
96
|
+
name: 'Gotify',
|
|
97
|
+
summary: '自建 Gotify 服务器',
|
|
98
|
+
fields: [
|
|
99
|
+
{ key: 'server', label: '服务器地址', kind: 'url', required: true, placeholder: 'https://gotify.example.com' },
|
|
100
|
+
{ key: 'token', label: '应用 Token', kind: 'secret', required: true, placeholder: 'A…' },
|
|
101
|
+
{ key: 'priority', label: '优先级(0-10)', kind: 'number', default: '5' },
|
|
102
|
+
],
|
|
103
|
+
build(config, note) {
|
|
104
|
+
const priority = Math.max(0, Math.min(10, Number(config.priority) || 5));
|
|
105
|
+
return {
|
|
106
|
+
url: `${joinUrl(config.server, 'message')}?token=${encodeURIComponent(config.token)}`,
|
|
107
|
+
method: 'POST',
|
|
108
|
+
headers: { 'content-type': 'application/json' },
|
|
109
|
+
body: JSON.stringify({ title: note.title, message: note.body, priority }),
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
check(status, text) {
|
|
113
|
+
if (status >= 200 && status < 300) return { ok: true };
|
|
114
|
+
return { ok: false, message: clamp(text, 200) || `HTTP ${status}` };
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
type: 'ntfy',
|
|
119
|
+
name: 'ntfy',
|
|
120
|
+
summary: 'ntfy 主题推送(公共或自建)',
|
|
121
|
+
fields: [
|
|
122
|
+
{ key: 'server', label: '服务器地址', kind: 'url', default: 'https://ntfy.sh', placeholder: 'https://ntfy.sh' },
|
|
123
|
+
{ key: 'topic', label: '主题 Topic', kind: 'text', required: true, placeholder: 'my-dsh-alerts' },
|
|
124
|
+
{ key: 'token', label: '访问 Token(可选)', kind: 'secret', placeholder: 'tk_…' },
|
|
125
|
+
],
|
|
126
|
+
build(config, note) {
|
|
127
|
+
const headers = { 'content-type': 'application/json' };
|
|
128
|
+
if (typeof config.token === 'string' && config.token.length > 0) headers.authorization = `Bearer ${config.token}`;
|
|
129
|
+
return {
|
|
130
|
+
url: config.server || 'https://ntfy.sh',
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers,
|
|
133
|
+
body: JSON.stringify({ topic: config.topic, title: note.title, message: note.body, priority: 3 }),
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
check(status, text) {
|
|
137
|
+
if (status >= 200 && status < 300) return { ok: true };
|
|
138
|
+
return { ok: false, message: clamp(text, 200) || `HTTP ${status}` };
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
type: 'pushdeer',
|
|
143
|
+
name: 'PushDeer',
|
|
144
|
+
summary: 'PushDeer 推送',
|
|
145
|
+
fields: [
|
|
146
|
+
{ key: 'server', label: '服务器地址', kind: 'url', default: 'https://api2.pushdeer.com', placeholder: 'https://api2.pushdeer.com' },
|
|
147
|
+
{ key: 'pushKey', label: 'PushKey', kind: 'secret', required: true, placeholder: 'PDU…' },
|
|
148
|
+
],
|
|
149
|
+
build(config, note) {
|
|
150
|
+
return {
|
|
151
|
+
url: joinUrl(config.server || 'https://api2.pushdeer.com', 'message/push'),
|
|
152
|
+
method: 'POST',
|
|
153
|
+
headers: { 'content-type': 'application/json' },
|
|
154
|
+
body: JSON.stringify({ pushkey: config.pushKey, text: note.title, desp: note.body, type: 'markdown' }),
|
|
155
|
+
};
|
|
156
|
+
},
|
|
157
|
+
check(status, text) {
|
|
158
|
+
const json = parseJson(text);
|
|
159
|
+
if (json && json.code === 0) return { ok: true };
|
|
160
|
+
return { ok: false, message: json?.error || clamp(text, 200) || `HTTP ${status}` };
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
type: 'serverchan',
|
|
165
|
+
name: 'Server酱',
|
|
166
|
+
summary: 'Server酱³ (ServerChan) 推送',
|
|
167
|
+
fields: [
|
|
168
|
+
{ key: 'sendKey', label: 'SendKey', kind: 'secret', required: true, placeholder: 'SCT…' },
|
|
169
|
+
],
|
|
170
|
+
build(config, note) {
|
|
171
|
+
return {
|
|
172
|
+
url: `https://sctapi.ftqq.com/${encodeURIComponent(config.sendKey)}.send`,
|
|
173
|
+
method: 'POST',
|
|
174
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
175
|
+
body: new URLSearchParams({ title: note.title, desp: note.body }).toString(),
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
check(status, text) {
|
|
179
|
+
const json = parseJson(text);
|
|
180
|
+
if (json && (json.code === 0 || json.errno === 0)) return { ok: true };
|
|
181
|
+
return { ok: false, message: json?.message || clamp(text, 200) || `HTTP ${status}` };
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
type: 'pushplus',
|
|
186
|
+
name: 'PushPlus',
|
|
187
|
+
summary: 'PushPlus (推送加) 推送',
|
|
188
|
+
fields: [
|
|
189
|
+
{ key: 'token', label: 'Token', kind: 'secret', required: true, placeholder: '推送加 token' },
|
|
190
|
+
],
|
|
191
|
+
build(config, note) {
|
|
192
|
+
return {
|
|
193
|
+
url: 'https://www.pushplus.plus/send',
|
|
194
|
+
method: 'POST',
|
|
195
|
+
headers: { 'content-type': 'application/json' },
|
|
196
|
+
body: JSON.stringify({ token: config.token, title: note.title, content: note.body, template: 'txt' }),
|
|
197
|
+
};
|
|
198
|
+
},
|
|
199
|
+
check(status, text) {
|
|
200
|
+
const json = parseJson(text);
|
|
201
|
+
if (json && (json.code === 200 || json.code === 0)) return { ok: true };
|
|
202
|
+
return { ok: false, message: json?.msg || clamp(text, 200) || `HTTP ${status}` };
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
type: 'bark',
|
|
207
|
+
name: 'Bark(额外服务器)',
|
|
208
|
+
summary: '再接入一台 Bark 服务器 / 另一组 Device Key',
|
|
209
|
+
fields: [
|
|
210
|
+
{ key: 'server', label: 'Bark Server', kind: 'url', default: 'https://api.day.app', placeholder: 'https://api.day.app' },
|
|
211
|
+
{ key: 'deviceKey', label: 'Device Key', kind: 'secret', required: true, placeholder: '设备密钥' },
|
|
212
|
+
{ key: 'group', label: '分组 Group', kind: 'text', default: 'DSH', placeholder: 'DSH' },
|
|
213
|
+
{ key: 'level', label: '级别', kind: 'select', default: 'active', options: [
|
|
214
|
+
{ value: 'active', label: '主动通知 active' },
|
|
215
|
+
{ value: 'timeSensitive', label: '时效性 timeSensitive' },
|
|
216
|
+
{ value: 'passive', label: '静默 passive' },
|
|
217
|
+
{ value: 'critical', label: '紧急 critical' },
|
|
218
|
+
] },
|
|
219
|
+
],
|
|
220
|
+
build(config, note) {
|
|
221
|
+
const server = String(config.server || 'https://api.day.app').replace(/\/+$/, '').replace(/\/push$/, '');
|
|
222
|
+
const payload = { device_key: config.deviceKey, title: note.title, body: note.body, group: config.group || 'DSH' };
|
|
223
|
+
if (typeof config.level === 'string' && config.level.length > 0) payload.level = config.level;
|
|
224
|
+
if (typeof note.url === 'string' && note.url.length > 0) payload.url = note.url;
|
|
225
|
+
return {
|
|
226
|
+
url: `${server}/push`,
|
|
227
|
+
method: 'POST',
|
|
228
|
+
headers: { 'content-type': 'application/json' },
|
|
229
|
+
body: JSON.stringify(payload),
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
check(status, text) {
|
|
233
|
+
const json = parseJson(text);
|
|
234
|
+
if (json && (json.code === 200 || json.code === null)) return { ok: true };
|
|
235
|
+
if (status >= 200 && status < 300 && (!json || json.code === undefined)) return { ok: true };
|
|
236
|
+
return { ok: false, message: json?.message || `HTTP ${status}` };
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
type: 'webhook',
|
|
241
|
+
name: '自定义 Webhook',
|
|
242
|
+
summary: '把通知 POST 到你自己的任意 HTTP 接口',
|
|
243
|
+
fields: [
|
|
244
|
+
{ key: 'url', label: 'URL', kind: 'url', required: true, placeholder: 'https://example.com/hook' },
|
|
245
|
+
{ key: 'method', label: '请求方法', kind: 'select', default: 'POST', options: [
|
|
246
|
+
{ value: 'POST', label: 'POST' }, { value: 'PUT', label: 'PUT' }, { value: 'GET', label: 'GET' },
|
|
247
|
+
] },
|
|
248
|
+
{ key: 'contentType', label: '内容类型', kind: 'select', default: 'application/json', options: [
|
|
249
|
+
{ value: 'application/json', label: 'application/json' },
|
|
250
|
+
{ value: 'application/x-www-form-urlencoded', label: 'x-www-form-urlencoded' },
|
|
251
|
+
{ value: 'text/plain', label: 'text/plain' },
|
|
252
|
+
] },
|
|
253
|
+
{ key: 'headers', label: '自定义请求头(JSON,可选)', kind: 'textarea', placeholder: '{"Authorization":"Bearer …"}' },
|
|
254
|
+
{ key: 'bodyTemplate', label: '请求体模板(可选)', kind: 'textarea', placeholder: '{"title":"{{title}}","body":"{{body}}","kind":"{{kind}}","url":"{{url}}"}' },
|
|
255
|
+
],
|
|
256
|
+
build(config, note) {
|
|
257
|
+
const method = ['POST', 'PUT', 'GET'].includes(config.method) ? config.method : 'POST';
|
|
258
|
+
const contentType = typeof config.contentType === 'string' && config.contentType.length > 0 ? config.contentType : 'application/json';
|
|
259
|
+
const values = { title: note.title, body: note.body, kind: note.kind, url: note.url };
|
|
260
|
+
const template = typeof config.bodyTemplate === 'string' && config.bodyTemplate.trim().length > 0
|
|
261
|
+
? config.bodyTemplate
|
|
262
|
+
: '{"title":"{{title}}","body":"{{body}}","kind":"{{kind}}","url":"{{url}}"}';
|
|
263
|
+
const escape = contentType.includes('json')
|
|
264
|
+
? (value) => JSON.stringify(String(value ?? '')).slice(1, -1)
|
|
265
|
+
: contentType.includes('x-www-form-urlencoded')
|
|
266
|
+
? (value) => encodeURIComponent(String(value ?? ''))
|
|
267
|
+
: (value) => String(value ?? '');
|
|
268
|
+
let body = template.replace(/\{\{\s*(title|body|kind|url)\s*\}\}/g, (_, key) => escape(values[key]));
|
|
269
|
+
const headers = { 'content-type': contentType };
|
|
270
|
+
if (typeof config.headers === 'string' && config.headers.trim().length > 0) {
|
|
271
|
+
const extra = parseJson(config.headers);
|
|
272
|
+
if (extra && typeof extra === 'object' && !Array.isArray(extra)) {
|
|
273
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
274
|
+
if (typeof value === 'string' || typeof value === 'number') headers[key] = String(value);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
let url = config.url;
|
|
279
|
+
if (method === 'GET') {
|
|
280
|
+
if (body.trim().length > 0) url += (url.includes('?') ? '&' : '?') + body;
|
|
281
|
+
return { url, method, headers, body: undefined };
|
|
282
|
+
}
|
|
283
|
+
return { url, method, headers, body };
|
|
284
|
+
},
|
|
285
|
+
check(status) {
|
|
286
|
+
if (status >= 200 && status < 300) return { ok: true };
|
|
287
|
+
return { ok: false, message: `HTTP ${status}` };
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
];
|
|
291
|
+
|
|
292
|
+
/** Look up one provider by type. */
|
|
293
|
+
export function providerFor(type) {
|
|
294
|
+
return PROVIDERS.find((entry) => entry.type === type);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The descriptor subset the management page needs, with no functions.
|
|
299
|
+
* @returns {Array<object>} channel type summaries.
|
|
300
|
+
*/
|
|
301
|
+
export function channelTypeSummaries() {
|
|
302
|
+
return PROVIDERS.map((entry) => ({
|
|
303
|
+
type: entry.type,
|
|
304
|
+
name: entry.name,
|
|
305
|
+
summary: entry.summary,
|
|
306
|
+
fields: entry.fields.map((field) => ({ ...field })),
|
|
307
|
+
}));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* A value that must be present before this channel can send.
|
|
312
|
+
* @param {object} channel - normalized channel.
|
|
313
|
+
* @returns {{ ok: boolean, missing?: string }} whether the channel is complete.
|
|
314
|
+
*/
|
|
315
|
+
export function channelReady(channel) {
|
|
316
|
+
const provider = providerFor(channel?.type);
|
|
317
|
+
if (!provider) return { ok: false, missing: '未知渠道类型' };
|
|
318
|
+
const config = channel.config ?? {};
|
|
319
|
+
for (const field of provider.fields) {
|
|
320
|
+
if (field.required !== true) continue;
|
|
321
|
+
if (typeof config[field.key] !== 'string' || config[field.key].trim().length === 0) {
|
|
322
|
+
return { ok: false, missing: field.label };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { ok: true };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Build the HTTP request for one channel + note.
|
|
330
|
+
* @param {object} channel - normalized channel.
|
|
331
|
+
* @param {object} note - `{ title, body, kind, url? }`.
|
|
332
|
+
* @returns {{ url: string, method: string, headers: object, body?: string }} request.
|
|
333
|
+
*/
|
|
334
|
+
export function buildChannelRequest(channel, note) {
|
|
335
|
+
const provider = providerFor(channel?.type);
|
|
336
|
+
if (!provider) throw new Error(`未知渠道类型:${channel?.type}`);
|
|
337
|
+
const ready = channelReady(channel);
|
|
338
|
+
if (!ready.ok) throw new Error(`渠道缺少必填项:${ready.missing}`);
|
|
339
|
+
return provider.build(channel.config ?? {}, note);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Interpret one channel's HTTP response.
|
|
344
|
+
* @param {string} type - provider type.
|
|
345
|
+
* @param {number} status - HTTP status.
|
|
346
|
+
* @param {string} text - response body.
|
|
347
|
+
* @returns {{ ok: boolean, message?: string }} verdict.
|
|
348
|
+
*/
|
|
349
|
+
export function checkChannelResponse(type, status, text) {
|
|
350
|
+
const provider = providerFor(type);
|
|
351
|
+
if (!provider) return { ok: false, message: '未知渠道类型' };
|
|
352
|
+
return provider.check(status, text);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Default delay used by the sender between retries.
|
|
357
|
+
* @param {number} ms - delay.
|
|
358
|
+
* @param {AbortSignal} [signal] - cancellation.
|
|
359
|
+
* @returns {Promise<void>} resolved after the delay.
|
|
360
|
+
*/
|
|
361
|
+
function sleep(ms, signal) {
|
|
362
|
+
return new Promise((resolve, reject) => {
|
|
363
|
+
if (signal?.aborted) {
|
|
364
|
+
reject(signal.reason ?? new Error('aborted'));
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const timer = setTimeout(() => {
|
|
368
|
+
signal?.removeEventListener?.('abort', onAbort);
|
|
369
|
+
resolve();
|
|
370
|
+
}, ms);
|
|
371
|
+
const onAbort = () => {
|
|
372
|
+
clearTimeout(timer);
|
|
373
|
+
reject(signal.reason ?? new Error('aborted'));
|
|
374
|
+
};
|
|
375
|
+
signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Delivers notes to every enabled extra channel, isolated per channel with the
|
|
381
|
+
* same bounded timeout / retry policy as the Bark client.
|
|
382
|
+
*/
|
|
383
|
+
export class ChannelSender {
|
|
384
|
+
/**
|
|
385
|
+
* @param {object} options - sender options.
|
|
386
|
+
* @param {() => Record<string, unknown>} options.getConfig - effective config.
|
|
387
|
+
* @param {{ warn: Function, debug: Function }} options.logger - redacting logger.
|
|
388
|
+
* @param {typeof fetch} [options.fetchImpl] - injectable fetch.
|
|
389
|
+
* @param {(ms: number, signal?: AbortSignal) => Promise<void>} [options.sleepImpl] - injectable delay.
|
|
390
|
+
* @param {() => number} [options.random] - jitter source.
|
|
391
|
+
* @param {AbortSignal} [options.signal] - plugin-lifetime cancellation.
|
|
392
|
+
*/
|
|
393
|
+
constructor({ getConfig, logger, fetchImpl = globalThis.fetch, sleepImpl = sleep, random = Math.random, signal }) {
|
|
394
|
+
this.getConfig = getConfig;
|
|
395
|
+
this.logger = logger;
|
|
396
|
+
this.fetchImpl = fetchImpl;
|
|
397
|
+
this.sleepImpl = sleepImpl;
|
|
398
|
+
this.random = random;
|
|
399
|
+
this.signal = signal;
|
|
400
|
+
this.lastWarnAt = 0;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Channels that are enabled and known.
|
|
405
|
+
* @returns {Array<object>} enabled channels.
|
|
406
|
+
*/
|
|
407
|
+
#enabled() {
|
|
408
|
+
const config = this.getConfig();
|
|
409
|
+
const list = Array.isArray(config.channels) ? config.channels : [];
|
|
410
|
+
return list.filter((channel) => channel && channel.enabled !== false && providerFor(channel.type));
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Whether any extra channel would receive a note.
|
|
415
|
+
* @returns {boolean} true when at least one channel is enabled.
|
|
416
|
+
*/
|
|
417
|
+
hasEnabled() {
|
|
418
|
+
return this.#enabled().length > 0;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Send a note to every enabled channel.
|
|
423
|
+
* @param {object} note - `{ title, body, kind, url? }`.
|
|
424
|
+
* @returns {Promise<{ ok: boolean, skipped?: boolean, results: Array<object> }>} outcome.
|
|
425
|
+
*/
|
|
426
|
+
async send(note) {
|
|
427
|
+
const channels = this.#enabled();
|
|
428
|
+
if (channels.length === 0) return { ok: true, skipped: true, reason: 'no-channels', results: [] };
|
|
429
|
+
const results = [];
|
|
430
|
+
for (const channel of channels) results.push(await this.#sendOne(channel, note));
|
|
431
|
+
return { ok: results.every((result) => result.ok === true), results };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Send a note to one channel by id (used by the per-channel test button).
|
|
436
|
+
* @param {string} id - channel id.
|
|
437
|
+
* @param {object} note - note.
|
|
438
|
+
* @returns {Promise<object>} result.
|
|
439
|
+
*/
|
|
440
|
+
async testOne(id, note) {
|
|
441
|
+
const config = this.getConfig();
|
|
442
|
+
const list = Array.isArray(config.channels) ? config.channels : [];
|
|
443
|
+
const channel = list.find((entry) => entry && entry.id === id);
|
|
444
|
+
if (!channel) return { ok: false, skipped: true, reason: 'channel-not-found', results: [] };
|
|
445
|
+
const result = await this.#sendOne(channel, note);
|
|
446
|
+
return { ok: result.ok === true, results: [result] };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Send one note to one channel with bounded retries.
|
|
451
|
+
* @param {object} channel - channel instance.
|
|
452
|
+
* @param {object} note - note.
|
|
453
|
+
* @returns {Promise<object>} per-channel result.
|
|
454
|
+
*/
|
|
455
|
+
async #sendOne(channel, note) {
|
|
456
|
+
const base = {
|
|
457
|
+
channelId: channel.id,
|
|
458
|
+
channelType: channel.type,
|
|
459
|
+
label: channelLabel(channel),
|
|
460
|
+
ok: false,
|
|
461
|
+
status: null,
|
|
462
|
+
attempts: 0,
|
|
463
|
+
};
|
|
464
|
+
let request;
|
|
465
|
+
try {
|
|
466
|
+
request = buildChannelRequest(channel, note);
|
|
467
|
+
} catch (error) {
|
|
468
|
+
return { ...base, skipped: true, reason: error?.message ?? String(error), message: error?.message ?? String(error) };
|
|
469
|
+
}
|
|
470
|
+
const config = this.getConfig();
|
|
471
|
+
const maxRetries = Math.max(0, Math.min(5, Number(config.maxRetries) || 0));
|
|
472
|
+
const timeoutMs = Math.max(1000, Math.min(30000, Number(config.timeoutMs) || 8000));
|
|
473
|
+
let last = { ...base, message: 'not sent' };
|
|
474
|
+
|
|
475
|
+
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
|
|
476
|
+
if (this.signal?.aborted) {
|
|
477
|
+
last = { ...base, message: 'aborted', attempts: attempt };
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
const started = Date.now();
|
|
481
|
+
try {
|
|
482
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
483
|
+
const signal = this.signal ? AbortSignal.any([this.signal, timeoutSignal]) : timeoutSignal;
|
|
484
|
+
const response = await this.fetchImpl(request.url, {
|
|
485
|
+
method: request.method,
|
|
486
|
+
headers: request.headers,
|
|
487
|
+
body: request.body,
|
|
488
|
+
signal,
|
|
489
|
+
});
|
|
490
|
+
const text = await response.text().catch(() => '');
|
|
491
|
+
const verdict = checkChannelResponse(channel.type, response.status, text);
|
|
492
|
+
last = {
|
|
493
|
+
...base,
|
|
494
|
+
ok: verdict.ok === true && response.status >= 200 && response.status < 300,
|
|
495
|
+
status: response.status,
|
|
496
|
+
attempts: attempt + 1,
|
|
497
|
+
ms: Date.now() - started,
|
|
498
|
+
message: verdict.message ?? '',
|
|
499
|
+
};
|
|
500
|
+
if (last.ok) {
|
|
501
|
+
this.logger?.debug?.(`bark-push: 渠道 ${base.label} 推送成功(HTTP ${response.status},${last.ms}ms)`);
|
|
502
|
+
return last;
|
|
503
|
+
}
|
|
504
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
505
|
+
if (!retryable || attempt >= maxRetries) break;
|
|
506
|
+
} catch (error) {
|
|
507
|
+
const timedOut = error?.name === 'TimeoutError' || error?.name === 'AbortError';
|
|
508
|
+
last = { ...base, message: timedOut ? '请求超时' : (error?.message ?? String(error)), attempts: attempt + 1, ms: Date.now() - started };
|
|
509
|
+
if (attempt >= maxRetries || this.signal?.aborted) break;
|
|
510
|
+
}
|
|
511
|
+
const delayBase = Math.max(50, Math.min(10000, Number(config.retryDelayMs) || 500));
|
|
512
|
+
const delay = Math.min(10000, delayBase * 2 ** attempt + Math.floor(this.random() * delayBase));
|
|
513
|
+
try {
|
|
514
|
+
await this.sleepImpl(delay, this.signal);
|
|
515
|
+
} catch {
|
|
516
|
+
last = { ...last, message: 'aborted', ok: false };
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const now = Date.now();
|
|
522
|
+
if (now - this.lastWarnAt > 60_000) {
|
|
523
|
+
this.lastWarnAt = now;
|
|
524
|
+
this.logger?.warn?.(`bark-push: 渠道 ${base.label} 推送失败(${last.message},尝试 ${last.attempts} 次)`);
|
|
525
|
+
}
|
|
526
|
+
return { ...last, ok: false };
|
|
527
|
+
}
|
|
528
|
+
}
|