mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 03:03:24 +08:00
feat: add WhatsApp QR channel
This commit is contained in:
parent
f8841da76f
commit
c54463843f
29 changed files with 4565 additions and 224 deletions
|
|
@ -105,3 +105,16 @@ export function DiscordLogoGlyph({ size } = {}) {
|
|||
d: 'M20.32 4.37a19.8 19.8 0 0 0-4.89-1.51c-.21.38-.46.89-.63 1.29a18.4 18.4 0 0 0-5.59 0 13 13 0 0 0-.64-1.29c-1.71.29-3.36.8-4.89 1.52C.59 9.09-.25 13.68.17 18.2a19.9 19.9 0 0 0 6 3.04c.48-.66.91-1.36 1.28-2.1-.7-.26-1.37-.58-2-.96.17-.12.33-.25.49-.38 3.86 1.79 8.04 1.79 11.86 0 .16.13.32.26.49.38-.64.38-1.31.7-2.01.97.37.73.8 1.44 1.28 2.09a19.8 19.8 0 0 0 6-3.04c.49-5.24-.84-9.79-3.24-13.83ZM8.02 15.42c-1.16 0-2.11-1.07-2.11-2.38s.93-2.38 2.11-2.38c1.18 0 2.13 1.08 2.11 2.38 0 1.31-.93 2.38-2.11 2.38Zm7.95 0c-1.16 0-2.11-1.07-2.11-2.38s.93-2.38 2.11-2.38c1.18 0 2.13 1.08 2.11 2.38 0 1.31-.93 2.38-2.11 2.38Z',
|
||||
}));
|
||||
}
|
||||
|
||||
export function WhatsappLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
viewBox: '0 0 24 24',
|
||||
focusable: 'false',
|
||||
'aria-hidden': 'true',
|
||||
'data-im-channel-logo': 'whatsapp',
|
||||
}, h('path', {
|
||||
fill: 'currentColor',
|
||||
d: 'M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.521.149-.173.198-.297.298-.495.099-.198.05-.372-.025-.521-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a12.8 12.8 0 0 0-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479s1.065 2.875 1.213 3.074c.149.198 2.095 3.2 5.077 4.487.709.306 1.262.489 1.694.626.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.29.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.981.999-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.83 9.83 0 0 1 2.893 6.991c-.003 5.45-4.437 9.884-9.886 9.884m8.413-18.297A11.8 11.8 0 0 0 12.055 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.9 11.9 0 0 0 5.688 1.448h.005c6.557 0 11.892-5.335 11.895-11.893a11.82 11.82 0 0 0-3.486-8.413',
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,13 @@ export function createTokenChannelSettings(definition) {
|
|||
emptyTitle,
|
||||
emptyDescription,
|
||||
platformLabel,
|
||||
CredentialPanel = null,
|
||||
credentialPayload = ({ secret }) => ({ token: secret }),
|
||||
credentialAriaLabel = `使用 Bot Token 接入 ${channel} 机器人`,
|
||||
credentialOpenLabel = '手动接入',
|
||||
credentialCloseLabel = '收起凭据',
|
||||
credentialNoun = 'Bot Token',
|
||||
emptyActionLabel = '填写 Bot Token',
|
||||
} = definition;
|
||||
|
||||
function AccountCard({ account, busy, removing, onReconnect, onRequestRemove, onConfirmRemove, onCancelRemove }) {
|
||||
|
|
@ -83,7 +90,7 @@ export function createTokenChannelSettings(definition) {
|
|||
}, '移除接入')))),
|
||||
removing ? h('div', { className: 'ddt-confirm dim-confirm', role: 'alertdialog' },
|
||||
h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`),
|
||||
h('p', null, `这会停止消息连接,并删除本机保存的 Bot Token、机器人配置及会话映射。${platformLabel}中的机器人不会被自动删除。`),
|
||||
h('p', null, `这会停止消息连接,并删除本机保存的 ${credentialNoun}、机器人配置及会话映射。${platformLabel}中的机器人不会被自动删除。`),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onCancelRemove, disabled: Boolean(busy) }, '保留机器人'),
|
||||
h(Button, { kind: 'danger', onClick: onConfirmRemove, disabled: Boolean(busy) },
|
||||
|
|
@ -153,11 +160,14 @@ export function createTokenChannelSettings(definition) {
|
|||
};
|
||||
}, [loadStatus, model.phase]);
|
||||
|
||||
const bindCredentials = React.useCallback(async ({ secret }) => {
|
||||
const bindCredentials = React.useCallback(async (values) => {
|
||||
setBusy(true);
|
||||
setCredentialError(null);
|
||||
try {
|
||||
const snapshot = api.normalizeSnapshot(await invoke(endpoints.bindCredentials, { token: secret }));
|
||||
const snapshot = api.normalizeSnapshot(await invoke(
|
||||
endpoints.bindCredentials,
|
||||
credentialPayload(values),
|
||||
));
|
||||
if (!mounted.current) return;
|
||||
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
|
||||
setCredentialOpen(false);
|
||||
|
|
@ -224,8 +234,8 @@ export function createTokenChannelSettings(definition) {
|
|||
onClick: () => { setCredentialOpen((value) => !value); setCredentialError(null); },
|
||||
disabled: busy,
|
||||
'aria-pressed': credentialOpen,
|
||||
'aria-label': `使用 Bot Token 接入 ${channel} 机器人`,
|
||||
}, h(CredentialActionIcon), credentialOpen ? '收起凭据' : '手动接入')),
|
||||
'aria-label': credentialAriaLabel,
|
||||
}, h(CredentialActionIcon), credentialOpen ? credentialCloseLabel : credentialOpenLabel)),
|
||||
model.totals.configured > 0
|
||||
? h('div', { className: 'ddt-badge dim-onlineBadge' },
|
||||
h('span', null, `${model.totals.connected} / ${model.totals.configured} 在线`))
|
||||
|
|
@ -242,15 +252,22 @@ export function createTokenChannelSettings(definition) {
|
|||
h('p', null, model.error?.message),
|
||||
h(Button, { onClick: () => void loadStatus() }, '重新读取')))
|
||||
: h(React.Fragment, null,
|
||||
credentialOpen ? h(CredentialBindingPanel, {
|
||||
channel,
|
||||
secretLabel: 'Bot Token',
|
||||
secretPlaceholder: tokenPlaceholder,
|
||||
busy,
|
||||
error: credentialError,
|
||||
onSubmit: bindCredentials,
|
||||
onCancel: () => { setCredentialOpen(false); setCredentialError(null); },
|
||||
}) : null,
|
||||
credentialOpen ? (CredentialPanel
|
||||
? h(CredentialPanel, {
|
||||
busy,
|
||||
error: credentialError,
|
||||
onSubmit: bindCredentials,
|
||||
onCancel: () => { setCredentialOpen(false); setCredentialError(null); },
|
||||
})
|
||||
: h(CredentialBindingPanel, {
|
||||
channel,
|
||||
secretLabel: 'Bot Token',
|
||||
secretPlaceholder: tokenPlaceholder,
|
||||
busy,
|
||||
error: credentialError,
|
||||
onSubmit: bindCredentials,
|
||||
onCancel: () => { setCredentialOpen(false); setCredentialError(null); },
|
||||
})) : null,
|
||||
model.bots.length === 0 && !credentialOpen
|
||||
? h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-cardBody ddt-empty dim-surfaceBody dim-emptyView' },
|
||||
|
|
@ -264,7 +281,7 @@ export function createTokenChannelSettings(definition) {
|
|||
h(Button, {
|
||||
kind: 'primary',
|
||||
onClick: () => setCredentialOpen(true),
|
||||
}, '填写 Bot Token'))),
|
||||
}, emptyActionLabel))),
|
||||
h('div', {
|
||||
className: `ddt-brandMark dim-emptyBrand ${avatarClass}`,
|
||||
'aria-hidden': 'true',
|
||||
|
|
|
|||
123
plugin-src/client/channels/whatsapp/api.js
Normal file
123
plugin-src/client/channels/whatsapp/api.js
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
export const WHATSAPP_RPC_CHANNEL = '/whatsapp';
|
||||
|
||||
export const WHATSAPP_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
beginProvisioning: 'provision.begin',
|
||||
pollProvisioning: 'provision.poll',
|
||||
cancelProvisioning: 'provision.cancel',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
|
||||
const PROVISION_STATES = new Set(['starting', 'pending', 'connecting', 'connected', 'failed', 'cancelled']);
|
||||
const BOT_STATES = new Set(['connected', 'connecting', 'offline', 'error']);
|
||||
const QR_DATA_URL = /^data:image\/(?:png|webp);base64,[a-z\d+/]+={0,2}$/i;
|
||||
|
||||
function isRecord(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function text(value, fallback, max = 240) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : fallback;
|
||||
}
|
||||
|
||||
function id(value) {
|
||||
const result = text(value, '', 128);
|
||||
return /^[a-z\d_-]+$/i.test(result) ? result : undefined;
|
||||
}
|
||||
|
||||
function timestamp(value) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
const parsed = typeof value === 'string' ? Date.parse(value) : Number.NaN;
|
||||
return Number.isNaN(parsed) ? undefined : parsed;
|
||||
}
|
||||
|
||||
export function unwrapRpcResult(result) {
|
||||
if (!isRecord(result) || typeof result.ok !== 'boolean') {
|
||||
throw new Error('WhatsApp 服务返回了无法识别的响应');
|
||||
}
|
||||
if (!result.ok) {
|
||||
const error = new Error(text(result.error?.message, 'WhatsApp 操作失败'));
|
||||
error.code = text(result.error?.code, 'WHATSAPP_RPC_ERROR', 80);
|
||||
throw error;
|
||||
}
|
||||
return result.value;
|
||||
}
|
||||
|
||||
export function safeQrSource(value) {
|
||||
return typeof value === 'string' && value.length <= 2 * 1024 * 1024 && QR_DATA_URL.test(value)
|
||||
? value : undefined;
|
||||
}
|
||||
|
||||
export function normalizeProvisioning(value, now = Date.now()) {
|
||||
const source = isRecord(value?.provisioning) ? value.provisioning : value;
|
||||
if (!isRecord(source)) throw new Error('WhatsApp 服务没有返回扫码进度');
|
||||
const attemptId = id(source.attemptId);
|
||||
if (!attemptId) throw new Error('WhatsApp 服务没有返回有效的扫码任务');
|
||||
const reported = text(source.status, 'failed', 32);
|
||||
const result = {
|
||||
attemptId,
|
||||
status: PROVISION_STATES.has(reported) ? reported : 'failed',
|
||||
expiresAt: timestamp(source.expiresAt) ?? now + 60_000,
|
||||
pollIntervalMs: Math.min(5_000, Math.max(500, Number(source.pollIntervalMs) || 1_000)),
|
||||
qrRevision: Number.isSafeInteger(source.qrRevision) ? source.qrRevision : 0,
|
||||
};
|
||||
const qrCodeDataUrl = safeQrSource(source.qrCodeDataUrl);
|
||||
if (qrCodeDataUrl) result.qrCodeDataUrl = qrCodeDataUrl;
|
||||
if (id(source.botId)) result.botId = id(source.botId);
|
||||
if (isRecord(source.error)) result.error = {
|
||||
code: text(source.error.code, 'WHATSAPP_PROVISION_FAILED', 80),
|
||||
message: text(source.error.message, 'WhatsApp 没有接入完成'),
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeBot(value) {
|
||||
if (!isRecord(value) || !id(value.botId)) return undefined;
|
||||
const connected = value.connected === true;
|
||||
const state = BOT_STATES.has(value.state) ? value.state : 'offline';
|
||||
return {
|
||||
botId: id(value.botId),
|
||||
connected,
|
||||
state: connected ? 'connected' : state,
|
||||
bot: {
|
||||
name: text(value.bot?.name, 'WhatsApp机器人', 100),
|
||||
idMasked: text(value.bot?.idMasked, 'WhatsApp账号', 140),
|
||||
},
|
||||
health: {
|
||||
summary: text(value.health?.summary, connected
|
||||
? 'WhatsApp Web 关联设备运行正常' : 'WhatsApp 连接尚未就绪'),
|
||||
lastCheckedAt: timestamp(value.health?.lastCheckedAt),
|
||||
},
|
||||
error: isRecord(value.error) ? {
|
||||
code: text(value.error.code, 'WHATSAPP_ACCOUNT_ERROR', 80),
|
||||
message: text(value.error.message, 'WhatsApp 连接尚未就绪'),
|
||||
} : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSnapshot(value) {
|
||||
const source = isRecord(value?.snapshot) ? value.snapshot : value;
|
||||
if (!isRecord(source) || !Array.isArray(source.bots)) {
|
||||
throw new Error('WhatsApp 服务没有返回有效的机器人列表');
|
||||
}
|
||||
const bots = source.bots.map(normalizeBot).filter(Boolean);
|
||||
return {
|
||||
revision: Number.isSafeInteger(source.revision) ? source.revision : 0,
|
||||
bots,
|
||||
totals: { configured: bots.length, connected: bots.filter((bot) => bot.connected).length },
|
||||
provisioning: source.provisioning ? normalizeProvisioning(source.provisioning) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function presentError(error) {
|
||||
return {
|
||||
code: text(error?.code, 'WHATSAPP_ERROR', 80),
|
||||
message: text(error?.message, 'WhatsApp 操作失败,请稍后重试'),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatRemaining(milliseconds) {
|
||||
const seconds = Math.max(0, Math.ceil(Number(milliseconds) / 1_000) || 0);
|
||||
return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
|
||||
}
|
||||
433
plugin-src/client/channels/whatsapp/index.js
Normal file
433
plugin-src/client/channels/whatsapp/index.js
Normal file
|
|
@ -0,0 +1,433 @@
|
|||
import * as React from 'react';
|
||||
|
||||
import { WhatsappLogoGlyph } from '../../channel-logos.js';
|
||||
import { QrActionIcon } from '../../credential-binding.js';
|
||||
import { installDingtalkStyles } from '../dingtalk/styles.js';
|
||||
import {
|
||||
WHATSAPP_ENDPOINTS,
|
||||
formatRemaining,
|
||||
normalizeProvisioning,
|
||||
normalizeSnapshot,
|
||||
presentError,
|
||||
safeQrSource,
|
||||
unwrapRpcResult,
|
||||
} from './api.js';
|
||||
import { installWhatsappStyles } from './styles.js';
|
||||
|
||||
const h = React.createElement;
|
||||
const ACTIVE_STATES = new Set(['pending', 'connecting']);
|
||||
|
||||
const Button = React.forwardRef(function Button(
|
||||
{ children, kind = 'secondary', className = '', ...props },
|
||||
ref,
|
||||
) {
|
||||
return h('button', {
|
||||
...props,
|
||||
ref,
|
||||
type: 'button',
|
||||
className: `ddt-button ${className}`.trim(),
|
||||
'data-kind': kind,
|
||||
}, children);
|
||||
});
|
||||
|
||||
function checkedTime(value) {
|
||||
if (!value) return '尚未检查';
|
||||
try {
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||||
}).format(new Date(value));
|
||||
} catch {
|
||||
return '刚刚';
|
||||
}
|
||||
}
|
||||
|
||||
function Heading({ totals, busy, onAdd, addButtonRef }) {
|
||||
return h('div', { className: 'ddt-heading' },
|
||||
h('div', { className: 'ddt-tools' },
|
||||
h('div', { className: 'dim-bindActions' },
|
||||
h(Button, {
|
||||
kind: 'primary',
|
||||
className: 'dim-scanButton',
|
||||
onClick: onAdd,
|
||||
disabled: busy,
|
||||
ref: addButtonRef,
|
||||
'aria-label': '扫码接入 WhatsApp 机器人',
|
||||
}, h(QrActionIcon), busy ? '正在接入' : '扫码接入机器人')),
|
||||
totals.configured > 0
|
||||
? h('div', { className: 'ddt-badge dim-onlineBadge' },
|
||||
h('span', null, `${totals.connected} / ${totals.configured} 在线`))
|
||||
: null));
|
||||
}
|
||||
|
||||
function LoadingView() {
|
||||
return h('div', {
|
||||
className: 'ddt-card ddt-loading dim-surfaceCard dim-loadingView',
|
||||
'aria-busy': 'true',
|
||||
}, h('div', { className: 'ddt-spinner dim-spinner' }), '正在读取 WhatsApp 机器人状态…');
|
||||
}
|
||||
|
||||
export function EmptyView({ busy, onStart }) {
|
||||
return h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-cardBody ddt-empty dim-surfaceBody dim-emptyView' },
|
||||
h('div', { className: 'dim-emptyCopy' },
|
||||
h('div', { className: 'ddt-stateLabel dim-stateLabel' },
|
||||
h('span', { className: 'ddt-dot dim-stateDot' }),
|
||||
h('span', null, '尚未接入 WhatsApp 机器人')),
|
||||
h('h3', null, '扫码绑定 WhatsApp 机器人'),
|
||||
h('p', null, '使用手机 WhatsApp 扫描二维码即可接入。'),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { kind: 'primary', onClick: onStart, disabled: busy },
|
||||
busy ? '正在生成二维码…' : '生成二维码'))),
|
||||
h('div', {
|
||||
className: 'ddt-brandMark dim-emptyBrand dwa-avatar',
|
||||
'aria-hidden': 'true',
|
||||
}, h(WhatsappLogoGlyph, { size: 64 }))));
|
||||
}
|
||||
|
||||
export function QrPanel({ provision, now, busy, onRefresh, onCancel }) {
|
||||
const source = safeQrSource(provision.qrCodeDataUrl);
|
||||
const remaining = Math.max(0, provision.expiresAt - now);
|
||||
const duration = Math.max(1, provision.durationMs ?? 60_000);
|
||||
const progress = Math.round(Math.min(1, remaining / duration) * 100);
|
||||
return h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-cardBody ddt-qrLayout dim-surfaceBody dim-qrLayout' },
|
||||
h('div', { className: 'ddt-qrColumn dim-qrColumn' },
|
||||
h('div', { className: 'ddt-qrFrame dim-qrFrame' },
|
||||
source ? h('img', {
|
||||
src: source,
|
||||
alt: '用于关联 WhatsApp 设备的一次性二维码',
|
||||
}) : h('div', { className: 'ddt-qrFallback dim-qrFallback' }, '二维码正在生成…')),
|
||||
h('div', { className: 'ddt-countdown dim-countdown' },
|
||||
h('div', { className: 'ddt-countdownTop dim-countdownTop' },
|
||||
h('span', null, '当前二维码有效时间'),
|
||||
h('strong', null, formatRemaining(remaining))),
|
||||
h('div', {
|
||||
className: 'ddt-progress dim-progress',
|
||||
style: { '--ddt-progress': `${progress}%` },
|
||||
}, h('span')))),
|
||||
h('div', { className: 'ddt-qrCopy dim-qrCopy' },
|
||||
h('div', { className: 'ddt-stateLabel dim-stateLabel' },
|
||||
h('span', { className: 'ddt-dot dim-stateDot', 'data-tone': 'warning' }),
|
||||
h('span', null, '等待 WhatsApp 扫码')),
|
||||
h('h3', null, '用手机 WhatsApp 扫描二维码'),
|
||||
h('ol', { className: 'ddt-steps dim-steps' },
|
||||
h('li', null, '打开 WhatsApp → 设置 → 已关联设备'),
|
||||
h('li', null, '点击“关联设备”并扫描左侧二维码')),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onRefresh, disabled: busy }, '重新生成二维码'),
|
||||
h(Button, { kind: 'quiet', onClick: onCancel, disabled: busy }, '取消')))));
|
||||
}
|
||||
|
||||
export function ProvisionView({ provision, busy, onRetry, onClose }) {
|
||||
if (provision.status === 'starting' || provision.status === 'connecting') {
|
||||
const starting = provision.status === 'starting';
|
||||
return h('div', {
|
||||
className: 'ddt-card ddt-loading dim-surfaceCard dim-specialView',
|
||||
'aria-busy': 'true',
|
||||
}, h('div', { className: 'ddt-spinner dim-spinner' }),
|
||||
h('h3', null, starting ? '正在生成 WhatsApp 二维码' : '已扫码,正在连接 WhatsApp'),
|
||||
h('p', null, starting
|
||||
? '正在建立安全的关联设备会话。'
|
||||
: '关联设备正在接入 DeepSeek Harness。'));
|
||||
}
|
||||
const error = provision.error ?? {
|
||||
code: 'WHATSAPP_PROVISION_FAILED',
|
||||
message: 'WhatsApp 没有接入完成',
|
||||
};
|
||||
return h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-inlineError dim-inlineError', role: 'alert' },
|
||||
h('h3', null, 'WhatsApp 没有接入完成'),
|
||||
h('p', null, error.message),
|
||||
h('span', { className: 'ddt-errorCode' }, error.code),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { kind: 'primary', onClick: onRetry, disabled: busy }, '重新生成二维码'),
|
||||
h(Button, { onClick: onClose, disabled: busy }, '关闭'))));
|
||||
}
|
||||
|
||||
function RemoveConfirmation({ account, busy, onConfirm, onCancel }) {
|
||||
return h('div', { className: 'ddt-confirm dim-confirm', role: 'alertdialog' },
|
||||
h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`),
|
||||
h('p', null, '这会停止消息连接,并删除本机保存的 WhatsApp 关联设备和会话映射。'),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onCancel, disabled: busy }, '保留机器人'),
|
||||
h(Button, { kind: 'danger', onClick: onConfirm, disabled: busy },
|
||||
busy ? '正在移除…' : '确认移除接入')));
|
||||
}
|
||||
|
||||
export function WhatsappAccountCard({
|
||||
account,
|
||||
busy,
|
||||
removing,
|
||||
onReconnect,
|
||||
onRequestRemove,
|
||||
onConfirmRemove,
|
||||
onCancelRemove,
|
||||
}) {
|
||||
const state = busy === 'reconnect' ? 'connecting' : account.state;
|
||||
const tone = account.connected ? 'success' : state === 'error' ? 'error' : 'warning';
|
||||
const stateLabel = account.connected ? '运行正常' : state === 'connecting' ? '正在连接' : '连接未就绪';
|
||||
const summary = account.error?.message ?? (account.connected ? null : account.health.summary);
|
||||
return h('article', { className: 'ddt-card dim-botCard', 'data-bot-id': account.botId },
|
||||
h('div', { className: 'ddt-cardBody dim-botCardBody' },
|
||||
h('div', { className: 'ddt-accountTop dim-botCardTop' },
|
||||
h('div', { className: 'ddt-accountIdentity dim-botIdentity' },
|
||||
h('div', {
|
||||
className: 'ddt-avatar dim-botAvatar dwa-avatar',
|
||||
'aria-hidden': 'true',
|
||||
}, h(WhatsappLogoGlyph, { size: 29 })),
|
||||
h('div', { className: 'dim-botName' },
|
||||
h('h3', null, account.bot.name), h('p', null, account.bot.idMasked))),
|
||||
h('div', { className: 'ddt-health dim-botHealth' },
|
||||
h('span', { className: 'ddt-dot dim-healthDot', 'data-tone': tone }),
|
||||
h('span', null, stateLabel))),
|
||||
h('dl', { className: 'ddt-metrics dim-botMetrics' },
|
||||
h('div', { className: 'ddt-metric dim-botMetric' },
|
||||
h('dt', null, '消息通道'),
|
||||
h('dd', null, account.connected ? 'WhatsApp Web' : '离线')),
|
||||
h('div', { className: 'ddt-metric dim-botMetric' },
|
||||
h('dt', null, '最近检查'), h('dd', null, checkedTime(account.health.lastCheckedAt)))),
|
||||
h('div', { className: 'ddt-accountFooter dim-cardFooter' },
|
||||
summary ? h('div', { className: 'ddt-summary dim-cardSummary' }, summary) : null,
|
||||
h('div', { className: 'ddt-actions dim-cardActions' },
|
||||
h(Button, {
|
||||
className: 'dim-cardAction', onClick: onReconnect, disabled: Boolean(busy),
|
||||
}, busy === 'reconnect' ? '检查中…' : account.connected ? '检查连接' : '重试连接'),
|
||||
h(Button, {
|
||||
className: 'dim-cardAction', kind: 'danger', onClick: onRequestRemove, disabled: Boolean(busy),
|
||||
}, '移除接入')))),
|
||||
removing ? h(RemoveConfirmation, {
|
||||
account,
|
||||
busy: busy === 'delete',
|
||||
onConfirm: onConfirmRemove,
|
||||
onCancel: onCancelRemove,
|
||||
}) : null);
|
||||
}
|
||||
|
||||
export function WhatsappSettingsTab({ rpcCall }) {
|
||||
const [model, setModel] = React.useState({
|
||||
phase: 'loading', bots: [], totals: { configured: 0, connected: 0 }, error: null,
|
||||
});
|
||||
const [provision, setProvision] = React.useState(null);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [busyByBot, setBusyByBot] = React.useState({});
|
||||
const [removeTarget, setRemoveTarget] = React.useState(null);
|
||||
const [now, setNow] = React.useState(Date.now());
|
||||
const mounted = React.useRef(true);
|
||||
const addButtonRef = React.useRef(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
const disposeDingtalk = installDingtalkStyles();
|
||||
const disposeWhatsapp = installWhatsappStyles();
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
disposeWhatsapp();
|
||||
disposeDingtalk();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const invoke = React.useCallback(async (endpoint, payload = {}, signal) => {
|
||||
if (typeof rpcCall !== 'function') throw new TypeError('WhatsApp 设置页缺少 RPC 连接');
|
||||
return unwrapRpcResult(await rpcCall(endpoint, payload, signal));
|
||||
}, [rpcCall]);
|
||||
|
||||
const loadStatus = React.useCallback(async ({ signal, silent = false, restore = false } = {}) => {
|
||||
if (!silent && mounted.current) setModel((current) => ({ ...current, phase: 'loading', error: null }));
|
||||
try {
|
||||
const snapshot = normalizeSnapshot(await invoke(WHATSAPP_ENDPOINTS.status, {}, signal));
|
||||
if (!mounted.current || signal?.aborted) return undefined;
|
||||
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
|
||||
if (restore && snapshot.provisioning) setProvision({
|
||||
...snapshot.provisioning,
|
||||
durationMs: Math.max(1, snapshot.provisioning.expiresAt - Date.now()),
|
||||
});
|
||||
return snapshot;
|
||||
} catch (error) {
|
||||
if (error?.name !== 'AbortError' && mounted.current && !signal?.aborted) {
|
||||
setModel((current) => ({
|
||||
...current,
|
||||
phase: silent ? current.phase : 'error',
|
||||
error: presentError(error),
|
||||
}));
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void loadStatus({ signal: controller.signal, restore: true });
|
||||
return () => controller.abort();
|
||||
}, [loadStatus]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (model.phase !== 'ready') return undefined;
|
||||
const controller = new AbortController();
|
||||
const timer = window.setInterval(
|
||||
() => void loadStatus({ signal: controller.signal, silent: true }),
|
||||
15_000,
|
||||
);
|
||||
return () => { controller.abort(); window.clearInterval(timer); };
|
||||
}, [loadStatus, model.phase]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!provision || !ACTIVE_STATES.has(provision.status)) return undefined;
|
||||
const timer = window.setInterval(() => mounted.current && setNow(Date.now()), 1_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [provision?.attemptId, provision?.status]);
|
||||
|
||||
const startProvisioning = React.useCallback(async (replace = false) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (replace && provision?.attemptId) {
|
||||
await invoke(WHATSAPP_ENDPOINTS.cancelProvisioning, { attemptId: provision.attemptId });
|
||||
}
|
||||
if (!mounted.current) return;
|
||||
setProvision({ status: 'starting' });
|
||||
const started = normalizeProvisioning(await invoke(WHATSAPP_ENDPOINTS.beginProvisioning, {}));
|
||||
if (!mounted.current) return;
|
||||
setNow(Date.now());
|
||||
setProvision({ ...started, durationMs: Math.max(1, started.expiresAt - Date.now()) });
|
||||
} catch (error) {
|
||||
if (mounted.current) setProvision({ status: 'failed', error: presentError(error) });
|
||||
} finally {
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
}, [invoke, provision?.attemptId]);
|
||||
|
||||
const closeProvision = React.useCallback(async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (provision?.attemptId && ACTIVE_STATES.has(provision.status)) {
|
||||
await invoke(WHATSAPP_ENDPOINTS.cancelProvisioning, { attemptId: provision.attemptId });
|
||||
}
|
||||
if (mounted.current) setProvision(null);
|
||||
} finally {
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
}, [invoke, provision?.attemptId, provision?.status]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const attemptId = provision?.attemptId;
|
||||
if (!attemptId || !ACTIVE_STATES.has(provision.status)) return undefined;
|
||||
const controller = new AbortController();
|
||||
let disposed = false;
|
||||
let timer;
|
||||
const schedule = (delay) => {
|
||||
if (disposed || controller.signal.aborted) return;
|
||||
timer = window.setTimeout(() => void poll(), delay);
|
||||
};
|
||||
const poll = async () => {
|
||||
try {
|
||||
const current = normalizeProvisioning(await invoke(
|
||||
WHATSAPP_ENDPOINTS.pollProvisioning,
|
||||
{ attemptId },
|
||||
controller.signal,
|
||||
));
|
||||
if (disposed || controller.signal.aborted || !mounted.current) return;
|
||||
if (current.status === 'connected') {
|
||||
setProvision(null);
|
||||
await loadStatus({ signal: controller.signal, silent: true });
|
||||
return;
|
||||
}
|
||||
setProvision((previous) => ({
|
||||
...current,
|
||||
durationMs: previous?.durationMs ?? Math.max(1, current.expiresAt - Date.now()),
|
||||
}));
|
||||
if (ACTIVE_STATES.has(current.status)) schedule(current.pollIntervalMs);
|
||||
} catch (error) {
|
||||
if (!disposed && !controller.signal.aborted && mounted.current) {
|
||||
setProvision({ status: 'failed', error: presentError(error) });
|
||||
}
|
||||
}
|
||||
};
|
||||
schedule(provision.pollIntervalMs ?? 1_000);
|
||||
return () => {
|
||||
disposed = true;
|
||||
controller.abort();
|
||||
if (timer) window.clearTimeout(timer);
|
||||
};
|
||||
}, [invoke, loadStatus, provision?.attemptId, provision?.status]);
|
||||
|
||||
const botAction = React.useCallback(async (account, operation, endpoint, payload) => {
|
||||
setBusyByBot((current) => ({ ...current, [account.botId]: operation }));
|
||||
try {
|
||||
const snapshot = normalizeSnapshot(await invoke(endpoint, payload));
|
||||
if (mounted.current) {
|
||||
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) setBusyByBot((current) => {
|
||||
const next = { ...current };
|
||||
delete next[account.botId];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
const botList = model.bots.length > 0
|
||||
? h('section', { className: 'dim-listSection' },
|
||||
h('div', { className: 'ddt-listHeading dim-listHeading' },
|
||||
h('h3', null, '已接入的 WhatsApp 机器人')),
|
||||
h('ul', { className: 'ddt-list dim-botList' }, model.bots.map((account) =>
|
||||
h('li', { key: account.botId }, h(WhatsappAccountCard, {
|
||||
account,
|
||||
busy: busyByBot[account.botId],
|
||||
removing: removeTarget === account.botId,
|
||||
onReconnect: () => void botAction(
|
||||
account,
|
||||
'reconnect',
|
||||
WHATSAPP_ENDPOINTS.reconnectBot,
|
||||
{ botId: account.botId },
|
||||
),
|
||||
onRequestRemove: () => setRemoveTarget(account.botId),
|
||||
onCancelRemove: () => setRemoveTarget(null),
|
||||
onConfirmRemove: async () => {
|
||||
await botAction(account, 'delete', WHATSAPP_ENDPOINTS.deleteBot, {
|
||||
botId: account.botId,
|
||||
confirm: true,
|
||||
});
|
||||
if (mounted.current) setRemoveTarget(null);
|
||||
},
|
||||
})))))
|
||||
: null;
|
||||
|
||||
return h('section', {
|
||||
className: 'ddt-page dwa-page dim-channelPage',
|
||||
'aria-label': 'WhatsApp 设置',
|
||||
},
|
||||
h(Heading, {
|
||||
totals: model.totals,
|
||||
busy,
|
||||
onAdd: () => void startProvisioning(false),
|
||||
addButtonRef,
|
||||
}),
|
||||
model.phase === 'loading'
|
||||
? h(LoadingView)
|
||||
: model.phase === 'error'
|
||||
? h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-inlineError dim-inlineError' },
|
||||
h('h3', null, '无法读取 WhatsApp 机器人状态'),
|
||||
h('p', null, model.error?.message),
|
||||
h(Button, { onClick: () => void loadStatus() }, '重新读取')))
|
||||
: h(React.Fragment, null,
|
||||
provision?.status === 'pending'
|
||||
? h(QrPanel, {
|
||||
provision,
|
||||
now,
|
||||
busy,
|
||||
onRefresh: () => void startProvisioning(true),
|
||||
onCancel: () => void closeProvision(),
|
||||
})
|
||||
: provision
|
||||
? h(ProvisionView, {
|
||||
provision,
|
||||
busy,
|
||||
onRetry: () => void startProvisioning(true),
|
||||
onClose: () => void closeProvision(),
|
||||
})
|
||||
: model.bots.length === 0
|
||||
? h(EmptyView, { busy, onStart: () => void startProvisioning(false) })
|
||||
: null,
|
||||
botList));
|
||||
}
|
||||
19
plugin-src/client/channels/whatsapp/styles.js
Normal file
19
plugin-src/client/channels/whatsapp/styles.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
export const WHATSAPP_STYLE_ID = 'xmanrui-dsh-im-whatsapp-settings';
|
||||
|
||||
const CSS = String.raw`
|
||||
.dwa-page { --ddt-accent: #25d366; --ddt-accent-deep: #128c7e; --ddt-accent-wash: #eafbf0; }
|
||||
.dwa-avatar { color: #fff; background: #25d366; }
|
||||
.dwa-avatar svg { display: block; }
|
||||
`;
|
||||
|
||||
export function installWhatsappStyles() {
|
||||
if (typeof document === 'undefined') return () => {};
|
||||
const existing = document.querySelector(`style[data-plugin-css="${WHATSAPP_STYLE_ID}"]`);
|
||||
if (existing) return () => {};
|
||||
const style = document.createElement('style');
|
||||
style.dataset.plugin = '@xmanrui/dsh-im';
|
||||
style.dataset.pluginCss = WHATSAPP_STYLE_ID;
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
return () => style.remove();
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
TelegramLogoGlyph,
|
||||
WecomLogoGlyph,
|
||||
WeixinLogoGlyph,
|
||||
WhatsappLogoGlyph,
|
||||
} from './channel-logos.js';
|
||||
import { DINGTALK_RPC_CHANNEL } from './channels/dingtalk/api.js';
|
||||
import { DingtalkSettingsTab } from './channels/dingtalk/index.js';
|
||||
|
|
@ -29,6 +30,9 @@ import { installWecomStyles } from './channels/wecom/styles.js';
|
|||
import { WeixinSettingsTab } from './channels/weixin/index.js';
|
||||
import { WEIXIN_RPC_CHANNEL } from './channels/weixin/api.js';
|
||||
import { installWeixinStyles } from './channels/weixin/styles.js';
|
||||
import { WHATSAPP_RPC_CHANNEL } from './channels/whatsapp/api.js';
|
||||
import { WhatsappSettingsTab } from './channels/whatsapp/index.js';
|
||||
import { installWhatsappStyles } from './channels/whatsapp/styles.js';
|
||||
import { installImStyles } from './styles.js';
|
||||
|
||||
const h = React.createElement;
|
||||
|
|
@ -44,6 +48,7 @@ const CHANNELS = Object.freeze([
|
|||
{ id: 'qq', label: 'QQ' },
|
||||
{ id: 'telegram', label: 'Telegram' },
|
||||
{ id: 'discord', label: 'Discord' },
|
||||
{ id: 'whatsapp', label: 'WhatsApp' },
|
||||
]);
|
||||
|
||||
function WeixinLogo() {
|
||||
|
|
@ -79,6 +84,11 @@ function DiscordLogo() {
|
|||
h(DiscordLogoGlyph));
|
||||
}
|
||||
|
||||
function WhatsappLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoWhatsapp', 'aria-hidden': 'true' },
|
||||
h(WhatsappLogoGlyph));
|
||||
}
|
||||
|
||||
function ChannelLogo({ channel }) {
|
||||
if (channel === 'weixin') return h(WeixinLogo);
|
||||
if (channel === 'feishu') return h(FeishuLogo);
|
||||
|
|
@ -86,7 +96,8 @@ function ChannelLogo({ channel }) {
|
|||
if (channel === 'wecom') return h(WecomLogo);
|
||||
if (channel === 'qq') return h(QqLogo);
|
||||
if (channel === 'telegram') return h(TelegramLogo);
|
||||
return h(DiscordLogo);
|
||||
if (channel === 'discord') return h(DiscordLogo);
|
||||
return h(WhatsappLogo);
|
||||
}
|
||||
|
||||
export function IMSettingsTab({
|
||||
|
|
@ -97,6 +108,7 @@ export function IMSettingsTab({
|
|||
telegramRpcCall,
|
||||
wecomRpcCall,
|
||||
weixinRpcCall,
|
||||
whatsappRpcCall,
|
||||
}) {
|
||||
const [selected, setSelected] = React.useState('weixin');
|
||||
const active = CHANNELS.find((channel) => channel.id === selected) ?? CHANNELS[0];
|
||||
|
|
@ -138,7 +150,9 @@ export function IMSettingsTab({
|
|||
? h(QqSettingsTab, { rpcCall: qqRpcCall })
|
||||
: active.id === 'telegram'
|
||||
? h(TelegramSettingsTab, { rpcCall: telegramRpcCall })
|
||||
: h(DiscordSettingsTab, { rpcCall: discordRpcCall })),
|
||||
: active.id === 'discord'
|
||||
? h(DiscordSettingsTab, { rpcCall: discordRpcCall })
|
||||
: h(WhatsappSettingsTab, { rpcCall: whatsappRpcCall })),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -152,6 +166,7 @@ export function apply(ctx) {
|
|||
installQqStyles(),
|
||||
installTelegramStyles(),
|
||||
installDiscordStyles(),
|
||||
installWhatsappStyles(),
|
||||
installImStyles(),
|
||||
];
|
||||
return () => {
|
||||
|
|
@ -173,6 +188,8 @@ export function apply(ctx) {
|
|||
ctx.connection.rpc.call(TELEGRAM_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const discordRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(DISCORD_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const whatsappRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(WHATSAPP_RPC_CHANNEL, endpoint, payload, signal);
|
||||
|
||||
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
|
||||
name: 'settings.plugins.tab',
|
||||
|
|
@ -187,6 +204,7 @@ export function apply(ctx) {
|
|||
telegramRpcCall,
|
||||
wecomRpcCall,
|
||||
weixinRpcCall,
|
||||
whatsappRpcCall,
|
||||
}),
|
||||
}, IMSettingsTab));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,11 +37,13 @@ const CSS = String.raw`
|
|||
.dim-logoTelegram svg { width: 21px; height: 21px; }
|
||||
.dim-logoDiscord { color: white; background: #5865f2; }
|
||||
.dim-logoDiscord svg { width: 21px; height: 21px; }
|
||||
.dim-logoWhatsapp { color: white; background: #25d366; }
|
||||
.dim-logoWhatsapp svg { width: 21px; height: 21px; }
|
||||
.dim-channelCopy { min-width: 0; display: block; }
|
||||
.dim-channelCopy strong { overflow: hidden; color: inherit; font-size: 14px; line-height: 20px; font-weight: 680; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dim-divider { width: 1px; min-height: 520px; background: var(--dsw-alias-line-divider, #eef0f3); }
|
||||
.dim-panel { min-width: 0; container-type: inline-size; }
|
||||
.dim-panel .bxf-page, .dim-panel .dxw-page, .dim-panel .ddt-page, .dim-panel .dqq-page, .dim-panel .dwecom-page { width: 100%; max-width: none; padding: 0 0 24px; }
|
||||
.dim-panel .bxf-page, .dim-panel .dxw-page, .dim-panel .ddt-page, .dim-panel .dqq-page, .dim-panel .dwecom-page, .dim-panel .dwa-page { width: 100%; max-width: none; padding: 0 0 24px; }
|
||||
.dim-panel .bxf-heading, .dim-panel .dxw-heading, .dim-panel .ddt-heading { justify-content: flex-end; }
|
||||
.dim-panel .bxf-headingTools, .dim-panel .dxw-tools, .dim-panel .ddt-tools { width: 100%; justify-content: space-between; }
|
||||
.dim-panel .dim-bindActions { min-width: 0; display: flex; align-items: center; flex-wrap: nowrap; gap: 8px; }
|
||||
|
|
|
|||
35
plugin-src/host/channels/whatsapp/index.mjs
Normal file
35
plugin-src/host/channels/whatsapp/index.mjs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installWhatsappRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-whatsapp-host';
|
||||
export const inject = ['connection', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) {
|
||||
return installWhatsappRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installWhatsappRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close WhatsApp Web connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createWhatsappHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
WHATSAPP_ENDPOINTS,
|
||||
WHATSAPP_RPC_CHANNEL,
|
||||
WHATSAPP_RPC_ENDPOINTS,
|
||||
createWhatsappRpcHandler,
|
||||
installWhatsappRpc,
|
||||
} from './rpc.mjs';
|
||||
export { WhatsappController } from '../../../../src/channels/whatsapp/whatsapp-controller.mjs';
|
||||
export { WhatsappRuntime } from '../../../../src/channels/whatsapp/whatsapp-runtime.mjs';
|
||||
121
plugin-src/host/channels/whatsapp/production.mjs
Normal file
121
plugin-src/host/channels/whatsapp/production.mjs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { rm, unlink } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
import { WhatsappConfigStore } from '../../../../src/channels/whatsapp/config-store.mjs';
|
||||
import { WhatsappHarnessClient } from '../../../../src/channels/whatsapp/harness-client.mjs';
|
||||
import { WhatsappStateStore } from '../../../../src/channels/whatsapp/state-store.mjs';
|
||||
import { WhatsappController } from '../../../../src/channels/whatsapp/whatsapp-controller.mjs';
|
||||
import { WhatsappRuntime } from '../../../../src/channels/whatsapp/whatsapp-runtime.mjs';
|
||||
import { createWhatsappWebSession } from '../../../../src/channels/whatsapp/whatsapp-web-session.mjs';
|
||||
import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
|
||||
|
||||
const AUTH_DIRECTORY_PATTERN = /^[a-f0-9-]{36}$/;
|
||||
|
||||
function harnessOrigin(webServer, configured) {
|
||||
if (configured !== undefined) return new URL(configured);
|
||||
const port = webServer?.port;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
||||
throw new Error('dsh-im WhatsApp requires an initialized DSH webServer port');
|
||||
}
|
||||
return new URL(`http://127.0.0.1:${port}`);
|
||||
}
|
||||
|
||||
function pluginPaths(config) {
|
||||
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
||||
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', 'dsh-whatsapp'));
|
||||
const authRoot = resolve(config.authDir ?? join(root, 'auth'));
|
||||
const authPath = (name) => {
|
||||
if (!AUTH_DIRECTORY_PATTERN.test(name ?? '')) throw new TypeError('Invalid WhatsApp auth directory');
|
||||
return resolve(authRoot, name);
|
||||
};
|
||||
return {
|
||||
config: resolve(config.configPath ?? join(root, 'config.json')),
|
||||
bots: resolve(config.botsDir ?? join(root, 'bots')),
|
||||
authPath,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createProductionController(ctx, config = {}, internals = {}) {
|
||||
if (!ctx?.webServer) throw new TypeError('dsh-im WhatsApp requires ctx.webServer');
|
||||
const logger = typeof ctx.logger === 'function'
|
||||
? ctx.logger('dsh-im:whatsapp') : (ctx.logger ?? console);
|
||||
const ConfigStore = internals.ConfigStore ?? WhatsappConfigStore;
|
||||
const StateStore = internals.StateStore ?? WhatsappStateStore;
|
||||
const Harness = internals.HarnessClient ?? WhatsappHarnessClient;
|
||||
const Controller = internals.Controller ?? WhatsappController;
|
||||
const Runtime = internals.Runtime ?? WhatsappRuntime;
|
||||
const createSession = internals.createSession ?? createWhatsappWebSession;
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
|
||||
const paths = pluginPaths(config);
|
||||
const configStore = await new ConfigStore(paths.config).load();
|
||||
const stateStores = new Map();
|
||||
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
|
||||
const stateFor = async (botId) => {
|
||||
let state = stateStores.get(botId);
|
||||
if (!state) {
|
||||
state = await new StateStore(statePath(botId)).load();
|
||||
stateStores.set(botId, state);
|
||||
}
|
||||
return state;
|
||||
};
|
||||
const harness = new Harness({
|
||||
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
|
||||
workspace: resolve(config.workspace ?? process.cwd()),
|
||||
agentPreset: config.agentPreset ?? 'standard',
|
||||
autostart: false,
|
||||
dshBin: config.dshBin ?? 'dsh',
|
||||
});
|
||||
const controller = new Controller({
|
||||
configStore,
|
||||
authPath: paths.authPath,
|
||||
createSession,
|
||||
logger,
|
||||
createRuntime: async ({ botId, config: botConfig, authDir }) => new Runtime({
|
||||
config: botConfig,
|
||||
authDir,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 30_000,
|
||||
createSession,
|
||||
logger: {
|
||||
error: (...args) => logger.error?.(`[${botId}]`, ...args),
|
||||
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
|
||||
info: (...args) => logger.info?.(`[${botId}]`, ...args),
|
||||
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
|
||||
},
|
||||
}),
|
||||
deleteAuth: (authDirectory) => rm(paths.authPath(authDirectory), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
}),
|
||||
deleteState: async ({ botId }) => {
|
||||
const state = stateStores.get(botId);
|
||||
stateStores.delete(botId);
|
||||
if (state && typeof state.remove === 'function') return state.remove();
|
||||
try {
|
||||
await unlink(statePath(botId));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
const supervisor = createSupervisor({
|
||||
channel: 'whatsapp',
|
||||
controller,
|
||||
harness,
|
||||
logger,
|
||||
retryDelaysMs: config.retryDelaysMs,
|
||||
healthyIntervalMs: config.healthyIntervalMs,
|
||||
}).start();
|
||||
return {
|
||||
controller,
|
||||
ready: supervisor.ready,
|
||||
async close() {
|
||||
await supervisor.close();
|
||||
await controller.close();
|
||||
harness.stopManagedProcess();
|
||||
},
|
||||
};
|
||||
}
|
||||
140
plugin-src/host/channels/whatsapp/rpc.mjs
Normal file
140
plugin-src/host/channels/whatsapp/rpc.mjs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import QRCode from 'qrcode';
|
||||
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const WHATSAPP_RPC_CHANNEL = '/whatsapp';
|
||||
export const WHATSAPP_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
beginProvisioning: 'provision.begin',
|
||||
pollProvisioning: 'provision.poll',
|
||||
cancelProvisioning: 'provision.cancel',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
export const WHATSAPP_RPC_ENDPOINTS = Object.freeze(Object.values(WHATSAPP_ENDPOINTS));
|
||||
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set(['qrValue', 'accountJid', 'authDirectory']);
|
||||
|
||||
function isRecord(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function exactKeys(value, allowed) {
|
||||
return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
|
||||
}
|
||||
|
||||
function validId(value) {
|
||||
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
|
||||
}
|
||||
|
||||
function payloadFailure(endpoint, payload) {
|
||||
if (!isRecord(payload)) return 'Payload must be an object.';
|
||||
if ([WHATSAPP_ENDPOINTS.status, WHATSAPP_ENDPOINTS.beginProvisioning].includes(endpoint)) {
|
||||
return exactKeys(payload, []) ? null : `${endpoint} does not accept fields.`;
|
||||
}
|
||||
if ([WHATSAPP_ENDPOINTS.pollProvisioning, WHATSAPP_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
|
||||
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
|
||||
? null : `${endpoint} requires an attemptId.`;
|
||||
}
|
||||
if (endpoint === WHATSAPP_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId)
|
||||
? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === WHATSAPP_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId)
|
||||
&& payload.confirm === true ? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown WhatsApp endpoint.';
|
||||
}
|
||||
|
||||
function sanitizePublic(value) {
|
||||
if (Array.isArray(value)) return value.map(sanitizePublic);
|
||||
if (!isRecord(value)) return value;
|
||||
const safe = {};
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (!FORBIDDEN_PUBLIC_KEYS.has(key)) safe[key] = sanitizePublic(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
async function qrDataUrl(value) {
|
||||
return QRCode.toDataURL(value, {
|
||||
type: 'image/png',
|
||||
errorCorrectionLevel: 'M',
|
||||
margin: 2,
|
||||
width: 320,
|
||||
});
|
||||
}
|
||||
|
||||
async function encodeAttempt(value, encodeQr) {
|
||||
if (!value || typeof value.qrValue !== 'string') return sanitizePublic(value);
|
||||
return sanitizePublic({ ...value, qrCodeDataUrl: await encodeQr(value.qrValue) });
|
||||
}
|
||||
|
||||
async function publicStatus(value, encodeQr) {
|
||||
const snapshot = structuredClone(value);
|
||||
if (snapshot?.provisioning) snapshot.provisioning = await encodeAttempt(snapshot.provisioning, encodeQr);
|
||||
return sanitizePublic(snapshot);
|
||||
}
|
||||
|
||||
export function createWhatsappRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
||||
for (const method of ['status', 'startProvisioning', 'registrationStatus', 'cancelProvisioning', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete WhatsApp controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
const qrCache = new Map();
|
||||
const cachedEncode = (value) => {
|
||||
let encoded = qrCache.get(value);
|
||||
if (!encoded) {
|
||||
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
||||
encoded = Promise.resolve().then(() => encodeQr(value));
|
||||
qrCache.set(value, encoded);
|
||||
}
|
||||
return encoded;
|
||||
};
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
if (!WHATSAPP_RPC_ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: 'Unknown WhatsApp endpoint.' } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === WHATSAPP_ENDPOINTS.status) {
|
||||
value = await publicStatus(await controller.status(), cachedEncode);
|
||||
} else if (endpoint === WHATSAPP_ENDPOINTS.beginProvisioning) {
|
||||
value = await encodeAttempt(await controller.startProvisioning(), cachedEncode);
|
||||
} else if (endpoint === WHATSAPP_ENDPOINTS.pollProvisioning) {
|
||||
const attempt = await controller.registrationStatus(payload.attemptId);
|
||||
if (!attempt) return { ok: false, error: { code: 'bad-request', message: 'The provisioning attempt no longer exists.' } };
|
||||
value = await encodeAttempt(attempt, cachedEncode);
|
||||
} else if (endpoint === WHATSAPP_ENDPOINTS.cancelProvisioning) {
|
||||
value = sanitizePublic(await controller.cancelProvisioning(payload.attemptId));
|
||||
} else if (endpoint === WHATSAPP_ENDPOINTS.reconnectBot) {
|
||||
value = await publicStatus(await controller.reconnectBot(payload.botId), cachedEncode);
|
||||
} else {
|
||||
value = await publicStatus(await controller.deleteBot(payload.botId), cachedEncode);
|
||||
}
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: true, value };
|
||||
} catch {
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: false, error: { code: 'whatsapp-operation-failed', message: 'WhatsApp 操作失败,请稍后重试。' } };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installWhatsappRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
WHATSAPP_RPC_CHANNEL,
|
||||
createWhatsappRpcHandler(controller, options),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { apply as applyQq } from './channels/qq/index.mjs';
|
|||
import { apply as applyTelegram } from './channels/telegram/index.mjs';
|
||||
import { apply as applyWecom } from './channels/wecom/index.mjs';
|
||||
import { apply as applyWeixin } from './channels/weixin/index.mjs';
|
||||
import { apply as applyWhatsapp } from './channels/whatsapp/index.mjs';
|
||||
|
||||
export const name = 'dsh-im-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
|
@ -24,6 +25,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
const startQq = internals.applyQq ?? applyQq;
|
||||
const startTelegram = internals.applyTelegram ?? applyTelegram;
|
||||
const startDiscord = internals.applyDiscord ?? applyDiscord;
|
||||
const startWhatsapp = internals.applyWhatsapp ?? applyWhatsapp;
|
||||
return Object.freeze({
|
||||
name,
|
||||
inject,
|
||||
|
|
@ -35,6 +37,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
await startQq(ctx, channelConfig(config, 'qq'));
|
||||
await startTelegram(ctx, channelConfig(config, 'telegram'));
|
||||
await startDiscord(ctx, channelConfig(config, 'discord'));
|
||||
await startWhatsapp(ctx, channelConfig(config, 'whatsapp'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue