Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
556 lines (509 loc) · 20.2 KB
/
Copy pathbackground.js
File metadata and controls
556 lines (509 loc) · 20.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
importScripts("lib/siyuan-storage-defaults.js", "lib/siyuan-api.js");
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({
id: "copy-to-siyuan",
title: chrome.i18n.getMessage("copy_to_siyuan"),
contexts: ["selection", "image"],
});
chrome.contextMenus.create({
id: "send",
title: chrome.i18n.getMessage("send"),
contexts: ["page"],
});
});
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
if (info.menuItemId === "copy-to-siyuan") {
safeTabsSendMessage(tab && tab.id, {
func: "copy",
tabId: tab && tab.id,
srcUrl: info.srcUrl,
});
} else if (info.menuItemId === "send") {
safeTabsSendMessage(tab && tab.id, {
func: "siyuanGetReadability",
tabId: tab && tab.id,
});
}
});
chrome.commands.onCommand.addListener(function (command) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
const tab = tabs[0];
if (!tab) return;
if (command === "copy-to-siyuan") {
safeTabsSendMessage(tab.id, {
func: "copy",
tabId: tab.id,
srcUrl: undefined,
});
} else if (command === "send-to-siyuan") {
safeTabsSendMessage(tab.id, {
func: "siyuanGetReadability",
tabId: tab.id,
});
}
});
});
function safeTabsSendMessage(tabId, message) {
if (!tabId) return;
try {
chrome.tabs.sendMessage(tabId, message, () => {
void chrome.runtime.lastError;
});
} catch (e) {
// ignore
}
}
/** @param {string} excerpt */
function formatClipExcerpt(excerpt) {
let text = (excerpt || "").trim();
if (text === "") return "";
// 将连续的三个换行符替换为两个换行符
text = text.replace(/\n{3,}/g, "\n\n");
// 从第二行开始,每行前面加两个空格 https://github.com/siyuan-note/siyuan/issues/11315
text = text.replace(/\n/g, "\n ");
return text.trim();
}
/** @param {string} href */
function decodeClipUrl(href) {
try {
return decodeURIComponent(href);
} catch (e) {
console.warn(e);
return href;
}
}
// 获取当前日期时间格式化函数
function getClipDateTime() {
const now = new Date();
const year = now.getFullYear();
let month = now.getMonth() + 1;
let day = now.getDate();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
if (month.toString().length === 1) {
month = "0" + month;
}
if (day.toString().length === 1) {
day = "0" + day;
}
if (hour.toString().length === 1) {
hour = "0" + hour;
}
if (minute.toString().length === 1) {
minute = "0" + minute;
}
if (second.toString().length === 1) {
second = "0" + second;
}
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
// 获取简单日期时间
function getClipSimpleDateTime() {
const now = new Date();
const date = now.toISOString().slice(0, 10);
const time = now.toTimeString().slice(0, 5);
return { date, time };
}
// 添加模板渲染函数
function renderClipTemplate(template, data) {
return template.replace(/\${([^}]+)}/g, function (match, key) {
// 检查是否为条件表达式
const conditionalMatch = key.match(/(.+?)\s*\?\s*(.*?)\s*:\s*(.*)/);
if (conditionalMatch) {
const conditionKey = conditionalMatch[1].trim();
const trueValueString = conditionalMatch[2].trim();
const falseValueString = conditionalMatch[3].trim();
const condition = conditionKey.split(".").reduce((obj, prop) => obj && obj[prop], data);
// 辅助函数,用于解析值中的变量或字符串
const getValue = (valueStr) => {
if (
(valueStr.startsWith("'") && valueStr.endsWith("'")) ||
(valueStr.startsWith('"') && valueStr.endsWith('"'))
) {
return valueStr.slice(1, -1); // 字符串字面量
}
// 尝试解析为变量
const parts = valueStr.split("+").map((part) => part.trim());
let result = "";
for (const part of parts) {
if ((part.startsWith("'") && part.endsWith("'")) || (part.startsWith('"') && part.endsWith('"'))) {
result += part.slice(1, -1);
} else {
const variableValue = part.split(".").reduce((obj, prop) => obj && obj[prop], data);
result += variableValue !== undefined ? variableValue : "";
}
}
return result;
};
if (condition) {
return getValue(trueValueString);
} else {
return getValue(falseValueString);
}
} else {
// 普通变量替换
const value = key.split(".").reduce((obj, prop) => obj && obj[prop], data);
return value !== undefined ? value : "";
}
});
}
// 默认剪藏格式的处理函数(当模板渲染失败时使用)
function getDefaultClipMarkdown(requestData, contentMd) {
let markdown = "---\n\n* " + (requestData.title || "Untitled");
const siteName = requestData.siteName || "";
if ("" !== siteName) {
markdown += " - " + siteName;
}
markdown += "\n";
const href = requestData.href;
markdown += "* " + "[" + decodeClipUrl(href) + "](" + href + ")\n";
const excerpt = formatClipExcerpt(requestData.excerpt);
if ("" !== excerpt) {
markdown += "* " + excerpt + "\n";
} else {
markdown += "\n";
}
markdown += "* " + getClipDateTime() + "\n\n---\n\n" + contentMd;
return markdown;
}
function buildClipMarkdown(requestData, contentMd, clipTemplate) {
const excerpt = formatClipExcerpt(requestData.excerpt);
const { date, time } = getClipSimpleDateTime();
const templateData = {
title: requestData.title || "Untitled",
siteName: requestData.siteName || "",
excerpt: excerpt || "",
url: requestData.href,
urlDecoded: decodeClipUrl(requestData.href),
date,
time,
tags: requestData.tags,
content: contentMd,
};
// 渲染模板
try {
return renderClipTemplate(clipTemplate || SIYUAN_DEFAULT_CLIP_TEMPLATE, templateData);
} catch (e) {
console.error("Template rendering error:", e);
// 如果模板渲染失败,使用默认格式
return getDefaultClipMarkdown(requestData, contentMd);
}
}
/** 在 background 中检测内核连通性,避免 content script 访问 localhost 触发 LNA 权限弹窗 */
async function siyuanCheckKernel({ ip, token, notebook, savePathTemplate, databaseID, databaseBlockID, databaseTemplateID }) {
const prereq = siyuanValidateClipPrereqs({
token,
notebook,
savePathTemplate,
databaseID,
databaseBlockID,
databaseTemplateID,
});
if (!prereq.ok) {
return prereq;
}
const result = await siyuanKernelFetch({
ip,
token,
path: "/api/notebook/lsNotebooks",
body: {},
});
if (!result.ok) {
return result;
}
const notebooks = result.data?.data?.notebooks;
if (!databaseTemplateID && (!Array.isArray(notebooks) || !notebooks.some((item) => item.id === notebook && !item.closed))) {
return { ok: false, error: "tip_save_path_miss" };
}
return { ok: true };
}
function normalizeClipDocumentPath(parentPath, title) {
let path = String(parentPath || "").trim().replaceAll("\\", "/");
path = path.replace(/\/{2,}/g, "/");
if (!path.startsWith("/")) path = "/" + path;
if (path.length > 1) path = path.replace(/\/+$/, "");
return (path === "/" ? "" : path) + "/" + title;
}
async function renderClipDocumentPath(requestData, title) {
const result = await siyuanKernelFetch({
ip: requestData.api,
token: requestData.token,
path: "/api/template/renderSprig",
body: { template: requestData.savePathTemplate || SIYUAN_DEFAULT_SAVE_PATH_TEMPLATE },
});
if (!result.ok) return result;
if (!result.data || result.data.code !== 0) {
if (result.data?.msg) return { ok: false, message: result.data.msg };
return { ok: false, error: "tip_siyuan_kernel_unavailable" };
}
return { ok: true, path: normalizeClipDocumentPath(result.data.data, title) };
}
async function resolveClipDocumentPath(requestData, title) {
if (requestData.savePathMode !== "template") {
return { ok: true, path: normalizeClipDocumentPath(requestData.savePathTemplate, title) };
}
return renderClipDocumentPath(requestData, title);
}
function newClipDocumentID() {
const now = new Date();
const timestamp = [now.getFullYear(), now.getMonth() + 1, now.getDate(),
now.getHours(), now.getMinutes(), now.getSeconds()]
.map((value, index) => String(value).padStart(index === 0 ? 4 : 2, "0")).join("");
const suffix = Array.from(crypto.getRandomValues(new Uint8Array(7)), value =>
"0123456789abcdefghijklmnopqrstuvwxyz"[value % 36]).join("");
return timestamp + "-" + suffix;
}
function normalizeClipDocumentTitle(title) {
// Match the kernel's plain-title cleanup, retaining ZWJ for joined emoji.
return title.replaceAll("\u00a0", " ")
.replace(/[^\p{L}\p{M}\p{N}\p{P}\p{S} \u3000\u200d]/gu, "").trim();
}
async function createClippedDocument(requestData, title, markdown, withMath) {
const options = { ip: requestData.api, token: requestData.token };
const content = { tags: requestData.tags, markdown, withMath,
clippingHref: requestData.href, listDocTree: requestData.listDocTree };
if (requestData.savePathMode !== "template") {
// Probe before writing: a failed query or creation must never trigger a legacy retry.
const result = await siyuanKernelFetch({ ...options,
path: "/api/notebook/getNotebookConf", body: { notebook: requestData.notebook } });
if (!result.ok || result.data?.code !== 0) return result;
const data = result.data.data;
if (data?.box !== requestData.notebook || !data.conf || typeof data.conf !== "object" || Array.isArray(data.conf)) {
return { ok: false, error: "tip_siyuan_kernel_unavailable" };
}
if (Object.prototype.hasOwnProperty.call(data, "documentCapabilities")) {
if (data.documentCapabilities?.structuredPaths !== true ||
!Array.isArray(data.documentCapabilities.titleFormats) ||
!data.documentCapabilities.titleFormats.includes("plain")) {
return { ok: false, error: "tip_siyuan_kernel_unavailable" };
}
// Only an explicitly selected notebook root can be represented by null.
if (!requestData.parentDoc && requestData.savePathTemplate !== "/") {
return { ok: false, error: "tip_save_path_miss" };
}
const id = newClipDocumentID();
const created = await siyuanKernelFetch({ ...options,
path: "/api/filetree/createDocByParent",
body: { ...content, notebook: requestData.notebook, parentID: requestData.parentDoc || null,
id, title: { format: "plain", text: normalizeClipDocumentTitle(title) } } });
// Normalize only successful results; retain structured failure details unchanged.
if (created.ok && created.data?.code === 0) {
if (created.data.data?.id !== id) return { ok: false, error: "tip_siyuan_kernel_unavailable" };
return { ...created, data: { ...created.data, data: id } };
}
return created;
}
}
const renderedPath = await resolveClipDocumentPath(requestData, title);
if (!renderedPath.ok) return renderedPath;
return siyuanKernelFetch({ ...options, path: "/api/filetree/createDocWithMd",
body: { ...content, notebook: requestData.notebook, parentID: requestData.parentDoc, path: renderedPath.path } });
}
function storageSyncGet(defaults) {
return new Promise((resolve) => {
chrome.storage.sync.get(defaults, resolve);
});
}
async function addClippedDocToDatabase(apiBase, token, docId, databaseID) {
// 先刷新 SQL 数据库
const flushResult = await siyuanKernelFetch({
ip: apiBase,
token,
path: "/api/sqlite/flushTransaction",
body: {},
});
if (!flushResult.ok || flushResult.data?.code !== 0) {
console.warn("flushTransaction failed:", flushResult);
return false;
}
// 刷新完成后再添加到数据库
const addResult = await siyuanKernelFetch({
ip: apiBase,
token,
path: "/api/av/addAttributeViewBlocks",
body: {
avID: databaseID,
srcs: [{ id: docId, isDetached: false }],
},
});
if (!addResult.ok || addResult.data?.code !== 0) {
console.warn("addAttributeViewBlocks failed:", addResult);
return false;
}
return true;
}
async function createClippedDocWithDatabaseTemplate(requestData, title, markdown, withMath) {
return siyuanKernelFetch({
ip: requestData.api,
token: requestData.token,
path: "/api/av/createAttributeViewItemWithMarkdown",
body: {
avID: requestData.selectedDatabaseID,
blockID: requestData.selectedDatabaseBlockID,
viewID: requestData.selectedDatabaseViewID,
templateID: requestData.selectedDatabaseTemplateID,
title,
markdown,
tags: requestData.tags,
withMath,
clippingHref: requestData.href,
listDocTree: requestData.listDocTree,
},
});
}
async function handleArticleClip(requestData, apiBase, copyData, fetchFileErr) {
let title = requestData.title ? requestData.title : "Untitled";
title = title.replace(/[\\/]/g, "/");
const { clipTemplate } = await storageSyncGet({ clipTemplate: SIYUAN_DEFAULT_CLIP_TEMPLATE });
const markdown = buildClipMarkdown(requestData, copyData.md, clipTemplate);
let createResult;
let templateCreated = false;
if (requestData.selectedDatabaseTemplateID) {
createResult = await createClippedDocWithDatabaseTemplate(requestData, title, markdown, copyData.withMath);
templateCreated = true;
} else {
createResult = await createClippedDocument(requestData, title, markdown, copyData.withMath);
}
if (!createResult.ok) {
safeTabsSendMessage(requestData.tabId, {
func: createResult.error ? "tipKey" : "tip",
msg: createResult.error || createResult.message,
tip: requestData.tip,
});
return;
}
const createResponse = createResult.data;
if (createResponse?.code !== 0) {
safeTabsSendMessage(requestData.tabId, createResponse?.msg ? {
func: "tip",
msg: createResponse.msg,
tip: requestData.tip,
} : {
func: "tipKey",
msg: createResponse?.code === 1 ? "tip_save_path_miss" : "tip_siyuan_kernel_unavailable",
tip: requestData.tip,
});
return;
}
const docId = templateCreated ? createResponse.data?.blockID : createResponse.data;
if (typeof docId !== "string" || !docId) {
safeTabsSendMessage(requestData.tabId, {
func: "tipKey",
msg: "tip_siyuan_kernel_unavailable",
tip: requestData.tip,
});
return;
}
let databaseAdded = true;
if (!templateCreated && requestData.selectedDatabaseID) {
const dbOk = await addClippedDocToDatabase(apiBase, requestData.token, docId, requestData.selectedDatabaseID);
databaseAdded = dbOk;
if (!dbOk) {
console.warn("Failed to add clipped doc to database:", docId, requestData.selectedDatabaseID);
}
}
safeTabsSendMessage(requestData.tabId, {
func: "tipKey",
msg: databaseAdded ? "tip_clip_ok" : "tip_clip_database_incomplete",
documentID: databaseAdded ? undefined : docId,
timeout: databaseAdded ? undefined : 15000,
tip: requestData.tip,
});
// 检查是否需要打开文档
const { expOpenAfterClip } = await storageSyncGet({ expOpenAfterClip: false });
if (expOpenAfterClip && docId) {
let documentUrl = apiBase + "?id=" + docId;
if (apiBase.startsWith("http://localhost:") || apiBase.startsWith("http://127.0.0.1:")) {
documentUrl = `siyuan://blocks/${docId}`;
}
chrome.tabs.create({ url: documentUrl });
}
if (fetchFileErr) {
// 可能因为跨域问题导致下载图片失败,这里调用内核接口 `网络图片转换为本地图片` https://github.com/siyuan-note/siyuan/issues/7224
void fetch(apiBase + "/api/format/netImg2LocalAssets", {
method: "POST",
headers: { Authorization: "Token " + requestData.token },
body: JSON.stringify({
id: docId,
url: requestData.href, // 改进浏览器剪藏扩展转换本地图片成功率 https://github.com/siyuan-note/siyuan/issues/7464
}),
});
}
// Keep partial-completion feedback visible instead of immediately reloading the page.
if (databaseAdded) {
safeTabsSendMessage(requestData.tabId, { func: "reload" });
}
}
async function handleUploadCopy(requestData) {
const apiBase = siyuanNormalizeBase(requestData.api);
const fetchFileErr = requestData.fetchFileErr;
const formData = new FormData();
formData.append("dom", requestData.dom);
for (const key of Object.keys(requestData.files)) {
const base64Response = await fetch(requestData.files[key].data);
formData.append(key, await base64Response.blob());
}
formData.append("notebook", requestData.notebook);
formData.append("href", requestData.href);
formData.append("tags", requestData.tags);
formData.append("clipType", requestData.type);
// 透传“下载资源”开关,链滴/流云整页剪藏时由内核按此开关决定是否下载网络资源到本地
formData.append("assets", requestData.assets);
try {
const copyHttpResponse = await fetch(apiBase + "/api/extension/copy", {
method: "POST",
headers: { Authorization: "Token " + requestData.token },
body: formData,
});
if (copyHttpResponse.redirected) {
safeTabsSendMessage(requestData.tabId, {
func: "tipKey",
msg: "tip_token_invalid",
tip: "tip",
});
return;
}
const copyResult = await copyHttpResponse.json();
if (copyResult.code < 0) {
safeTabsSendMessage(requestData.tabId, {
func: "tip",
msg: copyResult.msg,
tip: requestData.tip,
});
return;
}
safeTabsSendMessage(requestData.tabId, {
func: "copy2Clipboard",
data: copyResult.data.md,
});
if ("" !== copyResult.msg && requestData.type !== "article") {
safeTabsSendMessage(requestData.tabId, {
func: "tip",
msg: copyResult.msg,
tip: requestData.tip,
});
}
if (requestData.type === "article") {
await handleArticleClip(requestData, apiBase, copyResult.data, fetchFileErr);
}
} catch (e) {
console.error(e);
safeTabsSendMessage(requestData.tabId, {
func: "tipKey",
msg: "tip_siyuan_kernel_unavailable",
tip: "tip",
});
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.func === "check-kernel") {
siyuanCheckKernel(request.data).then(sendResponse);
return true;
}
if (request.func === "upload-copy") {
void handleUploadCopy(request.data);
}
});