-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeishu-api.js
More file actions
344 lines (311 loc) · 11.2 KB
/
Copy pathfeishu-api.js
File metadata and controls
344 lines (311 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// 后台脚本,用于处理Chrome扩展的后台任务和飞书API交互
// 飞书API配置(后续会由用户提供)
const FEISHU_CONFIG = {
appId: '', // 飞书应用ID
appSecret: '', // 飞书应用密钥
tableId: '', // 多维表格ID
taskViewId: '', // 任务视图ID
knowledgeViewId: '' // 知识库视图ID
};
// 监听安装事件
chrome.runtime.onInstalled.addListener(function() {
console.log('AI学习助手已安装');
// 初始化存储数据
chrome.storage.local.get(['tasks', 'knowledgeBase', 'feishuToken'], function(result) {
if (!result.tasks) {
chrome.storage.local.set({ tasks: [] });
}
if (!result.knowledgeBase) {
chrome.storage.local.set({ knowledgeBase: [] });
}
// 初始化飞书token存储
if (!result.feishuToken) {
chrome.storage.local.set({ feishuToken: null });
}
});
});
// 获取飞书访问令牌
async function getFeishuToken() {
try {
// 从存储中获取现有token
const result = await new Promise(resolve => {
chrome.storage.local.get(['feishuToken', 'tokenExpiry'], resolve);
});
// 检查token是否存在且未过期
const now = Date.now();
if (result.feishuToken && result.tokenExpiry && now < result.tokenExpiry) {
return result.feishuToken;
}
// 如果token不存在或已过期,获取新token
// 注意:这里需要根据飞书API的实际要求进行调整
const response = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'app_id': FEISHU_CONFIG.appId,
'app_secret': FEISHU_CONFIG.appSecret
})
});
const data = await response.json();
if (data.code === 0) {
// 保存token和过期时间(通常为2小时)
const expiry = now + (data.expire * 1000);
chrome.storage.local.set({
feishuToken: data.tenant_access_token,
tokenExpiry: expiry
});
return data.tenant_access_token;
} else {
throw new Error(`获取飞书token失败: ${data.msg}`);
}
} catch (error) {
console.error('获取飞书token出错:', error);
throw error;
}
}
// 向飞书多维表格添加文章记录
async function addArticleToFeishu(article) {
try {
const token = await getFeishuToken();
// 构建请求体,根据飞书多维表格的实际字段进行调整
const requestBody = {
fields: {
"标题": article.title,
"链接": article.url,
"分类": article.category,
"知识重要性": article.importance || "中",
"知识学习完成状态": "否",
"添加时间": new Date().toISOString()
}
};
// 调用飞书API添加记录
const response = await fetch(`https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_CONFIG.tableId}/tables/${FEISHU_CONFIG.knowledgeViewId}/records`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
if (data.code === 0) {
return { success: true, recordId: data.data.record_id };
} else {
throw new Error(`添加记录失败: ${data.msg}`);
}
} catch (error) {
console.error('添加文章到飞书出错:', error);
throw error;
}
}
// 从飞书获取知识库数据
async function getKnowledgeFromFeishu() {
try {
const token = await getFeishuToken();
// 调用飞书API获取记录
const response = await fetch(`https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_CONFIG.tableId}/tables/${FEISHU_CONFIG.knowledgeViewId}/records?page_size=100`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
if (data.code === 0) {
// 转换飞书数据格式为插件使用的格式
const knowledgeItems = data.data.items.map(item => {
const fields = item.fields;
return {
id: item.record_id,
title: fields['标题'] || '',
url: fields['链接'] || '',
category: fields['分类'] || 'other',
summary: fields['内容摘要'] || '',
importance: fields['知识重要性'] || '中',
completed: fields['知识学习完成状态'] === '是',
savedDate: fields['创建日期'] || new Date().toISOString()
};
});
return { success: true, data: knowledgeItems };
} else {
throw new Error(`获取知识库数据失败: ${data.msg}`);
}
} catch (error) {
console.error('从飞书获取知识库数据出错:', error);
throw error;
}
}
// 从飞书获取今日任务
async function getTodayTasksFromFeishu() {
try {
const token = await getFeishuToken();
// 获取今天的日期(格式:YYYY-MM-DD)
const today = new Date().toISOString().split('T')[0];
// 调用飞书API获取今日任务
const response = await fetch(`https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_CONFIG.tableId}/tables/${FEISHU_CONFIG.taskViewId}/records?filter=CurrentValue.[日期]=${today}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
if (data.code === 0) {
// 转换飞书数据格式为插件使用的格式
const taskItems = data.data.items.map(item => {
const fields = item.fields;
return {
id: item.record_id,
title: fields['标题'] || '',
url: fields['链接'] || '',
category: fields['分类'] || 'other',
summary: fields['摘要'] || '',
date: fields['日期'] || today,
completed: fields['完成状态'] === '已完成'
};
});
return { success: true, data: taskItems };
} else {
throw new Error(`获取今日任务失败: ${data.msg}`);
}
} catch (error) {
console.error('从飞书获取今日任务出错:', error);
throw error;
}
}
// 更新飞书任务状态
async function updateTaskStatusInFeishu(recordId, completed) {
try {
const token = await getFeishuToken();
// 构建请求体
const requestBody = {
fields: {
"完成状态": completed ? '已完成' : '未完成'
}
};
// 调用飞书API更新记录
const response = await fetch(`https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_CONFIG.tableId}/tables/${FEISHU_CONFIG.taskViewId}/records/${recordId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
if (data.code === 0) {
return { success: true };
} else {
throw new Error(`更新任务状态失败: ${data.msg}`);
}
} catch (error) {
console.error('更新飞书任务状态出错:', error);
throw error;
}
}
// 监听来自popup或content script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// 处理添加文章到飞书请求
if (request.action === 'addArticleToFeishu') {
addArticleToFeishu(request.article)
.then(result => sendResponse(result))
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // 保持消息通道开放,以便异步响应
}
// 处理更新知识库项目状态请求
if (request.action === 'updateKnowledgeStatus') {
updateKnowledgeStatusInFeishu(request.recordId, request.completed)
.then(result => {
if (result.success) {
// 更新本地存储中的知识状态
chrome.storage.local.get(['knowledgeBase'], function(data) {
const knowledgeBase = data.knowledgeBase || [];
const itemIndex = knowledgeBase.findIndex(item => item.id === request.recordId);
if (itemIndex !== -1) {
knowledgeBase[itemIndex].completed = request.completed;
chrome.storage.local.set({ knowledgeBase: knowledgeBase });
}
});
}
sendResponse(result);
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
// 处理更新知识重要性请求
if (request.action === 'updateKnowledgeImportance') {
updateKnowledgeImportanceInFeishu(request.recordId, request.importance)
.then(result => {
if (result.success) {
// 更新本地存储中的知识重要性
chrome.storage.local.get(['knowledgeBase'], function(data) {
const knowledgeBase = data.knowledgeBase || [];
const itemIndex = knowledgeBase.findIndex(item => item.id === request.recordId);
if (itemIndex !== -1) {
knowledgeBase[itemIndex].importance = request.importance;
chrome.storage.local.set({ knowledgeBase: knowledgeBase });
}
});
}
sendResponse(result);
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
// 处理从飞书同步知识库请求
if (request.action === 'syncKnowledgeFromFeishu') {
getKnowledgeFromFeishu()
.then(result => {
if (result.success) {
// 更新本地存储
chrome.storage.local.set({
knowledgeBase: result.data,
lastSync: new Date().getTime()
});
}
sendResponse(result);
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
// 处理从飞书获取今日任务请求
if (request.action === 'getTodayTasks') {
getTodayTasksFromFeishu()
.then(result => {
if (result.success) {
// 更新本地存储
chrome.storage.local.set({ tasks: result.data });
}
sendResponse(result);
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
// 处理更新任务状态请求
if (request.action === 'updateTaskStatus') {
updateTaskStatusInFeishu(request.recordId, request.completed)
.then(result => {
if (result.success) {
// 更新本地存储中的任务状态
chrome.storage.local.get(['tasks'], function(data) {
const tasks = data.tasks || [];
const taskIndex = tasks.findIndex(task => task.id === request.recordId);
if (taskIndex !== -1) {
tasks[taskIndex].completed = request.completed;
chrome.storage.local.set({ tasks: tasks });
}
});
}
sendResponse(result);
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
});
// 监听标签页更新事件,用于自动获取当前页面信息
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.url) {
// 可以在这里实现自动检测AI相关文章的逻辑
// 例如,检查URL是否包含特定关键词,或者分析页面内容
}
});