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

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
// 处理后台任务、右键菜单、消息传递
// 处理扩展的后台逻辑
// 默认配置
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 });
}
});
console.log('[InsightFlow] Extension installed');
// 创建右键菜单
chrome.contextMenus.create({
id: 'insightflow-clip-selection',
title: 'Clip selection to InsightFlow',
contexts: ['selection']
});
chrome.contextMenus.create({
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) => {
if (info.menuItemId === 'clipSelection') {
clipPage(tab, info.selectionText);
}
if (info.menuItemId === 'insightflow-clip-selection') {
clipSelection(tab);
} else if (info.menuItemId === 'insightflow-clip-page') {
clipPage(tab);
} else if (info.menuItemId === 'insightflow-clip-link') {
clipLink(tab, info.linkUrl);
}
});
// 处理扩展图标点击
chrome.action.onClicked.addListener((tab) => {
clipPage(tab);
});
// 监听来自内容脚本的消息
// 处理来自 popup 的消息
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;
}
if (request.action === 'clipPage') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
clipPage(tabs[0]).then(sendResponse);
}
});
return true;
} else if (request.action === 'clipSelection') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
clipSelection(tabs[0]).then(sendResponse);
}
});
return true;
} else if (request.action === 'openClipper') {
chrome.action.openPopup();
}
});
// 剪页面
async function clipPage(tab, selectionText = null) {
try {
// 获取配置
const config = await getConfig();
if (!config.apiKey) {
showNotification('请先配置 API Key', '点击扩展图标打开设置');
chrome.runtime.openOptionsPage();
return;
// 剪辑整个页面
async function clipPage(tab) {
try {
// 向 content script 发送消息提取内容
const response = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
if (response.success) {
// 保存到本地存储
await saveClip(response.data);
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()
};
// 获取页面内容
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractPageContent,
args: [selectionText]
await saveClip(clipData);
return { success: true, message: 'Link clipped successfully' };
}
// 保存剪辑内容
async function saveClip(data) {
// 获取现有剪辑
const result = await chrome.storage.local.get(['clips']);
const clips = result.clips || [];
// 添加新剪辑
clips.unshift({
id: generateId(),
...data,
synced: false
});
// 发送到 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';
// 只保留最近 100 条
if (clips.length > 100) {
clips.pop();
}
// 限制内容长度
if (data.content.length > 50000) {
data.content = data.content.substring(0, 50000) + '...';
data.truncated = true;
// 保存
await chrome.storage.local.set({ clips });
// 尝试同步到服务器
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;
}
}
// 获取元数据
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
const result = await chrome.storage.local.get(['clips']);
const clips = result.clips || [];
const unsyncedClips = clips.filter(c => !c.synced);
if (unsyncedClips.length === 0) return;
for (const clip of unsyncedClips) {
try {
const response = await fetch(`${serverUrl}/api/v1/plugins/chrome/import`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({
token: apiKey,
url: clip.url,
title: clip.title,
content: clip.content,
html_content: clip.html || null
})
});
if (response.ok) {
clip.synced = true;
clip.syncedAt = new Date().toISOString();
}
} catch (error) {
console.error('[InsightFlow] Sync failed:', error);
}
}
});
if (!response.ok) {
throw new Error('获取项目列表失败');
}
const data = await response.json();
return data.projects || [];
// 更新存储
await chrome.storage.local.set({ clips });
}
// 显示通知
function showNotification(title, message) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title,
message
});
}
// 生成唯一ID
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
// 定时同步每5分钟
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-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-clipper-btn {
animation: slideIn 0.3s ease-out;
}
.insightflow-float-btn:hover {
transform: scale(1.1);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
@keyframes slideIn {
from {
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;
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-toast {
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 15px 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
z-index: 999999;
animation: toastSlideIn 0.3s ease-out;
}
.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;
@keyframes toastSlideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}

View File

@@ -1,204 +1,197 @@
// 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();
'use strict';
// 避免重复注入
if (window.insightFlowInjected) return;
window.insightFlowInjected = true;
// 提取页面主要内容
function extractContent() {
const result = {
url: window.location.href,
title: document.title,
content: '',
html: document.documentElement.outerHTML,
meta: {
author: getMetaContent('author'),
description: getMetaContent('description'),
keywords: getMetaContent('keywords'),
publishedTime: getMetaContent('article:published_time') || getMetaContent('publishedDate'),
siteName: getMetaContent('og:site_name') || getMetaContent('application-name'),
language: document.documentElement.lang || 'unknown'
},
extractedAt: new Date().toISOString()
};
// 尝试提取正文内容
const article = extractArticleContent();
result.content = article.text;
result.contentHtml = article.html;
result.wordCount = article.text.split(/\s+/).length;
return result;
}
}
// 显示浮动按钮
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);
// 获取 meta 标签内容
function getMetaContent(name) {
const meta = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
return meta ? meta.getAttribute('content') : '';
}
// 提取文章正文(使用多种策略)
function extractArticleContent() {
// 策略1使用 Readability 算法(简化版)
let bestElement = findBestElement();
if (bestElement) {
return {
text: cleanText(bestElement.innerText),
html: bestElement.innerHTML
};
}
});
// 策略2回退到 body 内容
const body = document.body;
return {
text: cleanText(body.innerText),
html: body.innerHTML
};
}
// 定位按钮
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
// 查找最佳内容元素(基于文本密度)
function findBestElement() {
const candidates = [];
const elements = document.querySelectorAll('article, [role="main"], .post-content, .entry-content, .article-content, #content, .content');
elements.forEach(el => {
const text = el.innerText || '';
const linkDensity = calculateLinkDensity(el);
const textDensity = text.length / (el.innerHTML.length || 1);
candidates.push({
element: el,
score: text.length * textDensity * (1 - linkDensity),
textLength: text.length
});
});
});
});
}
// 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();
// 按分数排序
candidates.sort((a, b) => b.score - a.score);
return candidates.length > 0 ? candidates[0].element : null;
}
});
// 计算链接密度
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,
"name": "InsightFlow Clipper",
"version": "1.0.0",
"description": "将网页内容一键导入 InsightFlow 知识库",
"description": "一键将网页内容导入 InsightFlow 知识库",
"permissions": [
"activeTab",
"storage",
@@ -21,11 +21,6 @@
"128": "icons/icon128.png"
}
},
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {
"service_worker": "background.js"
},
@@ -36,11 +31,10 @@
"css": ["content.css"]
}
],
"options_page": "options.html",
"web_accessible_resources": [
{
"resources": ["icons/*.png"],
"matches": ["<all_urls>"]
}
]
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"options_page": "options.html"
}

View File

@@ -1,349 +1,247 @@
<!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>
<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, Oxygen, Ubuntu, sans-serif;
background: #f5f5f5;
min-height: 100vh;
padding: 40px 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 24px;
font-weight: 600;
}
.header p {
opacity: 0.9;
margin-top: 5px;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
}
.section-title {
font-size: 16px;
font-weight: 600;
color: #333;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #f0f0f0;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-size: 14px;
font-weight: 500;
color: #555;
margin-bottom: 8px;
}
input[type="text"],
input[type="password"],
input[type="url"] {
width: 100%;
padding: 12px 15px;
border: 2px solid #e0e0e0;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.2s;
}
input[type="text"]:focus,
input[type="password"]:focus,
input[type="url"]:focus {
outline: none;
border-color: #667eea;
}
.help-text {
font-size: 12px;
color: #888;
margin-top: 5px;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
}
input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
.btn {
padding: 12px 30px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: #f0f0f0;
color: #555;
margin-left: 10px;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.status {
padding: 12px 15px;
border-radius: 6px;
margin-top: 15px;
font-size: 14px;
display: none;
}
.status.success {
display: block;
background: #e8f5e9;
color: #2e7d32;
}
.status.error {
display: block;
background: #ffebee;
color: #c62828;
}
.info-box {
background: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 15px;
border-radius: 4px;
margin-bottom: 20px;
}
.info-box p {
font-size: 13px;
color: #1565c0;
line-height: 1.5;
}
.info-box code {
background: rgba(255,255,255,0.5);
padding: 2px 6px;
border-radius: 3px;
font-family: 'Courier New', monospace;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>⚙️ InsightFlow Clipper 设置</h1>
<p>配置您的知识库连接</p>
<div class="container">
<div class="header">
<h1>⚙️ InsightFlow 设置</h1>
<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 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>
<script src="options.js"></script>
</body>
</html>

View File

@@ -1,175 +1,105 @@
// 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';
// 加载保存的设置
loadSettings();
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) {
showTestResult('请填写服务器地址和 API Key', 'error');
testBtn.disabled = false;
testBtn.textContent = '测试连接';
return;
document.getElementById('serverUrl').value = settings.serverUrl || '';
document.getElementById('apiKey').value = settings.apiKey || '';
document.getElementById('showFloatingButton').checked = settings.showFloatingButton !== false;
document.getElementById('autoSync').checked = settings.autoSync !== false;
}
// 保存设置
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 {
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');
if (!apiKey) {
showStatus('请输入 API 令牌', 'error');
return;
}
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;
// 确保 URL 格式正确
let formattedUrl = serverUrl;
if (!formattedUrl.startsWith('http://') && !formattedUrl.startsWith('https://')) {
formattedUrl = 'https://' + formattedUrl;
}
await chrome.storage.sync.set({ insightflowConfig: config });
// 移除末尾的斜杠
formattedUrl = formattedUrl.replace(/\/$/, '');
// 显示保存成功
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>`;
// 保存
await chrome.storage.sync.set({
serverUrl: formattedUrl,
apiKey: apiKey,
showFloatingButton: showFloatingButton,
autoSync: autoSync
});
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;
}
});
showStatus('设置已保存!', 'success');
}
// 测试连接
async function testConnection() {
const serverUrl = document.getElementById('serverUrl').value.trim();
const apiKey = document.getElementById('apiKey').value.trim();
if (!serverUrl || !apiKey) {
showStatus('请先填写服务器地址和 API 令牌', 'error');
return;
}
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>
<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>
<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;
min-height: 400px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #f5f5f5;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 {
font-size: 20px;
font-weight: 600;
}
.header p {
font-size: 12px;
opacity: 0.9;
margin-top: 5px;
}
.content {
padding: 15px;
}
.page-info {
background: white;
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.page-info .title {
font-size: 14px;
font-weight: 600;
color: #333;
margin-bottom: 5px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.page-info .url {
font-size: 12px;
color: #666;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.stats {
display: flex;
gap: 15px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #eee;
}
.stat {
font-size: 12px;
color: #888;
}
.stat span {
color: #667eea;
font-weight: 600;
}
.actions {
display: flex;
flex-direction: column;
gap: 10px;
}
.btn {
padding: 12px 20px;
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: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: white;
color: #667eea;
border: 1px solid #667eea;
}
.btn-secondary:hover {
background: #f8f9ff;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.status {
text-align: center;
padding: 10px;
font-size: 12px;
color: #666;
}
.status.success {
color: #4CAF50;
}
.status.error {
color: #f44336;
}
.clips-list {
margin-top: 15px;
max-height: 200px;
overflow-y: auto;
}
.clip-item {
background: white;
border-radius: 6px;
padding: 10px;
margin-bottom: 8px;
font-size: 12px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.clip-item .clip-title {
font-weight: 600;
color: #333;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.clip-item .clip-time {
color: #999;
font-size: 11px;
margin-top: 3px;
}
.clip-item .clip-status {
display: inline-block;
padding: 2px 6px;
border-radius: 3px;
font-size: 10px;
margin-top: 5px;
}
.clip-status.synced {
background: #e8f5e9;
color: #4CAF50;
}
.clip-status.pending {
background: #fff3e0;
color: #ff9800;
}
.settings-link {
text-align: center;
margin-top: 15px;
}
.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>
<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 class="header">
<h1>📎 InsightFlow</h1>
<p>一键保存网页到知识库</p>
</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 class="content">
<div class="page-info" id="pageInfo">
<div class="title" id="pageTitle">加载中...</div>
<div class="url" id="pageUrl"></div>
<div class="stats">
<div class="stat">字数: <span id="wordCount">0</span></div>
<div class="stat">待同步: <span id="pendingCount">0</span></div>
</div>
</div>
<div class="actions">
<button class="btn btn-primary" id="clipPageBtn">
📄 保存整个页面
</button>
<button class="btn btn-secondary" id="clipSelectionBtn">
✏️ 保存选中内容
</button>
</div>
<div class="status" id="status"></div>
<div class="loading" id="loading">
<div class="spinner"></div>
<div>正在处理...</div>
</div>
<div class="clips-list" id="clipsList"></div>
<div class="settings-link">
<a href="#" id="openOptions">⚙️ 设置</a>
</div>
</div>
</div>
<div class="footer">
<a href="#" id="openDashboard">打开 InsightFlow 控制台 →</a>
</div>
<script src="popup.js"></script>
<script src="popup.js"></script>
</body>
</html>

View File

@@ -1,195 +1,154 @@
// 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> 保存中...';
// 更新页面信息
document.getElementById('pageTitle').textContent = tab.title || '未知标题';
document.getElementById('pageUrl').textContent = tab.url || '';
// 保存选中的项目
const projectId = projectSelect.value;
if (projectId) {
const config = await getConfig();
config.defaultProjectId = projectId;
await saveConfig(config);
}
// 获取页面统计
updateStats();
// 发送剪藏请求
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 });
});
// 加载最近的剪辑
loadRecentClips();
// 绑定按钮事件
document.getElementById('clipPageBtn').addEventListener('click', clipPage);
document.getElementById('clipSelectionBtn').addEventListener('click', clipSelection);
document.getElementById('openOptions').addEventListener('click', openOptions);
});
// 加载配置
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;
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// 获取字数统计
try {
const response = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
if (response.success) {
document.getElementById('wordCount').textContent = response.data.wordCount || 0;
}
} catch (error) {
console.log('Content script not available');
}
// 获取待同步数量
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) {
const messageEl = document.getElementById('message');
messageEl.textContent = text;
messageEl.className = `message ${type}`;
setTimeout(() => {
messageEl.className = 'message';
}, 3000);
// 保存整个页面
async function clipPage() {
setLoading(true);
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// 发送消息给 background script
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() {
return new Promise((resolve) => {
chrome.storage.sync.get(['insightflowConfig'], (result) => {
resolve(result.insightflowConfig || {
serverUrl: 'http://122.51.127.111:18000',
apiKey: '',
defaultProjectId: ''
});
});
});
// 保存选中内容
async function clipSelection() {
setLoading(true);
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
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) {
return new Promise((resolve) => {
chrome.storage.sync.set({ insightflowConfig: config }, resolve);
});
// 加载最近的剪辑
async function loadRecentClips() {
const result = await chrome.storage.local.get(['clips']);
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 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}