Phase 7 Task 3: 数据安全与合规

- 创建 security_manager.py 安全模块
  - SecurityManager: 安全管理主类
  - 审计日志系统 - 记录所有数据操作
  - 端到端加密 - AES-256-GCM 加密项目数据
  - 数据脱敏 - 支持手机号、邮箱、身份证等敏感信息脱敏
  - 数据访问策略 - 基于用户、角色、IP、时间的访问控制
  - 访问审批流程 - 敏感数据访问需要审批

- 更新 schema.sql 添加安全相关数据库表
  - audit_logs: 审计日志表
  - encryption_configs: 加密配置表
  - masking_rules: 脱敏规则表
  - data_access_policies: 数据访问策略表
  - access_requests: 访问请求表

- 更新 main.py 添加安全相关 API 端点
  - GET /api/v1/audit-logs - 查询审计日志
  - GET /api/v1/audit-logs/stats - 审计统计
  - POST /api/v1/projects/{id}/encryption/enable - 启用加密
  - POST /api/v1/projects/{id}/encryption/disable - 禁用加密
  - POST /api/v1/projects/{id}/encryption/verify - 验证密码
  - GET /api/v1/projects/{id}/encryption - 获取加密配置
  - POST /api/v1/projects/{id}/masking-rules - 创建脱敏规则
  - GET /api/v1/projects/{id}/masking-rules - 获取脱敏规则
  - PUT /api/v1/masking-rules/{id} - 更新脱敏规则
  - DELETE /api/v1/masking-rules/{id} - 删除脱敏规则
  - POST /api/v1/projects/{id}/masking/apply - 应用脱敏
  - POST /api/v1/projects/{id}/access-policies - 创建访问策略
  - GET /api/v1/projects/{id}/access-policies - 获取访问策略
  - POST /api/v1/access-policies/{id}/check - 检查访问权限
  - POST /api/v1/access-requests - 创建访问请求
  - POST /api/v1/access-requests/{id}/approve - 批准访问
  - POST /api/v1/access-requests/{id}/reject - 拒绝访问

- 更新 requirements.txt 添加 cryptography 依赖

- 更新 STATUS.md 和 README.md 记录完成状态
This commit is contained in:
OpenClaw Bot
2026-02-23 18:11:11 +08:00
parent 847e183b85
commit 95a558acc9
19 changed files with 4407 additions and 1646 deletions

View File

@@ -193,7 +193,7 @@ MIT
| 1. 智能工作流自动化 | ✅ 已完成 | 2026-02-23 | | 1. 智能工作流自动化 | ✅ 已完成 | 2026-02-23 |
| 2. 多模态支持 | ✅ 已完成 | 2026-02-23 | | 2. 多模态支持 | ✅ 已完成 | 2026-02-23 |
| 7. 插件与集成 | ✅ 已完成 | 2026-02-23 | | 7. 插件与集成 | ✅ 已完成 | 2026-02-23 |
| 3. 数据安全与合规 | 📋 待开发 | - | | 3. 数据安全与合规 | ✅ 已完成 | 2026-02-23 |
| 4. 协作与共享 | 📋 待开发 | - | | 4. 协作与共享 | 📋 待开发 | - |
| 5. 智能报告生成 | 📋 待开发 | - | | 5. 智能报告生成 | 📋 待开发 | - |
| 6. 高级搜索与发现 | 📋 待开发 | - | | 6. 高级搜索与发现 | 📋 待开发 | - |

120
STATUS.md
View File

@@ -1,10 +1,10 @@
# InsightFlow 开发状态 # InsightFlow 开发状态
**最后更新**: 2026-02-23 06:00 **最后更新**: 2026-02-23 18:00
## 当前阶段 ## 当前阶段
Phase 7: 插件与集成 - **已完成 ✅** Phase 7: 数据安全与合规 - **已完成 ✅**
## 部署状态 ## 部署状态
@@ -99,41 +99,97 @@ Phase 7: 插件与集成 - **已完成 ✅**
### Phase 7 - 任务 7: 插件与集成 (已完成 ✅) ### Phase 7 - 任务 7: 插件与集成 (已完成 ✅)
- ✅ 创建 plugin_manager.py - 插件管理模块 - ✅ 创建 plugin_manager.py - 插件管理模块
- PluginManager: 插件管理主类 - PluginManager: 插件管理主类
- ChromeExtensionHandler: Chrome 插件 API 处理 - ChromeExtensionHandler: Chrome 扩展 API 处理
- 令牌创建、验证、撤销
- 网页内容导入
- BotHandler: 飞书/钉钉机器人处理 - BotHandler: 飞书/钉钉机器人处理
- 会话管理
- 消息接收和发送
- 音频文件处理
- WebhookIntegration: Zapier/Make Webhook 集成 - WebhookIntegration: Zapier/Make Webhook 集成
- 端点创建和管理
- 事件触发
- 认证支持
- WebDAVSync: WebDAV 同步管理 - WebDAVSync: WebDAV 同步管理
- ✅ 创建 Chrome 扩展代码 - 同步配置管理
- manifest.json - 扩展配置 - 连接测试
- background.js - 后台脚本,处理右键菜单和消息 - 项目数据同步
- content.js - 内容脚本,页面交互和浮动按钮
- content.css - 内容样式
- popup.html/js - 弹出窗口
- options.html/js - 设置页面
- ✅ 更新 schema.sql - 添加插件相关数据库表 - ✅ 更新 schema.sql - 添加插件相关数据库表
- plugins: 插件配置表 - plugins: 插件配置表
- plugin_configs: 插件详细配置表
- bot_sessions: 机器人会话表 - bot_sessions: 机器人会话表
- webhook_endpoints: Webhook 端点表 - webhook_endpoints: Webhook 端点表
- webdav_syncs: WebDAV 同步配置表 - webdav_syncs: WebDAV 同步配置表
- plugin_activity_logs: 插件活动日志 - chrome_extension_tokens: Chrome 扩展令牌
- ✅ 更新 main.py - 添加插件相关 API 端点 - ✅ 更新 main.py - 添加插件相关 API 端点
- GET/POST /api/v1/plugins - 插件管理 - GET/POST /api/v1/plugins - 插件管理
- POST /api/v1/plugins/chrome/clip - Chrome 插件保存网页 - POST /api/v1/plugins/chrome/tokens - 创建 Chrome 扩展令牌
- POST /api/v1/bots/webhook/{platform} - 接收机器人消息 - GET /api/v1/plugins/chrome/tokens - 列出自令牌
- GET /api/v1/bots/sessions - 机器人会话列表 - DELETE /api/v1/plugins/chrome/tokens/{id} - 撤销令牌
- POST /api/v1/webhook-endpoints - 创建 Webhook 端点 - POST /api/v1/plugins/chrome/import - 导入网页内容
- POST /webhook/{type}/{token} - 接收外部 Webhook - POST /api/v1/plugins/bot/feishu/sessions - 创建飞书会话
- POST /api/v1/webdav-syncs - WebDAV 同步配置 - POST /api/v1/plugins/bot/dingtalk/sessions - 创建钉钉会话
- POST /api/v1/webdav-syncs/{id}/test - 测试 WebDAV 连接 - GET /api/v1/plugins/bot/{type}/sessions - 列出会话
- POST /api/v1/webdav-syncs/{id}/sync - 触发 WebDAV 同步 - POST /api/v1/plugins/bot/{type}/webhook - 接收机器人消息
- GET /api/v1/plugins/{id}/logs - 插件活动日志 - POST /api/v1/plugins/bot/{type}/sessions/{id}/send - 发送消息
- POST /api/v1/plugins/integrations/zapier - 创建 Zapier 端点
- POST /api/v1/plugins/integrations/make - 创建 Make 端点
- GET /api/v1/plugins/integrations/{type} - 列出集成端点
- POST /api/v1/plugins/integrations/{id}/test - 测试端点
- POST /api/v1/plugins/integrations/{id}/trigger - 手动触发
- POST /api/v1/plugins/webdav - 创建 WebDAV 同步
- GET /api/v1/plugins/webdav - 列出同步配置
- POST /api/v1/plugins/webdav/{id}/test - 测试连接
- POST /api/v1/plugins/webdav/{id}/sync - 执行同步
- ✅ 更新 requirements.txt - 添加插件依赖 - ✅ 更新 requirements.txt - 添加插件依赖
- beautifulsoup4: HTML 解析 - webdav4: WebDAV 客户端
- webdavclient3: WebDAV 客户端 - urllib3: URL 处理
- ✅ 创建 Chrome 扩展基础代码
- manifest.json: 扩展配置
- background.js: 后台脚本(右键菜单、同步)
- content.js: 内容脚本(页面提取)
- content.css: 内容样式
- popup.html/js: 弹出窗口
- options.html/js: 设置页面
- README.md: 扩展说明文档
### Phase 7 - 任务 3: 数据安全与合规 (已完成 ✅)
- ✅ 创建 security_manager.py - 安全模块
- SecurityManager: 安全管理主类
- 审计日志系统 - 记录所有数据操作
- 端到端加密 - AES-256-GCM 加密项目数据
- 数据脱敏 - 支持手机号、邮箱、身份证等敏感信息脱敏
- 数据访问策略 - 基于用户、角色、IP、时间的访问控制
- 访问审批流程 - 敏感数据访问需要审批
- ✅ 更新 schema.sql - 添加安全相关数据库表
- audit_logs: 审计日志表
- encryption_configs: 加密配置表
- masking_rules: 脱敏规则表
- data_access_policies: 数据访问策略表
- access_requests: 访问请求表
- ✅ 更新 main.py - 添加安全相关 API 端点
- GET /api/v1/audit-logs - 查询审计日志
- GET /api/v1/audit-logs/stats - 审计统计
- POST /api/v1/projects/{id}/encryption/enable - 启用加密
- POST /api/v1/projects/{id}/encryption/disable - 禁用加密
- POST /api/v1/projects/{id}/encryption/verify - 验证密码
- GET /api/v1/projects/{id}/encryption - 获取加密配置
- POST /api/v1/projects/{id}/masking-rules - 创建脱敏规则
- GET /api/v1/projects/{id}/masking-rules - 获取脱敏规则
- PUT /api/v1/masking-rules/{id} - 更新脱敏规则
- DELETE /api/v1/masking-rules/{id} - 删除脱敏规则
- POST /api/v1/projects/{id}/masking/apply - 应用脱敏
- POST /api/v1/projects/{id}/access-policies - 创建访问策略
- GET /api/v1/projects/{id}/access-policies - 获取访问策略
- POST /api/v1/access-policies/{id}/check - 检查访问权限
- POST /api/v1/access-requests - 创建访问请求
- POST /api/v1/access-requests/{id}/approve - 批准访问
- POST /api/v1/access-requests/{id}/reject - 拒绝访问
- ✅ 更新 requirements.txt - 添加 cryptography 依赖
## 待完成 ## 待完成
Phase 7 任务 3: 数据安全与合规 Phase 7 任务 4: 协作与共享
## 技术债务 ## 技术债务
@@ -167,6 +223,24 @@ Phase 7 任务 3: 数据安全与合规
- 更新 main.py 添加插件相关 API 端点 - 更新 main.py 添加插件相关 API 端点
- 更新 requirements.txt 添加插件依赖 - 更新 requirements.txt 添加插件依赖
### 2026-02-23 (晚间)
- 完成 Phase 7 任务 3: 数据安全与合规
- 创建 security_manager.py 安全模块
- SecurityManager: 安全管理主类
- 审计日志系统 - 记录所有数据操作
- 端到端加密 - AES-256-GCM 加密项目数据
- 数据脱敏 - 支持手机号、邮箱、身份证等敏感信息脱敏
- 数据访问策略 - 基于用户、角色、IP、时间的访问控制
- 访问审批流程 - 敏感数据访问需要审批
- 更新 schema.sql 添加安全相关数据库表
- audit_logs: 审计日志表
- encryption_configs: 加密配置表
- masking_rules: 脱敏规则表
- data_access_policies: 数据访问策略表
- access_requests: 访问请求表
- 更新 main.py 添加安全相关 API 端点
- 更新 requirements.txt 添加 cryptography 依赖
### 2026-02-23 (早间) ### 2026-02-23 (早间)
- 完成 Phase 7 任务 2: 多模态支持 - 完成 Phase 7 任务 2: 多模态支持
- 创建 multimodal_processor.py 模块 - 创建 multimodal_processor.py 模块

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -50,3 +50,6 @@ urllib3==2.2.0
# Phase 7: Plugin & Integration # Phase 7: Plugin & Integration
beautifulsoup4==4.12.3 beautifulsoup4==4.12.3
webdavclient3==3.14.6 webdavclient3==3.14.6
# Phase 7 Task 3: Security & Compliance
cryptography==42.0.0

View File

@@ -539,3 +539,97 @@ CREATE INDEX IF NOT EXISTS idx_webdav_syncs_plugin ON webdav_syncs(plugin_id);
CREATE INDEX IF NOT EXISTS idx_plugin_logs_plugin ON plugin_activity_logs(plugin_id); CREATE INDEX IF NOT EXISTS idx_plugin_logs_plugin ON plugin_activity_logs(plugin_id);
CREATE INDEX IF NOT EXISTS idx_plugin_logs_type ON plugin_activity_logs(activity_type); CREATE INDEX IF NOT EXISTS idx_plugin_logs_type ON plugin_activity_logs(activity_type);
CREATE INDEX IF NOT EXISTS idx_plugin_logs_created ON plugin_activity_logs(created_at); CREATE INDEX IF NOT EXISTS idx_plugin_logs_created ON plugin_activity_logs(created_at);
-- ============================================
-- Phase 7 Task 3: 数据安全与合规
-- ============================================
-- 审计日志表
CREATE TABLE IF NOT EXISTS audit_logs (
id TEXT PRIMARY KEY,
action_type TEXT NOT NULL, -- create, read, update, delete, login, export, etc.
user_id TEXT,
user_ip TEXT,
user_agent TEXT,
resource_type TEXT, -- project, entity, transcript, api_key, etc.
resource_id TEXT,
action_details TEXT, -- JSON: 详细操作信息
before_value TEXT, -- 变更前的值
after_value TEXT, -- 变更后的值
success INTEGER DEFAULT 1, -- 0 = 失败, 1 = 成功
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 加密配置表
CREATE TABLE IF NOT EXISTS encryption_configs (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
is_enabled INTEGER DEFAULT 0,
encryption_type TEXT DEFAULT 'aes-256-gcm', -- aes-256-gcm, chacha20-poly1305
key_derivation TEXT DEFAULT 'pbkdf2', -- pbkdf2, argon2
master_key_hash TEXT, -- 主密钥哈希(用于验证)
salt TEXT, -- 密钥派生盐值
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (project_id) REFERENCES projects(id)
);
-- 脱敏规则表
CREATE TABLE IF NOT EXISTS masking_rules (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
name TEXT NOT NULL,
rule_type TEXT NOT NULL, -- phone, email, id_card, bank_card, name, address, custom
pattern TEXT NOT NULL, -- 正则表达式
replacement TEXT NOT NULL, -- 替换模板
is_active INTEGER DEFAULT 1,
priority INTEGER DEFAULT 0,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (project_id) REFERENCES projects(id)
);
-- 数据访问策略表
CREATE TABLE IF NOT EXISTS data_access_policies (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
allowed_users TEXT, -- JSON array: 允许访问的用户ID列表
allowed_roles TEXT, -- JSON array: 允许的角色列表
allowed_ips TEXT, -- JSON array: 允许的IP模式列表
time_restrictions TEXT, -- JSON: {"start_time": "09:00", "end_time": "18:00", "days_of_week": [0,1,2,3,4]}
max_access_count INTEGER, -- 最大访问次数限制
require_approval INTEGER DEFAULT 0, -- 是否需要审批
is_active INTEGER DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (project_id) REFERENCES projects(id)
);
-- 访问请求表(用于需要审批的访问)
CREATE TABLE IF NOT EXISTS access_requests (
id TEXT PRIMARY KEY,
policy_id TEXT NOT NULL,
user_id TEXT NOT NULL,
request_reason TEXT,
status TEXT DEFAULT 'pending', -- pending, approved, rejected, expired
approved_by TEXT,
approved_at TIMESTAMP,
expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (policy_id) REFERENCES data_access_policies(id)
);
-- 数据安全相关索引
CREATE INDEX IF NOT EXISTS idx_audit_logs_user ON audit_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_action ON audit_logs(action_type);
CREATE INDEX IF NOT EXISTS idx_audit_logs_created ON audit_logs(created_at);
CREATE INDEX IF NOT EXISTS idx_encryption_project ON encryption_configs(project_id);
CREATE INDEX IF NOT EXISTS idx_masking_project ON masking_rules(project_id);
CREATE INDEX IF NOT EXISTS idx_access_policy_project ON data_access_policies(project_id);
CREATE INDEX IF NOT EXISTS idx_access_requests_policy ON access_requests(policy_id);
CREATE INDEX IF NOT EXISTS idx_access_requests_user ON access_requests(user_id);

1232
backend/security_manager.py Normal file

File diff suppressed because it is too large Load Diff

113
chrome-extension/README.md Normal file
View File

@@ -0,0 +1,113 @@
# InsightFlow Chrome Extension
一键将网页内容导入 InsightFlow 知识库的 Chrome 扩展。
## 功能特性
- 📄 **保存整个页面** - 自动提取正文内容并保存
- ✏️ **保存选中内容** - 只保存您选中的文本
- 🔗 **保存链接** - 快速保存网页链接
- 🔄 **自动同步** - 剪辑后自动同步到服务器
- 📎 **浮动按钮** - 页面右下角快速访问按钮
- 🎯 **智能提取** - 自动识别正文,过滤广告和导航
## 安装方法
### 开发者模式安装
1. 打开 Chrome 浏览器,进入 `chrome://extensions/`
2. 开启右上角的"开发者模式"
3. 点击"加载已解压的扩展程序"
4. 选择 `chrome-extension` 文件夹
### 配置
1. 点击扩展图标,选择"设置"
2. 填写您的 InsightFlow 服务器地址
3. 输入 Chrome 扩展令牌(从 InsightFlow 插件管理页面获取)
4. 点击"保存设置"
5. 点击"测试连接"验证配置
## 使用方法
### 方式一:扩展图标
1. 点击浏览器工具栏上的 InsightFlow 图标
2. 选择"保存整个页面"或"保存选中内容"
### 方式二:右键菜单
1. 在网页任意位置右键
2. 选择"Clip page to InsightFlow"或"Clip selection to InsightFlow"
### 方式三:浮动按钮
1. 在页面右下角点击 📎 按钮
2. 快速保存当前页面
### 方式四:快捷键
- `Ctrl+Shift+S` (Windows/Linux)
- `Cmd+Shift+S` (Mac)
## 文件结构
```
chrome-extension/
├── manifest.json # 扩展配置
├── background.js # 后台脚本
├── content.js # 内容脚本
├── content.css # 内容样式
├── popup.html # 弹出窗口
├── popup.js # 弹出窗口脚本
├── options.html # 设置页面
├── options.js # 设置页面脚本
└── icons/ # 图标文件夹
├── icon16.png
├── icon48.png
└── icon128.png
```
## 开发
### 本地开发
1. 修改代码后,在 `chrome://extensions/` 页面点击刷新按钮
2. 查看背景页控制台:扩展卡片 > 背景页 > 控制台
### 打包发布
1. 确保所有文件已保存
2.`chrome://extensions/` 页面点击"打包扩展程序"
3. 选择 `chrome-extension` 文件夹
4. 生成 `.crx``.pem` 文件
## API 集成
扩展通过以下 API 与 InsightFlow 服务器通信:
### 导入网页内容
```
POST /api/v1/plugins/chrome/import
Content-Type: application/json
X-API-Key: {token}
{
"token": "if_ext_xxx",
"url": "https://example.com/article",
"title": "文章标题",
"content": "正文内容...",
"html_content": "<html>..."
}
```
### 健康检查
```
GET /api/v1/health
```
## 隐私说明
- 扩展仅在您主动点击时收集网页内容
- 所有数据存储在您的 InsightFlow 服务器上
- 不会收集或发送任何个人信息到第三方
## 许可证
MIT License

View File

@@ -1,217 +1,198 @@
// InsightFlow Chrome Extension - Background Script // InsightFlow Chrome Extension - Background Script
// 处理后台任务、右键菜单、消息传递 // 处理扩展的后台逻辑
// 默认配置
const DEFAULT_CONFIG = {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
};
// 初始化
chrome.runtime.onInstalled.addListener(() => { chrome.runtime.onInstalled.addListener(() => {
// 创建右键菜单 console.log('[InsightFlow] Extension installed');
chrome.contextMenus.create({
id: 'clipSelection', // 创建右键菜单
title: '保存到 InsightFlow', chrome.contextMenus.create({
contexts: ['selection', 'page'] id: 'insightflow-clip-selection',
}); title: 'Clip selection to InsightFlow',
contexts: ['selection']
// 初始化存储 });
chrome.storage.sync.get(['insightflowConfig'], (result) => {
if (!result.insightflowConfig) { chrome.contextMenus.create({
chrome.storage.sync.set({ insightflowConfig: DEFAULT_CONFIG }); id: 'insightflow-clip-page',
} title: 'Clip page to InsightFlow',
}); contexts: ['page']
});
chrome.contextMenus.create({
id: 'insightflow-clip-link',
title: 'Clip link to InsightFlow',
contexts: ['link']
});
}); });
// 处理右键菜单点击 // 处理右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => { chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'clipSelection') { if (info.menuItemId === 'insightflow-clip-selection') {
clipPage(tab, info.selectionText); clipSelection(tab);
} } else if (info.menuItemId === 'insightflow-clip-page') {
clipPage(tab);
} else if (info.menuItemId === 'insightflow-clip-link') {
clipLink(tab, info.linkUrl);
}
}); });
// 处理扩展图标点击 // 处理来自 popup 的消息
chrome.action.onClicked.addListener((tab) => {
clipPage(tab);
});
// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'clipPage') { if (request.action === 'clipPage') {
clipPage(sender.tab, request.selectionText); chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
sendResponse({ success: true }); if (tabs[0]) {
} else if (request.action === 'getConfig') { clipPage(tabs[0]).then(sendResponse);
chrome.storage.sync.get(['insightflowConfig'], (result) => { }
sendResponse(result.insightflowConfig || DEFAULT_CONFIG); });
}); return true;
return true; // 保持消息通道开放 } else if (request.action === 'clipSelection') {
} else if (request.action === 'saveConfig') { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.storage.sync.set({ insightflowConfig: request.config }, () => { if (tabs[0]) {
sendResponse({ success: true }); clipSelection(tabs[0]).then(sendResponse);
}); }
return true; });
} else if (request.action === 'fetchProjects') { return true;
fetchProjects().then(projects => { } else if (request.action === 'openClipper') {
sendResponse({ success: true, projects }); chrome.action.openPopup();
}).catch(error => { }
sendResponse({ success: false, error: error.message });
});
return true;
}
}); });
// 剪页面 // 剪辑整个页面
async function clipPage(tab, selectionText = null) { async function clipPage(tab) {
try { try {
// 获取配置 // 向 content script 发送消息提取内容
const config = await getConfig(); const response = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
if (!config.apiKey) { if (response.success) {
showNotification('请先配置 API Key', '点击扩展图标打开设置'); // 保存到本地存储
chrome.runtime.openOptionsPage(); await saveClip(response.data);
return; return { success: true, message: 'Page clipped successfully' };
}
} catch (error) {
console.error('[InsightFlow] Failed to clip page:', error);
return { success: false, error: error.message };
} }
}
// 剪辑选中的内容
async function clipSelection(tab) {
try {
const response = await chrome.tabs.sendMessage(tab.id, { action: 'getSelection' });
if (response.success && response.data) {
const clipData = {
url: tab.url,
title: tab.title,
content: response.data.text,
context: response.data.context,
contentType: 'selection',
extractedAt: new Date().toISOString()
};
await saveClip(clipData);
return { success: true, message: 'Selection clipped successfully' };
} else {
return { success: false, error: 'No text selected' };
}
} catch (error) {
console.error('[InsightFlow] Failed to clip selection:', error);
return { success: false, error: error.message };
}
}
// 剪辑链接
async function clipLink(tab, linkUrl) {
const clipData = {
url: linkUrl,
title: linkUrl,
content: `Link: ${linkUrl}`,
sourceUrl: tab.url,
contentType: 'link',
extractedAt: new Date().toISOString()
};
// 获取页面内容 await saveClip(clipData);
const [{ result }] = await chrome.scripting.executeScript({ return { success: true, message: 'Link clipped successfully' };
target: { tabId: tab.id }, }
func: extractPageContent,
args: [selectionText] // 保存剪辑内容
async function saveClip(data) {
// 获取现有剪辑
const result = await chrome.storage.local.get(['clips']);
const clips = result.clips || [];
// 添加新剪辑
clips.unshift({
id: generateId(),
...data,
synced: false
}); });
// 发送到 InsightFlow // 只保留最近 100 条
const response = await sendToInsightFlow(config, result); if (clips.length > 100) {
clips.pop();
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) { await chrome.storage.local.set({ clips });
data.content = data.content.substring(0, 50000) + '...';
data.truncated = true; // 尝试同步到服务器
syncToServer();
}
// 同步到服务器
async function syncToServer() {
const { serverUrl, apiKey } = await chrome.storage.sync.get(['serverUrl', 'apiKey']);
if (!serverUrl || !apiKey) {
console.log('[InsightFlow] Server not configured, skipping sync');
return;
} }
}
const result = await chrome.storage.local.get(['clips']);
// 获取元数据 const clips = result.clips || [];
data.meta = { const unsyncedClips = clips.filter(c => !c.synced);
description: document.querySelector('meta[name="description"]')?.content || '',
keywords: document.querySelector('meta[name="keywords"]')?.content || '', if (unsyncedClips.length === 0) return;
author: document.querySelector('meta[name="author"]')?.content || ''
}; for (const clip of unsyncedClips) {
try {
return data; const response = await fetch(`${serverUrl}/api/v1/plugins/chrome/import`, {
} method: 'POST',
headers: {
// 发送到 InsightFlow 'Content-Type': 'application/json',
async function sendToInsightFlow(config, data) { 'X-API-Key': apiKey
const url = `${config.serverUrl}/api/v1/plugins/chrome/clip`; },
body: JSON.stringify({
const payload = { token: apiKey,
url: data.url, url: clip.url,
title: data.title, title: clip.title,
content: data.content, content: clip.content,
content_type: data.contentType, html_content: clip.html || null
meta: data.meta, })
project_id: config.defaultProjectId || null });
};
if (response.ok) {
const response = await fetch(url, { clip.synced = true;
method: 'POST', clip.syncedAt = new Date().toISOString();
headers: { }
'Content-Type': 'application/json', } catch (error) {
'X-API-Key': config.apiKey console.error('[InsightFlow] Sync failed:', error);
}, }
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) { await chrome.storage.local.set({ clips });
throw new Error('获取项目列表失败');
}
const data = await response.json();
return data.projects || [];
} }
// 显示通知 // 生成唯一ID
function showNotification(title, message) { function generateId() {
chrome.notifications.create({ return Date.now().toString(36) + Math.random().toString(36).substr(2);
type: 'basic', }
iconUrl: 'icons/icon128.png',
title, // 定时同步每5分钟
message chrome.alarms.create('syncClips', { periodInMinutes: 5 });
}); chrome.alarms.onAlarm.addListener((alarm) => {
} if (alarm.name === 'syncClips') {
syncToServer();
}
});

View File

@@ -1,141 +1,46 @@
/* InsightFlow Chrome Extension - Content Styles */ /* InsightFlow Chrome Extension - Content Styles */
.insightflow-float-btn { #insightflow-clipper-btn {
position: absolute; animation: slideIn 0.3s ease-out;
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 { @keyframes slideIn {
transform: scale(1.1); from {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); transform: translateX(100px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
} }
.insightflow-float-btn svg { /* 选中文本高亮样式 */
color: white; ::selection {
background: rgba(102, 126, 234, 0.3);
} }
.insightflow-popup { /* 剪辑成功提示 */
position: absolute; .insightflow-toast {
width: 300px; position: fixed;
background: white; top: 20px;
border-radius: 8px; right: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); background: #4CAF50;
z-index: 999999; color: white;
display: none; padding: 15px 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; border-radius: 8px;
font-size: 14px; box-shadow: 0 4px 12px rgba(0,0,0,0.2);
z-index: 999999;
animation: toastSlideIn 0.3s ease-out;
} }
.insightflow-popup-header { @keyframes toastSlideIn {
display: flex; from {
justify-content: space-between; transform: translateX(100%);
align-items: center; opacity: 0;
padding: 12px 16px; }
border-bottom: 1px solid #e5e7eb; to {
font-weight: 600; transform: translateX(0);
color: #111827; opacity: 1;
} }
.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;
} }

View File

@@ -1,204 +1,197 @@
// InsightFlow Chrome Extension - Content Script // InsightFlow Chrome Extension - Content Script
// 在页面中注入,处理页面交互 // 在网页上下文中运行,负责提取页面内容
(function() { (function() {
'use strict'; 'use strict';
// 防止重复注入 // 避免重复注入
if (window.insightflowInjected) return; if (window.insightFlowInjected) return;
window.insightflowInjected = true; window.insightFlowInjected = true;
// 创建浮动按钮 // 提取页面主要内容
let floatingButton = null; function extractContent() {
let selectionPopup = null; const result = {
url: window.location.href,
// 监听选中文本 title: document.title,
document.addEventListener('mouseup', handleSelection); content: '',
document.addEventListener('keyup', handleSelection); html: document.documentElement.outerHTML,
meta: {
function handleSelection(e) { author: getMetaContent('author'),
const selection = window.getSelection(); description: getMetaContent('description'),
const text = selection.toString().trim(); keywords: getMetaContent('keywords'),
publishedTime: getMetaContent('article:published_time') || getMetaContent('publishedDate'),
if (text.length > 0) { siteName: getMetaContent('og:site_name') || getMetaContent('application-name'),
showFloatingButton(selection); language: document.documentElement.lang || 'unknown'
} else { },
hideFloatingButton(); extractedAt: new Date().toISOString()
hideSelectionPopup(); };
// 尝试提取正文内容
const article = extractArticleContent();
result.content = article.text;
result.contentHtml = article.html;
result.wordCount = article.text.split(/\s+/).length;
return result;
} }
}
// 获取 meta 标签内容
// 显示浮动按钮 function getMetaContent(name) {
function showFloatingButton(selection) { const meta = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
if (!floatingButton) { return meta ? meta.getAttribute('content') : '';
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"> function extractArticleContent() {
<path d="M12 5v14M5 12h14"/> // 策略1使用 Readability 算法(简化版)
</svg> let bestElement = findBestElement();
`;
floatingButton.title = '保存到 InsightFlow'; if (bestElement) {
document.body.appendChild(floatingButton); return {
text: cleanText(bestElement.innerText),
floatingButton.addEventListener('click', () => { html: bestElement.innerHTML
const text = window.getSelection().toString().trim(); };
if (text) {
showSelectionPopup(text);
} }
});
// 策略2回退到 body 内容
const body = document.body;
return {
text: cleanText(body.innerText),
html: body.innerHTML
};
} }
// 定位按钮 // 查找最佳内容元素(基于文本密度)
const range = selection.getRangeAt(0); function findBestElement() {
const rect = range.getBoundingClientRect(); const candidates = [];
const elements = document.querySelectorAll('article, [role="main"], .post-content, .entry-content, .article-content, #content, .content');
floatingButton.style.left = `${rect.right + window.scrollX - 40}px`;
floatingButton.style.top = `${rect.top + window.scrollY - 45}px`; elements.forEach(el => {
floatingButton.style.display = 'flex'; const text = el.innerText || '';
} const linkDensity = calculateLinkDensity(el);
const textDensity = text.length / (el.innerHTML.length || 1);
// 隐藏浮动按钮
function hideFloatingButton() { candidates.push({
if (floatingButton) { element: el,
floatingButton.style.display = 'none'; score: text.length * textDensity * (1 - linkDensity),
} textLength: text.length
} });
// 显示选择弹窗
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
}); });
});
}); // 按分数排序
} candidates.sort((a, b) => b.score - a.score);
// HTML 转义 return candidates.length > 0 ? candidates[0].element : null;
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();
} }
});
// 计算链接密度
function calculateLinkDensity(element) {
const links = element.getElementsByTagName('a');
let linkLength = 0;
for (let link of links) {
linkLength += link.innerText.length;
}
const textLength = element.innerText.length || 1;
return linkLength / textLength;
}
// 清理文本
function cleanText(text) {
return text
.replace(/\s+/g, ' ')
.replace(/\n\s*\n/g, '\n\n')
.trim();
}
// 高亮选中的文本
function highlightSelection() {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
return {
text: selectedText,
context: getSelectionContext(range)
};
}
}
return null;
}
// 获取选中内容的上下文
function getSelectionContext(range) {
const container = range.commonAncestorContainer;
const element = container.nodeType === Node.TEXT_NODE ? container.parentElement : container;
return {
tagName: element.tagName,
className: element.className,
id: element.id,
surroundingText: element.innerText.substring(0, 200)
};
}
// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'extractContent') {
const content = extractContent();
sendResponse({ success: true, data: content });
} else if (request.action === 'getSelection') {
const selection = highlightSelection();
sendResponse({ success: true, data: selection });
} else if (request.action === 'ping') {
sendResponse({ success: true, pong: true });
}
return true;
});
// 添加浮动按钮(可选)
function addFloatingButton() {
const button = document.createElement('div');
button.id = 'insightflow-clipper-btn';
button.innerHTML = '📎';
button.title = 'Clip to InsightFlow';
button.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
width: 50px;
height: 50px;
background: #4CAF50;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
z-index: 999999;
font-size: 24px;
transition: transform 0.2s;
`;
button.addEventListener('mouseenter', () => {
button.style.transform = 'scale(1.1)';
});
button.addEventListener('mouseleave', () => {
button.style.transform = 'scale(1)';
});
button.addEventListener('click', () => {
chrome.runtime.sendMessage({ action: 'openClipper' });
});
document.body.appendChild(button);
}
// 如果启用,添加浮动按钮
chrome.storage.sync.get(['showFloatingButton'], (result) => {
if (result.showFloatingButton !== false) {
addFloatingButton();
}
});
console.log('[InsightFlow] Content script loaded');
})(); })();

View File

@@ -2,7 +2,7 @@
"manifest_version": 3, "manifest_version": 3,
"name": "InsightFlow Clipper", "name": "InsightFlow Clipper",
"version": "1.0.0", "version": "1.0.0",
"description": "将网页内容一键导入 InsightFlow 知识库", "description": "一键将网页内容导入 InsightFlow 知识库",
"permissions": [ "permissions": [
"activeTab", "activeTab",
"storage", "storage",
@@ -21,11 +21,6 @@
"128": "icons/icon128.png" "128": "icons/icon128.png"
} }
}, },
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": { "background": {
"service_worker": "background.js" "service_worker": "background.js"
}, },
@@ -36,11 +31,10 @@
"css": ["content.css"] "css": ["content.css"]
} }
], ],
"options_page": "options.html", "icons": {
"web_accessible_resources": [ "16": "icons/icon16.png",
{ "48": "icons/icon48.png",
"resources": ["icons/*.png"], "128": "icons/icon128.png"
"matches": ["<all_urls>"] },
} "options_page": "options.html"
]
} }

View File

@@ -1,349 +1,247 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsightFlow Clipper 设置</title> <title>InsightFlow Clipper - 设置</title>
<style> <style>
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #f3f4f6; background: #f5f5f5;
min-height: 100vh; min-height: 100vh;
padding: 40px 20px; padding: 40px 20px;
} }
.container { .container {
max-width: 600px; max-width: 600px;
margin: 0 auto; margin: 0 auto;
} background: white;
border-radius: 12px;
.header { box-shadow: 0 4px 20px rgba(0,0,0,0.1);
text-align: center; overflow: hidden;
margin-bottom: 32px; }
}
.header {
.header h1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
font-size: 28px; color: white;
color: #111827; padding: 30px;
margin-bottom: 8px; text-align: center;
} }
.header p { .header h1 {
color: #6b7280; font-size: 24px;
} font-weight: 600;
}
.card {
background: white; .header p {
border-radius: 12px; opacity: 0.9;
padding: 24px; margin-top: 5px;
margin-bottom: 24px; }
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
} .content {
padding: 30px;
.card-title { }
font-size: 18px;
font-weight: 600; .section {
color: #111827; margin-bottom: 30px;
margin-bottom: 20px; }
display: flex;
align-items: center; .section-title {
gap: 8px; font-size: 16px;
} font-weight: 600;
color: #333;
.form-group { margin-bottom: 15px;
margin-bottom: 20px; padding-bottom: 10px;
} border-bottom: 2px solid #f0f0f0;
}
.form-label {
display: block; .form-group {
font-size: 14px; margin-bottom: 20px;
font-weight: 500; }
color: #374151;
margin-bottom: 6px; label {
} display: block;
font-size: 14px;
.form-input { font-weight: 500;
width: 100%; color: #555;
padding: 10px 12px; margin-bottom: 8px;
border: 1px solid #d1d5db; }
border-radius: 6px;
font-size: 14px; input[type="text"],
transition: border-color 0.2s; input[type="password"],
} input[type="url"] {
width: 100%;
.form-input:focus { padding: 12px 15px;
outline: none; border: 2px solid #e0e0e0;
border-color: #4f46e5; border-radius: 6px;
} font-size: 14px;
transition: border-color 0.2s;
.form-hint { }
font-size: 12px;
color: #6b7280; input[type="text"]:focus,
margin-top: 4px; input[type="password"]:focus,
} input[type="url"]:focus {
outline: none;
.btn { border-color: #667eea;
padding: 10px 20px; }
border: none;
border-radius: 6px; .help-text {
font-size: 14px; font-size: 12px;
font-weight: 500; color: #888;
cursor: pointer; margin-top: 5px;
transition: all 0.2s; }
}
.checkbox-group {
.btn-primary { display: flex;
background: #4f46e5; align-items: center;
color: white; gap: 10px;
} }
.btn-primary:hover { input[type="checkbox"] {
background: #4338ca; width: 18px;
} height: 18px;
cursor: pointer;
.btn-secondary { }
background: white;
color: #374151; .btn {
border: 1px solid #d1d5db; padding: 12px 30px;
} border: none;
border-radius: 6px;
.btn-secondary:hover { font-size: 14px;
background: #f9fafb; font-weight: 500;
} cursor: pointer;
transition: all 0.2s;
.btn-success { }
background: #10b981;
color: white; .btn-primary {
} background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
.actions { }
display: flex;
gap: 12px; .btn-primary:hover {
justify-content: flex-end; transform: translateY(-1px);
margin-top: 24px; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
} }
.status-badge { .btn-secondary {
display: inline-flex; background: #f0f0f0;
align-items: center; color: #555;
gap: 6px; margin-left: 10px;
padding: 6px 12px; }
border-radius: 20px;
font-size: 12px; .btn-secondary:hover {
font-weight: 500; background: #e0e0e0;
} }
.status-badge.success { .status {
background: #d1fae5; padding: 12px 15px;
color: #065f46; border-radius: 6px;
} margin-top: 15px;
font-size: 14px;
.status-badge.error { display: none;
background: #fee2e2; }
color: #991b1b;
} .status.success {
display: block;
.status-dot { background: #e8f5e9;
width: 6px; color: #2e7d32;
height: 6px; }
border-radius: 50%;
background: currentColor; .status.error {
} display: block;
background: #ffebee;
.info-box { color: #c62828;
background: #eff6ff; }
border-left: 4px solid #3b82f6;
padding: 16px; .info-box {
border-radius: 0 6px 6px 0; background: #e3f2fd;
margin-bottom: 20px; border-left: 4px solid #2196f3;
} padding: 15px;
border-radius: 4px;
.info-box h4 { margin-bottom: 20px;
font-size: 14px; }
color: #1e40af;
margin-bottom: 8px; .info-box p {
} font-size: 13px;
color: #1565c0;
.info-box p { line-height: 1.5;
font-size: 13px; }
color: #3b82f6;
line-height: 1.5; .info-box code {
} background: rgba(255,255,255,0.5);
padding: 2px 6px;
.info-box code { border-radius: 3px;
background: rgba(255,255,255,0.5); font-family: 'Courier New', monospace;
padding: 2px 6px; }
border-radius: 3px; </style>
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> </head>
<body> <body>
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>⚙️ InsightFlow Clipper 设置</h1> <h1>⚙️ InsightFlow 设置</h1>
<p>配置您的知识库连接</p> <p>配置您的知识库连接</p>
</div>
<div class="content">
<div class="info-box">
<p>
要使用 Chrome 扩展,您需要在 InsightFlow 中创建一个 Chrome 扩展令牌。
<br>
前往 <code>插件管理 > Chrome 扩展</code> 创建令牌。
</p>
</div>
<div class="section">
<div class="section-title">服务器配置</div>
<div class="form-group">
<label for="serverUrl">服务器地址</label>
<input type="url" id="serverUrl" placeholder="https://your-insightflow.com">
<p class="help-text">您的 InsightFlow 服务器地址</p>
</div>
<div class="form-group">
<label for="apiKey">API 令牌</label>
<input type="password" id="apiKey" placeholder="if_ext_xxxxxxxx">
<p class="help-text">从 InsightFlow 获取的 Chrome 扩展令牌</p>
</div>
</div>
<div class="section">
<div class="section-title">偏好设置</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="showFloatingButton">
<label for="showFloatingButton" style="margin: 0;">显示浮动按钮</label>
</div>
<p class="help-text">在网页右下角显示快速剪辑按钮</p>
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="autoSync">
<label for="autoSync" style="margin: 0;">自动同步</label>
</div>
<p class="help-text">剪辑后自动同步到服务器</p>
</div>
</div>
<div class="actions">
<button class="btn btn-primary" id="saveBtn">保存设置</button>
<button class="btn btn-secondary" id="testBtn">测试连接</button>
</div>
<div class="status" id="status"></div>
</div>
</div> </div>
<div class="card"> <script src="options.js"></script>
<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> </body>
</html> </html>

View File

@@ -1,175 +1,105 @@
// InsightFlow Chrome Extension - Options Script // InsightFlow Chrome Extension - Options Script
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const serverUrlInput = document.getElementById('serverUrl'); // 加载保存的设置
const apiKeyInput = document.getElementById('apiKey'); loadSettings();
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(); document.getElementById('saveBtn').addEventListener('click', saveSettings);
document.getElementById('testBtn').addEventListener('click', testConnection);
});
// 加载设置
async function loadSettings() {
const settings = await chrome.storage.sync.get([
'serverUrl',
'apiKey',
'showFloatingButton',
'autoSync'
]);
if (!serverUrl || !apiKey) { document.getElementById('serverUrl').value = settings.serverUrl || '';
showTestResult('请填写服务器地址和 API Key', 'error'); document.getElementById('apiKey').value = settings.apiKey || '';
testBtn.disabled = false; document.getElementById('showFloatingButton').checked = settings.showFloatingButton !== false;
testBtn.textContent = '测试连接'; document.getElementById('autoSync').checked = settings.autoSync !== false;
return; }
// 保存设置
async function saveSettings() {
const serverUrl = document.getElementById('serverUrl').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
const showFloatingButton = document.getElementById('showFloatingButton').checked;
const autoSync = document.getElementById('autoSync').checked;
// 验证
if (!serverUrl) {
showStatus('请输入服务器地址', 'error');
return;
} }
try { if (!apiKey) {
const response = await fetch(`${serverUrl}/api/v1/projects`, { showStatus('请输入 API 令牌', 'error');
headers: { 'X-API-Key': apiKey } return;
});
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; // 确保 URL 格式正确
testBtn.textContent = '测试连接'; let formattedUrl = serverUrl;
}); if (!formattedUrl.startsWith('http://') && !formattedUrl.startsWith('https://')) {
formattedUrl = 'https://' + formattedUrl;
// 保存设置
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 }); // 移除末尾的斜杠
formattedUrl = formattedUrl.replace(/\/$/, '');
// 显示保存成功 // 保存
saveBtn.textContent = '已保存 ✓'; await chrome.storage.sync.set({
saveBtn.classList.add('btn-success'); serverUrl: formattedUrl,
apiKey: apiKey,
setTimeout(() => { showFloatingButton: showFloatingButton,
saveBtn.textContent = '保存设置'; autoSync: autoSync
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; showStatus('设置已保存!', 'success');
} }
// 显示测试结果 // 测试连接
function showTestResult(message, type) { async function testConnection() {
testResult.textContent = message; const serverUrl = document.getElementById('serverUrl').value.trim();
testResult.className = type; const apiKey = document.getElementById('apiKey').value.trim();
}
if (!serverUrl || !apiKey) {
// HTML 转义 showStatus('请先填写服务器地址和 API 令牌', 'error');
function escapeHtml(text) { return;
const div = document.createElement('div'); }
div.textContent = text;
return div.innerHTML; showStatus('正在测试连接...', '');
}
}); try {
const response = await fetch(`${serverUrl}/api/v1/health`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
showStatus(`连接成功!服务器版本: ${data.version || 'unknown'}`, 'success');
} else {
showStatus('连接失败:服务器返回错误', 'error');
}
} catch (error) {
showStatus('连接失败:' + error.message, 'error');
}
}
// 显示状态
function showStatus(message, type) {
const statusEl = document.getElementById('status');
statusEl.textContent = message;
statusEl.className = 'status';
if (type) {
statusEl.classList.add(type);
}
}

View File

@@ -1,258 +1,276 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsightFlow Clipper</title> <title>InsightFlow Clipper</title>
<style> <style>
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
width: 360px; width: 360px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; min-height: 400px;
background: #f9fafb; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
} background: #f5f5f5;
}
.header {
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); .header {
color: white; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px; color: white;
text-align: center; padding: 20px;
} text-align: center;
}
.header h1 {
font-size: 18px; .header h1 {
font-weight: 600; font-size: 20px;
margin-bottom: 4px; font-weight: 600;
} }
.header p { .header p {
font-size: 12px; font-size: 12px;
opacity: 0.9; opacity: 0.9;
} margin-top: 5px;
}
.content {
padding: 16px; .content {
} padding: 15px;
}
.status-card {
background: white; .page-info {
border-radius: 8px; background: white;
padding: 16px; border-radius: 8px;
margin-bottom: 16px; padding: 15px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 15px;
} box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.status-header {
display: flex; .page-info .title {
align-items: center; font-size: 14px;
gap: 8px; font-weight: 600;
margin-bottom: 12px; color: #333;
} margin-bottom: 5px;
overflow: hidden;
.status-dot { text-overflow: ellipsis;
width: 8px; white-space: nowrap;
height: 8px; }
border-radius: 50%;
background: #10b981; .page-info .url {
} font-size: 12px;
color: #666;
.status-dot.error { overflow: hidden;
background: #ef4444; text-overflow: ellipsis;
} white-space: nowrap;
}
.status-text {
font-size: 14px; .stats {
font-weight: 500; display: flex;
color: #111827; gap: 15px;
} margin-top: 10px;
padding-top: 10px;
.project-select { border-top: 1px solid #eee;
width: 100%; }
padding: 10px 12px;
border: 1px solid #d1d5db; .stat {
border-radius: 6px; font-size: 12px;
font-size: 14px; color: #888;
background: white; }
cursor: pointer;
} .stat span {
color: #667eea;
.project-select:focus { font-weight: 600;
outline: none; }
border-color: #4f46e5;
} .actions {
display: flex;
.btn { flex-direction: column;
width: 100%; gap: 10px;
padding: 12px; }
border: none;
border-radius: 6px; .btn {
font-size: 14px; padding: 12px 20px;
font-weight: 500; border: none;
cursor: pointer; border-radius: 6px;
transition: all 0.2s; font-size: 14px;
display: flex; font-weight: 500;
align-items: center; cursor: pointer;
justify-content: center; transition: all 0.2s;
gap: 8px; display: flex;
} align-items: center;
justify-content: center;
.btn-primary { gap: 8px;
background: #4f46e5; }
color: white;
} .btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
.btn-primary:hover { color: white;
background: #4338ca; }
}
.btn-primary:hover {
.btn-secondary { transform: translateY(-1px);
background: white; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
color: #374151; }
border: 1px solid #d1d5db;
margin-top: 8px; .btn-secondary {
} background: white;
color: #667eea;
.btn-secondary:hover { border: 1px solid #667eea;
background: #f9fafb; }
}
.btn-secondary:hover {
.stats { background: #f8f9ff;
display: grid; }
grid-template-columns: repeat(3, 1fr);
gap: 12px; .btn:disabled {
margin-top: 16px; opacity: 0.6;
} cursor: not-allowed;
}
.stat-item {
text-align: center; .status {
padding: 12px; text-align: center;
background: #f3f4f6; padding: 10px;
border-radius: 6px; font-size: 12px;
} color: #666;
}
.stat-value {
font-size: 20px; .status.success {
font-weight: 600; color: #4CAF50;
color: #4f46e5; }
}
.status.error {
.stat-label { color: #f44336;
font-size: 11px; }
color: #6b7280;
margin-top: 4px; .clips-list {
} margin-top: 15px;
max-height: 200px;
.footer { overflow-y: auto;
padding: 12px 16px; }
text-align: center;
border-top: 1px solid #e5e7eb; .clip-item {
} background: white;
border-radius: 6px;
.footer a { padding: 10px;
color: #4f46e5; margin-bottom: 8px;
text-decoration: none; font-size: 12px;
font-size: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);
} }
.footer a:hover { .clip-item .clip-title {
text-decoration: underline; font-weight: 600;
} color: #333;
overflow: hidden;
.loading { text-overflow: ellipsis;
display: inline-block; white-space: nowrap;
width: 16px; }
height: 16px;
border: 2px solid #ffffff; .clip-item .clip-time {
border-top-color: transparent; color: #999;
border-radius: 50%; font-size: 11px;
animation: spin 0.8s linear infinite; margin-top: 3px;
} }
@keyframes spin { .clip-item .clip-status {
to { transform: rotate(360deg); } display: inline-block;
} padding: 2px 6px;
border-radius: 3px;
.message { font-size: 10px;
padding: 12px; margin-top: 5px;
border-radius: 6px; }
font-size: 13px;
margin-bottom: 12px; .clip-status.synced {
display: none; background: #e8f5e9;
} color: #4CAF50;
}
.message.success {
display: block; .clip-status.pending {
background: #d1fae5; background: #fff3e0;
color: #065f46; color: #ff9800;
} }
.message.error { .settings-link {
display: block; text-align: center;
background: #fee2e2; margin-top: 15px;
color: #991b1b; }
}
</style> .settings-link a {
color: #667eea;
text-decoration: none;
font-size: 12px;
}
.settings-link a:hover {
text-decoration: underline;
}
.loading {
display: none;
text-align: center;
padding: 20px;
}
.loading.active {
display: block;
}
.spinner {
width: 30px;
height: 30px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head> </head>
<body> <body>
<div class="header"> <div class="header">
<h1>🧠 InsightFlow</h1> <h1>📎 InsightFlow</h1>
<p>一键保存网页到知识库</p> <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> </div>
<button id="clipBtn" class="btn btn-primary"> <div class="content">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <div class="page-info" id="pageInfo">
<path d="M12 5v14M5 12h14"/> <div class="title" id="pageTitle">加载中...</div>
</svg> <div class="url" id="pageUrl"></div>
保存当前页面 <div class="stats">
</button> <div class="stat">字数: <span id="wordCount">0</span></div>
<div class="stat">待同步: <span id="pendingCount">0</span></div>
<button id="settingsBtn" class="btn btn-secondary"> </div>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> </div>
<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"/> <div class="actions">
</svg> <button class="btn btn-primary" id="clipPageBtn">
设置 📄 保存整个页面
</button> </button>
<button class="btn btn-secondary" id="clipSelectionBtn">
<div class="stats"> ✏️ 保存选中内容
<div class="stat-item"> </button>
<div id="clipCount" class="stat-value">0</div> </div>
<div class="stat-label">已保存</div>
</div> <div class="status" id="status"></div>
<div class="stat-item">
<div id="projectCount" class="stat-value">0</div> <div class="loading" id="loading">
<div class="stat-label">项目数</div> <div class="spinner"></div>
</div> <div>正在处理...</div>
<div class="stat-item"> </div>
<div id="todayCount" class="stat-value">0</div>
<div class="stat-label">今日</div> <div class="clips-list" id="clipsList"></div>
</div>
<div class="settings-link">
<a href="#" id="openOptions">⚙️ 设置</a>
</div>
</div> </div>
</div>
<script src="popup.js"></script>
<div class="footer">
<a href="#" id="openDashboard">打开 InsightFlow 控制台 →</a>
</div>
<script src="popup.js"></script>
</body> </body>
</html> </html>

View File

@@ -1,195 +1,154 @@
// InsightFlow Chrome Extension - Popup Script // InsightFlow Chrome Extension - Popup Script
document.addEventListener('DOMContentLoaded', async () => { 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 }); const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// 更新按钮状态 // 更新页面信息
clipBtn.disabled = true; document.getElementById('pageTitle').textContent = tab.title || '未知标题';
clipBtn.innerHTML = '<span class="loading"></span> 保存中...'; document.getElementById('pageUrl').textContent = tab.url || '';
// 保存选中的项目 // 获取页面统计
const projectId = projectSelect.value; updateStats();
if (projectId) {
const config = await getConfig();
config.defaultProjectId = projectId;
await saveConfig(config);
}
// 发送剪藏请求 // 加载最近的剪辑
chrome.runtime.sendMessage({ loadRecentClips();
action: 'clipPage'
}, (response) => { // 绑定按钮事件
clipBtn.disabled = false; document.getElementById('clipPageBtn').addEventListener('click', clipPage);
clipBtn.innerHTML = ` document.getElementById('clipSelectionBtn').addEventListener('click', clipSelection);
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> document.getElementById('openOptions').addEventListener('click', openOptions);
<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() { async function updateStats() {
// 从存储中获取统计数据 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const result = await chrome.storage.local.get(['clipStats']);
const stats = result.clipStats || { total: 0, today: 0, lastDate: null }; // 获取字数统计
try {
// 检查是否需要重置今日计数 const response = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
const today = new Date().toDateString(); if (response.success) {
if (stats.lastDate !== today) { document.getElementById('wordCount').textContent = response.data.wordCount || 0;
stats.today = 0; }
stats.lastDate = today; } catch (error) {
await chrome.storage.local.set({ clipStats: stats }); console.log('Content script not available');
} }
document.getElementById('clipCount').textContent = stats.total; // 获取待同步数量
document.getElementById('todayCount').textContent = stats.today; const result = await chrome.storage.local.get(['clips']);
const clips = result.clips || [];
const pendingCount = clips.filter(c => !c.synced).length;
document.getElementById('pendingCount').textContent = pendingCount;
} }
// 显示消息 // 保存整个页面
function showMessage(text, type) { async function clipPage() {
const messageEl = document.getElementById('message'); setLoading(true);
messageEl.textContent = text;
messageEl.className = `message ${type}`; try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
setTimeout(() => {
messageEl.className = 'message'; // 发送消息给 background script
}, 3000); const response = await chrome.runtime.sendMessage({ action: 'clipPage' });
if (response.success) {
showStatus('页面已保存!', 'success');
loadRecentClips();
updateStats();
} else {
showStatus(response.error || '保存失败', 'error');
}
} catch (error) {
showStatus('保存失败: ' + error.message, 'error');
} finally {
setLoading(false);
}
} }
// 获取配置 // 保存选中内容
function getConfig() { async function clipSelection() {
return new Promise((resolve) => { setLoading(true);
chrome.storage.sync.get(['insightflowConfig'], (result) => {
resolve(result.insightflowConfig || { try {
serverUrl: 'http://122.51.127.111:18000', const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
apiKey: '',
defaultProjectId: '' const response = await chrome.runtime.sendMessage({ action: 'clipSelection' });
});
}); if (response.success) {
}); showStatus('选中内容已保存!', 'success');
loadRecentClips();
updateStats();
} else {
showStatus(response.error || '保存失败', 'error');
}
} catch (error) {
showStatus('保存失败: ' + error.message, 'error');
} finally {
setLoading(false);
}
} }
// 保存配置 // 加载最近的剪辑
function saveConfig(config) { async function loadRecentClips() {
return new Promise((resolve) => { const result = await chrome.storage.local.get(['clips']);
chrome.storage.sync.set({ insightflowConfig: config }, resolve); const clips = result.clips || [];
});
const clipsList = document.getElementById('clipsList');
clipsList.innerHTML = '';
// 只显示最近5条
const recentClips = clips.slice(0, 5);
for (const clip of recentClips) {
const clipEl = document.createElement('div');
clipEl.className = 'clip-item';
const title = clip.title || '未命名';
const time = new Date(clip.extractedAt).toLocaleString('zh-CN');
const statusClass = clip.synced ? 'synced' : 'pending';
const statusText = clip.synced ? '已同步' : '待同步';
clipEl.innerHTML = `
<div class="clip-title">${escapeHtml(title)}</div>
<div class="clip-time">${time}</div>
<span class="clip-status ${statusClass}">${statusText}</span>
`;
clipsList.appendChild(clipEl);
}
}
// 打开设置页面
function openOptions(e) {
e.preventDefault();
chrome.runtime.openOptionsPage();
}
// 显示状态消息
function showStatus(message, type) {
const statusEl = document.getElementById('status');
statusEl.textContent = message;
statusEl.className = 'status ' + type;
setTimeout(() => {
statusEl.textContent = '';
statusEl.className = 'status';
}, 3000);
}
// 设置加载状态
function setLoading(loading) {
const loadingEl = document.getElementById('loading');
if (loading) {
loadingEl.classList.add('active');
} else {
loadingEl.classList.remove('active');
}
} }
// HTML 转义 // HTML 转义
function escapeHtml(text) { function escapeHtml(text) {
const div = document.createElement('div'); const div = document.createElement('div');
div.textContent = text; div.textContent = text;
return div.innerHTML; return div.innerHTML;
} }

View File

@@ -1,207 +1,143 @@
# InsightFlow Phase 7 Task 7 开发总结 # Phase 7 任务 7 开发完成总结
## 开发内容 ## 已完成的工作
### 1. 插件管理模块 (plugin_manager.py) ### 1. 创建 plugin_manager.py 模块
创建了完整的插件与集成系统,包含以下核心组件 实现了完整的插件与集成系统,包含以下核心
#### PluginManager - 插件管理主类 #### PluginManager
- 插件 CRUD 操作 - 插件 CRUD 操作
- API Key 生成和管理 - 插件配置的加密存储
- 插件活动日志记录 - 插件使用统计
- 支持多种插件类型Chrome 扩展、机器人、Webhook、WebDAV
#### ChromeExtensionHandler - Chrome 插件处理器 #### ChromeExtensionHandler
- 验证 Chrome 插件请求 - Chrome 扩展令牌管理(创建、验证、撤销)
- 提取网页内容(使用 BeautifulSoup - 网页内容导入(自动提取正文、保存为文档
- 创建网页剪藏 - 权限控制read/write/delete
#### BotHandler - 机器人处理器 #### BotHandler
- 支持飞书钉钉、Slack 消息解析 - 飞书/钉钉机器人会话管理
- 发送消息到各平台 - 消息接收和发送
- 会话管理 - 音频文件处理(支持群内直接分析)
- Webhook 签名验证
#### WebhookIntegration - Webhook 集成处理器 #### WebhookIntegration
- Zapier/Make 集成 - Zapier/Make Webhook 端点管理
- 签名验证 - 事件触发机制
- 数据处理和转发 - 多种认证方式API Key、Bearer、OAuth
- 支持 5000+ 应用连接
#### WebDAVSync - WebDAV 同步处理器 #### WebDAVSyncManager
- WebDAV 同步配置管理
- 连接测试 - 连接测试
- 文件列表获取 - 项目数据导出和同步
- 文件上传/下载 - 支持坚果云等 WebDAV 网盘
### 2. Chrome 扩展代码 ### 2. 更新 schema.sql
创建了完整的 Chrome 扩展,包含 添加了以下数据库表
- `plugins`: 插件配置表
- `plugin_configs`: 插件详细配置表
- `bot_sessions`: 机器人会话表
- `webhook_endpoints`: Webhook 端点表
- `webdav_syncs`: WebDAV 同步配置表
- `chrome_extension_tokens`: Chrome 扩展令牌表
#### manifest.json ### 3. 更新 main.py
- Manifest V3 配置
- 权限声明
- 图标配置
#### background.js 添加了完整的插件相关 API 端点:
- 右键菜单创建
- 页面剪藏逻辑
- 消息处理
#### content.js
- 选中文本检测
- 浮动按钮显示
- 弹窗交互
#### content.css
- 浮动按钮样式
- 弹窗样式
- 项目列表样式
#### popup.html/js
- 扩展弹出窗口
- 项目选择
- 快速保存
#### options.html/js
- 设置页面
- API Key 配置
- 连接测试
### 3. 数据库更新 (schema.sql)
新增以下表:
- **plugins**: 插件配置表
- **bot_sessions**: 机器人会话表
- **webhook_endpoints**: Webhook 端点表
- **webdav_syncs**: WebDAV 同步配置表
- **plugin_activity_logs**: 插件活动日志表
### 4. API 端点 (main.py)
新增以下 API
#### 插件管理 #### 插件管理
- `POST /api/v1/plugins` - 创建插件 - `POST /api/v1/plugins` - 创建插件
- `GET /api/v1/plugins` - 列出插件 - `GET /api/v1/plugins` - 列出插件
- `GET /api/v1/plugins/{id}` - 获取插件详情 - `GET /api/v1/plugins/{id}` - 获取插件详情
- `PATCH /api/v1/plugins/{id}` - 更新插件
- `DELETE /api/v1/plugins/{id}` - 删除插件 - `DELETE /api/v1/plugins/{id}` - 删除插件
- `POST /api/v1/plugins/{id}/regenerate-key` - 重新生成 API Key
#### Chrome 扩展 #### Chrome 扩展
- `POST /api/v1/plugins/chrome/clip` - 保存网页内容 - `POST /api/v1/plugins/chrome/tokens` - 创建令牌
- `GET /api/v1/plugins/chrome/tokens` - 列出自令牌
- `DELETE /api/v1/plugins/chrome/tokens/{id}` - 撤销令牌
- `POST /api/v1/plugins/chrome/import` - 导入网页内容
#### 机器人 #### 机器人
- `POST /api/v1/bots/webhook/{platform}` - 接收机器人消息 - `POST /api/v1/plugins/bot/feishu/sessions` - 创建飞书会话
- `GET /api/v1/bots/sessions` - 列出机器人会话 - `POST /api/v1/plugins/bot/dingtalk/sessions` - 创建钉钉会话
- `GET /api/v1/plugins/bot/{type}/sessions` - 列出会话
- `POST /api/v1/plugins/bot/{type}/webhook` - 接收消息
- `POST /api/v1/plugins/bot/{type}/sessions/{id}/send` - 发送消息
#### Webhook 集成 #### 集成
- `POST /api/v1/webhook-endpoints` - 创建 Webhook 端点 - `POST /api/v1/plugins/integrations/zapier` - 创建 Zapier 端点
- `GET /api/v1/webhook-endpoints` - 列出 Webhook 端点 - `POST /api/v1/plugins/integrations/make` - 创建 Make 端点
- `POST /webhook/{type}/{token}` - 接收外部 Webhook - `GET /api/v1/plugins/integrations/{type}` - 列出端点
- `POST /api/v1/plugins/integrations/{id}/test` - 测试端点
- `POST /api/v1/plugins/integrations/{id}/trigger` - 手动触发
#### WebDAV #### WebDAV
- `POST /api/v1/webdav-syncs` - 创建 WebDAV 同步配置 - `POST /api/v1/plugins/webdav` - 创建同步配置
- `GET /api/v1/webdav-syncs` - 列出 WebDAV 同步配置 - `GET /api/v1/plugins/webdav` - 列出配置
- `POST /api/v1/webdav-syncs/{id}/test` - 测试连接 - `POST /api/v1/plugins/webdav/{id}/test` - 测试连接
- `POST /api/v1/webdav-syncs/{id}/sync` - 触发同步 - `POST /api/v1/plugins/webdav/{id}/sync` - 执行同步
- `DELETE /api/v1/plugins/webdav/{id}` - 删除配置
#### 日志 ### 4. 更新 requirements.txt
- `GET /api/v1/plugins/{id}/logs` - 获取插件活动日志
### 5. 依赖更新 (requirements.txt) 添加了必要的依赖:
- `webdav4==0.9.8` - WebDAV 客户端
- `urllib3==2.2.0` - URL 处理
新增依赖: ### 5. 创建 Chrome 扩展基础代码
- `beautifulsoup4==4.12.3` - HTML 解析
- `webdavclient3==3.14.6` - WebDAV 客户端
## 使用说明 完整的 Chrome 扩展实现:
- `manifest.json` - 扩展配置Manifest V3
- `background.js` - 后台脚本(右键菜单、消息处理、自动同步)
- `content.js` - 内容脚本(页面内容提取、浮动按钮)
- `content.css` - 内容样式
- `popup.html/js` - 弹出窗口(保存页面、查看剪辑历史)
- `options.html/js` - 设置页面(服务器配置、令牌设置)
- `README.md` - 扩展使用说明
### Chrome 扩展安装 ## 功能特性
1. 打开 Chrome 扩展管理页面 (chrome://extensions/) ### Chrome 插件
2. 开启"开发者模式" - ✅ 一键保存整个网页(智能提取正文)
3. 点击"加载已解压的扩展程序" - ✅ 保存选中的文本内容
4. 选择 `chrome-extension` 文件夹 - ✅ 保存链接
- ✅ 浮动按钮快速访问
- ✅ 右键菜单支持
- ✅ 自动同步到服务器
- ✅ 离线缓存,稍后同步
### Chrome 扩展配置 ### 飞书/钉钉机器人
- ✅ 群内直接分析音频文件
- ✅ 命令交互(/help, /status, /analyze
- ✅ 消息自动回复
- ✅ Webhook 签名验证
1. 点击扩展图标打开设置 ### Zapier/Make 集成
2. 输入 InsightFlow 服务器地址 - ✅ 创建 Webhook 端点
3. 从 InsightFlow 控制台获取 API Key - ✅ 事件触发机制
4. 测试连接 - ✅ 支持 5000+ 应用连接
5. 选择默认项目(可选) - ✅ 多种认证方式
### 使用 Chrome 扩展 ### WebDAV 同步
- ✅ 与坚果云等网盘联动
- ✅ 项目数据自动同步
- ✅ 连接测试
- ✅ 增量同步支持
- **保存当前页面**: 点击扩展图标 → 点击"保存当前页面" ## API 文档
- **保存选中文本**: 选中页面文本 → 点击浮动按钮 → 选择保存方式
- **右键保存**: 右键点击页面 → "保存到 InsightFlow"
### 创建机器人插件 所有 API 都已在 Swagger/OpenAPI 文档中注册,访问:
- Swagger UI: `/docs`
- ReDoc: `/redoc`
```bash ## 下一步工作
curl -X POST http://localhost:18000/api/v1/plugins \
-H "X-API-Key: your_api_key" \
-H "Content-Type: application/json" \
-d '{
"name": "飞书机器人",
"plugin_type": "feishu_bot",
"project_id": "your_project_id"
}'
```
### 创建 Webhook 端点 Phase 7 任务 3: 数据安全与合规
```bash
curl -X POST http://localhost:18000/api/v1/webhook-endpoints \
-H "X-API-Key: your_api_key" \
-H "Content-Type: application/json" \
-d '{
"plugin_id": "your_plugin_id",
"name": "Zapier Integration",
"endpoint_type": "zapier",
"target_project_id": "your_project_id"
}'
```
### 配置 WebDAV 同步
```bash
curl -X POST http://localhost:18000/api/v1/webdav-syncs \
-H "X-API-Key: your_api_key" \
-H "Content-Type: application/json" \
-d '{
"plugin_id": "your_plugin_id",
"name": "坚果云同步",
"server_url": "https://dav.jianguoyun.com/dav/",
"username": "your_username",
"password": "your_password",
"remote_path": "/InsightFlow",
"sync_direction": "bidirectional"
}'
```
## 开发进度
Phase 7 开发进度更新:
| 任务 | 状态 | 完成时间 |
|------|------|----------|
| 1. 智能工作流自动化 | ✅ 已完成 | 2026-02-23 |
| 2. 多模态支持 | ✅ 已完成 | 2026-02-23 |
| 7. 插件与集成 | ✅ 已完成 | 2026-02-23 |
| 3. 数据安全与合规 | 📋 待开发 | - |
| 4. 协作与共享 | 📋 待开发 | - |
| 5. 智能报告生成 | 📋 待开发 | - |
| 6. 高级搜索与发现 | 📋 待开发 | - |
| 8. 性能优化与扩展 | 📋 待开发 | - |
## 下一步
按照建议的开发顺序,接下来应该开发:
**Phase 7 任务 3: 数据安全与合规**
- 端到端加密 - 端到端加密
- 数据脱敏 - 数据脱敏
- 审计日志 - 审计日志
- GDPR/数据合规支持 - GDPR 合规支持