-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathscript.ts
More file actions
1461 lines (1372 loc) · 49.5 KB
/
script.ts
File metadata and controls
1461 lines (1372 loc) · 49.5 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { fetchScriptBody, parseMetadata, prepareScriptByCode } from "@App/pkg/utils/script";
import { uuidv4 } from "@App/pkg/utils/uuid";
import type { Group } from "@Packages/message/server";
import Logger from "@App/app/logger/logger";
import LoggerCore from "@App/app/logger/core";
import {
checkSilenceUpdate,
getBrowserType,
getStorageName,
openInCurrentTab,
stringMatching,
} from "@App/pkg/utils/utils";
import { ltever } from "@App/pkg/utils/semver";
import type {
SCMetadata,
Script,
SCRIPT_RUN_STATUS,
ScriptDAO,
ScriptRunResource,
ScriptSite,
} from "@App/app/repo/scripts";
import { SCRIPT_STATUS_DISABLE, SCRIPT_STATUS_ENABLE, ScriptCodeDAO } from "@App/app/repo/scripts";
import { type IMessageQueue } from "@Packages/message/message_queue";
import { type ScriptInfo, type InstallSource, createTempCodeEntry } from "@App/pkg/utils/scriptInstall";
import { type ResourceService } from "./resource";
import { type ValueService } from "./value";
import { compileScriptCode } from "../content/utils";
import { type SystemConfig } from "@App/pkg/config/config";
import type {
TScriptRunStatus,
TDeleteScript,
TEnableScript,
TInstallScript,
TSortedScript,
TInstallScriptParams,
} from "../queue";
import { buildScriptRunResourceBasic, selfMetadataUpdate } from "./utils";
import {
BatchUpdateListActionCode,
type TBatchUpdateListAction,
UpdateStatusCode,
type TBatchUpdateRecord,
} from "./types";
import { getSimilarityScore, ScriptUpdateCheck } from "./script_update_check";
import { LocalStorageDAO } from "@App/app/repo/localStorage";
import { CompiledResourceDAO } from "@App/app/repo/resource";
import { initRegularUpdateCheck } from "./regular_updatecheck";
import { TempStorageDAO, TempStorageItemType } from "@App/app/repo/tempStorage";
import { cleanupStaleTempStorageEntries } from "./temp";
export type TCheckScriptUpdateOption = Partial<
{ checkType: "user"; noUpdateCheck?: number } | ({ checkType: "system" } & Record<string, any>)
>;
export type TOpenBatchUpdatePageOption = { q: string; dontCheckNow: boolean };
export type TScriptInstallParam = {
script: Script; // 脚本信息(包含脚本的基础元数据)
code: string; // 脚本源码内容
upsertBy?: InstallSource; // 安装/更新来源(用于标识脚本来源渠道)
createtime?: number; // 导入时指定的创建时间(时间戳,毫秒)
updatetime?: number; // 导入时指定的最后更新时间(时间戳,毫秒)
};
export type TScriptInstallReturn = {
update: boolean; // 是否为更新操作(true 表示更新,false 表示新增)
updatetime: number | undefined; // 实际生效的更新时间(时间戳,毫秒)
};
export class ScriptService {
logger: Logger;
scriptCodeDAO: ScriptCodeDAO = new ScriptCodeDAO();
localStorageDAO: LocalStorageDAO = new LocalStorageDAO();
compiledResourceDAO: CompiledResourceDAO = new CompiledResourceDAO();
private readonly scriptUpdateCheck;
constructor(
private readonly systemConfig: SystemConfig,
private readonly group: Group,
private readonly mq: IMessageQueue,
private readonly valueService: ValueService,
private readonly resourceService: ResourceService,
private readonly scriptDAO: ScriptDAO
) {
this.logger = LoggerCore.logger().with({ service: "script" });
this.scriptCodeDAO.enableCache();
this.scriptUpdateCheck = new ScriptUpdateCheck(systemConfig, group, mq, valueService, resourceService, scriptDAO);
}
listenerScriptInstall() {
// 初始化脚本安装监听
chrome.webNavigation.onBeforeNavigate.addListener(
(req: chrome.webNavigation.WebNavigationBaseCallbackDetails) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.webNavigation.onBeforeNavigate:", lastError);
return;
}
// 处理url, 实现安装脚本
let targetUrl: string;
// 判断是否为 file:///*/*.user.js
if (req.url.startsWith("file://") && req.url.endsWith(".user.js")) {
targetUrl = req.url;
} else {
const reqUrl = new URL(req.url);
// 判断是否有hash
if (!reqUrl.hash) {
return undefined;
}
// 判断是否有url参数
const idx = reqUrl.hash.indexOf("url=");
if (idx < 0) {
return undefined;
}
// 获取url参数
targetUrl = reqUrl.hash.substring(idx + 4);
}
// 读取脚本url内容, 进行安装
const logger = this.logger.with({ url: targetUrl });
logger.debug("install script");
this.openInstallPageByUrl(targetUrl, { source: "user", byWebRequest: true })
.catch((e) => {
logger.error("install script error", Logger.E(e));
// 不再重定向当前url
chrome.declarativeNetRequest.updateDynamicRules(
{
removeRuleIds: [2],
addRules: [
{
id: 2,
priority: 1,
action: {
type: "allow" as chrome.declarativeNetRequest.RuleActionType,
},
condition: {
regexFilter: targetUrl,
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
},
},
],
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateDynamicRules:",
chrome.runtime.lastError
);
}
}
);
})
.finally(() => {
// 回退到到安装页
chrome.scripting.executeScript({
target: { tabId: req.tabId },
func: function () {
history.back();
},
});
});
},
{
url: [
{ schemes: ["http", "https"], hostEquals: "docs.scriptcat.org", pathPrefix: "/docs/script_installation/" },
{ schemes: ["http", "https"], hostEquals: "docs.scriptcat.org", pathPrefix: "/en/docs/script_installation/" },
{ schemes: ["http", "https"], hostEquals: "www.tampermonkey.net", pathPrefix: "/script_installation.php" },
{ schemes: ["file"], pathSuffix: ".user.js" },
],
}
);
// 兼容 chrome 内核 < 128 处理
const browserType = getBrowserType();
const addResponseHeaders = browserType.chrome && browserType.chromeVersion >= 128;
// Chrome 84+
const conditions: chrome.declarativeNetRequest.RuleCondition[] = [
{
regexFilter: "^([^?#]+?\\.user(\\.bg|\\.sub)?\\.js)", // Chrome 84+
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME], // Chrome 84+
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false, // Chrome 84+
excludedRequestDomains: ["github.com", "gitlab.com", "gitea.com", "bitbucket.org"], // Chrome 101+
},
{
regexFilter: "^(.+?\\.user(\\.bg|\\.sub)?\\.js&response-content-type=application%2Foctet-stream)",
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["githubusercontent.com"], // Chrome 101+
},
{
regexFilter:
"^(https?:\\/\\/github.com\\/[^\\s/?#]+\\/[^\\s/?#]+\\/releases/[^\\s/?#]+/download/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://github.com/<user>/<repo>/releases/latest/download/file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter:
"^(https?:\\/\\/gitlab\\.com\\/[^\\s/?#]+\\/[^\\s/?#]+\\/-\\/raw\\/[a-z0-9_/.-]+\\/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["gitlab.com"], // Chrome 101+
},
{
regexFilter: "^(https?:\\/\\/github\\.com\\/[^\\/]+\\/[^\\/]+\\/releases\\/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://github.com/<user>/<repo>/releases/latest/download/file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter: "^(https?://github.com/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z]+/[^?#]+?.user(\\.bg|\\.sub)?.js)",
// https://github.com/<user>/<repo>/raw/refs/heads/main/.../file.user.js
// https://github.com/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod], // Chrome 91+
isUrlFilterCaseSensitive: false,
requestDomains: ["github.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://gitlab\\.com/[^\\s/?#]+/[^\\s/?#]+/-/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://gitlab.com/<user>/<repo>/-/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["gitlab.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://gitea\\.com/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://gitea.com/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["gitea.com"], // Chrome 101+
},
{
regexFilter:
"^(https?://bitbucket\\.org/[^\\s/?#]+/[^\\s/?#]+/raw/[a-z0-9_/.-]+/[^?#]+?\\.user(\\.bg|\\.sub)?\\.js)",
// https://bitbucket.org/<user>/<repo>/raw/<branch>/.../file.user.js
resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME],
requestMethods: ["get" as chrome.declarativeNetRequest.RequestMethod],
isUrlFilterCaseSensitive: false,
requestDomains: ["bitbucket.org"], // Chrome 101+
},
];
const installPageURL = chrome.runtime.getURL("src/install.html");
const rules = conditions.map((condition, idx) => {
Object.assign(condition, {
excludedTabIds: [chrome.tabs.TAB_ID_NONE],
});
if (addResponseHeaders) {
Object.assign(condition, {
responseHeaders: [
{
header: "Content-Type",
values: [
"text/javascript*",
"application/javascript*",
"text/html*",
"text/plain*",
"application/octet-stream*",
"application/force-download*",
],
},
],
});
}
return {
id: 1000 + idx,
priority: 1,
action: {
type: "redirect" as chrome.declarativeNetRequest.RuleActionType,
redirect: {
regexSubstitution: `${installPageURL}?url=\\1`,
},
},
condition: condition,
} as chrome.declarativeNetRequest.Rule;
});
// 重定向到脚本安装页
chrome.declarativeNetRequest.updateDynamicRules(
{
removeRuleIds: [1],
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateDynamicRules:",
chrome.runtime.lastError
);
}
}
);
chrome.declarativeNetRequest.updateSessionRules(
{
removeRuleIds: [...rules.map((rule) => rule.id)],
addRules: rules,
},
() => {
if (chrome.runtime.lastError) {
console.error(
"chrome.runtime.lastError in chrome.declarativeNetRequest.updateSessionRules:",
chrome.runtime.lastError
);
}
}
);
}
public async openInstallPageByUrl(
url: string,
options: { source: InstallSource; byWebRequest?: boolean }
): Promise<{ success: boolean; msg: string }> {
try {
const installPageUrl = await this.getInstallPageUrl(url, options);
if (!installPageUrl) throw new Error("getInstallPageUrl failed");
await openInCurrentTab(installPageUrl);
return { success: true, msg: "" };
} catch (err: any) {
console.error(err);
return { success: false, msg: err.message };
}
}
public async getInstallPageUrl(
url: string,
options: { source: InstallSource; byWebRequest?: boolean }
): Promise<string> {
const uuid = uuidv4();
try {
await this.openUpdateOrInstallPage(uuid, url, options, false);
return `/src/install.html?uuid=${uuid}`;
} catch (err: any) {
console.error(err);
return "";
}
}
// 直接通过url静默安装脚本
async installByUrl(url: string, source: InstallSource, subscribeUrl?: string) {
const uuid = uuidv4();
const code = await fetchScriptBody(url);
const { script } = await prepareScriptByCode(code, url, uuid);
script.subscribeUrl = subscribeUrl;
await this.installScript({
script,
code,
upsertBy: source,
});
return script;
}
// 直接通过code静默安装脚本
async installByCode(param: { uuid: string; code: string; upsertBy: InstallSource }) {
const { code, upsertBy, uuid } = param;
const { script } = await prepareScriptByCode(code, "", uuid, true);
await this.installScript({
script,
code,
upsertBy,
});
return script;
}
// 获取安装信息
async getInstallInfo(uuid: string) {
const entry = await new TempStorageDAO().get(uuid);
cleanupStaleTempStorageEntries();
return <[boolean, ScriptInfo, Record<string, any>]>entry?.value;
}
publishInstallScript(scriptFull: Script, options: any) {
const { uuid, type, status, name, namespace, origin, checkUpdateUrl, downloadUrl } = scriptFull;
const script = { uuid, type, status, name, namespace, origin, checkUpdateUrl, downloadUrl } as TInstallScriptParams;
return this.mq.publish<TInstallScript>("installScript", { script, ...options });
}
// 安装脚本 / 更新脚本
async installScript(param: TScriptInstallParam): Promise<TScriptInstallReturn> {
param.upsertBy = param.upsertBy || "user";
const { script, upsertBy, createtime, updatetime } = param;
// 删 storage cache
const compiledResourceUpdatePromise = this.compiledResourceDAO.delete(script.uuid);
const logger = this.logger.with({
name: script.name,
uuid: script.uuid,
version: script.metadata.version?.[0] || "0.0",
upsertBy,
});
let update = false;
// 判断是否已经安装
const oldScript = await this.scriptDAO.get(script.uuid);
if (oldScript) {
// 执行更新逻辑
update = true;
script.selfMetadata = oldScript.selfMetadata;
// 如果已安装的脚本是由 Subscribe 安装,即使是手动更新也不会影响跟 Subscribe 关联
if (oldScript.subscribeUrl && oldScript.origin) {
// origin 和 subscribeUrl 保持不变
// @downloadURL @updateURL 随脚本最新代码而更新
script.origin = oldScript.origin;
script.subscribeUrl = oldScript.subscribeUrl;
}
}
if (script.ignoreVersion) script.ignoreVersion = "";
if (createtime) {
script.createtime = createtime;
}
if (updatetime) {
script.updatetime = updatetime;
}
return this.scriptDAO
.save(script)
.then(async () => {
await this.scriptCodeDAO.save({
uuid: script.uuid,
code: param.code,
});
logger.info("install success");
// Cache更新 & 下载资源
await Promise.all([
compiledResourceUpdatePromise,
this.resourceService.updateResourceByType(script, "require"),
this.resourceService.updateResourceByType(script, "require-css"),
this.resourceService.updateResourceByType(script, "resource"),
]);
// 广播一下
// Runtime 会负责更新 CompiledResource
this.publishInstallScript(script, { update, upsertBy });
// 传回(由后台控制的)实际更新时间,让 editor 中的script能保持正确的更新时间
return { update, updatetime: script.updatetime };
})
.catch((e: any) => {
logger.error("install error", Logger.E(e));
throw e;
});
}
async deleteScript(uuid: string, deleteBy?: InstallSource) {
let logger = this.logger.with({ uuid });
const script = await this.scriptDAO.get(uuid);
if (!script) {
logger.error("script not found");
throw new Error("script not found");
}
logger = logger.with({ name: script.name });
const storageName = getStorageName(script);
return this.scriptDAO
.delete(uuid)
.then(async () => {
await this.scriptCodeDAO.delete(uuid);
await this.compiledResourceDAO.delete(uuid);
logger.info("delete success");
const data = [{ uuid, storageName, type: script.type, deleteBy }] as TDeleteScript[];
this.mq.publish("deleteScripts", data);
return true;
})
.catch((e) => {
logger.error("delete error", Logger.E(e));
throw e;
});
}
async deleteScripts(uuids: string[]) {
const logger = this.logger.with({ uuids });
const scripts = (await this.scriptDAO.gets(uuids)).filter((s) => !!s);
if (!scripts.length) {
logger.error("scripts not found");
throw new Error("scripts not found");
}
return this.scriptDAO
.deletes(uuids)
.then(async () => {
await this.scriptCodeDAO.deletes(uuids);
await this.compiledResourceDAO.deletes(uuids);
logger.info("delete success");
const data = scripts.map((script) => ({
uuid: script.uuid,
storageName: getStorageName(script),
type: script.type,
})) as TDeleteScript[];
this.mq.publish<TDeleteScript[]>("deleteScripts", data);
return true;
})
.catch((e) => {
logger.error("delete error", Logger.E(e));
throw e;
});
}
async enableScript(param: { uuid: string; enable: boolean }) {
const { uuid, enable } = param;
const logger = this.logger.with({ uuid, enable });
const script = await this.scriptDAO.get(uuid);
if (!script) {
logger.error("script not found");
throw new Error("script not found");
}
return this.scriptDAO
.update(uuid, {
status: enable ? SCRIPT_STATUS_ENABLE : SCRIPT_STATUS_DISABLE,
updatetime: Date.now(),
})
.then(() => {
logger.info("enable success");
this.mq.publish<TEnableScript[]>("enableScripts", [{ uuid: uuid, enable: enable }]);
return {};
})
.catch((e) => {
logger.error("enable error", Logger.E(e));
throw e;
});
}
async enableScripts(param: { uuids: string[]; enable: boolean }) {
const { uuids, enable } = param;
const logger = this.logger.with({ uuids, enable });
const scripts = await this.scriptDAO.gets(uuids);
const uuids2: string[] = [];
for (let i = 0, l = uuids.length; i < l; i++) {
const script = scripts[i];
if (script && script.uuid && script.uuid === uuids[i]) {
uuids2.push(script.uuid);
}
}
if (!uuids2.length) {
logger.error("scripts not found");
throw new Error("scripts not found");
}
return this.scriptDAO
.updates(uuids2, {
status: enable ? SCRIPT_STATUS_ENABLE : SCRIPT_STATUS_DISABLE,
updatetime: Date.now(),
})
.then(() => {
logger.info("enable success");
this.mq.publish<TEnableScript[]>(
"enableScripts",
uuids2.map((uuid) => ({ uuid, enable }))
);
return {};
})
.catch((e) => {
logger.error("enable error", Logger.E(e));
throw e;
});
}
async fetchInfo(uuid: string) {
const script = await this.scriptDAO.get(uuid);
if (!script) {
return null;
}
return script;
}
async updateRunStatus(params: { uuid: string; runStatus: SCRIPT_RUN_STATUS; error?: string; nextruntime?: number }) {
// 如果脚本删除了就不再更新状态
const script = await this.scriptDAO.get(params.uuid);
if (!script) {
return false;
}
if (
(await this.scriptDAO.update(params.uuid, {
runStatus: params.runStatus,
lastruntime: Date.now(),
error: params.error,
nextruntime: params.nextruntime,
})) === false
) {
throw new Error("update error");
}
this.mq.publish<TScriptRunStatus>("scriptRunStatus", params);
return true;
}
async getFilterResult(req: { value: string }) {
const OPTION_CASE_INSENSITIVE = true;
const scripts = await this.scriptDAO.all();
const scriptCodes = await Promise.all(
scripts.map((script) => this.scriptCodeDAO.get(script.uuid).catch((_) => undefined))
);
const keyword = req.value.toLocaleLowerCase();
// 空格分开关键字搜索
const keys = keyword.split(/\s+/).filter((e) => e.length);
const results: Partial<Record<string, string | boolean>>[] = [];
const codeCache: Partial<Record<string, string>> = {}; // temp cache
if (!keys.length) return results;
for (let i = 0, l = scripts.length; i < l; i++) {
const script = scripts[i];
const scriptCode = scriptCodes[i];
const uuid = script.uuid;
const result: Partial<Record<string, string | boolean>> = { uuid };
const searchName = (keyword: string) => {
if (OPTION_CASE_INSENSITIVE) {
return stringMatching(script.name.toLowerCase(), keyword.toLowerCase());
}
return stringMatching(script.name, keyword);
};
const searchCode = (keyword: string) => {
let c = codeCache[script.uuid];
if (!c) {
const code = scriptCode;
if (code && code.uuid === script.uuid) {
codeCache[script.uuid] = c = code.code;
c = code.code;
}
}
if (c) {
if (OPTION_CASE_INSENSITIVE) {
return stringMatching(c.toLowerCase(), keyword.toLowerCase());
}
return stringMatching(c, keyword);
}
return false;
};
let codeMatched = true;
let nameMatched = true;
for (const key of keys) {
if (codeMatched && !searchCode(key)) {
codeMatched = false;
}
if (nameMatched && !searchName(key)) {
nameMatched = false;
}
if (!codeMatched && !nameMatched) break;
}
result.code = codeMatched;
result.name = nameMatched;
if (result.name || result.code) {
result.auto = true;
}
results.push(result);
}
return results;
}
async getScriptRunResourceByUUID(uuid: string) {
const script = await this.fetchInfo(uuid);
if (!script) return null;
const scriptRes = await this.buildScriptRunResource(script);
scriptRes.code = compileScriptCode(scriptRes);
return scriptRes;
}
async buildScriptRunResource(script: Script): Promise<ScriptRunResource> {
const ret = buildScriptRunResourceBasic(script);
return Promise.all([
this.valueService.getScriptValue(ret),
this.resourceService.getScriptResources(ret, true),
this.scriptCodeDAO.get(script.uuid),
]).then(([value, resource, code]) => {
if (!code) {
throw new Error("code is null");
}
ret.value = value;
ret.resource = resource;
ret.code = code.code;
return ret;
});
}
// ScriptMenuList 的 excludeUrl - 排除或回复
async excludeUrl({ uuid, excludePattern, remove }: { uuid: string; excludePattern: string; remove: boolean }) {
let script = await this.scriptDAO.get(uuid);
if (!script) {
throw new Error("script not found");
}
// 建立Set去掉重复(如有)
const excludeSet = new Set(script.selfMetadata?.exclude || script.metadata?.exclude || []);
if (remove) {
const deleted = excludeSet.delete(excludePattern);
if (!deleted) {
return; // scriptDAO 不用更新
}
} else {
excludeSet.add(excludePattern);
}
// 更新 script.selfMetadata.exclude
script = selfMetadataUpdate(script, "exclude", excludeSet);
return this.scriptDAO
.update(uuid, script)
.then(() => {
// 广播一下
this.publishInstallScript(script, { update: true });
return true;
})
.catch((e) => {
this.logger.error("exclude url error", Logger.E(e));
throw e;
});
}
async resetExclude({ uuid, exclude }: { uuid: string; exclude: string[] | undefined }) {
let script = await this.scriptDAO.get(uuid);
if (!script) {
throw new Error("script not found");
}
// 建立Set去掉重复(如有)
const excludeSet = new Set(exclude || []);
// 更新 script.selfMetadata.exclude
script = selfMetadataUpdate(script, "exclude", excludeSet);
return this.scriptDAO
.update(uuid, script)
.then(() => {
// 广播一下
this.publishInstallScript(script, { update: true });
return true;
})
.catch((e) => {
this.logger.error("reset exclude error", Logger.E(e));
throw e;
});
}
async resetMatch({ uuid, match }: { uuid: string; match: string[] | undefined }) {
let script = await this.scriptDAO.get(uuid);
if (!script) {
throw new Error("script not found");
}
// 建立Set去掉重复(如有)
const matchSet = new Set(match || []);
// 更新 script.selfMetadata.match
script = selfMetadataUpdate(script, "match", matchSet);
return this.scriptDAO
.update(uuid, script)
.then(() => {
// 广播一下
this.publishInstallScript(script, { update: true });
return true;
})
.catch((e) => {
this.logger.error("reset match error", Logger.E(e));
throw e;
});
}
async checkUpdatesAvailable(
uuids: string[],
opts: {
MIN_DELAY: number;
MAX_DELAY: number;
}
) {
// 检查更新有无
// 更新 checktime 并返回 script资料列表
const scripts = await this.scriptDAO.updates(uuids, { checktime: Date.now() });
const checkScripts = scripts.filter((script) => script && typeof script === "object" && script.checkUpdateUrl);
if (checkScripts.length === 0) return [];
const n = checkScripts.length;
let i = 0;
const { MIN_DELAY, MAX_DELAY } = opts;
const delayFn = () =>
new Promise((resolve) =>
setTimeout(resolve, Math.round(MIN_DELAY + ((++i / n + Math.random()) / 2) * (MAX_DELAY - MIN_DELAY)))
);
const CHECK_UPDATE_TIMEOUT_MS = 300_000; // 5 分钟超时
const results = new Map<
string,
| false
| {
updateAvailable: true;
code: string;
metadata: Partial<Record<string, string[]>>;
}
>();
// 预初始化 Map 确保顺序
for (const uuid of uuids as string[]) {
results.set(uuid, false);
}
const abortController = new AbortController();
let timeoutId: ReturnType<typeof setTimeout>;
const timeoutPromise = new Promise<void>((resolve) => {
timeoutId = setTimeout(() => {
abortController.abort();
resolve();
}, CHECK_UPDATE_TIMEOUT_MS);
});
await Promise.race([
timeoutPromise,
Promise.allSettled(
(uuids as string[]).map(async (uuid, _idx) => {
const script = scripts[_idx];
const res =
!script || script.uuid !== uuid || !checkScripts.includes(script)
? false
: await this._checkUpdateAvailable(script, delayFn, abortController.signal);
if (!res) return false;
results.set(uuid, res);
return res;
})
).finally(() => {
clearTimeout(timeoutId);
}),
]);
return [...results.values()];
}
async _checkUpdateAvailable(
script: {
uuid: string;
name: string;
checkUpdateUrl?: string;
metadata: Partial<Record<string, any>>;
},
delayFn?: () => Promise<any>,
signal?: AbortSignal
): Promise<false | { updateAvailable: true; code: string; metadata: SCMetadata }> {
const { uuid, name, checkUpdateUrl } = script;
if (!checkUpdateUrl) {
return false;
}
const logger = LoggerCore.logger({
uuid,
name,
});
try {
if (delayFn) {
if (signal?.aborted) return false;
await delayFn();
}
if (signal?.aborted) return false;
const code = await fetchScriptBody(checkUpdateUrl, signal);
const metadata = parseMetadata(code);
if (!metadata) {
logger.error("parse metadata failed");
return false;
}
const newVersion = metadata.version?.[0] || "0.0";
const oldVersion = script.metadata.version?.[0] || "0.0";
// 对比版本大小
if (ltever(newVersion, oldVersion)) {
return false;
}
return { updateAvailable: true, code, metadata };
} catch (e) {
logger.error("check update failed", Logger.E(e));
return false;
}
}
async checkUpdateAvailable(uuid_: string) {
// 检查更新
const script = await this.scriptDAO.get(uuid_);
if (!script || !script.checkUpdateUrl) {
return false;
}
await this.scriptDAO.update(uuid_, { checktime: Date.now() });
const res = await this._checkUpdateAvailable(script);
if (!res) return false;
return script;
}
async openUpdateOrInstallPage(
uuid: string,
url: string,
options: { source: InstallSource; byWebRequest?: boolean },
update: boolean,
logger?: Logger
) {
const upsertBy = options.source;
const code = await fetchScriptBody(url);
if (update && (await this.systemConfig.getSilenceUpdateScript())) {
try {
const { oldScript, script } = await prepareScriptByCode(code, url, uuid);
if (checkSilenceUpdate(oldScript!.metadata, script.metadata)) {
logger?.info("silence update script");
await this.installScript({
script,
code,
upsertBy,
});
return 2;
}
// 如果不符合静默更新规则,走后面的流程
logger?.info("not silence update script, open install page");
} catch (e) {
logger?.error("prepare script failed", Logger.E(e));
}
}
const metadata = parseMetadata(code);
if (!metadata) {
throw new Error("parse script info failed");
}
const si = await createTempCodeEntry(update, uuid, code, url, upsertBy, metadata, options);
await new TempStorageDAO().save({
key: uuid,
value: si,
savedAt: Date.now(),
type: TempStorageItemType.tempCode,
});
return 1;
}
// 打开更新窗口
public async openUpdatePage(script: Script, source: "user" | "system") {
const { uuid, name, downloadUrl, checkUpdateUrl } = script;
const logger = this.logger.with({
uuid,
name,
downloadUrl,
checkUpdateUrl,
});
const url = downloadUrl || checkUpdateUrl!;
try {
const ret = await this.openUpdateOrInstallPage(uuid, url, { source }, true, logger);
if (ret === 2) return; // slience update
// 打开安装页面
openInCurrentTab(`/src/install.html?uuid=${uuid}`);
} catch (e) {
logger.error("fetch script info failed", Logger.E(e));
}
}
async openBatchUpdatePage(opts: TOpenBatchUpdatePageOption) {
const { q, dontCheckNow } = opts;
const p = q ? `?${q}` : "";
await openInCurrentTab(`/src/batchupdate.html${p}`);
if (!dontCheckNow) {
await this.checkScriptUpdate({ checkType: "user", noUpdateCheck: 10 * 60 * 1000 });
}
return true;
}
shouldIgnoreUpdate(script: Script, newMeta: Partial<Record<string, string[]>> | null) {
const newVersion = newMeta?.version?.[0];
return typeof newVersion === "string" && script.ignoreVersion === newVersion;
}
// 用于定时自动检查脚本更新
async _checkScriptUpdate(opts: TCheckScriptUpdateOption): Promise<
| {
ok: true;
targetSites: string[];
err?: undefined;
fresh: boolean;
checktime: number;
}
| {
ok: false;
targetSites?: undefined;
err?: string | Error;
}
> {
// const executeSlienceUpdate = opts.checkType === "system";
const executeSlienceUpdate = opts.checkType === "system" && (await this.systemConfig.getSilenceUpdateScript());
// const executeSlienceUpdate = true;
const checkCycle = await this.systemConfig.getCheckScriptUpdateCycle();
if (!checkCycle) {
return {
ok: false,
err: "checkCycle is undefined.",
};
}
const checkDisableScript = await this.systemConfig.getUpdateDisableScript();
const scripts = await this.scriptDAO.all();
// const now = Date.now();
const checkScripts = scripts.filter((script) => {
// 不检查更新
if (script.checkUpdate === false || !script.checkUpdateUrl) {
return false;
}
// 是否检查禁用脚本
if (!checkDisableScript && script.status === SCRIPT_STATUS_DISABLE) {
return false;
}
// 检查是否符合
// if (script.checktime + checkCycle * 1000 > now) {
// return false;
// }
return true;
});
const checkDelay =