mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 01:53:21 +08:00
Add WeCom QR bot channel
This commit is contained in:
parent
601271a7f8
commit
4874d3e354
33 changed files with 5200 additions and 440 deletions
|
|
@ -57,3 +57,25 @@ export function QqLogoGlyph({ size } = {}) {
|
|||
d: 'M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673.54.065 2.103-2.472 2.103-2.472 0 1.469.756 3.387 2.394 4.771-.612.188-1.363.479-1.845.835-.434.32-.379.646-.301.778.343.578 5.883.369 7.482.189 1.6.18 7.14.389 7.483-.189.078-.132.132-.458-.301-.778-.483-.356-1.233-.646-1.846-.836 1.637-1.384 2.393-3.302 2.393-4.771 0 0 1.563 2.537 2.103 2.472.251-.03.581-1.39-.438-4.673',
|
||||
}));
|
||||
}
|
||||
|
||||
export function WecomLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
viewBox: '0 0 24 24',
|
||||
focusable: 'false',
|
||||
'aria-hidden': 'true',
|
||||
'data-im-channel-logo': 'wecom',
|
||||
},
|
||||
h('path', {
|
||||
fill: 'none',
|
||||
stroke: '#3370FF',
|
||||
strokeWidth: '2.35',
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
d: 'M17.7 14.5c1.05-1.12 1.65-2.52 1.65-4.03 0-3.82-3.58-6.92-8-6.92s-8 3.1-8 6.92 3.58 6.92 8 6.92c1.17 0 2.28-.22 3.28-.62',
|
||||
}),
|
||||
h('path', { fill: '#07C160', d: 'M16.1 15.15c.7-.7 1.83-.7 2.53 0s.7 1.83 0 2.53-1.83.7-2.53 0-.7-1.83 0-2.53Z' }),
|
||||
h('path', { fill: '#FFB800', d: 'M19.25 13.45a1.36 1.36 0 1 1 1.92 1.92 1.36 1.36 0 0 1-1.92-1.92Z' }),
|
||||
h('path', { fill: '#FF7A00', d: 'M19.55 18.05a1.16 1.16 0 1 1 1.64 1.64 1.16 1.16 0 0 1-1.64-1.64Z' }),
|
||||
h('path', { fill: '#3370FF', d: 'M15.25 18.75a.92.92 0 1 1 1.3 1.3.92.92 0 0 1-1.3-1.3Z' }));
|
||||
}
|
||||
|
|
|
|||
118
plugin-src/client/channels/wecom/api.js
Normal file
118
plugin-src/client/channels/wecom/api.js
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
export const WECOM_RPC_CHANNEL = '/wecom';
|
||||
|
||||
export const WECOM_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', 'refreshing', 'connecting', 'connected', 'failed', 'cancelled']);
|
||||
const ACCOUNT_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('企业微信服务返回了无法识别的响应');
|
||||
if (!result.ok) {
|
||||
const error = new Error(text(result.error?.message, '企业微信操作失败'));
|
||||
error.code = text(result.error?.code, 'WECOM_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('企业微信服务没有返回扫码绑定进度');
|
||||
const attemptId = id(source.attemptId);
|
||||
if (!attemptId) throw new Error('企业微信扫码服务没有返回有效的绑定任务');
|
||||
const reported = text(source.status, 'failed', 32);
|
||||
const result = {
|
||||
attemptId,
|
||||
status: PROVISION_STATES.has(reported) ? reported : 'failed',
|
||||
expiresAt: timestamp(source.expiresAt) ?? now + 5 * 60_000,
|
||||
pollIntervalMs: Math.min(10_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, 'WECOM_PROVISION_FAILED', 80),
|
||||
message: text(source.error.message, '企业微信机器人没有接入完成'),
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeBot(value) {
|
||||
if (!isRecord(value) || !id(value.botId)) return undefined;
|
||||
const connected = value.connected === true;
|
||||
const state = ACCOUNT_STATES.has(value.state) ? value.state : 'offline';
|
||||
return {
|
||||
botId: id(value.botId),
|
||||
connected,
|
||||
state: connected ? 'connected' : state,
|
||||
bot: {
|
||||
name: text(value.bot?.name, '企业微信机器人', 100),
|
||||
appIdMasked: text(value.bot?.appIdMasked, '应用标识已安全保存', 140),
|
||||
},
|
||||
health: {
|
||||
summary: text(value.health?.summary, connected ? '企业微信 WebSocket 长连接运行正常' : '企业微信连接尚未就绪'),
|
||||
lastCheckedAt: timestamp(value.health?.lastCheckedAt),
|
||||
},
|
||||
error: isRecord(value.error) ? {
|
||||
code: text(value.error.code, 'WECOM_ACCOUNT_ERROR', 80),
|
||||
message: text(value.error.message, '企业微信连接尚未就绪'),
|
||||
} : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSnapshot(value) {
|
||||
const source = isRecord(value?.snapshot) ? value.snapshot : value;
|
||||
if (!isRecord(source) || !Array.isArray(source.bots)) throw new Error('企业微信服务没有返回有效的机器人列表');
|
||||
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, 'WECOM_ERROR', 80),
|
||||
message: text(error?.message, '企业微信操作失败,请稍后重试'),
|
||||
};
|
||||
}
|
||||
|
||||
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')}`;
|
||||
}
|
||||
344
plugin-src/client/channels/wecom/index.js
Normal file
344
plugin-src/client/channels/wecom/index.js
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
import * as React from 'react';
|
||||
|
||||
import { WecomLogoGlyph } from '../../channel-logos.js';
|
||||
import { installDingtalkStyles } from '../dingtalk/styles.js';
|
||||
import {
|
||||
WECOM_ENDPOINTS,
|
||||
WECOM_RPC_CHANNEL,
|
||||
formatRemaining,
|
||||
normalizeProvisioning,
|
||||
normalizeSnapshot,
|
||||
presentError,
|
||||
safeQrSource,
|
||||
unwrapRpcResult,
|
||||
} from './api.js';
|
||||
import { installWecomStyles } from './styles.js';
|
||||
|
||||
const h = React.createElement;
|
||||
const ACTIVE_STATES = new Set(['pending', 'refreshing', '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, adding, busy, onAdd, addButtonRef }) {
|
||||
return h('div', { className: 'ddt-heading' },
|
||||
h('div', { className: 'ddt-tools' },
|
||||
h(Button, {
|
||||
kind: 'primary',
|
||||
className: 'dim-scanButton',
|
||||
onClick: onAdd,
|
||||
disabled: adding || busy,
|
||||
ref: addButtonRef,
|
||||
}, adding ? '正在绑定' : '扫码绑定企业微信机器人'),
|
||||
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' }),
|
||||
h('span', null, '正在读取企业微信机器人状态…'));
|
||||
}
|
||||
|
||||
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, '尚未绑定企业微信机器人')),
|
||||
h('h3', null, '使用企业微信 App 扫码创建智能机器人'),
|
||||
h('p', null, '扫码由腾讯官方页面完成,不需要手动填写 Bot ID 或 Secret。创建成功后,机器人会自动连接 DeepSeek Harness。'),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { kind: 'primary', onClick: onStart, disabled: busy },
|
||||
busy ? '正在生成二维码…' : '生成企业微信二维码'))),
|
||||
h('div', { className: 'ddt-brandMark dim-emptyBrand dwecom-brand', 'aria-hidden': 'true' },
|
||||
h(WecomLogoGlyph, { size: 64 }))));
|
||||
}
|
||||
|
||||
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 ?? 5 * 60_000);
|
||||
const progress = Math.round(Math.min(1, remaining / duration) * 100);
|
||||
const refreshing = provision.status === 'refreshing';
|
||||
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: '用于绑定企业微信机器人的一次性二维码' })
|
||||
: h('div', { className: 'ddt-qrFallback dim-qrFallback' },
|
||||
refreshing ? '二维码正在自动刷新…' : '二维码图片正在生成…')),
|
||||
h('div', { className: 'ddt-countdown dim-countdown' },
|
||||
h('div', { className: 'ddt-countdownTop dim-countdownTop' },
|
||||
h('span', null, '当前二维码有效时间'),
|
||||
h('strong', null, refreshing ? '--:--' : 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, refreshing ? '正在刷新二维码' : '等待企业微信 App 扫码')),
|
||||
h('h3', null, '使用企业微信 App 完成智能机器人授权'),
|
||||
h('p', null, '企业微信官方页面会创建一个智能机器人,并把连接凭据安全交给本机 Harness Host。'),
|
||||
h('ol', { className: 'ddt-steps dim-steps' },
|
||||
h('li', null, '打开企业微信 App,扫描左侧二维码'),
|
||||
h('li', null, '在腾讯授权页面确认创建智能机器人'),
|
||||
h('li', null, '返回这里等待连接完成')),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onRefresh, disabled: busy }, '重新生成二维码'),
|
||||
h(Button, { kind: 'quiet', onClick: onCancel, disabled: busy }, '取消')))));
|
||||
}
|
||||
|
||||
function ProvisionView({ provision, busy, onRetry, onClose }) {
|
||||
if (provision.status === 'connecting') {
|
||||
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, '企业微信已授权,正在连接机器人'),
|
||||
h('p', null, '凭据正在写入本机,并启动企业微信 WebSocket 消息连接。'));
|
||||
}
|
||||
const error = provision.error ?? { code: 'WECOM_PROVISION_FAILED', message: '企业微信机器人没有绑定完成' };
|
||||
return h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-inlineError dim-inlineError', role: 'alert' },
|
||||
h('h3', null, '企业微信机器人没有绑定完成'),
|
||||
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, '这会停止消息连接,并删除本机保存的应用凭据、机器人配置及会话映射。企业微信平台中的机器人不会被自动删除。'),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onCancel, disabled: busy }, '保留机器人'),
|
||||
h(Button, { kind: 'danger', onClick: onConfirm, disabled: busy }, busy ? '正在移除…' : '确认移除接入')));
|
||||
}
|
||||
|
||||
export function AccountCard({ account, busy, removing, onReconnect, onRequestRemove, onConfirmRemove, onCancelRemove }) {
|
||||
const tone = account.connected ? 'success' : account.state === 'error' ? 'error' : 'warning';
|
||||
const stateLabel = account.connected ? '运行正常' : account.state === 'connecting' ? '正在连接' : '连接未就绪';
|
||||
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 dwecom-avatar', 'aria-hidden': 'true' }, h(WecomLogoGlyph, { size: 29 })),
|
||||
h('div', { className: 'dim-botName' },
|
||||
h('h3', null, account.bot.name), h('p', null, account.bot.appIdMasked))),
|
||||
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 ? 'WebSocket 长连接' : '离线')),
|
||||
h('div', { className: 'ddt-metric dim-botMetric' }, h('dt', null, '最近检查'), h('dd', null, checkedTime(account.health.lastCheckedAt)))),
|
||||
h('div', { className: 'ddt-accountFooter dim-cardFooter' },
|
||||
h('div', { className: 'ddt-summary dim-cardSummary' }, account.error?.message ?? account.health.summary),
|
||||
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 WecomSettingsTab({ 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 disposeWecom = installWecomStyles();
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
disposeWecom();
|
||||
disposeDingtalk();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const invoke = React.useCallback(async (endpoint, payload = {}, signal) => {
|
||||
if (typeof rpcCall !== 'function') throw new TypeError('企业微信设置页缺少 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(WECOM_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(WECOM_ENDPOINTS.cancelProvisioning, { attemptId: provision.attemptId });
|
||||
if (!mounted.current) return;
|
||||
setProvision({ status: 'starting' });
|
||||
const started = normalizeProvisioning(await invoke(WECOM_ENDPOINTS.beginProvisioning, { locale: 'zh-CN' }));
|
||||
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(WECOM_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 poll = async () => {
|
||||
try {
|
||||
const current = normalizeProvisioning(await invoke(WECOM_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) => previous?.attemptId === attemptId
|
||||
? { ...previous, ...current, durationMs: current.qrRevision !== previous.qrRevision
|
||||
? Math.max(1, current.expiresAt - Date.now()) : previous.durationMs }
|
||||
: previous);
|
||||
if (ACTIVE_STATES.has(current.status)) timer = window.setTimeout(poll, current.pollIntervalMs);
|
||||
} catch (error) {
|
||||
if (!disposed && !controller.signal.aborted && mounted.current) {
|
||||
setProvision((current) => ({ ...current, status: 'failed', error: presentError(error) }));
|
||||
}
|
||||
}
|
||||
};
|
||||
timer = window.setTimeout(poll, provision.pollIntervalMs ?? 1_000);
|
||||
return () => { disposed = true; controller.abort(); window.clearTimeout(timer); };
|
||||
}, [invoke, loadStatus, provision?.attemptId, provision?.pollIntervalMs, 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 });
|
||||
return snapshot;
|
||||
} finally {
|
||||
if (mounted.current) setBusyByBot((current) => {
|
||||
const next = { ...current }; delete next[account.botId]; return next;
|
||||
});
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
let provisionView = null;
|
||||
if (provision?.status === 'starting') provisionView = h('div', { className: 'ddt-card ddt-loading dim-surfaceCard' }, h('div', { className: 'ddt-spinner' }), '正在申请企业微信二维码…');
|
||||
else if (['pending', 'refreshing'].includes(provision?.status)) provisionView = h(QrPanel, {
|
||||
provision, now, busy, onRefresh: () => void startProvisioning(true), onCancel: () => void closeProvision(),
|
||||
});
|
||||
else if (provision) provisionView = h(ProvisionView, {
|
||||
provision, busy, onRetry: () => void startProvisioning(true), onClose: () => void closeProvision(),
|
||||
});
|
||||
|
||||
const botList = model.bots.length > 0
|
||||
? h('section', { className: 'dim-listSection' },
|
||||
h('div', { className: 'ddt-listHeading dim-listHeading' },
|
||||
h('h3', null, '已绑定的企业微信机器人'), h('span', null, `${model.bots.length} 个`)),
|
||||
h('ul', { className: 'ddt-list dim-botList' }, model.bots.map((account) =>
|
||||
h('li', { key: account.botId }, h(AccountCard, {
|
||||
account,
|
||||
busy: busyByBot[account.botId],
|
||||
removing: removeTarget === account.botId,
|
||||
onReconnect: () => void botAction(account, 'reconnect', WECOM_ENDPOINTS.reconnectBot, { botId: account.botId }),
|
||||
onRequestRemove: () => setRemoveTarget(account.botId),
|
||||
onCancelRemove: () => setRemoveTarget(null),
|
||||
onConfirmRemove: async () => {
|
||||
await botAction(account, 'delete', WECOM_ENDPOINTS.deleteBot, { botId: account.botId, confirm: true });
|
||||
if (mounted.current) setRemoveTarget(null);
|
||||
},
|
||||
})))))
|
||||
: null;
|
||||
|
||||
return h('section', { className: 'ddt-page dwecom-page dim-channelPage', 'aria-label': '企业微信设置' },
|
||||
h(Heading, { totals: model.totals, adding: Boolean(provision), busy, onAdd: () => void startProvisioning(), 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, '无法读取企业微信机器人状态'), h('p', null, model.error?.message), h(Button, { onClick: () => void loadStatus() }, '重新读取')))
|
||||
: h(React.Fragment, null,
|
||||
provisionView,
|
||||
model.bots.length === 0 && !provision ? h(EmptyView, { busy, onStart: () => void startProvisioning() }) : null,
|
||||
botList));
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
ctx.effect(() => installWecomStyles(), 'wecom-settings: install client styles');
|
||||
const rpcCall = (endpoint, payload, signal) => ctx.connection.rpc.call(WECOM_RPC_CHANNEL, endpoint, payload, signal);
|
||||
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
|
||||
name: 'settings.plugins.tab', id: 'wecom', order: 45, label: '企业微信', inject: () => ({ rpcCall }),
|
||||
}, WecomSettingsTab));
|
||||
}
|
||||
19
plugin-src/client/channels/wecom/styles.js
Normal file
19
plugin-src/client/channels/wecom/styles.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
export const WECOM_STYLE_ID = 'xmanrui-dsh-im-wecom-settings';
|
||||
|
||||
const CSS = String.raw`
|
||||
.dwecom-page { --ddt-accent: #3370ff; --ddt-accent-deep: #245bdb; --ddt-accent-wash: #eef4ff; }
|
||||
.dwecom-avatar, .dwecom-brand { color: #3370ff; background: #fff; border: 1px solid var(--dsw-alias-line-border, #e5e6eb); }
|
||||
.dwecom-avatar svg, .dwecom-brand svg { display: block; }
|
||||
`;
|
||||
|
||||
export function installWecomStyles() {
|
||||
if (typeof document === 'undefined') return () => {};
|
||||
const existing = document.querySelector(`style[data-plugin-css="${WECOM_STYLE_ID}"]`);
|
||||
if (existing) return () => {};
|
||||
const style = document.createElement('style');
|
||||
style.dataset.plugin = '@xmanrui/dsh-im';
|
||||
style.dataset.pluginCss = WECOM_STYLE_ID;
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
return () => style.remove();
|
||||
}
|
||||
|
|
@ -1,6 +1,12 @@
|
|||
import * as React from 'react';
|
||||
|
||||
import { DingtalkLogoGlyph, FeishuLogoGlyph, QqLogoGlyph, WeixinLogoGlyph } from './channel-logos.js';
|
||||
import {
|
||||
DingtalkLogoGlyph,
|
||||
FeishuLogoGlyph,
|
||||
QqLogoGlyph,
|
||||
WecomLogoGlyph,
|
||||
WeixinLogoGlyph,
|
||||
} from './channel-logos.js';
|
||||
import { DINGTALK_RPC_CHANNEL } from './channels/dingtalk/api.js';
|
||||
import { DingtalkSettingsTab } from './channels/dingtalk/index.js';
|
||||
import { FeishuSettingsTab } from './channels/feishu/index.js';
|
||||
|
|
@ -9,6 +15,9 @@ import { installFeishuStyles } from './channels/feishu/styles.js';
|
|||
import { QQ_RPC_CHANNEL } from './channels/qq/api.js';
|
||||
import { QqSettingsTab } from './channels/qq/index.js';
|
||||
import { installQqStyles } from './channels/qq/styles.js';
|
||||
import { WECOM_RPC_CHANNEL } from './channels/wecom/api.js';
|
||||
import { WecomSettingsTab } from './channels/wecom/index.js';
|
||||
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';
|
||||
|
|
@ -23,6 +32,7 @@ const CHANNELS = Object.freeze([
|
|||
{ id: 'weixin', label: '微信' },
|
||||
{ id: 'feishu', label: '飞书' },
|
||||
{ id: 'dingtalk', label: '钉钉' },
|
||||
{ id: 'wecom', label: '企业微信' },
|
||||
{ id: 'qq', label: 'QQ' },
|
||||
]);
|
||||
|
||||
|
|
@ -45,14 +55,19 @@ function QqLogo() {
|
|||
return h('span', { className: 'dim-logo dim-logoQq', 'aria-hidden': 'true' }, h(QqLogoGlyph));
|
||||
}
|
||||
|
||||
function WecomLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoWecom', 'aria-hidden': 'true' }, h(WecomLogoGlyph));
|
||||
}
|
||||
|
||||
function ChannelLogo({ channel }) {
|
||||
if (channel === 'weixin') return h(WeixinLogo);
|
||||
if (channel === 'feishu') return h(FeishuLogo);
|
||||
if (channel === 'dingtalk') return h(DingtalkLogo);
|
||||
if (channel === 'wecom') return h(WecomLogo);
|
||||
return h(QqLogo);
|
||||
}
|
||||
|
||||
export function IMSettingsTab({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, weixinRpcCall }) {
|
||||
export function IMSettingsTab({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, wecomRpcCall, weixinRpcCall }) {
|
||||
const [selected, setSelected] = React.useState('weixin');
|
||||
const active = CHANNELS.find((channel) => channel.id === selected) ?? CHANNELS[0];
|
||||
return h('section', { className: 'dim-page', 'aria-label': 'IM机器人设置' },
|
||||
|
|
@ -87,14 +102,22 @@ export function IMSettingsTab({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, weixi
|
|||
? h(FeishuSettingsTab, { rpcCall: feishuRpcCall })
|
||||
: active.id === 'dingtalk'
|
||||
? h(DingtalkSettingsTab, { rpcCall: dingtalkRpcCall })
|
||||
: h(QqSettingsTab, { rpcCall: qqRpcCall })),
|
||||
: active.id === 'wecom'
|
||||
? h(WecomSettingsTab, { rpcCall: wecomRpcCall })
|
||||
: h(QqSettingsTab, { rpcCall: qqRpcCall })),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
ctx.effect(() => {
|
||||
const disposers = [installFeishuStyles(), installWeixinStyles(), installQqStyles(), installImStyles()];
|
||||
const disposers = [
|
||||
installFeishuStyles(),
|
||||
installWeixinStyles(),
|
||||
installWecomStyles(),
|
||||
installQqStyles(),
|
||||
installImStyles(),
|
||||
];
|
||||
return () => {
|
||||
for (const dispose of disposers.reverse()) dispose();
|
||||
};
|
||||
|
|
@ -108,12 +131,14 @@ export function apply(ctx) {
|
|||
ctx.connection.rpc.call(DINGTALK_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const qqRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(QQ_RPC_CHANNEL, endpoint, payload, signal);
|
||||
const wecomRpcCall = (endpoint, payload, signal) =>
|
||||
ctx.connection.rpc.call(WECOM_RPC_CHANNEL, endpoint, payload, signal);
|
||||
|
||||
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
|
||||
name: 'settings.plugins.tab',
|
||||
id: 'im',
|
||||
order: 20,
|
||||
label: 'IM机器人',
|
||||
inject: () => ({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, weixinRpcCall }),
|
||||
inject: () => ({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, wecomRpcCall, weixinRpcCall }),
|
||||
}, IMSettingsTab));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,11 +31,13 @@ const CSS = String.raw`
|
|||
.dim-logoDingtalk svg { width: 24px; height: 24px; }
|
||||
.dim-logoQq { color: white; background: #1677ff; }
|
||||
.dim-logoQq svg { width: 21px; height: 21px; }
|
||||
.dim-logoWecom { background: white; border: 1px solid var(--dsw-alias-line-border, #e5e6eb); }
|
||||
.dim-logoWecom svg { width: 22px; height: 22px; }
|
||||
.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 { 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 { 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 .bxf-headingTools .dim-scanButton, .dim-panel .dxw-tools .dim-scanButton, .dim-panel .ddt-tools .dim-scanButton { flex: none; min-height: 34px; padding: 0 13px; border: 1px solid #1677ff; border-radius: 8px; color: #fff; background: #1677ff; box-shadow: none; font: inherit; font-size: 13px; font-weight: 560; white-space: nowrap; }
|
||||
|
|
|
|||
124
plugin-src/host/channels/wecom/connection-supervisor.mjs
Normal file
124
plugin-src/host/channels/wecom/connection-supervisor.mjs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
const DEFAULT_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000, 5_000, 10_000, 30_000]);
|
||||
|
||||
function retryDelays(value) {
|
||||
if (!Array.isArray(value) || value.length === 0) return [...DEFAULT_RETRY_DELAYS_MS];
|
||||
const valid = value.filter((delay) => Number.isFinite(delay) && delay >= 0);
|
||||
return valid.length > 0 ? valid : [...DEFAULT_RETRY_DELAYS_MS];
|
||||
}
|
||||
|
||||
export class ConnectionSupervisor {
|
||||
#controller;
|
||||
#harness;
|
||||
#logger;
|
||||
#retryDelays;
|
||||
#healthyIntervalMs;
|
||||
#setTimeout;
|
||||
#clearTimeout;
|
||||
#timer = null;
|
||||
#running = null;
|
||||
#retryIndex = 0;
|
||||
#closed = false;
|
||||
#started = false;
|
||||
#ready;
|
||||
#resolveReady;
|
||||
|
||||
constructor({
|
||||
controller,
|
||||
harness,
|
||||
logger = console,
|
||||
retryDelaysMs,
|
||||
healthyIntervalMs = 15_000,
|
||||
setTimeoutImpl = setTimeout,
|
||||
clearTimeoutImpl = clearTimeout,
|
||||
}) {
|
||||
if (!controller || typeof controller.initialize !== 'function' || typeof controller.status !== 'function') {
|
||||
throw new TypeError('ConnectionSupervisor requires a controller');
|
||||
}
|
||||
if (!harness || typeof harness.ensureRunning !== 'function') {
|
||||
throw new TypeError('ConnectionSupervisor requires a Harness client');
|
||||
}
|
||||
this.#controller = controller;
|
||||
this.#harness = harness;
|
||||
this.#logger = logger;
|
||||
this.#retryDelays = retryDelays(retryDelaysMs);
|
||||
this.#healthyIntervalMs = Number.isFinite(healthyIntervalMs) && healthyIntervalMs >= 0
|
||||
? healthyIntervalMs : 15_000;
|
||||
this.#setTimeout = setTimeoutImpl;
|
||||
this.#clearTimeout = clearTimeoutImpl;
|
||||
this.#ready = new Promise((resolve) => {
|
||||
this.#resolveReady = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
get ready() {
|
||||
return this.#ready;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.#started || this.#closed) return this;
|
||||
this.#started = true;
|
||||
this.#schedule(0);
|
||||
return this;
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.#closed) return;
|
||||
this.#closed = true;
|
||||
if (this.#timer !== null) this.#clearTimeout(this.#timer);
|
||||
this.#timer = null;
|
||||
await this.#running?.catch(() => undefined);
|
||||
this.#resolveReady?.(null);
|
||||
this.#resolveReady = null;
|
||||
}
|
||||
|
||||
#schedule(delayMs) {
|
||||
if (this.#closed) return;
|
||||
this.#timer = this.#setTimeout(() => {
|
||||
this.#timer = null;
|
||||
void this.#run();
|
||||
}, delayMs);
|
||||
this.#timer?.unref?.();
|
||||
}
|
||||
|
||||
async #run() {
|
||||
if (this.#closed || this.#running) return;
|
||||
const operation = this.#reconcile();
|
||||
this.#running = operation;
|
||||
try {
|
||||
await operation;
|
||||
} finally {
|
||||
if (this.#running === operation) this.#running = null;
|
||||
}
|
||||
}
|
||||
|
||||
async #reconcile() {
|
||||
try {
|
||||
await this.#harness.ensureRunning();
|
||||
if (this.#closed) return;
|
||||
const status = await this.#controller.initialize();
|
||||
if (this.#closed) return;
|
||||
this.#resolveReady?.(status);
|
||||
this.#resolveReady = null;
|
||||
const { configured, connected } = status.totals;
|
||||
if (connected < configured) {
|
||||
const delay = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
|
||||
this.#retryIndex += 1;
|
||||
this.#logger.warn?.(`[dsh-im:wecom] ${connected}/${configured} bots connected; retrying in ${delay}ms`);
|
||||
this.#schedule(delay);
|
||||
return;
|
||||
}
|
||||
this.#retryIndex = 0;
|
||||
this.#schedule(this.#healthyIntervalMs);
|
||||
} catch (error) {
|
||||
if (this.#closed) return;
|
||||
const delay = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
|
||||
this.#retryIndex += 1;
|
||||
this.#logger.warn?.(`[dsh-im:wecom] connection reconciliation failed; retrying in ${delay}ms`, error);
|
||||
this.#schedule(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createConnectionSupervisor(options) {
|
||||
return new ConnectionSupervisor(options);
|
||||
}
|
||||
29
plugin-src/host/channels/wecom/index.mjs
Normal file
29
plugin-src/host/channels/wecom/index.mjs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installWecomRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-wecom-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installWecomRpc(ctx, config.controller, config.rpcOptions);
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installWecomRpc(ctx, production.controller, config.rpcOptions);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Enterprise WeChat bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createWecomHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createConnectionSupervisor, ConnectionSupervisor } from './connection-supervisor.mjs';
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
WECOM_ENDPOINTS,
|
||||
WECOM_RPC_CHANNEL,
|
||||
WECOM_RPC_ENDPOINTS,
|
||||
createWecomRpcHandler,
|
||||
installWecomRpc,
|
||||
} from './rpc.mjs';
|
||||
export { WecomController } from '../../../../src/channels/wecom/wecom-controller.mjs';
|
||||
export { WecomRuntime } from '../../../../src/channels/wecom/wecom-runtime.mjs';
|
||||
113
plugin-src/host/channels/wecom/production.mjs
Normal file
113
plugin-src/host/channels/wecom/production.mjs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { unlink } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
import { WecomConfigStore } from '../../../../src/channels/wecom/config-store.mjs';
|
||||
import { WecomHarnessClient } from '../../../../src/channels/wecom/harness-client.mjs';
|
||||
import { WecomQrAuth } from '../../../../src/channels/wecom/qr-auth.mjs';
|
||||
import { WecomStateStore } from '../../../../src/channels/wecom/state-store.mjs';
|
||||
import { WecomController } from '../../../../src/channels/wecom/wecom-controller.mjs';
|
||||
import { WecomRuntime } from '../../../../src/channels/wecom/wecom-runtime.mjs';
|
||||
import { createConnectionSupervisor } from './connection-supervisor.mjs';
|
||||
|
||||
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 Enterprise WeChat 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-wecom'));
|
||||
return {
|
||||
config: resolve(config.configPath ?? join(root, 'config.json')),
|
||||
bots: resolve(config.botsDir ?? join(root, 'bots')),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createProductionController(ctx, config = {}, internals = {}) {
|
||||
if (!ctx?.credentials) throw new TypeError('dsh-im Enterprise WeChat requires ctx.credentials');
|
||||
if (!ctx?.webServer) throw new TypeError('dsh-im Enterprise WeChat requires ctx.webServer');
|
||||
|
||||
const ConfigStore = internals.ConfigStore ?? WecomConfigStore;
|
||||
const StateStore = internals.StateStore ?? WecomStateStore;
|
||||
const Harness = internals.HarnessClient ?? WecomHarnessClient;
|
||||
const Controller = internals.Controller ?? WecomController;
|
||||
const Runtime = internals.Runtime ?? WecomRuntime;
|
||||
const QrAuth = internals.QrAuth ?? WecomQrAuth;
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createConnectionSupervisor;
|
||||
const logger = typeof ctx.logger === 'function' ? ctx.logger('dsh-im:wecom') : (ctx.logger ?? console);
|
||||
const paths = pluginPaths(config);
|
||||
const configStore = await new ConfigStore(paths.config).load();
|
||||
const qrAuth = internals.qrAuth ?? new QrAuth({
|
||||
source: config.qrSource ?? 'deepseek-harness',
|
||||
platform: config.qrPlatform,
|
||||
});
|
||||
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({
|
||||
qrAuth,
|
||||
credentials: ctx.credentials,
|
||||
configStore,
|
||||
logger,
|
||||
createRuntime: async ({ botId, config: botConfig, secret }) => new Runtime({
|
||||
config: botConfig,
|
||||
secret,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
maxReconnectAttempts: config.maxReconnectAttempts ?? 10,
|
||||
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),
|
||||
},
|
||||
}),
|
||||
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({
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
137
plugin-src/host/channels/wecom/rpc.mjs
Normal file
137
plugin-src/host/channels/wecom/rpc.mjs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import QRCode from 'qrcode';
|
||||
|
||||
export const WECOM_RPC_CHANNEL = '/wecom';
|
||||
export const WECOM_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
beginProvisioning: 'provision.begin',
|
||||
pollProvisioning: 'provision.poll',
|
||||
cancelProvisioning: 'provision.cancel',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
export const WECOM_RPC_ENDPOINTS = Object.freeze(Object.values(WECOM_ENDPOINTS));
|
||||
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
||||
'secret', 'secretRef', 'scode', 'remoteBotId', 'verificationUrl', 'bot_info', 'botid',
|
||||
]);
|
||||
|
||||
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 (endpoint === WECOM_ENDPOINTS.status) return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
||||
if (endpoint === WECOM_ENDPOINTS.beginProvisioning) {
|
||||
return exactKeys(payload, ['locale']) && (payload.locale === undefined || payload.locale === 'zh-CN')
|
||||
? null : 'provision.begin received unsupported fields.';
|
||||
}
|
||||
if ([WECOM_ENDPOINTS.pollProvisioning, WECOM_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
|
||||
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
|
||||
? null : `${endpoint} requires an attemptId.`;
|
||||
}
|
||||
if (endpoint === WECOM_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId) ? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === WECOM_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown Enterprise WeChat 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 withEncodedQr(value, encodeQr) {
|
||||
if (!value || typeof value.verificationUrl !== 'string') return sanitizePublic(value);
|
||||
return sanitizePublic({ ...value, qrCodeDataUrl: await encodeQr(value.verificationUrl) });
|
||||
}
|
||||
|
||||
async function publicStatus(status, encodeQr) {
|
||||
const value = structuredClone(status);
|
||||
if (value?.provisioning) value.provisioning = await withEncodedQr(value.provisioning, encodeQr);
|
||||
return sanitizePublic(value);
|
||||
}
|
||||
|
||||
export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
||||
for (const method of ['status', 'startProvisioning', 'registrationStatus', 'cancelProvisioning', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete Enterprise WeChat controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
const qrCache = new Map();
|
||||
const cachedEncode = (url) => {
|
||||
let encoded = qrCache.get(url);
|
||||
if (!encoded) {
|
||||
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
||||
encoded = Promise.resolve().then(() => encodeQr(url));
|
||||
qrCache.set(url, encoded);
|
||||
}
|
||||
return encoded;
|
||||
};
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
if (!WECOM_RPC_ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: 'Unknown Enterprise WeChat endpoint.' } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === WECOM_ENDPOINTS.status) value = await publicStatus(await controller.status(), cachedEncode);
|
||||
else if (endpoint === WECOM_ENDPOINTS.beginProvisioning) {
|
||||
value = await withEncodedQr(await controller.startProvisioning(), cachedEncode);
|
||||
} else if (endpoint === WECOM_ENDPOINTS.pollProvisioning) {
|
||||
const current = await controller.registrationStatus(payload.attemptId);
|
||||
if (!current) return { ok: false, error: { code: 'bad-request', message: 'The provisioning attempt no longer exists.' } };
|
||||
value = await withEncodedQr(current, cachedEncode);
|
||||
} else if (endpoint === WECOM_ENDPOINTS.cancelProvisioning) {
|
||||
value = sanitizePublic(await controller.cancelProvisioning(payload.attemptId));
|
||||
} else if (endpoint === WECOM_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: 'wecom-operation-failed', message: '企业微信操作失败,请稍后重试。' } };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installWecomRpc(ctx, controller, options) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
WECOM_RPC_CHANNEL,
|
||||
createWecomRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { apply as applyDingtalk } from './channels/dingtalk/index.mjs';
|
||||
import { apply as applyFeishu } from './channels/feishu/index.mjs';
|
||||
import { apply as applyQq } from './channels/qq/index.mjs';
|
||||
import { apply as applyWecom } from './channels/wecom/index.mjs';
|
||||
import { apply as applyWeixin } from './channels/weixin/index.mjs';
|
||||
|
||||
export const name = 'dsh-im-host';
|
||||
|
|
@ -10,6 +11,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
const startFeishu = internals.applyFeishu ?? applyFeishu;
|
||||
const startWeixin = internals.applyWeixin ?? applyWeixin;
|
||||
const startDingtalk = internals.applyDingtalk ?? applyDingtalk;
|
||||
const startWecom = internals.applyWecom ?? applyWecom;
|
||||
const startQq = internals.applyQq ?? applyQq;
|
||||
return Object.freeze({
|
||||
name,
|
||||
|
|
@ -18,6 +20,7 @@ export function createImHostPlugin(internals = {}) {
|
|||
await startFeishu(ctx, config.feishu ?? {});
|
||||
await startWeixin(ctx, config.weixin ?? {});
|
||||
await startDingtalk(ctx, config.dingtalk ?? {});
|
||||
await startWecom(ctx, config.wecom ?? {});
|
||||
await startQq(ctx, config.qq ?? {});
|
||||
},
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue