mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 03:03:24 +08:00
Add Telegram and Discord IM channels
This commit is contained in:
parent
7123fce47a
commit
cb74e1c4c7
66 changed files with 8579 additions and 1910 deletions
|
|
@ -79,3 +79,29 @@ export function WecomLogoGlyph({ size } = {}) {
|
|||
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' }));
|
||||
}
|
||||
|
||||
export function TelegramLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
viewBox: '0 0 24 24',
|
||||
focusable: 'false',
|
||||
'aria-hidden': 'true',
|
||||
'data-im-channel-logo': 'telegram',
|
||||
}, h('path', {
|
||||
fill: 'currentColor',
|
||||
d: 'M23.95 4.57c-.36-1.45-1.43-1.76-2.82-1.24L1.5 10.9c-1.34.52-1.32 1.27-.24 1.6l5.03 1.57 11.66-7.36c.55-.34 1.05-.16.64.21l-9.44 8.52-.37 5.12c.54 0 .78-.24 1.08-.53l2.59-2.51 5.38 3.97c.99.55 1.7.27 1.95-.92L23.95 4.57Z',
|
||||
}));
|
||||
}
|
||||
|
||||
export function DiscordLogoGlyph({ size } = {}) {
|
||||
return h('svg', {
|
||||
...dimensions(size),
|
||||
viewBox: '0 0 24 24',
|
||||
focusable: 'false',
|
||||
'aria-hidden': 'true',
|
||||
'data-im-channel-logo': 'discord',
|
||||
}, h('path', {
|
||||
fill: 'currentColor',
|
||||
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',
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
11
plugin-src/client/channels/discord/api.js
Normal file
11
plugin-src/client/channels/discord/api.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { TOKEN_BOT_ENDPOINTS, createTokenChannelApi } from '../shared/token-api.js';
|
||||
|
||||
export const DISCORD_RPC_CHANNEL = '/discord';
|
||||
export const DISCORD_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
|
||||
const api = createTokenChannelApi('Discord', ' Gateway 长连接');
|
||||
|
||||
export const unwrapRpcResult = api.unwrapRpcResult;
|
||||
export const normalizeSnapshot = api.normalizeSnapshot;
|
||||
export const presentError = api.presentError;
|
||||
export { api as discordClientApi };
|
||||
25
plugin-src/client/channels/discord/index.js
Normal file
25
plugin-src/client/channels/discord/index.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { DiscordLogoGlyph } from '../../channel-logos.js';
|
||||
import { createTokenChannelSettings } from '../shared/token-channel.js';
|
||||
import {
|
||||
DISCORD_ENDPOINTS,
|
||||
discordClientApi,
|
||||
} from './api.js';
|
||||
import { installDiscordStyles } from './styles.js';
|
||||
|
||||
const channel = createTokenChannelSettings({
|
||||
channel: 'Discord',
|
||||
endpoints: DISCORD_ENDPOINTS,
|
||||
api: discordClientApi,
|
||||
LogoGlyph: DiscordLogoGlyph,
|
||||
installStyles: installDiscordStyles,
|
||||
pageClass: 'ddc-page',
|
||||
avatarClass: 'ddc-avatar',
|
||||
connectionLabel: 'Gateway 长连接',
|
||||
tokenPlaceholder: '填写 Discord Developer Portal 的 Bot Token',
|
||||
emptyTitle: '接入 Discord 机器人',
|
||||
emptyDescription: '先在 Developer Portal 创建 Bot 并邀请到服务器,再在这里完成接入。',
|
||||
platformLabel: 'Discord Developer Portal',
|
||||
});
|
||||
|
||||
export const DiscordSettingsTab = channel.SettingsTab;
|
||||
export const DiscordAccountCard = channel.AccountCard;
|
||||
19
plugin-src/client/channels/discord/styles.js
Normal file
19
plugin-src/client/channels/discord/styles.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
export const DISCORD_STYLE_ID = 'xmanrui-dsh-im-discord-settings';
|
||||
|
||||
const CSS = String.raw`
|
||||
.ddc-page { --ddt-accent: #5865f2; --ddt-accent-deep: #4752c4; --ddt-accent-wash: #eef0ff; }
|
||||
.ddc-avatar { color: #fff; background: #5865f2; }
|
||||
.ddc-avatar svg { display: block; }
|
||||
`;
|
||||
|
||||
export function installDiscordStyles() {
|
||||
if (typeof document === 'undefined') return () => {};
|
||||
const existing = document.querySelector(`style[data-plugin-css="${DISCORD_STYLE_ID}"]`);
|
||||
if (existing) return () => {};
|
||||
const style = document.createElement('style');
|
||||
style.dataset.plugin = '@xmanrui/dsh-im';
|
||||
style.dataset.pluginCss = DISCORD_STYLE_ID;
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
return () => style.remove();
|
||||
}
|
||||
88
plugin-src/client/channels/shared/token-api.js
Normal file
88
plugin-src/client/channels/shared/token-api.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
const ACCOUNT_STATES = new Set(['connected', 'connecting', 'offline', 'error']);
|
||||
|
||||
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 const TOKEN_BOT_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
bindCredentials: 'bot.bind-credentials',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
|
||||
export function createTokenChannelApi(channel, connectionSummary) {
|
||||
const unwrapRpcResult = (result) => {
|
||||
if (!isRecord(result) || typeof result.ok !== 'boolean') {
|
||||
throw new Error(`${channel} 服务返回了无法识别的响应`);
|
||||
}
|
||||
if (!result.ok) {
|
||||
const error = new Error(text(result.error?.message, `${channel} 操作失败`));
|
||||
error.code = text(result.error?.code, `${channel.toUpperCase()}_RPC_ERROR`, 80);
|
||||
throw error;
|
||||
}
|
||||
return result.value;
|
||||
};
|
||||
|
||||
const 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, `${channel}机器人`, 100),
|
||||
username: text(value.bot?.username, '', 100),
|
||||
idMasked: text(value.bot?.idMasked, '机器人标识已安全保存', 140),
|
||||
},
|
||||
health: {
|
||||
summary: text(
|
||||
value.health?.summary,
|
||||
connected ? `${channel}${connectionSummary}运行正常` : `${channel}连接尚未就绪`,
|
||||
),
|
||||
lastCheckedAt: timestamp(value.health?.lastCheckedAt),
|
||||
},
|
||||
error: isRecord(value.error) ? {
|
||||
code: text(value.error.code, `${channel.toUpperCase()}_ACCOUNT_ERROR`, 80),
|
||||
message: text(value.error.message, `${channel}连接尚未就绪`),
|
||||
} : null,
|
||||
};
|
||||
};
|
||||
|
||||
const normalizeSnapshot = (value) => {
|
||||
const source = isRecord(value?.snapshot) ? value.snapshot : value;
|
||||
if (!isRecord(source) || !Array.isArray(source.bots)) {
|
||||
throw new Error(`${channel} 服务没有返回有效的机器人列表`);
|
||||
}
|
||||
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 },
|
||||
};
|
||||
};
|
||||
|
||||
const presentError = (error) => ({
|
||||
code: text(error?.code, `${channel.toUpperCase()}_ERROR`, 80),
|
||||
message: text(error?.message, `${channel}操作失败,请稍后重试`),
|
||||
});
|
||||
|
||||
return Object.freeze({ unwrapRpcResult, normalizeSnapshot, presentError });
|
||||
}
|
||||
277
plugin-src/client/channels/shared/token-channel.js
Normal file
277
plugin-src/client/channels/shared/token-channel.js
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
import * as React from 'react';
|
||||
|
||||
import { CredentialActionIcon, CredentialBindingPanel } from '../../credential-binding.js';
|
||||
import { installDingtalkStyles } from '../dingtalk/styles.js';
|
||||
|
||||
const h = React.createElement;
|
||||
|
||||
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 '刚刚';
|
||||
}
|
||||
}
|
||||
|
||||
export function createTokenChannelSettings(definition) {
|
||||
const {
|
||||
channel,
|
||||
endpoints,
|
||||
api,
|
||||
LogoGlyph,
|
||||
installStyles,
|
||||
pageClass,
|
||||
avatarClass,
|
||||
connectionLabel,
|
||||
tokenPlaceholder,
|
||||
emptyTitle,
|
||||
emptyDescription,
|
||||
platformLabel,
|
||||
} = definition;
|
||||
|
||||
function AccountCard({ 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);
|
||||
const identity = account.bot.username ? `@${account.bot.username}` : account.bot.idMasked;
|
||||
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 ${avatarClass}`, 'aria-hidden': 'true' },
|
||||
h(LogoGlyph, { size: 29 })),
|
||||
h('div', { className: 'dim-botName' },
|
||||
h('h3', null, account.bot.name), h('p', null, identity))),
|
||||
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 ? connectionLabel : '离线')),
|
||||
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('div', { className: 'ddt-confirm dim-confirm', role: 'alertdialog' },
|
||||
h('strong', null, `从 DeepSeek Harness 移除“${account.bot.name}”?`),
|
||||
h('p', null, `这会停止消息连接,并删除本机保存的 Bot Token、机器人配置及会话映射。${platformLabel}中的机器人不会被自动删除。`),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, { onClick: onCancelRemove, disabled: Boolean(busy) }, '保留机器人'),
|
||||
h(Button, { kind: 'danger', onClick: onConfirmRemove, disabled: Boolean(busy) },
|
||||
busy === 'delete' ? '正在移除…' : '确认移除接入'))) : null);
|
||||
}
|
||||
|
||||
function SettingsTab({ rpcCall }) {
|
||||
const [model, setModel] = React.useState({
|
||||
phase: 'loading', bots: [], totals: { configured: 0, connected: 0 }, error: null,
|
||||
});
|
||||
const [credentialOpen, setCredentialOpen] = React.useState(false);
|
||||
const [credentialError, setCredentialError] = React.useState(null);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [busyByBot, setBusyByBot] = React.useState({});
|
||||
const [removeTarget, setRemoveTarget] = React.useState(null);
|
||||
const mounted = React.useRef(true);
|
||||
|
||||
React.useEffect(() => {
|
||||
const disposeDingtalk = installDingtalkStyles();
|
||||
const disposeChannel = installStyles();
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
disposeChannel();
|
||||
disposeDingtalk();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const invoke = React.useCallback(async (endpoint, payload = {}, signal) => {
|
||||
if (typeof rpcCall !== 'function') throw new TypeError(`${channel} 设置页缺少 RPC 连接`);
|
||||
return api.unwrapRpcResult(await rpcCall(endpoint, payload, signal));
|
||||
}, [rpcCall]);
|
||||
|
||||
const loadStatus = React.useCallback(async ({ signal, silent = false } = {}) => {
|
||||
if (!silent && mounted.current) setModel((current) => ({ ...current, phase: 'loading', error: null }));
|
||||
try {
|
||||
const snapshot = api.normalizeSnapshot(await invoke(endpoints.status, {}, signal));
|
||||
if (!mounted.current || signal?.aborted) return;
|
||||
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
|
||||
} catch (error) {
|
||||
if (error?.name !== 'AbortError' && mounted.current && !signal?.aborted) {
|
||||
setModel((current) => ({
|
||||
...current,
|
||||
phase: silent ? current.phase : 'error',
|
||||
error: api.presentError(error),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void loadStatus({ signal: controller.signal });
|
||||
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]);
|
||||
|
||||
const bindCredentials = React.useCallback(async ({ secret }) => {
|
||||
setBusy(true);
|
||||
setCredentialError(null);
|
||||
try {
|
||||
const snapshot = api.normalizeSnapshot(await invoke(endpoints.bindCredentials, { token: secret }));
|
||||
if (!mounted.current) return;
|
||||
setModel({ phase: 'ready', bots: snapshot.bots, totals: snapshot.totals, error: null });
|
||||
setCredentialOpen(false);
|
||||
} catch (error) {
|
||||
if (mounted.current) setCredentialError(api.presentError(error));
|
||||
} finally {
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
}, [invoke]);
|
||||
|
||||
const botAction = React.useCallback(async (account, operation, endpoint, payload) => {
|
||||
setBusyByBot((current) => ({ ...current, [account.botId]: operation }));
|
||||
try {
|
||||
const snapshot = api.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, `已接入的 ${channel} 机器人`)),
|
||||
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',
|
||||
endpoints.reconnectBot,
|
||||
{ botId: account.botId },
|
||||
),
|
||||
onRequestRemove: () => setRemoveTarget(account.botId),
|
||||
onCancelRemove: () => setRemoveTarget(null),
|
||||
onConfirmRemove: async () => {
|
||||
await botAction(account, 'delete', endpoints.deleteBot, {
|
||||
botId: account.botId,
|
||||
confirm: true,
|
||||
});
|
||||
if (mounted.current) setRemoveTarget(null);
|
||||
},
|
||||
})))))
|
||||
: null;
|
||||
|
||||
return h('section', {
|
||||
className: `ddt-page ${pageClass} dim-channelPage`,
|
||||
'aria-label': `${channel} 设置`,
|
||||
},
|
||||
h('div', { className: 'ddt-heading' },
|
||||
h('div', { className: 'ddt-tools' },
|
||||
h('div', { className: 'dim-bindActions' },
|
||||
h(Button, {
|
||||
kind: 'credential',
|
||||
className: 'dim-credentialButton',
|
||||
onClick: () => { setCredentialOpen((value) => !value); setCredentialError(null); },
|
||||
disabled: busy,
|
||||
'aria-pressed': credentialOpen,
|
||||
'aria-label': `使用 Bot Token 接入 ${channel} 机器人`,
|
||||
}, h(CredentialActionIcon), credentialOpen ? '收起凭据' : '手动接入')),
|
||||
model.totals.configured > 0
|
||||
? h('div', { className: 'ddt-badge dim-onlineBadge' },
|
||||
h('span', null, `${model.totals.connected} / ${model.totals.configured} 在线`))
|
||||
: null)),
|
||||
model.phase === 'loading'
|
||||
? h('div', {
|
||||
className: 'ddt-card ddt-loading dim-surfaceCard dim-loadingView',
|
||||
'aria-busy': 'true',
|
||||
}, h('div', { className: 'ddt-spinner dim-spinner' }), `正在读取 ${channel} 机器人状态…`)
|
||||
: model.phase === 'error'
|
||||
? h('div', { className: 'ddt-card dim-surfaceCard' },
|
||||
h('div', { className: 'ddt-inlineError dim-inlineError' },
|
||||
h('h3', null, `无法读取 ${channel} 机器人状态`),
|
||||
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,
|
||||
model.bots.length === 0 && !credentialOpen
|
||||
? 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, `尚未接入 ${channel} 机器人`)),
|
||||
h('h3', null, emptyTitle),
|
||||
h('p', null, emptyDescription),
|
||||
h('div', { className: 'ddt-actions dim-viewActions' },
|
||||
h(Button, {
|
||||
kind: 'primary',
|
||||
onClick: () => setCredentialOpen(true),
|
||||
}, '填写 Bot Token'))),
|
||||
h('div', {
|
||||
className: `ddt-brandMark dim-emptyBrand ${avatarClass}`,
|
||||
'aria-hidden': 'true',
|
||||
}, h(LogoGlyph, { size: 64 }))))
|
||||
: null,
|
||||
botList));
|
||||
}
|
||||
|
||||
return { SettingsTab, AccountCard };
|
||||
}
|
||||
11
plugin-src/client/channels/telegram/api.js
Normal file
11
plugin-src/client/channels/telegram/api.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { TOKEN_BOT_ENDPOINTS, createTokenChannelApi } from '../shared/token-api.js';
|
||||
|
||||
export const TELEGRAM_RPC_CHANNEL = '/telegram';
|
||||
export const TELEGRAM_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
|
||||
const api = createTokenChannelApi('Telegram', ' Bot API 长轮询');
|
||||
|
||||
export const unwrapRpcResult = api.unwrapRpcResult;
|
||||
export const normalizeSnapshot = api.normalizeSnapshot;
|
||||
export const presentError = api.presentError;
|
||||
export { api as telegramClientApi };
|
||||
25
plugin-src/client/channels/telegram/index.js
Normal file
25
plugin-src/client/channels/telegram/index.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { TelegramLogoGlyph } from '../../channel-logos.js';
|
||||
import { createTokenChannelSettings } from '../shared/token-channel.js';
|
||||
import {
|
||||
TELEGRAM_ENDPOINTS,
|
||||
telegramClientApi,
|
||||
} from './api.js';
|
||||
import { installTelegramStyles } from './styles.js';
|
||||
|
||||
const channel = createTokenChannelSettings({
|
||||
channel: 'Telegram',
|
||||
endpoints: TELEGRAM_ENDPOINTS,
|
||||
api: telegramClientApi,
|
||||
LogoGlyph: TelegramLogoGlyph,
|
||||
installStyles: installTelegramStyles,
|
||||
pageClass: 'dtg-page',
|
||||
avatarClass: 'dtg-avatar',
|
||||
connectionLabel: 'Bot API 长轮询',
|
||||
tokenPlaceholder: '填写 @BotFather 生成的 Bot Token',
|
||||
emptyTitle: '接入 Telegram 机器人',
|
||||
emptyDescription: '先通过 @BotFather 获取 Bot Token,再在这里完成接入。',
|
||||
platformLabel: 'Telegram',
|
||||
});
|
||||
|
||||
export const TelegramSettingsTab = channel.SettingsTab;
|
||||
export const TelegramAccountCard = channel.AccountCard;
|
||||
19
plugin-src/client/channels/telegram/styles.js
Normal file
19
plugin-src/client/channels/telegram/styles.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
export const TELEGRAM_STYLE_ID = 'xmanrui-dsh-im-telegram-settings';
|
||||
|
||||
const CSS = String.raw`
|
||||
.dtg-page { --ddt-accent: #229ed9; --ddt-accent-deep: #1687bd; --ddt-accent-wash: #eaf7fd; }
|
||||
.dtg-avatar { color: #fff; background: #229ed9; }
|
||||
.dtg-avatar svg { display: block; }
|
||||
`;
|
||||
|
||||
export function installTelegramStyles() {
|
||||
if (typeof document === 'undefined') return () => {};
|
||||
const existing = document.querySelector(`style[data-plugin-css="${TELEGRAM_STYLE_ID}"]`);
|
||||
if (existing) return () => {};
|
||||
const style = document.createElement('style');
|
||||
style.dataset.plugin = '@xmanrui/dsh-im';
|
||||
style.dataset.pluginCss = TELEGRAM_STYLE_ID;
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
return () => style.remove();
|
||||
}
|
||||
|
|
@ -52,12 +52,13 @@ export function CredentialBindingPanel({
|
|||
const [identity, setIdentity] = React.useState('');
|
||||
const [secret, setSecret] = React.useState('');
|
||||
const headingId = React.useId();
|
||||
const hasIdentity = Boolean(identityLabel);
|
||||
|
||||
const submit = (event) => {
|
||||
event.preventDefault();
|
||||
const normalizedIdentity = identity.trim();
|
||||
const normalizedSecret = secret.trim();
|
||||
if (!normalizedIdentity || !normalizedSecret || busy) return;
|
||||
if ((hasIdentity && !normalizedIdentity) || !normalizedSecret || busy) return;
|
||||
void onSubmit?.({ identity: normalizedIdentity, secret: normalizedSecret });
|
||||
};
|
||||
|
||||
|
|
@ -66,8 +67,11 @@ export function CredentialBindingPanel({
|
|||
'aria-labelledby': headingId,
|
||||
},
|
||||
h('h3', { id: headingId, className: 'dim-credentialTitle' }, `手动接入${channel}机器人`),
|
||||
h('form', { className: 'dim-credentialForm', onSubmit: submit },
|
||||
h('label', { className: 'dim-credentialField' },
|
||||
h('form', {
|
||||
className: `dim-credentialForm${hasIdentity ? '' : ' dim-credentialFormSingle'}`,
|
||||
onSubmit: submit,
|
||||
},
|
||||
hasIdentity ? h('label', { className: 'dim-credentialField' },
|
||||
h('span', null, identityLabel),
|
||||
h('input', {
|
||||
value: identity,
|
||||
|
|
@ -80,7 +84,7 @@ export function CredentialBindingPanel({
|
|||
autoComplete: 'off',
|
||||
disabled: busy,
|
||||
required: true,
|
||||
})),
|
||||
})) : null,
|
||||
h('label', { className: 'dim-credentialField' },
|
||||
h('span', null, secretLabel),
|
||||
h('input', {
|
||||
|
|
@ -102,7 +106,7 @@ export function CredentialBindingPanel({
|
|||
type: 'submit',
|
||||
className: 'ddt-button',
|
||||
'data-kind': 'primary',
|
||||
disabled: busy || !identity.trim() || !secret.trim(),
|
||||
disabled: busy || (hasIdentity && !identity.trim()) || !secret.trim(),
|
||||
}, busy ? '正在绑定…' : '绑定并连接'),
|
||||
h('button', {
|
||||
type: 'button',
|
||||
|
|
|
|||
|
|
@ -2,19 +2,27 @@ import * as React from 'react';
|
|||
|
||||
import {
|
||||
DingtalkLogoGlyph,
|
||||
DiscordLogoGlyph,
|
||||
FeishuLogoGlyph,
|
||||
QqLogoGlyph,
|
||||
TelegramLogoGlyph,
|
||||
WecomLogoGlyph,
|
||||
WeixinLogoGlyph,
|
||||
} from './channel-logos.js';
|
||||
import { DINGTALK_RPC_CHANNEL } from './channels/dingtalk/api.js';
|
||||
import { DingtalkSettingsTab } from './channels/dingtalk/index.js';
|
||||
import { DISCORD_RPC_CHANNEL } from './channels/discord/api.js';
|
||||
import { DiscordSettingsTab } from './channels/discord/index.js';
|
||||
import { installDiscordStyles } from './channels/discord/styles.js';
|
||||
import { FeishuSettingsTab } from './channels/feishu/index.js';
|
||||
import { FEISHU_RPC_CHANNEL } from './channels/feishu/api.js';
|
||||
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 { TELEGRAM_RPC_CHANNEL } from './channels/telegram/api.js';
|
||||
import { TelegramSettingsTab } from './channels/telegram/index.js';
|
||||
import { installTelegramStyles } from './channels/telegram/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';
|
||||
|
|
@ -34,6 +42,8 @@ const CHANNELS = Object.freeze([
|
|||
{ id: 'dingtalk', label: '钉钉' },
|
||||
{ id: 'wecom', label: '企业微信' },
|
||||
{ id: 'qq', label: 'QQ' },
|
||||
{ id: 'telegram', label: 'Telegram' },
|
||||
{ id: 'discord', label: 'Discord' },
|
||||
]);
|
||||
|
||||
function WeixinLogo() {
|
||||
|
|
@ -59,20 +69,40 @@ function WecomLogo() {
|
|||
return h('span', { className: 'dim-logo dim-logoWecom', 'aria-hidden': 'true' }, h(WecomLogoGlyph));
|
||||
}
|
||||
|
||||
function TelegramLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoTelegram', 'aria-hidden': 'true' },
|
||||
h(TelegramLogoGlyph));
|
||||
}
|
||||
|
||||
function DiscordLogo() {
|
||||
return h('span', { className: 'dim-logo dim-logoDiscord', 'aria-hidden': 'true' },
|
||||
h(DiscordLogoGlyph));
|
||||
}
|
||||
|
||||
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);
|
||||
if (channel === 'qq') return h(QqLogo);
|
||||
if (channel === 'telegram') return h(TelegramLogo);
|
||||
return h(DiscordLogo);
|
||||
}
|
||||
|
||||
export function IMSettingsTab({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, wecomRpcCall, weixinRpcCall }) {
|
||||
export function IMSettingsTab({
|
||||
dingtalkRpcCall,
|
||||
discordRpcCall,
|
||||
feishuRpcCall,
|
||||
qqRpcCall,
|
||||
telegramRpcCall,
|
||||
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机器人设置' },
|
||||
h('header', { className: 'dim-title' },
|
||||
h('p', null, '通过扫码把机器人接入 DeepSeek Harness'),
|
||||
h('p', null, '把机器人接入 DeepSeek Harness'),
|
||||
),
|
||||
h('div', { className: 'dim-layout' },
|
||||
h('nav', { className: 'dim-rail', role: 'tablist', 'aria-label': 'IM 渠道' },
|
||||
|
|
@ -104,7 +134,11 @@ export function IMSettingsTab({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, wecom
|
|||
? h(DingtalkSettingsTab, { rpcCall: dingtalkRpcCall })
|
||||
: active.id === 'wecom'
|
||||
? h(WecomSettingsTab, { rpcCall: wecomRpcCall })
|
||||
: h(QqSettingsTab, { rpcCall: qqRpcCall })),
|
||||
: active.id === 'qq'
|
||||
? h(QqSettingsTab, { rpcCall: qqRpcCall })
|
||||
: active.id === 'telegram'
|
||||
? h(TelegramSettingsTab, { rpcCall: telegramRpcCall })
|
||||
: h(DiscordSettingsTab, { rpcCall: discordRpcCall })),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -116,6 +150,8 @@ export function apply(ctx) {
|
|||
installWeixinStyles(),
|
||||
installWecomStyles(),
|
||||
installQqStyles(),
|
||||
installTelegramStyles(),
|
||||
installDiscordStyles(),
|
||||
installImStyles(),
|
||||
];
|
||||
return () => {
|
||||
|
|
@ -133,12 +169,24 @@ export function apply(ctx) {
|
|||
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);
|
||||
const telegramRpcCall = (endpoint, payload, signal) =>
|
||||
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);
|
||||
|
||||
ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
|
||||
name: 'settings.plugins.tab',
|
||||
id: 'im',
|
||||
order: 20,
|
||||
label: 'IM机器人',
|
||||
inject: () => ({ dingtalkRpcCall, feishuRpcCall, qqRpcCall, wecomRpcCall, weixinRpcCall }),
|
||||
inject: () => ({
|
||||
dingtalkRpcCall,
|
||||
discordRpcCall,
|
||||
feishuRpcCall,
|
||||
qqRpcCall,
|
||||
telegramRpcCall,
|
||||
wecomRpcCall,
|
||||
weixinRpcCall,
|
||||
}),
|
||||
}, IMSettingsTab));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,10 @@ const CSS = String.raw`
|
|||
.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-logoTelegram { color: white; background: #229ed9; }
|
||||
.dim-logoTelegram svg { width: 21px; height: 21px; }
|
||||
.dim-logoDiscord { color: white; background: #5865f2; }
|
||||
.dim-logoDiscord 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); }
|
||||
|
|
@ -55,6 +59,7 @@ const CSS = String.raw`
|
|||
.dim-panel .dim-credentialPanel { display: grid; gap: 18px; padding: 20px; }
|
||||
.dim-panel .dim-credentialTitle { margin: 0; color: var(--dsw-alias-label-primary, #1f2329); font-size: 17px; line-height: 1.35; font-weight: 650; }
|
||||
.dim-panel .dim-credentialForm { min-width: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 12px; }
|
||||
.dim-panel .dim-credentialFormSingle { grid-template-columns: minmax(0, 1fr); }
|
||||
.dim-panel .dim-credentialField { min-width: 0; display: grid; gap: 7px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: normal; font-weight: 560; }
|
||||
.dim-panel .dim-credentialField input { width: 100%; min-width: 0; height: 38px; padding: 0 11px; border: 1px solid var(--dsw-alias-line-border, #dfe1e5); border-radius: 8px; outline: none; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-body, #fff); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; transition: border-color .16s ease, box-shadow .16s ease; }
|
||||
.dim-panel .dim-credentialField input:focus { border-color: #4e5969; box-shadow: 0 0 0 3px rgb(78 89 105 / 10%); }
|
||||
|
|
|
|||
|
|
@ -5,10 +5,17 @@ export const name = 'dsh-dingtalk-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installDingtalkRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installDingtalkRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installDingtalkRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installDingtalkRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-dingtalk: close bot connections');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const DINGTALK_RPC_CHANNEL = '/dingtalk';
|
||||
export const DINGTALK_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -224,13 +225,13 @@ export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } =
|
|||
};
|
||||
}
|
||||
|
||||
export function installDingtalkRpc(ctx, controller, options) {
|
||||
export function installDingtalkRpc(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(
|
||||
DINGTALK_RPC_CHANNEL,
|
||||
createDingtalkRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
30
plugin-src/host/channels/discord/index.mjs
Normal file
30
plugin-src/host/channels/discord/index.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installDiscordRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-discord-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) {
|
||||
return installDiscordRpc(ctx, config.controller, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installDiscordRpc(ctx, production.controller, config.rpcAuthority);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Discord bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createDiscordHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
DISCORD_ENDPOINTS,
|
||||
DISCORD_RPC_CHANNEL,
|
||||
DISCORD_RPC_ENDPOINTS,
|
||||
createDiscordRpcHandler,
|
||||
installDiscordRpc,
|
||||
} from './rpc.mjs';
|
||||
export { DiscordController } from '../../../../src/channels/discord/discord-controller.mjs';
|
||||
export { DiscordRuntime } from '../../../../src/channels/discord/discord-runtime.mjs';
|
||||
17
plugin-src/host/channels/discord/production.mjs
Normal file
17
plugin-src/host/channels/discord/production.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { DiscordConfigStore } from '../../../../src/channels/discord/config-store.mjs';
|
||||
import { DiscordController } from '../../../../src/channels/discord/discord-controller.mjs';
|
||||
import { DiscordHarnessClient } from '../../../../src/channels/discord/harness-client.mjs';
|
||||
import { DiscordRuntime } from '../../../../src/channels/discord/discord-runtime.mjs';
|
||||
import { DiscordStateStore } from '../../../../src/channels/discord/state-store.mjs';
|
||||
import { createTokenProductionController } from '../shared/production.mjs';
|
||||
|
||||
export function createProductionController(ctx, config = {}, internals = {}) {
|
||||
return createTokenProductionController(ctx, config, internals, {
|
||||
channel: 'discord',
|
||||
ConfigStore: DiscordConfigStore,
|
||||
StateStore: DiscordStateStore,
|
||||
HarnessClient: DiscordHarnessClient,
|
||||
Controller: DiscordController,
|
||||
Runtime: DiscordRuntime,
|
||||
});
|
||||
}
|
||||
21
plugin-src/host/channels/discord/rpc.mjs
Normal file
21
plugin-src/host/channels/discord/rpc.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import {
|
||||
TOKEN_BOT_ENDPOINTS,
|
||||
createTokenBotRpcHandler,
|
||||
installTokenBotRpc,
|
||||
} from '../shared/rpc.mjs';
|
||||
|
||||
export const DISCORD_RPC_CHANNEL = '/discord';
|
||||
export const DISCORD_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
export const DISCORD_RPC_ENDPOINTS = Object.freeze(Object.values(DISCORD_ENDPOINTS));
|
||||
|
||||
export function createDiscordRpcHandler(controller) {
|
||||
return createTokenBotRpcHandler(controller, { channel: 'Discord' });
|
||||
}
|
||||
|
||||
export function installDiscordRpc(ctx, controller, authority) {
|
||||
return installTokenBotRpc(ctx, controller, {
|
||||
channel: 'Discord',
|
||||
rpcChannel: DISCORD_RPC_CHANNEL,
|
||||
authority,
|
||||
});
|
||||
}
|
||||
|
|
@ -24,10 +24,17 @@ function controllerFrom(ctx, config) {
|
|||
*/
|
||||
export async function apply(ctx, config = {}) {
|
||||
const controller = controllerFrom(ctx, config);
|
||||
if (controller) return installFeishuRpc(ctx, controller);
|
||||
if (controller) {
|
||||
return installFeishuRpc(ctx, controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config);
|
||||
const disposeRpc = installFeishuRpc(ctx, production.controller);
|
||||
const disposeRpc = installFeishuRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-feishu: close controller and live connection');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
import {
|
||||
FEISHU_ENDPOINTS,
|
||||
FEISHU_RPC_CHANNEL,
|
||||
|
|
@ -440,14 +441,14 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
|
|||
};
|
||||
}
|
||||
|
||||
/** Register the loopback-only `/feishu` logical channel. */
|
||||
export function installFeishuRpc(ctx, controller, options) {
|
||||
/** Register the `/feishu` logical channel with its configured browser authority. */
|
||||
export function installFeishuRpc(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(
|
||||
FEISHU_RPC_CHANNEL,
|
||||
createFeishuRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,16 @@ export const name = 'dsh-im-qq-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installQqRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installQqRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installQqRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installQqRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close QQ bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const QQ_RPC_CHANNEL = '/qq';
|
||||
export const QQ_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -133,9 +134,13 @@ export function createQqRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
|||
};
|
||||
}
|
||||
|
||||
export function installQqRpc(ctx, controller, options) {
|
||||
export function installQqRpc(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(QQ_RPC_CHANNEL, createQqRpcHandler(controller, options), { authority: 'loopback' });
|
||||
return ctx.connection.rpc.handle(
|
||||
QQ_RPC_CHANNEL,
|
||||
createQqRpcHandler(controller, options),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
133
plugin-src/host/channels/shared/connection-supervisor.mjs
Normal file
133
plugin-src/host/channels/shared/connection-supervisor.mjs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
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 TokenConnectionSupervisor {
|
||||
#channel;
|
||||
#controller;
|
||||
#harness;
|
||||
#logger;
|
||||
#retryDelays;
|
||||
#healthyIntervalMs;
|
||||
#setTimeout;
|
||||
#clearTimeout;
|
||||
#timer = null;
|
||||
#running = null;
|
||||
#retryIndex = 0;
|
||||
#closed = false;
|
||||
#started = false;
|
||||
#ready;
|
||||
#resolveReady;
|
||||
|
||||
constructor({
|
||||
channel,
|
||||
controller,
|
||||
harness,
|
||||
logger = console,
|
||||
retryDelaysMs,
|
||||
healthyIntervalMs = 15_000,
|
||||
setTimeoutImpl = setTimeout,
|
||||
clearTimeoutImpl = clearTimeout,
|
||||
}) {
|
||||
if (!channel) throw new TypeError('TokenConnectionSupervisor requires a channel');
|
||||
if (!controller || typeof controller.initialize !== 'function' || typeof controller.status !== 'function') {
|
||||
throw new TypeError('TokenConnectionSupervisor requires a controller');
|
||||
}
|
||||
if (!harness || typeof harness.ensureRunning !== 'function') {
|
||||
throw new TypeError('TokenConnectionSupervisor requires a Harness client');
|
||||
}
|
||||
this.#channel = channel;
|
||||
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:${this.#channel}] ${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:${this.#channel}] connection reconciliation failed; retrying in ${delay}ms`,
|
||||
error,
|
||||
);
|
||||
this.#schedule(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createTokenConnectionSupervisor(options) {
|
||||
return new TokenConnectionSupervisor(options);
|
||||
}
|
||||
104
plugin-src/host/channels/shared/production.mjs
Normal file
104
plugin-src/host/channels/shared/production.mjs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { unlink } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
import { createTokenConnectionSupervisor } 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 token channel requires an initialized DSH webServer port');
|
||||
}
|
||||
return new URL(`http://127.0.0.1:${port}`);
|
||||
}
|
||||
|
||||
function pluginPaths(config, channel) {
|
||||
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
||||
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', `dsh-${channel}`));
|
||||
return {
|
||||
config: resolve(config.configPath ?? join(root, 'config.json')),
|
||||
bots: resolve(config.botsDir ?? join(root, 'bots')),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createTokenProductionController(ctx, config, internals, definitions) {
|
||||
const { channel, ConfigStore, StateStore, HarnessClient, Controller, Runtime } = definitions;
|
||||
if (!ctx?.credentials) throw new TypeError(`dsh-im ${channel} requires ctx.credentials`);
|
||||
if (!ctx?.webServer) throw new TypeError(`dsh-im ${channel} requires ctx.webServer`);
|
||||
|
||||
const ResolvedConfigStore = internals.ConfigStore ?? ConfigStore;
|
||||
const ResolvedStateStore = internals.StateStore ?? StateStore;
|
||||
const ResolvedHarness = internals.HarnessClient ?? HarnessClient;
|
||||
const ResolvedController = internals.Controller ?? Controller;
|
||||
const ResolvedRuntime = internals.Runtime ?? Runtime;
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
|
||||
const logger = typeof ctx.logger === 'function'
|
||||
? ctx.logger(`dsh-im:${channel}`) : (ctx.logger ?? console);
|
||||
const paths = pluginPaths(config, channel);
|
||||
const configStore = await new ResolvedConfigStore(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 ResolvedStateStore(statePath(botId)).load();
|
||||
stateStores.set(botId, state);
|
||||
}
|
||||
return state;
|
||||
};
|
||||
const harness = new ResolvedHarness({
|
||||
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 ResolvedController({
|
||||
credentials: ctx.credentials,
|
||||
configStore,
|
||||
logger,
|
||||
...(internals.inspectToken ? { inspectToken: internals.inspectToken } : {}),
|
||||
createRuntime: async ({ botId, config: botConfig, token }) => new ResolvedRuntime({
|
||||
config: botConfig,
|
||||
token,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
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({
|
||||
channel,
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
119
plugin-src/host/channels/shared/rpc.mjs
Normal file
119
plugin-src/host/channels/shared/rpc.mjs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const TOKEN_BOT_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
bindCredentials: 'bot.bind-credentials',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
|
||||
const ENDPOINTS = Object.freeze(Object.values(TOKEN_BOT_ENDPOINTS));
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
||||
'token', 'botToken', 'tokenRef', 'platformId', 'secret', 'secretRef',
|
||||
]);
|
||||
|
||||
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 validToken(value) {
|
||||
return typeof value === 'string' && value.trim().length >= 20 && value.length <= 4_096;
|
||||
}
|
||||
|
||||
function payloadFailure(endpoint, payload) {
|
||||
if (!isRecord(payload)) return 'Payload must be an object.';
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.status) {
|
||||
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.bindCredentials) {
|
||||
return exactKeys(payload, ['token']) && validToken(payload.token)
|
||||
? null : 'bot.bind-credentials requires a Bot Token.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId)
|
||||
? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown bot 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;
|
||||
}
|
||||
|
||||
function operationError(channel, error) {
|
||||
if (error?.code === 'webhook-configured') {
|
||||
return { code: 'webhook-configured', message: error.message };
|
||||
}
|
||||
if (error?.code === 'telegram-401' || error?.code === 'discord-401') {
|
||||
return { code: 'invalid-token', message: `${channel} Bot Token 无效,请重新填写。` };
|
||||
}
|
||||
if (error?.code === 'discord-intents') {
|
||||
return { code: 'discord-intents', message: error.message };
|
||||
}
|
||||
return { code: `${channel.toLowerCase()}-operation-failed`, message: `${channel} 操作失败,请稍后重试。` };
|
||||
}
|
||||
|
||||
export function createTokenBotRpcHandler(controller, { channel }) {
|
||||
for (const method of ['status', 'bindCredentials', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete ${channel} controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) {
|
||||
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
}
|
||||
if (!ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: `Unknown ${channel} endpoint.` } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.status) value = await controller.status();
|
||||
else if (endpoint === TOKEN_BOT_ENDPOINTS.bindCredentials) {
|
||||
value = await controller.bindCredentials(payload);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.reconnectBot) {
|
||||
value = await controller.reconnectBot(payload.botId);
|
||||
} else {
|
||||
value = await controller.deleteBot(payload.botId);
|
||||
}
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: true, value: sanitizePublic(value) };
|
||||
} catch (error) {
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: false, error: operationError(channel, error) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installTokenBotRpc(ctx, controller, { channel, rpcChannel, 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(
|
||||
rpcChannel,
|
||||
createTokenBotRpcHandler(controller, { channel }),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
30
plugin-src/host/channels/telegram/index.mjs
Normal file
30
plugin-src/host/channels/telegram/index.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installTelegramRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-telegram-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) {
|
||||
return installTelegramRpc(ctx, config.controller, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installTelegramRpc(ctx, production.controller, config.rpcAuthority);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Telegram bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createTelegramHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
TELEGRAM_ENDPOINTS,
|
||||
TELEGRAM_RPC_CHANNEL,
|
||||
TELEGRAM_RPC_ENDPOINTS,
|
||||
createTelegramRpcHandler,
|
||||
installTelegramRpc,
|
||||
} from './rpc.mjs';
|
||||
export { TelegramController } from '../../../../src/channels/telegram/telegram-controller.mjs';
|
||||
export { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runtime.mjs';
|
||||
17
plugin-src/host/channels/telegram/production.mjs
Normal file
17
plugin-src/host/channels/telegram/production.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { TelegramConfigStore } from '../../../../src/channels/telegram/config-store.mjs';
|
||||
import { TelegramHarnessClient } from '../../../../src/channels/telegram/harness-client.mjs';
|
||||
import { TelegramController } from '../../../../src/channels/telegram/telegram-controller.mjs';
|
||||
import { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runtime.mjs';
|
||||
import { TelegramStateStore } from '../../../../src/channels/telegram/state-store.mjs';
|
||||
import { createTokenProductionController } from '../shared/production.mjs';
|
||||
|
||||
export function createProductionController(ctx, config = {}, internals = {}) {
|
||||
return createTokenProductionController(ctx, config, internals, {
|
||||
channel: 'telegram',
|
||||
ConfigStore: TelegramConfigStore,
|
||||
StateStore: TelegramStateStore,
|
||||
HarnessClient: TelegramHarnessClient,
|
||||
Controller: TelegramController,
|
||||
Runtime: TelegramRuntime,
|
||||
});
|
||||
}
|
||||
21
plugin-src/host/channels/telegram/rpc.mjs
Normal file
21
plugin-src/host/channels/telegram/rpc.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import {
|
||||
TOKEN_BOT_ENDPOINTS,
|
||||
createTokenBotRpcHandler,
|
||||
installTokenBotRpc,
|
||||
} from '../shared/rpc.mjs';
|
||||
|
||||
export const TELEGRAM_RPC_CHANNEL = '/telegram';
|
||||
export const TELEGRAM_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
export const TELEGRAM_RPC_ENDPOINTS = Object.freeze(Object.values(TELEGRAM_ENDPOINTS));
|
||||
|
||||
export function createTelegramRpcHandler(controller) {
|
||||
return createTokenBotRpcHandler(controller, { channel: 'Telegram' });
|
||||
}
|
||||
|
||||
export function installTelegramRpc(ctx, controller, authority) {
|
||||
return installTokenBotRpc(ctx, controller, {
|
||||
channel: 'Telegram',
|
||||
rpcChannel: TELEGRAM_RPC_CHANNEL,
|
||||
authority,
|
||||
});
|
||||
}
|
||||
|
|
@ -5,9 +5,16 @@ 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);
|
||||
if (config?.controller) {
|
||||
return installWecomRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installWecomRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installWecomRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Enterprise WeChat bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const WECOM_RPC_CHANNEL = '/wecom';
|
||||
export const WECOM_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -138,13 +139,13 @@ export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {})
|
|||
};
|
||||
}
|
||||
|
||||
export function installWecomRpc(ctx, controller, options) {
|
||||
export function installWecomRpc(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(
|
||||
WECOM_RPC_CHANNEL,
|
||||
createWecomRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,10 +5,17 @@ export const name = 'dsh-weixin-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installWeixinRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installWeixinRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installWeixinRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installWeixinRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-weixin: close account connections');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const WEIXIN_RPC_CHANNEL = '/weixin';
|
||||
export const WEIXIN_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -165,13 +166,13 @@ export function createWeixinRpcHandler(controller, { encodeQr = qrDataUrl } = {}
|
|||
};
|
||||
}
|
||||
|
||||
export function installWeixinRpc(ctx, controller, options) {
|
||||
export function installWeixinRpc(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(
|
||||
WEIXIN_RPC_CHANNEL,
|
||||
createWeixinRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,40 @@
|
|||
import { apply as applyDingtalk } from './channels/dingtalk/index.mjs';
|
||||
import { apply as applyDiscord } from './channels/discord/index.mjs';
|
||||
import { apply as applyFeishu } from './channels/feishu/index.mjs';
|
||||
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';
|
||||
|
||||
export const name = 'dsh-im-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
function channelConfig(config, name) {
|
||||
const channel = config[name] ?? {};
|
||||
return config.rpcAuthority === undefined
|
||||
? channel
|
||||
: { ...channel, rpcAuthority: config.rpcAuthority };
|
||||
}
|
||||
|
||||
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;
|
||||
const startTelegram = internals.applyTelegram ?? applyTelegram;
|
||||
const startDiscord = internals.applyDiscord ?? applyDiscord;
|
||||
return Object.freeze({
|
||||
name,
|
||||
inject,
|
||||
async apply(ctx, config = {}) {
|
||||
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 ?? {});
|
||||
await startFeishu(ctx, channelConfig(config, 'feishu'));
|
||||
await startWeixin(ctx, channelConfig(config, 'weixin'));
|
||||
await startDingtalk(ctx, channelConfig(config, 'dingtalk'));
|
||||
await startWecom(ctx, channelConfig(config, 'wecom'));
|
||||
await startQq(ctx, channelConfig(config, 'qq'));
|
||||
await startTelegram(ctx, channelConfig(config, 'telegram'));
|
||||
await startDiscord(ctx, channelConfig(config, 'discord'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
11
plugin-src/host/rpc-authority.mjs
Normal file
11
plugin-src/host/rpc-authority.mjs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
const RPC_AUTHORITIES = new Set(['loopback', 'trusted-host']);
|
||||
|
||||
/**
|
||||
* Resolve the browser authority accepted by an IM management RPC channel.
|
||||
* The default keeps credential and bot-management operations on loopback.
|
||||
*/
|
||||
export function resolveRpcAuthority(value) {
|
||||
if (value === undefined) return 'loopback';
|
||||
if (RPC_AUTHORITIES.has(value)) return value;
|
||||
throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"');
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue