mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-07-20 21:57:14 +08:00
feat(feishu): one-click QR-scan app creation
This commit is contained in:
@@ -78,6 +78,19 @@ const I18N = {
|
||||
wecom_scan_success: '创建成功,正在启动通道...',
|
||||
wecom_scan_fail: '创建失败',
|
||||
wecom_mode_scan: '扫码接入', wecom_mode_manual: '手动填写',
|
||||
feishu_scan_btn: '一键创建飞书应用',
|
||||
feishu_scan_desc: '使用飞书 App 扫码,自动创建应用并预置全部权限与事件订阅',
|
||||
feishu_scan_replace_desc: '使用飞书 App 扫码创建新机器人,将覆盖当前的 App ID / Secret',
|
||||
feishu_scan_loading: '正在向飞书申请二维码...',
|
||||
feishu_scan_waiting: '等待扫码...',
|
||||
feishu_scan_tip: '二维码 10 分钟内有效,仅供一次扫描',
|
||||
feishu_scan_open_link: '或点击此处在浏览器中打开',
|
||||
feishu_scan_success: '应用创建成功,正在启动通道...',
|
||||
feishu_scan_expired: '二维码已过期,请重试',
|
||||
feishu_scan_denied: '已取消授权',
|
||||
feishu_scan_fail: '创建失败',
|
||||
feishu_scan_retry: '重试',
|
||||
feishu_mode_scan: '扫码创建', feishu_mode_manual: '手动填写',
|
||||
tasks_title: '定时任务', tasks_desc: '查看和管理定时任务',
|
||||
tasks_coming: '即将推出', tasks_coming_desc: '定时任务管理功能即将在此提供',
|
||||
logs_title: '日志', logs_desc: '实时日志输出 (run.log)',
|
||||
@@ -164,6 +177,19 @@ const I18N = {
|
||||
wecom_scan_success: 'Bot created, starting channel...',
|
||||
wecom_scan_fail: 'Bot creation failed',
|
||||
wecom_mode_scan: 'Scan QR', wecom_mode_manual: 'Manual',
|
||||
feishu_scan_btn: 'One-click Create Feishu App',
|
||||
feishu_scan_desc: 'Scan with Feishu App to create an app with all required permissions pre-configured',
|
||||
feishu_scan_replace_desc: 'Scan with Feishu App to create a new bot — will overwrite the current App ID / Secret',
|
||||
feishu_scan_loading: 'Requesting QR code from Feishu...',
|
||||
feishu_scan_waiting: 'Waiting for scan...',
|
||||
feishu_scan_tip: 'QR code expires in 10 minutes, single use only',
|
||||
feishu_scan_open_link: 'Or click here to open in browser',
|
||||
feishu_scan_success: 'App created, starting channel...',
|
||||
feishu_scan_expired: 'QR code expired, please retry',
|
||||
feishu_scan_denied: 'Authorization cancelled',
|
||||
feishu_scan_fail: 'App creation failed',
|
||||
feishu_scan_retry: 'Retry',
|
||||
feishu_mode_scan: 'Scan QR', feishu_mode_manual: 'Manual',
|
||||
tasks_title: 'Scheduled Tasks', tasks_desc: 'View and manage scheduled tasks',
|
||||
tasks_coming: 'Coming Soon', tasks_coming_desc: 'Scheduled task management will be available here',
|
||||
logs_title: 'Logs', logs_desc: 'Real-time log output (run.log)',
|
||||
@@ -2999,6 +3025,8 @@ function renderActiveChannels() {
|
||||
|
||||
const weixinWaiting = ch.name === 'weixin' && ch.login_status && ch.login_status !== 'logged_in';
|
||||
const wecomNeedsCreds = ch.name === 'wecom_bot' && !_wecomBotHasCreds(ch);
|
||||
// 飞书 active 卡片渲染带 Tab 的 panel:手动填写 + 扫码重建(覆盖现有配置)
|
||||
const isFeishu = ch.name === 'feishu';
|
||||
let statusDot, statusText;
|
||||
if (weixinWaiting) {
|
||||
statusDot = 'bg-amber-400 animate-pulse';
|
||||
@@ -3014,7 +3042,7 @@ function renderActiveChannels() {
|
||||
}
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="flex items-center gap-4${hasFields || weixinWaiting || wecomNeedsCreds ? ' mb-5' : ''}">
|
||||
<div class="flex items-center gap-4${hasFields || weixinWaiting || wecomNeedsCreds || isFeishu ? ' mb-5' : ''}">
|
||||
<div class="w-10 h-10 rounded-xl bg-${ch.color}-50 dark:bg-${ch.color}-900/20 flex items-center justify-center flex-shrink-0">
|
||||
<i class="fas ${ch.icon} text-${ch.color}-500 text-base"></i>
|
||||
</div>
|
||||
@@ -3050,7 +3078,7 @@ function renderActiveChannels() {
|
||||
</button>
|
||||
<div id="wecom-card-scan-status" class="mt-3"></div>
|
||||
</div>` : ''}
|
||||
${hasFields ? `<div class="space-y-4">
|
||||
${isFeishu ? buildFeishuPanel(ch, true) : (hasFields ? `<div class="space-y-4">
|
||||
${fieldsHtml}
|
||||
<div class="flex items-center justify-end gap-3 pt-1">
|
||||
<span id="ch-status-${ch.name}" class="text-xs text-primary-500 opacity-0 transition-opacity duration-300"></span>
|
||||
@@ -3059,7 +3087,7 @@ function renderActiveChannels() {
|
||||
cursor-pointer transition-colors duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
id="ch-save-${ch.name}">${t('channels_save')}</button>
|
||||
</div>
|
||||
</div>` : ''}`;
|
||||
</div>` : '')}`;
|
||||
|
||||
container.appendChild(card);
|
||||
bindSecretFieldEvents(card);
|
||||
@@ -3256,6 +3284,7 @@ function openAddChannelPanel() {
|
||||
|
||||
function closeAddChannelPanel() {
|
||||
stopWeixinQrPoll();
|
||||
stopFeishuRegisterPoll();
|
||||
const panel = document.getElementById('channels-add-panel');
|
||||
if (panel) {
|
||||
panel.classList.add('hidden');
|
||||
@@ -3267,6 +3296,7 @@ function closeAddChannelPanel() {
|
||||
|
||||
function onAddChannelSelect(chName) {
|
||||
stopWeixinQrPoll();
|
||||
stopFeishuRegisterPoll();
|
||||
const fieldsContainer = document.getElementById('add-channel-fields');
|
||||
const actions = document.getElementById('add-channel-actions');
|
||||
|
||||
@@ -3293,6 +3323,13 @@ function onAddChannelSelect(chName) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (chName === 'feishu') {
|
||||
actions.classList.add('hidden');
|
||||
const ch = channelsData.find(c => c.name === chName);
|
||||
fieldsContainer.innerHTML = buildFeishuPanel(ch);
|
||||
return;
|
||||
}
|
||||
|
||||
const ch = channelsData.find(c => c.name === chName);
|
||||
if (!ch) return;
|
||||
|
||||
@@ -3690,15 +3727,246 @@ function startWecomBotAuthInCard() {
|
||||
// Initialize wecom bot panel with correct default mode when inserted into DOM
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const observer = new MutationObserver(function() {
|
||||
const panel = document.getElementById('wecom-bot-panel');
|
||||
if (panel && !panel.dataset.initialized) {
|
||||
panel.dataset.initialized = '1';
|
||||
switchWecomBotMode(panel.dataset.defaultMode || 'scan');
|
||||
const wecomPanel = document.getElementById('wecom-bot-panel');
|
||||
if (wecomPanel && !wecomPanel.dataset.initialized) {
|
||||
wecomPanel.dataset.initialized = '1';
|
||||
switchWecomBotMode(wecomPanel.dataset.defaultMode || 'scan');
|
||||
}
|
||||
const feishuPanel = document.getElementById('feishu-panel');
|
||||
if (feishuPanel && !feishuPanel.dataset.initialized) {
|
||||
feishuPanel.dataset.initialized = '1';
|
||||
switchFeishuMode(feishuPanel.dataset.defaultMode || 'scan');
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
});
|
||||
|
||||
// =====================================================================
|
||||
// Feishu One-click App Registration (lark-oapi register_app)
|
||||
// =====================================================================
|
||||
let _feishuRegisterPollTimer = null;
|
||||
|
||||
function _feishuHasCreds(ch) {
|
||||
if (!ch || !ch.fields) return false;
|
||||
const idField = ch.fields.find(f => f.key === 'feishu_app_id');
|
||||
const secretField = ch.fields.find(f => f.key === 'feishu_app_secret');
|
||||
return !!(idField && idField.value && secretField && secretField.value);
|
||||
}
|
||||
|
||||
function buildFeishuPanel(ch, isActive) {
|
||||
const scanLabel = t('feishu_mode_scan');
|
||||
const manualLabel = t('feishu_mode_manual');
|
||||
// 已有凭据时默认进入手动 Tab,方便修改;否则推荐扫码
|
||||
const defaultMode = _feishuHasCreds(ch) ? 'manual' : 'scan';
|
||||
const activeAttr = isActive ? 'data-active="1"' : '';
|
||||
return `
|
||||
<div id="feishu-panel" data-default-mode="${defaultMode}" ${activeAttr}>
|
||||
<div class="flex items-center justify-center gap-1 mb-5 bg-slate-100 dark:bg-white/5 rounded-lg p-1">
|
||||
<button id="feishu-tab-scan" onclick="switchFeishuMode('scan')"
|
||||
class="flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors
|
||||
bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-100 shadow-sm">
|
||||
${scanLabel}
|
||||
</button>
|
||||
<button id="feishu-tab-manual" onclick="switchFeishuMode('manual')"
|
||||
class="flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors
|
||||
text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200">
|
||||
${manualLabel}
|
||||
</button>
|
||||
</div>
|
||||
<div id="feishu-mode-content"></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function switchFeishuMode(mode) {
|
||||
const panel = document.getElementById('feishu-panel');
|
||||
const scanTab = document.getElementById('feishu-tab-scan');
|
||||
const manualTab = document.getElementById('feishu-tab-manual');
|
||||
const content = document.getElementById('feishu-mode-content');
|
||||
if (!scanTab || !manualTab || !content) return;
|
||||
|
||||
// 已激活通道卡片中嵌入此 panel 时,没有 add-channel-actions(保存按钮就近渲染)
|
||||
const isActive = panel && panel.dataset.active === '1';
|
||||
const actions = isActive ? null : document.getElementById('add-channel-actions');
|
||||
|
||||
const activeClasses = 'bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-100 shadow-sm';
|
||||
const inactiveClasses = 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200';
|
||||
|
||||
stopFeishuRegisterPoll();
|
||||
|
||||
if (mode === 'scan') {
|
||||
scanTab.className = `flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${activeClasses}`;
|
||||
manualTab.className = `flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${inactiveClasses}`;
|
||||
if (actions) actions.classList.add('hidden');
|
||||
// active 卡片下扫码替换的提示文案,强调"创建新机器人会覆盖现有配置"
|
||||
const desc = isActive
|
||||
? t('feishu_scan_replace_desc')
|
||||
: t('feishu_scan_desc');
|
||||
content.innerHTML = `
|
||||
<div id="feishu-scan-panel" class="flex flex-col items-center py-4">
|
||||
<p class="text-sm text-slate-600 dark:text-slate-300 mb-3 text-center">${desc}</p>
|
||||
<button onclick="startFeishuRegister()"
|
||||
class="mt-2 px-6 py-2.5 rounded-lg bg-emerald-500 hover:bg-emerald-600 text-white text-sm font-medium
|
||||
cursor-pointer transition-colors duration-150">
|
||||
<i class="fas fa-qrcode mr-2"></i>${t('feishu_scan_btn')}
|
||||
</button>
|
||||
<div id="feishu-scan-status" class="mt-4 w-full"></div>
|
||||
</div>`;
|
||||
} else {
|
||||
manualTab.className = `flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${activeClasses}`;
|
||||
scanTab.className = `flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${inactiveClasses}`;
|
||||
const ch = channelsData.find(c => c.name === 'feishu');
|
||||
const fieldsHtml = buildChannelFieldsHtml('feishu', ch ? ch.fields || [] : []);
|
||||
if (isActive) {
|
||||
// 已接入卡片:内置保存按钮,复用 saveChannelConfig 走 update 流程
|
||||
content.innerHTML = `
|
||||
<div class="space-y-4">
|
||||
${fieldsHtml}
|
||||
<div class="flex items-center justify-end gap-3 pt-1">
|
||||
<span id="ch-status-feishu" class="text-xs text-primary-500 opacity-0 transition-opacity duration-300"></span>
|
||||
<button onclick="saveChannelConfig('feishu')"
|
||||
class="px-4 py-2 rounded-lg bg-primary-500 hover:bg-primary-600 text-white text-sm font-medium
|
||||
cursor-pointer transition-colors duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
id="ch-save-feishu">${t('channels_save')}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
} else {
|
||||
content.innerHTML = `<div class="space-y-4">${fieldsHtml}</div>`;
|
||||
if (actions) actions.classList.remove('hidden');
|
||||
}
|
||||
bindSecretFieldEvents(content);
|
||||
}
|
||||
}
|
||||
|
||||
function stopFeishuRegisterPoll() {
|
||||
if (_feishuRegisterPollTimer) {
|
||||
clearTimeout(_feishuRegisterPollTimer);
|
||||
_feishuRegisterPollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function startFeishuRegister(targetStatusId) {
|
||||
const statusId = targetStatusId || 'feishu-scan-status';
|
||||
const statusEl = document.getElementById(statusId);
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = `<p class="text-sm text-slate-500 dark:text-slate-400 text-center">${t('feishu_scan_loading')}</p>`;
|
||||
}
|
||||
stopFeishuRegisterPoll();
|
||||
fetch('/api/feishu/register')
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.status !== 'success') {
|
||||
renderFeishuRegisterError(statusId, data.message || t('feishu_scan_fail'));
|
||||
return;
|
||||
}
|
||||
renderFeishuQr(statusId, data.qr_image, data.qrcode_url);
|
||||
pollFeishuRegisterStatus(statusId);
|
||||
})
|
||||
.catch(err => {
|
||||
renderFeishuRegisterError(statusId, err.message || t('feishu_scan_fail'));
|
||||
});
|
||||
}
|
||||
|
||||
function renderFeishuQr(statusId, qrImage, qrUrl) {
|
||||
const statusEl = document.getElementById(statusId);
|
||||
if (!statusEl) return;
|
||||
const imgHtml = qrImage
|
||||
? `<img src="${qrImage}" alt="QR" class="w-44 h-44 rounded-lg border border-slate-200 dark:border-white/10 bg-white p-2"/>`
|
||||
: `<div class="w-44 h-44 rounded-lg border border-dashed border-slate-300 flex items-center justify-center text-xs text-slate-400">QR</div>`;
|
||||
statusEl.innerHTML = `
|
||||
<div class="flex flex-col items-center gap-3">
|
||||
${imgHtml}
|
||||
<p class="text-xs text-amber-500">${t('feishu_scan_waiting')}</p>
|
||||
<p class="text-xs text-slate-400 dark:text-slate-500">${t('feishu_scan_tip')}</p>
|
||||
${qrUrl ? `<a href="${qrUrl}" target="_blank" rel="noopener"
|
||||
class="text-xs text-blue-500 hover:text-blue-600 underline">${t('feishu_scan_open_link')}</a>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderFeishuRegisterError(statusId, message) {
|
||||
const statusEl = document.getElementById(statusId);
|
||||
if (!statusEl) return;
|
||||
statusEl.innerHTML = `
|
||||
<div class="flex flex-col items-center gap-2 py-2">
|
||||
<p class="text-sm text-red-500 text-center">${message}</p>
|
||||
<button onclick="startFeishuRegister('${statusId}')"
|
||||
class="mt-1 px-4 py-1.5 rounded-md text-xs font-medium
|
||||
bg-slate-100 dark:bg-white/10 text-slate-700 dark:text-slate-200
|
||||
hover:bg-slate-200 dark:hover:bg-white/20 cursor-pointer">
|
||||
<i class="fas fa-rotate-right mr-1"></i>${t('feishu_scan_retry')}
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function pollFeishuRegisterStatus(statusId) {
|
||||
stopFeishuRegisterPoll();
|
||||
_feishuRegisterPollTimer = setTimeout(() => {
|
||||
fetch('/api/feishu/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'poll' })
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.status !== 'success') {
|
||||
renderFeishuRegisterError(statusId, data.message || t('feishu_scan_fail'));
|
||||
return;
|
||||
}
|
||||
const rs = data.register_status;
|
||||
if (rs === 'done') {
|
||||
const statusEl = document.getElementById(statusId);
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = `
|
||||
<div class="flex flex-col items-center py-2">
|
||||
<div class="w-10 h-10 rounded-full bg-emerald-50 dark:bg-emerald-900/30 flex items-center justify-center mb-2">
|
||||
<i class="fas fa-check text-emerald-500 text-lg"></i>
|
||||
</div>
|
||||
<p class="text-sm font-medium text-emerald-600 dark:text-emerald-400">${t('feishu_scan_success')}</p>
|
||||
</div>`;
|
||||
}
|
||||
connectFeishuAfterRegister(data.app_id, data.app_secret);
|
||||
} else if (rs === 'expired') {
|
||||
renderFeishuRegisterError(statusId, t('feishu_scan_expired'));
|
||||
} else if (rs === 'denied') {
|
||||
renderFeishuRegisterError(statusId, t('feishu_scan_denied'));
|
||||
} else if (rs === 'error') {
|
||||
renderFeishuRegisterError(statusId, data.message || t('feishu_scan_fail'));
|
||||
} else {
|
||||
pollFeishuRegisterStatus(statusId);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
pollFeishuRegisterStatus(statusId);
|
||||
});
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function connectFeishuAfterRegister(appId, appSecret) {
|
||||
fetch('/api/channels', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'connect',
|
||||
channel: 'feishu',
|
||||
config: { feishu_app_id: appId, feishu_app_secret: appSecret }
|
||||
})
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.status === 'success') {
|
||||
const ch = channelsData.find(c => c.name === 'feishu');
|
||||
if (ch) {
|
||||
ch.active = true;
|
||||
(ch.fields || []).forEach(f => {
|
||||
if (f.key === 'feishu_app_id') f.value = appId;
|
||||
if (f.key === 'feishu_app_secret') f.value = ChannelsHandler_maskSecret(appSecret);
|
||||
});
|
||||
}
|
||||
setTimeout(() => renderActiveChannels(), 1500);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Scheduler View
|
||||
// =====================================================================
|
||||
|
||||
@@ -575,6 +575,7 @@ class WebChannel(ChatChannel):
|
||||
'/config', 'ConfigHandler',
|
||||
'/api/channels', 'ChannelsHandler',
|
||||
'/api/weixin/qrlogin', 'WeixinQrHandler',
|
||||
'/api/feishu/register', 'FeishuRegisterHandler',
|
||||
'/api/tools', 'ToolsHandler',
|
||||
'/api/skills', 'SkillsHandler',
|
||||
'/api/memory', 'MemoryHandler',
|
||||
@@ -1034,8 +1035,6 @@ class ChannelsHandler:
|
||||
"fields": [
|
||||
{"key": "feishu_app_id", "label": "App ID", "type": "text"},
|
||||
{"key": "feishu_app_secret", "label": "App Secret", "type": "secret"},
|
||||
{"key": "feishu_token", "label": "Verification Token", "type": "secret"},
|
||||
{"key": "feishu_bot_name", "label": "Bot Name", "type": "text"},
|
||||
],
|
||||
}),
|
||||
("dingtalk", {
|
||||
@@ -1530,6 +1529,174 @@ class WeixinQrHandler:
|
||||
return json.dumps({"status": "success", "qr_status": qr_status})
|
||||
|
||||
|
||||
class FeishuRegisterHandler:
|
||||
"""飞书智能体应用一键创建(OAuth 设备授权流,基于 lark.register_app SDK)。
|
||||
|
||||
GET /api/feishu/register → 启动注册:调用 SDK 生成二维码 URL,立即返回;
|
||||
后台线程继续轮询飞书侧直到用户扫码授权。
|
||||
POST /api/feishu/register → 轮询当前会话状态(pending / done / error / expired)。
|
||||
注册成功后不直接写 config,由前端再调
|
||||
/api/channels {action:'connect'} 走标准启用流程。
|
||||
"""
|
||||
|
||||
# 进程内单例状态({url, expire_in, status, app_id, app_secret, error, thread})。
|
||||
# 简单的本地自部署场景下不需要 session 隔离。
|
||||
_state = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def _qr_to_data_uri(data: str) -> str:
|
||||
"""复用 WeixinQrHandler 的二维码渲染。"""
|
||||
return WeixinQrHandler._qr_to_data_uri(data)
|
||||
|
||||
@classmethod
|
||||
def _reset_state(cls):
|
||||
with cls._lock:
|
||||
cls._state = {}
|
||||
|
||||
@classmethod
|
||||
def _start_register_thread(cls):
|
||||
"""启动一次新的注册会话。如已有进行中的会话,先取消(通过 cancel_event)。"""
|
||||
# 先取消可能存在的上一次会话,避免两个 SDK 线程并发 poll 同一个端点
|
||||
with cls._lock:
|
||||
old_cancel = cls._state.get("cancel_event") if cls._state else None
|
||||
if old_cancel is not None:
|
||||
old_cancel.set()
|
||||
cancel_event = threading.Event()
|
||||
cls._state = {"status": "starting", "cancel_event": cancel_event}
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
import lark_oapi as lark
|
||||
except ImportError:
|
||||
with cls._lock:
|
||||
cls._state["status"] = "error"
|
||||
cls._state["error"] = "lark-oapi SDK 未安装,请执行 pip install -U lark-oapi"
|
||||
return
|
||||
|
||||
def _on_qr(info):
|
||||
# SDK 拿到二维码 URL 后立即回调;写入 state 让前端 GET 立刻能拿到
|
||||
with cls._lock:
|
||||
cls._state["url"] = info.get("url", "")
|
||||
cls._state["expire_in"] = info.get("expire_in", 600)
|
||||
cls._state["qr_image"] = cls._qr_to_data_uri(info.get("url", ""))
|
||||
cls._state["status"] = "pending"
|
||||
logger.info(f"[FeishuRegister] QR ready, expire_in={info.get('expire_in')}s")
|
||||
|
||||
def _on_status(info):
|
||||
# 过滤掉 polling 心跳(每 5 秒一次,纯噪音);
|
||||
# 保留 slow_down / domain_switched 等真正的状态切换事件
|
||||
status = info.get("status")
|
||||
if status == "polling":
|
||||
return
|
||||
logger.info(f"[FeishuRegister] SDK status: {info}")
|
||||
|
||||
try:
|
||||
result = lark.register_app(
|
||||
on_qr_code=_on_qr,
|
||||
on_status_change=_on_status,
|
||||
source="cowagent",
|
||||
cancel_event=cancel_event,
|
||||
)
|
||||
with cls._lock:
|
||||
cls._state["status"] = "done"
|
||||
cls._state["app_id"] = result.get("client_id", "")
|
||||
cls._state["app_secret"] = result.get("client_secret", "")
|
||||
logger.info(f"[FeishuRegister] App created: app_id={result.get('client_id')}")
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
err_cls = e.__class__.__name__
|
||||
# 飞书 SDK 抛出的 AppExpiredError / AppAccessDeniedError / RegisterAppError
|
||||
if "Expired" in err_cls:
|
||||
status = "expired"
|
||||
elif "Denied" in err_cls:
|
||||
status = "denied"
|
||||
elif "abort" in err_msg.lower() or "cancel" in err_msg.lower():
|
||||
# 被新一轮注册抢占,保持安静
|
||||
return
|
||||
else:
|
||||
status = "error"
|
||||
with cls._lock:
|
||||
# 仅当当前 state 仍属于本次 worker 时才写入,避免覆盖更新的会话
|
||||
if cls._state.get("cancel_event") is cancel_event:
|
||||
cls._state["status"] = status
|
||||
cls._state["error"] = err_msg
|
||||
logger.warning(f"[FeishuRegister] Register failed ({err_cls}): {err_msg}")
|
||||
|
||||
threading.Thread(target=_worker, daemon=True, name="feishu-register").start()
|
||||
|
||||
def GET(self):
|
||||
"""启动一次新的注册会话。如果已有 pending/done 会话则覆盖。"""
|
||||
_require_auth()
|
||||
web.header('Content-Type', 'application/json; charset=utf-8')
|
||||
try:
|
||||
self._start_register_thread()
|
||||
# 等待 SDK 拿到二维码 URL(最多 10s)。SDK 内部会马上回调 _on_qr。
|
||||
import time as _t
|
||||
for _ in range(100):
|
||||
with self._lock:
|
||||
if self._state.get("url") or self._state.get("status") in ("error", "expired", "denied"):
|
||||
break
|
||||
_t.sleep(0.1)
|
||||
with self._lock:
|
||||
if self._state.get("status") in ("error", "expired", "denied"):
|
||||
return json.dumps({
|
||||
"status": "error",
|
||||
"message": self._state.get("error", "register failed"),
|
||||
})
|
||||
if not self._state.get("url"):
|
||||
return json.dumps({
|
||||
"status": "error",
|
||||
"message": "等待飞书二维码超时,请重试",
|
||||
})
|
||||
return json.dumps({
|
||||
"status": "success",
|
||||
"qrcode_url": self._state["url"],
|
||||
"qr_image": self._state.get("qr_image", ""),
|
||||
"expire_in": self._state.get("expire_in", 600),
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(f"[WebChannel] FeishuRegister GET error: {e}")
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
def POST(self):
|
||||
"""轮询注册结果。"""
|
||||
_require_auth()
|
||||
web.header('Content-Type', 'application/json; charset=utf-8')
|
||||
try:
|
||||
body = json.loads(web.data() or b"{}")
|
||||
action = body.get("action", "poll")
|
||||
if action != "poll":
|
||||
return json.dumps({"status": "error", "message": f"unknown action: {action}"})
|
||||
|
||||
with self._lock:
|
||||
status = self._state.get("status", "idle")
|
||||
if status == "done":
|
||||
payload = {
|
||||
"status": "success",
|
||||
"register_status": "done",
|
||||
"app_id": self._state.get("app_id", ""),
|
||||
"app_secret": self._state.get("app_secret", ""),
|
||||
}
|
||||
# 一次性返回凭据后清掉,避免敏感信息长期驻留内存
|
||||
self._state = {}
|
||||
return json.dumps(payload)
|
||||
if status in ("error", "expired", "denied"):
|
||||
return json.dumps({
|
||||
"status": "success",
|
||||
"register_status": status,
|
||||
"message": self._state.get("error", ""),
|
||||
})
|
||||
# pending / starting:还在等用户扫码
|
||||
return json.dumps({
|
||||
"status": "success",
|
||||
"register_status": "pending",
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(f"[WebChannel] FeishuRegister POST error: {e}")
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
|
||||
def _get_workspace_root():
|
||||
"""Resolve the agent workspace directory."""
|
||||
from common.utils import expand_path
|
||||
|
||||
Reference in New Issue
Block a user