Phase 7 Task 7: 插件与集成系统

- 创建 plugin_manager.py 模块
  - PluginManager: 插件管理主类
  - ChromeExtensionHandler: Chrome 插件处理
  - BotHandler: 飞书/钉钉/Slack 机器人处理
  - WebhookIntegration: Zapier/Make Webhook 集成
  - WebDAVSync: WebDAV 同步管理

- 创建完整的 Chrome 扩展代码
  - manifest.json, background.js, content.js, content.css
  - popup.html/js: 弹出窗口界面
  - options.html/js: 设置页面
  - 支持网页剪藏、选中文本保存、项目选择

- 更新 schema.sql 添加插件相关数据库表
  - plugins: 插件配置表
  - bot_sessions: 机器人会话表
  - webhook_endpoints: Webhook 端点表
  - webdav_syncs: WebDAV 同步配置表
  - plugin_activity_logs: 插件活动日志表

- 更新 main.py 添加插件相关 API 端点
  - GET/POST /api/v1/plugins - 插件管理
  - POST /api/v1/plugins/chrome/clip - Chrome 插件保存网页
  - POST /api/v1/bots/webhook/{platform} - 接收机器人消息
  - GET /api/v1/bots/sessions - 机器人会话列表
  - POST /api/v1/webhook-endpoints - 创建 Webhook 端点
  - POST /webhook/{type}/{token} - 接收外部 Webhook
  - POST /api/v1/webdav-syncs - WebDAV 同步配置
  - POST /api/v1/webdav-syncs/{id}/test - 测试 WebDAV 连接
  - POST /api/v1/webdav-syncs/{id}/sync - 触发 WebDAV 同步

- 更新 requirements.txt 添加插件依赖
  - beautifulsoup4: HTML 解析
  - webdavclient3: WebDAV 客户端

- 更新 STATUS.md 和 README.md 开发进度
This commit is contained in:
OpenClaw Bot
2026-02-23 12:09:15 +08:00
parent 08535e54ba
commit 797ca58e8e
27 changed files with 7350 additions and 11 deletions

View File

@@ -0,0 +1,217 @@
// InsightFlow Chrome Extension - Background Script
// 处理后台任务、右键菜单、消息传递
// 默认配置
const DEFAULT_CONFIG = {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
};
// 初始化
chrome.runtime.onInstalled.addListener(() => {
// 创建右键菜单
chrome.contextMenus.create({
id: 'clipSelection',
title: '保存到 InsightFlow',
contexts: ['selection', 'page']
});
// 初始化存储
chrome.storage.sync.get(['insightflowConfig'], (result) => {
if (!result.insightflowConfig) {
chrome.storage.sync.set({ insightflowConfig: DEFAULT_CONFIG });
}
});
});
// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'clipSelection') {
clipPage(tab, info.selectionText);
}
});
// 处理扩展图标点击
chrome.action.onClicked.addListener((tab) => {
clipPage(tab);
});
// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'clipPage') {
clipPage(sender.tab, request.selectionText);
sendResponse({ success: true });
} else if (request.action === 'getConfig') {
chrome.storage.sync.get(['insightflowConfig'], (result) => {
sendResponse(result.insightflowConfig || DEFAULT_CONFIG);
});
return true; // 保持消息通道开放
} else if (request.action === 'saveConfig') {
chrome.storage.sync.set({ insightflowConfig: request.config }, () => {
sendResponse({ success: true });
});
return true;
} else if (request.action === 'fetchProjects') {
fetchProjects().then(projects => {
sendResponse({ success: true, projects });
}).catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
}
});
// 剪藏页面
async function clipPage(tab, selectionText = null) {
try {
// 获取配置
const config = await getConfig();
if (!config.apiKey) {
showNotification('请先配置 API Key', '点击扩展图标打开设置');
chrome.runtime.openOptionsPage();
return;
}
// 获取页面内容
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractPageContent,
args: [selectionText]
});
// 发送到 InsightFlow
const response = await sendToInsightFlow(config, result);
if (response.success) {
showNotification('保存成功', '内容已导入 InsightFlow');
} else {
showNotification('保存失败', response.error || '未知错误');
}
} catch (error) {
console.error('Clip error:', error);
showNotification('保存失败', error.message);
}
}
// 提取页面内容
function extractPageContent(selectionText) {
const data = {
url: window.location.href,
title: document.title,
selection: selectionText,
timestamp: new Date().toISOString()
};
if (selectionText) {
// 只保存选中的文本
data.content = selectionText;
data.contentType = 'selection';
} else {
// 保存整个页面
// 获取主要内容
const article = document.querySelector('article') ||
document.querySelector('main') ||
document.querySelector('.content') ||
document.querySelector('#content');
if (article) {
data.content = article.innerText;
data.contentType = 'article';
} else {
// 获取 body 文本,但移除脚本和样式
const bodyClone = document.body.cloneNode(true);
const scripts = bodyClone.querySelectorAll('script, style, nav, header, footer, aside');
scripts.forEach(el => el.remove());
data.content = bodyClone.innerText;
data.contentType = 'page';
}
// 限制内容长度
if (data.content.length > 50000) {
data.content = data.content.substring(0, 50000) + '...';
data.truncated = true;
}
}
// 获取元数据
data.meta = {
description: document.querySelector('meta[name="description"]')?.content || '',
keywords: document.querySelector('meta[name="keywords"]')?.content || '',
author: document.querySelector('meta[name="author"]')?.content || ''
};
return data;
}
// 发送到 InsightFlow
async function sendToInsightFlow(config, data) {
const url = `${config.serverUrl}/api/v1/plugins/chrome/clip`;
const payload = {
url: data.url,
title: data.title,
content: data.content,
content_type: data.contentType,
meta: data.meta,
project_id: config.defaultProjectId || null
};
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': config.apiKey
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const error = await response.text();
throw new Error(error);
}
return await response.json();
}
// 获取配置
function getConfig() {
return new Promise((resolve) => {
chrome.storage.sync.get(['insightflowConfig'], (result) => {
resolve(result.insightflowConfig || DEFAULT_CONFIG);
});
});
}
// 获取项目列表
async function fetchProjects() {
const config = await getConfig();
if (!config.apiKey) {
throw new Error('请先配置 API Key');
}
const response = await fetch(`${config.serverUrl}/api/v1/projects`, {
headers: {
'X-API-Key': config.apiKey
}
});
if (!response.ok) {
throw new Error('获取项目列表失败');
}
const data = await response.json();
return data.projects || [];
}
// 显示通知
function showNotification(title, message) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title,
message
});
}

View File

@@ -0,0 +1,141 @@
/* InsightFlow Chrome Extension - Content Styles */
.insightflow-float-btn {
position: absolute;
width: 36px;
height: 36px;
background: #4f46e5;
border-radius: 50%;
display: none;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
z-index: 999999;
transition: transform 0.2s, box-shadow 0.2s;
}
.insightflow-float-btn:hover {
transform: scale(1.1);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.insightflow-float-btn svg {
color: white;
}
.insightflow-popup {
position: absolute;
width: 300px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
z-index: 999999;
display: none;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
}
.insightflow-popup-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
border-bottom: 1px solid #e5e7eb;
font-weight: 600;
color: #111827;
}
.insightflow-close-btn {
background: none;
border: none;
font-size: 20px;
color: #6b7280;
cursor: pointer;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
}
.insightflow-close-btn:hover {
color: #111827;
}
.insightflow-popup-content {
padding: 16px;
}
.insightflow-text-preview {
background: #f3f4f6;
padding: 12px;
border-radius: 6px;
font-size: 13px;
color: #4b5563;
line-height: 1.5;
max-height: 120px;
overflow-y: auto;
margin-bottom: 12px;
}
.insightflow-actions {
display: flex;
gap: 8px;
}
.insightflow-btn {
flex: 1;
padding: 8px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
background: white;
color: #374151;
font-size: 13px;
cursor: pointer;
transition: all 0.2s;
}
.insightflow-btn:hover {
background: #f9fafb;
border-color: #9ca3af;
}
.insightflow-btn-primary {
background: #4f46e5;
border-color: #4f46e5;
color: white;
}
.insightflow-btn-primary:hover {
background: #4338ca;
border-color: #4338ca;
}
.insightflow-project-list {
max-height: 200px;
overflow-y: auto;
}
.insightflow-project-item {
padding: 12px;
border-radius: 6px;
cursor: pointer;
transition: background 0.2s;
}
.insightflow-project-item:hover {
background: #f3f4f6;
}
.insightflow-project-name {
font-weight: 500;
color: #111827;
margin-bottom: 4px;
}
.insightflow-project-desc {
font-size: 12px;
color: #6b7280;
}

204
chrome-extension/content.js Normal file
View File

@@ -0,0 +1,204 @@
// InsightFlow Chrome Extension - Content Script
// 在页面中注入,处理页面交互
(function() {
'use strict';
// 防止重复注入
if (window.insightflowInjected) return;
window.insightflowInjected = true;
// 创建浮动按钮
let floatingButton = null;
let selectionPopup = null;
// 监听选中文本
document.addEventListener('mouseup', handleSelection);
document.addEventListener('keyup', handleSelection);
function handleSelection(e) {
const selection = window.getSelection();
const text = selection.toString().trim();
if (text.length > 0) {
showFloatingButton(selection);
} else {
hideFloatingButton();
hideSelectionPopup();
}
}
// 显示浮动按钮
function showFloatingButton(selection) {
if (!floatingButton) {
floatingButton = document.createElement('div');
floatingButton.className = 'insightflow-float-btn';
floatingButton.innerHTML = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 5v14M5 12h14"/>
</svg>
`;
floatingButton.title = '保存到 InsightFlow';
document.body.appendChild(floatingButton);
floatingButton.addEventListener('click', () => {
const text = window.getSelection().toString().trim();
if (text) {
showSelectionPopup(text);
}
});
}
// 定位按钮
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
floatingButton.style.left = `${rect.right + window.scrollX - 40}px`;
floatingButton.style.top = `${rect.top + window.scrollY - 45}px`;
floatingButton.style.display = 'flex';
}
// 隐藏浮动按钮
function hideFloatingButton() {
if (floatingButton) {
floatingButton.style.display = 'none';
}
}
// 显示选择弹窗
function showSelectionPopup(text) {
hideFloatingButton();
if (!selectionPopup) {
selectionPopup = document.createElement('div');
selectionPopup.className = 'insightflow-popup';
document.body.appendChild(selectionPopup);
}
selectionPopup.innerHTML = `
<div class="insightflow-popup-header">
<span>保存到 InsightFlow</span>
<button class="insightflow-close-btn">&times;</button>
</div>
<div class="insightflow-popup-content">
<div class="insightflow-text-preview">${escapeHtml(text.substring(0, 200))}${text.length > 200 ? '...' : ''}</div>
<div class="insightflow-actions">
<button class="insightflow-btn insightflow-btn-primary" id="if-save-quick">快速保存</button>
<button class="insightflow-btn" id="if-save-select">选择项目...</button>
</div>
</div>
`;
selectionPopup.style.display = 'block';
// 定位弹窗
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
selectionPopup.style.left = `${Math.min(rect.left + window.scrollX, window.innerWidth - 320)}px`;
selectionPopup.style.top = `${rect.bottom + window.scrollY + 10}px`;
// 绑定事件
selectionPopup.querySelector('.insightflow-close-btn').addEventListener('click', hideSelectionPopup);
selectionPopup.querySelector('#if-save-quick').addEventListener('click', () => saveQuick(text));
selectionPopup.querySelector('#if-save-select').addEventListener('click', () => saveWithProject(text));
}
// 隐藏选择弹窗
function hideSelectionPopup() {
if (selectionPopup) {
selectionPopup.style.display = 'none';
}
}
// 快速保存
async function saveQuick(text) {
hideSelectionPopup();
chrome.runtime.sendMessage({
action: 'clipPage',
selectionText: text
});
}
// 选择项目保存
async function saveWithProject(text) {
// 获取项目列表
chrome.runtime.sendMessage({ action: 'fetchProjects' }, (response) => {
if (response.success && response.projects.length > 0) {
showProjectSelector(text, response.projects);
} else {
saveQuick(text); // 失败时快速保存
}
});
}
// 显示项目选择器
function showProjectSelector(text, projects) {
selectionPopup.innerHTML = `
<div class="insightflow-popup-header">
<span>选择项目</span>
<button class="insightflow-close-btn">&times;</button>
</div>
<div class="insightflow-popup-content">
<div class="insightflow-project-list">
${projects.map(p => `
<div class="insightflow-project-item" data-id="${p.id}">
<div class="insightflow-project-name">${escapeHtml(p.name)}</div>
<div class="insightflow-project-desc">${escapeHtml(p.description || '').substring(0, 50)}</div>
</div>
`).join('')}
</div>
</div>
`;
selectionPopup.querySelector('.insightflow-close-btn').addEventListener('click', hideSelectionPopup);
// 绑定项目选择事件
selectionPopup.querySelectorAll('.insightflow-project-item').forEach(item => {
item.addEventListener('click', () => {
const projectId = item.dataset.id;
saveToProject(text, projectId);
});
});
}
// 保存到指定项目
async function saveToProject(text, projectId) {
hideSelectionPopup();
chrome.runtime.sendMessage({
action: 'getConfig'
}, (config) => {
// 临时设置默认项目
config.defaultProjectId = projectId;
chrome.runtime.sendMessage({
action: 'saveConfig',
config: config
}, () => {
chrome.runtime.sendMessage({
action: 'clipPage',
selectionText: text
});
});
});
}
// HTML 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 点击页面其他地方关闭弹窗
document.addEventListener('click', (e) => {
if (selectionPopup && !selectionPopup.contains(e.target) &&
floatingButton && !floatingButton.contains(e.target)) {
hideSelectionPopup();
hideFloatingButton();
}
});
})();

View File

@@ -0,0 +1,46 @@
{
"manifest_version": 3,
"name": "InsightFlow Clipper",
"version": "1.0.0",
"description": "将网页内容一键导入 InsightFlow 知识库",
"permissions": [
"activeTab",
"storage",
"contextMenus",
"scripting"
],
"host_permissions": [
"http://*/*",
"https://*/*"
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["content.css"]
}
],
"options_page": "options.html",
"web_accessible_resources": [
{
"resources": ["icons/*.png"],
"matches": ["<all_urls>"]
}
]
}

View File

@@ -0,0 +1,349 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsightFlow Clipper 设置</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f3f4f6;
min-height: 100vh;
padding: 40px 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 32px;
}
.header h1 {
font-size: 28px;
color: #111827;
margin-bottom: 8px;
}
.header p {
color: #6b7280;
}
.card {
background: white;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.card-title {
font-size: 18px;
font-weight: 600;
color: #111827;
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 8px;
}
.form-group {
margin-bottom: 20px;
}
.form-label {
display: block;
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 6px;
}
.form-input {
width: 100%;
padding: 10px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.2s;
}
.form-input:focus {
outline: none;
border-color: #4f46e5;
}
.form-hint {
font-size: 12px;
color: #6b7280;
margin-top: 4px;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: #4f46e5;
color: white;
}
.btn-primary:hover {
background: #4338ca;
}
.btn-secondary {
background: white;
color: #374151;
border: 1px solid #d1d5db;
}
.btn-secondary:hover {
background: #f9fafb;
}
.btn-success {
background: #10b981;
color: white;
}
.actions {
display: flex;
gap: 12px;
justify-content: flex-end;
margin-top: 24px;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 500;
}
.status-badge.success {
background: #d1fae5;
color: #065f46;
}
.status-badge.error {
background: #fee2e2;
color: #991b1b;
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.info-box {
background: #eff6ff;
border-left: 4px solid #3b82f6;
padding: 16px;
border-radius: 0 6px 6px 0;
margin-bottom: 20px;
}
.info-box h4 {
font-size: 14px;
color: #1e40af;
margin-bottom: 8px;
}
.info-box p {
font-size: 13px;
color: #3b82f6;
line-height: 1.5;
}
.info-box code {
background: rgba(255,255,255,0.5);
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
.shortcut-list {
list-style: none;
}
.shortcut-list li {
display: flex;
justify-content: space-between;
padding: 12px 0;
border-bottom: 1px solid #e5e7eb;
}
.shortcut-list li:last-child {
border-bottom: none;
}
.shortcut-key {
background: #f3f4f6;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-family: monospace;
color: #374151;
}
.footer {
text-align: center;
padding: 24px;
color: #6b7280;
font-size: 13px;
}
.footer a {
color: #4f46e5;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
#testResult {
margin-top: 12px;
padding: 12px;
border-radius: 6px;
font-size: 13px;
display: none;
}
#testResult.success {
display: block;
background: #d1fae5;
color: #065f46;
}
#testResult.error {
display: block;
background: #fee2e2;
color: #991b1b;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>⚙️ InsightFlow Clipper 设置</h1>
<p>配置您的知识库连接</p>
</div>
<div class="card">
<div class="card-title">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
服务器连接
</div>
<div class="info-box">
<h4>如何获取 API Key</h4>
<p>
1. 登录 InsightFlow 控制台<br>
2. 进入「插件管理」页面<br>
3. 创建 Chrome 插件并复制 API Key
</p>
</div>
<div class="form-group">
<label class="form-label">服务器地址</label>
<input type="text" id="serverUrl" class="form-input" placeholder="http://122.51.127.111:18000">
<p class="form-hint">InsightFlow 服务器的 URL 地址</p>
</div>
<div class="form-group">
<label class="form-label">API Key</label>
<input type="password" id="apiKey" class="form-input" placeholder="if_plugin_xxxxxxxx...">
<p class="form-hint">从 InsightFlow 控制台获取的插件 API Key</p>
</div>
<div class="form-group">
<button id="testBtn" class="btn btn-secondary">测试连接</button>
<div id="testResult"></div>
</div>
</div>
<div class="card">
<div class="card-title">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
<path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
</svg>
默认设置
</div>
<div class="form-group">
<label class="form-label">默认项目</label>
<select id="defaultProject" class="form-input">
<option value="">不设置默认项目</option>
</select>
<p class="form-hint">保存内容时默认导入的项目</p>
</div>
</div>
<div class="card">
<div class="card-title">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
使用说明
</div>
<ul class="shortcut-list">
<li>
<span>保存当前页面</span>
<span class="shortcut-key">点击扩展图标</span>
</li>
<li>
<span>保存选中文本</span>
<span class="shortcut-key">右键 → 保存到 InsightFlow</span>
</li>
<li>
<span>快速保存选中内容</span>
<span class="shortcut-key">选中文本后点击浮动按钮</span>
</li>
<li>
<span>选择项目保存</span>
<span class="shortcut-key">选中文本后点击"选择项目"</span>
</li>
</ul>
</div>
<div class="actions">
<button id="resetBtn" class="btn btn-secondary">重置</button>
<button id="saveBtn" class="btn btn-primary">保存设置</button>
</div>
<div class="footer">
<p>InsightFlow Clipper v1.0.0</p>
<p><a href="#" id="openConsole">打开 InsightFlow 控制台</a> | <a href="#" id="helpLink">帮助文档</a></p>
</div>
</div>
<script src="options.js"></script>
</body>
</html>

175
chrome-extension/options.js Normal file
View File

@@ -0,0 +1,175 @@
// InsightFlow Chrome Extension - Options Script
document.addEventListener('DOMContentLoaded', () => {
const serverUrlInput = document.getElementById('serverUrl');
const apiKeyInput = document.getElementById('apiKey');
const defaultProjectSelect = document.getElementById('defaultProject');
const testBtn = document.getElementById('testBtn');
const testResult = document.getElementById('testResult');
const saveBtn = document.getElementById('saveBtn');
const resetBtn = document.getElementById('resetBtn');
const openConsole = document.getElementById('openConsole');
const helpLink = document.getElementById('helpLink');
// 加载配置
loadConfig();
// 测试连接
testBtn.addEventListener('click', async () => {
testBtn.disabled = true;
testBtn.textContent = '测试中...';
testResult.className = '';
testResult.style.display = 'none';
const serverUrl = serverUrlInput.value.trim();
const apiKey = apiKeyInput.value.trim();
if (!serverUrl || !apiKey) {
showTestResult('请填写服务器地址和 API Key', 'error');
testBtn.disabled = false;
testBtn.textContent = '测试连接';
return;
}
try {
const response = await fetch(`${serverUrl}/api/v1/projects`, {
headers: { 'X-API-Key': apiKey }
});
if (response.ok) {
const data = await response.json();
showTestResult(`连接成功!找到 ${data.projects?.length || 0} 个项目`, 'success');
// 更新项目列表
updateProjectList(data.projects || []);
} else if (response.status === 401) {
showTestResult('API Key 无效,请检查', 'error');
} else {
showTestResult(`连接失败: HTTP ${response.status}`, 'error');
}
} catch (error) {
showTestResult(`连接错误: ${error.message}`, 'error');
}
testBtn.disabled = false;
testBtn.textContent = '测试连接';
});
// 保存设置
saveBtn.addEventListener('click', async () => {
const config = {
serverUrl: serverUrlInput.value.trim(),
apiKey: apiKeyInput.value.trim(),
defaultProjectId: defaultProjectSelect.value
};
if (!config.serverUrl) {
alert('请填写服务器地址');
return;
}
await chrome.storage.sync.set({ insightflowConfig: config });
// 显示保存成功
saveBtn.textContent = '已保存 ✓';
saveBtn.classList.add('btn-success');
setTimeout(() => {
saveBtn.textContent = '保存设置';
saveBtn.classList.remove('btn-success');
}, 2000);
});
// 重置设置
resetBtn.addEventListener('click', () => {
if (confirm('确定要重置所有设置吗?')) {
const defaultConfig = {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
};
chrome.storage.sync.set({ insightflowConfig: defaultConfig }, () => {
loadConfig();
showTestResult('设置已重置', 'success');
});
}
});
// 打开控制台
openConsole.addEventListener('click', (e) => {
e.preventDefault();
const serverUrl = serverUrlInput.value.trim();
if (serverUrl) {
chrome.tabs.create({ url: serverUrl });
}
});
// 帮助链接
helpLink.addEventListener('click', (e) => {
e.preventDefault();
const serverUrl = serverUrlInput.value.trim();
if (serverUrl) {
chrome.tabs.create({ url: `${serverUrl}/docs` });
}
});
// 加载配置
async function loadConfig() {
const result = await chrome.storage.sync.get(['insightflowConfig']);
const config = result.insightflowConfig || {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
};
serverUrlInput.value = config.serverUrl;
apiKeyInput.value = config.apiKey;
// 如果有 API Key加载项目列表
if (config.apiKey) {
loadProjects(config);
}
}
// 加载项目列表
async function loadProjects(config) {
try {
const response = await fetch(`${config.serverUrl}/api/v1/projects`, {
headers: { 'X-API-Key': config.apiKey }
});
if (response.ok) {
const data = await response.json();
updateProjectList(data.projects || [], config.defaultProjectId);
}
} catch (error) {
console.error('Failed to load projects:', error);
}
}
// 更新项目列表
function updateProjectList(projects, selectedId = '') {
let html = '<option value="">不设置默认项目</option>';
projects.forEach(project => {
const selected = project.id === selectedId ? 'selected' : '';
html += `<option value="${project.id}" ${selected}>${escapeHtml(project.name)}</option>`;
});
defaultProjectSelect.innerHTML = html;
}
// 显示测试结果
function showTestResult(message, type) {
testResult.textContent = message;
testResult.className = type;
}
// HTML 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
});

258
chrome-extension/popup.html Normal file
View File

@@ -0,0 +1,258 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsightFlow Clipper</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 360px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f9fafb;
}
.header {
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 {
font-size: 18px;
font-weight: 600;
margin-bottom: 4px;
}
.header p {
font-size: 12px;
opacity: 0.9;
}
.content {
padding: 16px;
}
.status-card {
background: white;
border-radius: 8px;
padding: 16px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.status-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #10b981;
}
.status-dot.error {
background: #ef4444;
}
.status-text {
font-size: 14px;
font-weight: 500;
color: #111827;
}
.project-select {
width: 100%;
padding: 10px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 14px;
background: white;
cursor: pointer;
}
.project-select:focus {
outline: none;
border-color: #4f46e5;
}
.btn {
width: 100%;
padding: 12px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-primary {
background: #4f46e5;
color: white;
}
.btn-primary:hover {
background: #4338ca;
}
.btn-secondary {
background: white;
color: #374151;
border: 1px solid #d1d5db;
margin-top: 8px;
}
.btn-secondary:hover {
background: #f9fafb;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-top: 16px;
}
.stat-item {
text-align: center;
padding: 12px;
background: #f3f4f6;
border-radius: 6px;
}
.stat-value {
font-size: 20px;
font-weight: 600;
color: #4f46e5;
}
.stat-label {
font-size: 11px;
color: #6b7280;
margin-top: 4px;
}
.footer {
padding: 12px 16px;
text-align: center;
border-top: 1px solid #e5e7eb;
}
.footer a {
color: #4f46e5;
text-decoration: none;
font-size: 12px;
}
.footer a:hover {
text-decoration: underline;
}
.loading {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #ffffff;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.message {
padding: 12px;
border-radius: 6px;
font-size: 13px;
margin-bottom: 12px;
display: none;
}
.message.success {
display: block;
background: #d1fae5;
color: #065f46;
}
.message.error {
display: block;
background: #fee2e2;
color: #991b1b;
}
</style>
</head>
<body>
<div class="header">
<h1>🧠 InsightFlow</h1>
<p>一键保存网页到知识库</p>
</div>
<div class="content">
<div id="message" class="message"></div>
<div class="status-card">
<div class="status-header">
<div id="statusDot" class="status-dot"></div>
<span id="statusText" class="status-text">连接中...</span>
</div>
<select id="projectSelect" class="project-select">
<option value="">选择保存项目...</option>
</select>
</div>
<button id="clipBtn" class="btn btn-primary">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 5v14M5 12h14"/>
</svg>
保存当前页面
</button>
<button id="settingsBtn" class="btn btn-secondary">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
<path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
</svg>
设置
</button>
<div class="stats">
<div class="stat-item">
<div id="clipCount" class="stat-value">0</div>
<div class="stat-label">已保存</div>
</div>
<div class="stat-item">
<div id="projectCount" class="stat-value">0</div>
<div class="stat-label">项目数</div>
</div>
<div class="stat-item">
<div id="todayCount" class="stat-value">0</div>
<div class="stat-label">今日</div>
</div>
</div>
</div>
<div class="footer">
<a href="#" id="openDashboard">打开 InsightFlow 控制台 →</a>
</div>
<script src="popup.js"></script>
</body>
</html>

195
chrome-extension/popup.js Normal file
View File

@@ -0,0 +1,195 @@
// InsightFlow Chrome Extension - Popup Script
document.addEventListener('DOMContentLoaded', async () => {
const clipBtn = document.getElementById('clipBtn');
const settingsBtn = document.getElementById('settingsBtn');
const projectSelect = document.getElementById('projectSelect');
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const messageEl = document.getElementById('message');
const openDashboard = document.getElementById('openDashboard');
// 加载配置和项目列表
await loadConfig();
// 保存当前页面按钮
clipBtn.addEventListener('click', async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// 更新按钮状态
clipBtn.disabled = true;
clipBtn.innerHTML = '<span class="loading"></span> 保存中...';
// 保存选中的项目
const projectId = projectSelect.value;
if (projectId) {
const config = await getConfig();
config.defaultProjectId = projectId;
await saveConfig(config);
}
// 发送剪藏请求
chrome.runtime.sendMessage({
action: 'clipPage'
}, (response) => {
clipBtn.disabled = false;
clipBtn.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 5v14M5 12h14"/>
</svg>
保存当前页面
`;
if (response && response.success) {
showMessage('保存成功!', 'success');
updateStats();
} else {
showMessage(response?.error || '保存失败', 'error');
}
});
});
// 设置按钮
settingsBtn.addEventListener('click', () => {
chrome.runtime.openOptionsPage();
});
// 打开控制台
openDashboard.addEventListener('click', async (e) => {
e.preventDefault();
const config = await getConfig();
chrome.tabs.create({ url: config.serverUrl });
});
});
// 加载配置
async function loadConfig() {
const config = await getConfig();
// 检查连接状态
checkConnection(config);
// 加载项目列表
loadProjects(config);
// 更新统计
updateStats();
}
// 检查连接状态
async function checkConnection(config) {
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
if (!config.apiKey) {
statusDot.classList.add('error');
statusText.textContent = '未配置 API Key';
return;
}
try {
const response = await fetch(`${config.serverUrl}/api/v1/projects`, {
headers: { 'X-API-Key': config.apiKey }
});
if (response.ok) {
statusText.textContent = '已连接';
} else {
statusDot.classList.add('error');
statusText.textContent = '连接失败';
}
} catch (error) {
statusDot.classList.add('error');
statusText.textContent = '连接错误';
}
}
// 加载项目列表
async function loadProjects(config) {
const projectSelect = document.getElementById('projectSelect');
if (!config.apiKey) {
projectSelect.innerHTML = '<option>请先配置 API Key</option>';
return;
}
try {
const response = await fetch(`${config.serverUrl}/api/v1/projects`, {
headers: { 'X-API-Key': config.apiKey }
});
if (response.ok) {
const data = await response.json();
const projects = data.projects || [];
// 更新项目数统计
document.getElementById('projectCount').textContent = projects.length;
// 填充下拉框
let html = '<option value="">选择保存项目...</option>';
projects.forEach(project => {
const selected = project.id === config.defaultProjectId ? 'selected' : '';
html += `<option value="${project.id}" ${selected}>${escapeHtml(project.name)}</option>`;
});
projectSelect.innerHTML = html;
}
} catch (error) {
console.error('Failed to load projects:', error);
}
}
// 更新统计
async function updateStats() {
// 从存储中获取统计数据
const result = await chrome.storage.local.get(['clipStats']);
const stats = result.clipStats || { total: 0, today: 0, lastDate: null };
// 检查是否需要重置今日计数
const today = new Date().toDateString();
if (stats.lastDate !== today) {
stats.today = 0;
stats.lastDate = today;
await chrome.storage.local.set({ clipStats: stats });
}
document.getElementById('clipCount').textContent = stats.total;
document.getElementById('todayCount').textContent = stats.today;
}
// 显示消息
function showMessage(text, type) {
const messageEl = document.getElementById('message');
messageEl.textContent = text;
messageEl.className = `message ${type}`;
setTimeout(() => {
messageEl.className = 'message';
}, 3000);
}
// 获取配置
function getConfig() {
return new Promise((resolve) => {
chrome.storage.sync.get(['insightflowConfig'], (result) => {
resolve(result.insightflowConfig || {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
});
});
});
}
// 保存配置
function saveConfig(config) {
return new Promise((resolve) => {
chrome.storage.sync.set({ insightflowConfig: config }, resolve);
});
}
// HTML 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}