-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpopup.js
More file actions
1811 lines (1647 loc) · 59 KB
/
popup.js
File metadata and controls
1811 lines (1647 loc) · 59 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
// Linux DO 自动浏览 - Popup Script (极简风格)
const AVAILABLE_THEMES = [
{ id: 'system', name: '跟随系统' },
{ id: 'healing', name: '治愈' },
{ id: 'newyear', name: '新年' }
];
const DAILY_AUTO_KEY = 'linuxDoDailyAuto';
const DEFAULT_DAILY_AUTO = {
// 固定:每日任务默认开启
enabled: true,
// 固定:每日执行 10 次(浏览 10 个话题)
target: 10,
time: '01:00',
endTime: '11:00',
date: '',
count: 0,
running: false,
requireHidden: true
};
const INTERNAL_LOG_KEY = 'linuxDoInternalLogs';
const INTERNAL_LOG_UI_KEY = 'linuxDoDebugUi';
const STOP_SIGNAL_KEY = 'linuxDoStopSignalAt';
const DEBUG_UNLOCK_CLICK_COUNT = 3;
const DEBUG_UNLOCK_CLICK_GAP = 600;
function safeStorageGet(keys) {
return new Promise((resolve) => {
if (!chrome?.storage?.local) {
resolve({});
return;
}
try {
chrome.storage.local.get(keys, (result) => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
console.warn('[Popup] storage.get failed', lastError.message);
resolve({});
return;
}
resolve(result || {});
});
} catch (error) {
console.warn('[Popup] storage.get threw', error);
resolve({});
}
});
}
function safeStorageSet(payload) {
return new Promise((resolve) => {
if (!chrome?.storage?.local) {
resolve();
return;
}
try {
chrome.storage.local.set(payload, () => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
console.warn('[Popup] storage.set failed', lastError.message);
}
resolve();
});
} catch (error) {
console.warn('[Popup] storage.set threw', error);
resolve();
}
});
}
function safeSessionGet(keys) {
return new Promise((resolve) => {
const sessionStorage = chrome?.storage?.session;
if (!sessionStorage) {
resolve({});
return;
}
try {
sessionStorage.get(keys, (result) => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
console.warn('[Popup] storage.session.get failed', lastError.message);
resolve({});
return;
}
resolve(result || {});
});
} catch (error) {
console.warn('[Popup] storage.session.get threw', error);
resolve({});
}
});
}
function safeSessionSet(payload) {
return new Promise((resolve) => {
const sessionStorage = chrome?.storage?.session;
if (!sessionStorage) {
resolve();
return;
}
try {
sessionStorage.set(payload, () => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
console.warn('[Popup] storage.session.set failed', lastError.message);
}
resolve();
});
} catch (error) {
console.warn('[Popup] storage.session.set threw', error);
resolve();
}
});
}
function safeChromePromise(promise, fallback) {
return Promise.resolve(promise).catch((error) => {
console.warn('[Popup] chrome promise rejected', error);
return fallback;
});
}
function safeTabsQuery(queryInfo) {
try {
return safeChromePromise(chrome.tabs.query(queryInfo), []);
} catch (error) {
console.warn('[Popup] tabs.query threw', error);
return Promise.resolve([]);
}
}
function safeTabsCreate(createProperties) {
try {
safeChromePromise(chrome.tabs.create(createProperties), null);
} catch (error) {
console.warn('[Popup] tabs.create threw', error);
}
}
function safeRuntimeSendMessage(message, fallback) {
try {
return safeChromePromise(chrome.runtime.sendMessage(message), fallback);
} catch (error) {
console.warn('[Popup] runtime.sendMessage threw', error);
return Promise.resolve(fallback);
}
}
class PopupPluginHost {
constructor() {
this.m_plugins = [];
}
register(plugin) {
if (!plugin || this.m_plugins.includes(plugin)) return;
this.m_plugins.push(plugin);
}
emitTabChanged(tabName) {
this.m_plugins.forEach((plugin) => {
if (typeof plugin.onTabChanged === 'function') {
plugin.onTabChanged(tabName);
}
});
}
emitThemeChanged(themeId) {
this.m_plugins.forEach((plugin) => {
if (typeof plugin.onThemeChanged === 'function') {
plugin.onThemeChanged(themeId);
}
});
}
}
class ThemeManager {
constructor(options = {}) {
this.storageKey = 'linuxDoTheme';
this.themes = AVAILABLE_THEMES;
this.currentThemeId = 'system';
this.panelEl = null;
this.openEl = null;
this.closeEl = null;
this.m_onThemeChanged = typeof options.onThemeChanged === 'function' ? options.onThemeChanged : null;
}
init() {
this.panelEl = document.getElementById('themePanel');
this.openEl = document.getElementById('openThemePanel');
this.closeEl = document.getElementById('closeThemePanel');
if (!this.panelEl || !this.openEl || !this.closeEl) return;
this.bindEvents();
this.loadStoredTheme();
}
loadStoredTheme() {
safeStorageGet([this.storageKey]).then((result) => {
const storedId = result[this.storageKey];
this.setTheme(this.isSupported(storedId) ? storedId : 'system', false);
});
}
bindEvents() {
this.openEl.addEventListener('click', () => this.openPanel());
this.closeEl.addEventListener('click', () => this.closePanel());
this.panelEl.addEventListener('click', (event) => {
if (event.target.classList.contains('theme-modal__backdrop')) {
this.closePanel();
}
});
this.panelEl.querySelectorAll('.theme-card').forEach((card) => {
card.addEventListener('click', () => {
const themeId = card.getAttribute('data-theme-id');
this.setTheme(themeId);
this.closePanel();
});
});
}
setTheme(themeId, persist = true) {
const targetId = this.isSupported(themeId) ? themeId : 'system';
if (targetId === 'system') {
document.body.removeAttribute('data-theme');
} else {
document.body.setAttribute('data-theme', targetId);
}
this.currentThemeId = targetId;
this.markActiveCard(targetId);
if (persist) {
safeStorageSet({ [this.storageKey]: targetId });
}
// 重新渲染统计页面的图表以应用新主题颜色
if (this.m_onThemeChanged) {
this.m_onThemeChanged(targetId);
return;
}
const statsPanel = document.querySelector('[data-panel="stats"]');
if (statsPanel && statsPanel.classList.contains('active') && typeof statsTab !== 'undefined') {
statsTab._renderStats();
}
}
isSupported(themeId) {
return this.themes.some((theme) => theme.id === themeId);
}
markActiveCard(themeId) {
const cards = this.panelEl?.querySelectorAll('.theme-card');
if (!cards) return;
cards.forEach((card) => {
const isActive = card.getAttribute('data-theme-id') === themeId;
card.classList.toggle('active', isActive);
});
}
openPanel() {
this.panelEl?.removeAttribute('hidden');
this.markActiveCard(this.currentThemeId);
}
closePanel() {
this.panelEl?.setAttribute('hidden', '');
}
}
class SiteManager {
constructor() {
this.storageKey = 'useIdcflareSite';
this.useIdcflare = false;
this.checkboxEl = null;
this.siteButtons = [];
}
async init() {
this.checkboxEl = document.getElementById('useIdcflareSite');
this.siteButtons = Array.from(document.querySelectorAll('.site-chip[data-site-id]'));
const data = await this.loadFromStorage();
this.useIdcflare = data || false;
this.updateUI();
this.bindEvents();
}
getBaseUrl() {
return this.useIdcflare ? 'https://idcflare.com' : 'https://linux.do';
}
getLatestUrl() {
return `${this.getBaseUrl()}/latest`;
}
getConnectBaseUrl() {
return this.useIdcflare ? 'https://connect.idcflare.com' : 'https://connect.linux.do';
}
getConnectHomeUrl() {
return `${this.getConnectBaseUrl()}/`;
}
isCurrentSite(tabUrl) {
if (this.useIdcflare) {
return /idcflare\.com/.test(tabUrl);
}
return /linux\.do/.test(tabUrl);
}
getSiteName() {
return this.useIdcflare ? 'IDCFlare' : 'Linux DO';
}
async toggle(value) {
this.useIdcflare = value;
await this.saveToStorage();
this.updateUI();
}
updateUI() {
const nameEl = document.getElementById('currentSiteName');
const inlineNameEl = document.getElementById('currentSiteNameInline');
const activeId = this.useIdcflare ? 'idcflare' : 'linuxdo';
if (document.body) {
document.body.setAttribute('data-site', activeId);
}
if (nameEl) {
nameEl.textContent = this.getSiteName();
}
if (inlineNameEl) {
inlineNameEl.textContent = this.getSiteName();
}
if (this.checkboxEl) {
this.checkboxEl.checked = this.useIdcflare;
}
if (this.siteButtons.length > 0) {
this.siteButtons.forEach((btn) => {
const isActive = btn.getAttribute('data-site-id') === activeId;
btn.classList.toggle('is-active', isActive);
btn.setAttribute('aria-checked', isActive ? 'true' : 'false');
});
}
if (activeId !== 'linuxdo') {
const invitesTab = document.querySelector('[data-tab="invites"]');
const controlTab = document.querySelector('[data-tab="control"]');
if (invitesTab?.classList.contains('active') && controlTab) {
controlTab.click();
}
}
}
bindEvents() {
if (this.checkboxEl) {
this.checkboxEl.addEventListener('change', (e) => {
this.toggle(e.target.checked);
});
}
if (this.siteButtons.length > 0) {
this.siteButtons.forEach((btn) => {
btn.addEventListener('click', () => {
const siteId = btn.getAttribute('data-site-id');
if (siteId === 'idcflare') {
this.toggle(true);
return;
}
if (siteId === 'linuxdo') {
this.toggle(false);
}
});
});
}
}
async loadFromStorage() {
const result = await safeStorageGet([this.storageKey]);
return result[this.storageKey];
}
async saveToStorage() {
await safeStorageSet({
[this.storageKey]: this.useIdcflare
});
}
}
class PopupController {
constructor() {
this.isRunning = false;
this.stats = {
totalBrowsed: 0,
startTime: null,
errors: 0,
currentPost: null
};
this.accumulatedTime = 0;
this.lastStartTime = null;
this.logs = [];
this.lastLogTimes = {};
this.dailyAutoToggleEl = null;
this.dailyAutoTimeEl = null;
this.dailyAutoRequireHiddenEl = null;
this.guidePanelEl = null;
this.guideOpenEl = null;
this.guideCloseEl = null;
this.versionBadgeEl = null;
this.debugClickCount = 0;
this.debugClickLastAt = 0;
this.debugUiEnabled = false;
this.config = {
minScrollDelay: 800,
maxScrollDelay: 3000,
minPageStay: 5000,
maxPageStay: 15000,
readDepth: 0.7,
clickProbability: 0.6,
quickMode: false,
skipDailyIdleWait: false
};
this.pluginHost = new PopupPluginHost();
this.themeManager = new ThemeManager({
onThemeChanged: (themeId) => this.pluginHost.emitThemeChanged(themeId)
});
this.siteManager = new SiteManager();
this.init();
}
registerPlugin(plugin) {
this.pluginHost.register(plugin);
}
init() {
this.themeManager.init();
this.siteManager.init();
this.initGuidePanel();
this.initVersionBadge();
this.bindEvents();
this.initInternalLogTools();
this.ensureDailyAutoConfig();
this.loadSettings();
this.loadLevelSummary();
this.initLevelBanner();
this.startTimer();
this.checkStatus().then(() => {
this.updateStatus();
});
// 初始化统计模块
if (typeof statsTab !== 'undefined') {
if (typeof statsTab.setTabChangeHandler === 'function') {
statsTab.setTabChangeHandler((tabName) => this.pluginHost.emitTabChanged(tabName));
}
statsTab.init();
this.pluginHost.register(statsTab);
}
}
async checkStatus() {
const [tab] = await safeTabsQuery({ active: true, currentWindow: true });
if (!tab.url || !this.siteManager.isCurrentSite(tab.url)) {
return;
}
const result = await safeStorageGet(['linux_do_auto_state']);
if (result.linux_do_auto_state) {
const state = result.linux_do_auto_state;
this.isRunning = state.isRunning || false;
if (state.stats) {
this.stats.totalBrowsed = state.stats.totalBrowsed || 0;
this.stats.startTime = state.stats.startTime || null;
this.stats.errors = state.stats.errors || 0;
}
this.accumulatedTime = state.accumulatedTime || 0;
this.lastStartTime = state.lastStartTime || null;
this.updateStats();
}
}
initLevelBanner() {
const levelBanner = document.getElementById('levelBanner');
if (!levelBanner) return;
levelBanner.addEventListener('click', (event) => {
if (event.target.closest('#levelLoginBtn')) return;
if (levelBanner.dataset.loginNeeded === 'true') {
safeTabsCreate({ url: this.siteManager.getConnectHomeUrl() });
}
});
}
initVersionBadge() {
this.versionBadgeEl = document.getElementById('versionBadge');
if (!this.versionBadgeEl) return;
const manifest = chrome?.runtime?.getManifest?.();
const versionText = manifest?.version ? `v${manifest.version}` : 'v0.0.0';
this.versionBadgeEl.textContent = versionText;
if (manifest?.version) {
this.versionBadgeEl.setAttribute('title', `版本 ${manifest.version}`);
}
this.versionBadgeEl.addEventListener('click', () => this.handleDebugUnlockClick());
this.versionBadgeEl.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this.handleDebugUnlockClick();
}
});
}
handleDebugUnlockClick() {
if (this.debugUiEnabled) return;
const now = Date.now();
if (now - this.debugClickLastAt > DEBUG_UNLOCK_CLICK_GAP) {
this.debugClickCount = 0;
}
this.debugClickLastAt = now;
this.debugClickCount += 1;
if (this.debugClickCount >= DEBUG_UNLOCK_CLICK_COUNT) {
this.debugClickCount = 0;
this.enableDebugUi(true);
}
}
enableDebugUi(persist = true) {
if (this.debugUiEnabled) return;
this.debugUiEnabled = true;
if (document.body) {
document.body.classList.add('debug-ui-enabled');
}
const toolsEl = document.getElementById('internalLogTools');
if (toolsEl) {
toolsEl.removeAttribute('hidden');
}
const logsSectionEl = document.getElementById('logsSection');
if (logsSectionEl) {
logsSectionEl.removeAttribute('hidden');
}
if (this.versionBadgeEl) {
this.versionBadgeEl.classList.add('version-badge--active');
}
if (persist) {
safeSessionSet({ [INTERNAL_LOG_UI_KEY]: true });
}
}
initInternalLogTools() {
const toolsEl = document.getElementById('internalLogTools');
if (!toolsEl) return;
safeSessionGet([INTERNAL_LOG_UI_KEY]).then((result) => {
if (result[INTERNAL_LOG_UI_KEY]) {
this.enableDebugUi(false);
}
});
safeStorageGet([INTERNAL_LOG_UI_KEY]).then((result) => {
if (result[INTERNAL_LOG_UI_KEY]) {
safeStorageSet({ [INTERNAL_LOG_UI_KEY]: false });
}
});
}
bindEvents() {
document.getElementById('startBtn').addEventListener('click', () => this.start());
document.getElementById('stopBtn').addEventListener('click', () => this.stop());
document.getElementById('resetBtn').addEventListener('click', () => this.resetAndStart());
document.getElementById('clearHistoryBtn').addEventListener('click', () => this.clearHistory());
document.getElementById('applySettings').addEventListener('click', () => this.applySettings());
document.getElementById('clearLogs').addEventListener('click', () => this.clearLogs());
document.getElementById('copyLogs').addEventListener('click', () => this.copyLogs());
const exportInternalLogs = document.getElementById('exportInternalLogs');
if (exportInternalLogs) {
exportInternalLogs.addEventListener('click', () => this.exportInternalLogs());
}
const clearInternalLogs = document.getElementById('clearInternalLogs');
if (clearInternalLogs) {
clearInternalLogs.addEventListener('click', () => this.clearInternalLogs());
}
const openLatest = document.getElementById('openLatest');
if (openLatest) {
openLatest.addEventListener('click', (e) => {
e.preventDefault();
safeTabsCreate({ url: this.siteManager.getLatestUrl() });
});
}
const latestStats = document.getElementById('openLatestStats');
if (latestStats) {
latestStats.addEventListener('click', (e) => {
e.preventDefault();
safeTabsCreate({ url: this.siteManager.getLatestUrl() });
});
}
const latestInvites = document.getElementById('openLatestInvites');
if (latestInvites) {
latestInvites.addEventListener('click', (e) => {
e.preventDefault();
safeTabsCreate({ url: this.siteManager.getLatestUrl() });
});
}
// [交互增强] 监听设置面板展开事件,自动滚动到底部
const settingsPanel = document.getElementById('settingsPanel');
if (settingsPanel) {
settingsPanel.addEventListener('toggle', (e) => {
if (settingsPanel.open) {
// 给一点时间让浏览器渲染展开动画
setTimeout(() => {
// 平滑滚动到底部
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
}, 150);
}
});
}
}
async start() {
const [tab] = await safeTabsQuery({ active: true, currentWindow: true });
if (!tab.url || !this.siteManager.isCurrentSite(tab.url)) {
this.log(`请在 ${this.siteManager.getSiteName()} 页面使用`, 'error');
return;
}
this.sendMessageWithRetry(tab.id, { action: 'start' }, (response) => {
if (response?.success && this.isRunning) {
this.updateStatus();
this.log('开始自动浏览', 'info');
}
});
}
sendMessageWithRetry(tabId, message, callback, retries = 3, silent = false) {
try {
chrome.tabs.sendMessage(tabId, message, (response) => {
if (chrome.runtime.lastError) {
if (retries > 0) {
setTimeout(() => {
this.sendMessageWithRetry(tabId, message, callback, retries - 1, silent);
}, 500);
} else {
if (!silent) {
this.log('请刷新页面后重试', 'error');
}
}
return;
}
if (callback) callback(response);
});
} catch (error) {
if (retries > 0) {
setTimeout(() => {
this.sendMessageWithRetry(tabId, message, callback, retries - 1, silent);
}, 500);
} else if (!silent) {
this.log('请刷新页面后重试', 'error');
}
}
}
async stop() {
await safeStorageSet({ [STOP_SIGNAL_KEY]: Date.now() });
const tabs = await safeTabsQuery({
url: ['https://linux.do/*', 'https://idcflare.com/*']
});
if (!tabs.length) {
this.isRunning = false;
this.updateStatus();
this.log('没有可停止的浏览任务', 'warning');
return;
}
tabs.forEach((tab) => {
if (!tab?.id) return;
this.sendMessageWithRetry(tab.id, { action: 'stop' }, null, 3, true);
});
this.isRunning = false;
this.updateStatus();
this.log('已发送停止指令', 'warning');
}
initGuidePanel() {
this.guidePanelEl = document.getElementById('guidePanel');
this.guideOpenEl = document.getElementById('openGuidePanel');
this.guideCloseEl = document.getElementById('closeGuidePanel');
if (!this.guidePanelEl || !this.guideOpenEl || !this.guideCloseEl) return;
this.guideOpenEl.addEventListener('click', () => this.openGuidePanel());
this.guideCloseEl.addEventListener('click', () => this.closeGuidePanel());
this.guidePanelEl.addEventListener('click', (event) => {
if (event.target.classList.contains('theme-modal__backdrop')) {
this.closeGuidePanel();
}
});
}
openGuidePanel() {
this.guidePanelEl?.removeAttribute('hidden');
}
closeGuidePanel() {
this.guidePanelEl?.setAttribute('hidden', '');
}
async resetAndStart() {
const [tab] = await safeTabsQuery({ active: true, currentWindow: true });
if (!tab.url || !this.siteManager.isCurrentSite(tab.url)) {
this.log(`请在 ${this.siteManager.getSiteName()} 页面使用`, 'error');
return;
}
this.sendMessageWithRetry(tab.id, { action: 'resetAndStart' }, (response) => {
if (response?.success && this.isRunning) {
this.stats.totalBrowsed = 0;
this.updateStatus();
this.updateStats();
this.log('重置并重新开始浏览', 'warning');
}
});
}
async clearHistory() {
const [tab] = await safeTabsQuery({ active: true, currentWindow: true });
this.sendMessageWithRetry(tab.id, { action: 'resetHistory' }, (response) => {
if (response?.success) {
this.stats.totalBrowsed = 0;
this.updateStats();
this.log('已清空浏览历史', 'info');
}
});
}
async applySettings() {
let minCommentRead = parseFloat(document.getElementById('minCommentRead').value) * 1000;
let maxCommentRead = parseFloat(document.getElementById('maxCommentRead').value) * 1000;
let minPageStay = parseInt(document.getElementById('minPageStay').value) * 1000;
let maxPageStay = parseInt(document.getElementById('maxPageStay').value) * 1000;
if (minCommentRead > maxCommentRead) [minCommentRead, maxCommentRead] = [maxCommentRead, minCommentRead];
if (minPageStay > maxPageStay) [minPageStay, maxPageStay] = [maxPageStay, minPageStay];
const newConfig = {
minScrollDelay: 800,
maxScrollDelay: 3000,
minCommentRead: minCommentRead,
maxCommentRead: maxCommentRead,
minPageStay: minPageStay,
maxPageStay: maxPageStay,
readDepth: 0.7,
clickProbability: parseFloat(document.getElementById('clickProbability').value),
quickMode: document.getElementById('quickMode').checked,
skipDailyIdleWait: document.getElementById('skipDailyIdleWait').checked
};
if (newConfig.minCommentRead >= newConfig.maxCommentRead) {
this.log('最小评论阅读时间必须小于最大评论阅读时间', 'error');
return;
}
if (newConfig.minPageStay >= newConfig.maxPageStay) {
this.log('最小页面停留时间必须小于最大页面停留时间', 'error');
return;
}
this.config = newConfig;
this.saveSettings();
const [tab] = await safeTabsQuery({ active: true, currentWindow: true });
if (tab?.id) {
this.sendMessageWithRetry(tab.id, {
action: 'updateConfig',
config: this.config
});
}
this.log('设置已更新', 'info');
// 应用后自动收起
const settingsPanel = document.getElementById('settingsPanel');
if (settingsPanel) settingsPanel.removeAttribute('open');
}
updateStatus() {
const statusBadge = document.getElementById('statusBadge');
const statusText = statusBadge.querySelector('.status-text');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
if (this.isRunning) {
statusBadge.classList.add('running');
statusText.textContent = '运行中';
startBtn.disabled = true;
stopBtn.disabled = false;
} else {
statusBadge.classList.remove('running');
statusText.textContent = '未运行';
startBtn.disabled = false;
stopBtn.disabled = true;
}
}
updateStats() {
const totalBrowsed = Number(this.stats.totalBrowsed) || 0;
const errors = Number(this.stats.errors) || 0;
const browsedEl = document.getElementById('browsedCount');
if (browsedEl) {
browsedEl.textContent = totalBrowsed;
}
}
async loadLevelSummary() {
const titleEl = document.getElementById('levelTitle');
const metaEl = document.getElementById('levelMeta');
const badgeEl = document.getElementById('levelBadge');
const visitEl = document.getElementById('levelVisitDays');
const topicsEl = document.getElementById('levelTopics');
const postsEl = document.getElementById('levelPosts');
const heroValueEl = document.getElementById('levelHeroValue');
const heroNameEl = document.getElementById('levelHeroName');
const heroDescEl = document.getElementById('levelHeroDesc');
const loginBtn = document.getElementById('levelLoginBtn');
const bannerEl = document.getElementById('levelBanner');
if (!titleEl || !metaEl || !badgeEl) return;
const resetMetric = (el) => {
if (!el) return;
el.textContent = '—';
const metricEl = el.closest('.level-metric');
if (metricEl) {
metricEl.style.setProperty('--progress', '0');
metricEl.classList.remove('is-met');
}
};
const setLoadingState = () => {
titleEl.textContent = '信任级别 —';
metaEl.textContent = '正在获取 Connect 数据…';
badgeEl.textContent = '读取中';
badgeEl.className = 'badge';
if (heroValueEl) heroValueEl.textContent = '—';
if (heroNameEl) heroNameEl.textContent = '信任级别';
if (heroDescEl) heroDescEl.textContent = metaEl.textContent;
if (loginBtn) loginBtn.setAttribute('hidden', '');
if (bannerEl) {
bannerEl.dataset.loginNeeded = 'false';
bannerEl.classList.remove('is-login-needed');
bannerEl.classList.remove('is-empty');
}
resetMetric(visitEl);
resetMetric(topicsEl);
resetMetric(postsEl);
};
setLoadingState();
const parseConnectDocument = (doc) => {
const PATTERNS = {
TRUST_LEVEL: /(.*) - 信任级别 (\\d+)/,
TRUST_LEVEL_H1: /你好,.*?\\(([^)]+)\\)\\s*(\\d+)级用户/
};
const getText = (el) => (el?.textContent || '').trim();
const findSection = () => {
const candidates = Array.from(doc.querySelectorAll('.bg-white.p-6.rounded-lg, .card'));
return candidates.find((d) => {
const titleText = getText(d.querySelector('h2, .card-title'));
return /信任级别|trust\\s*level/i.test(titleText) || !!d.querySelector('.tl3-rings, .tl3-bars, .tl3-quota, .tl3-veto');
}) || null;
};
const pageTitle = doc.querySelector('title')?.textContent || '';
let username = null;
let level = null;
const h1El = doc.querySelector('h1');
if (h1El) {
const h1Match = getText(h1El).match(PATTERNS.TRUST_LEVEL_H1);
if (h1Match) {
username = h1Match[1];
level = h1Match[2];
}
}
const userInfoText = getText(doc.querySelector('.user-menu-info div:last-child')) || getText(doc.querySelector('.user-menu-info'));
if (userInfoText) {
const userInfoMatch = userInfoText.match(/@([^@\\s·|]+).*?(?:信任级别|trust\\s*level)\\s*(\\d+)/i);
if (userInfoMatch) {
if (!username) username = userInfoMatch[1];
if (!level) level = userInfoMatch[2];
}
}
const section = findSection();
const heading = getText(section?.querySelector('h2, .card-title'));
if (heading) {
const oldMatch = heading.match(PATTERNS.TRUST_LEVEL);
if (oldMatch) {
if (!username) username = oldMatch[1].trim();
if (!level) level = oldMatch[2];
}
const levelMatch = heading.match(/(?:信任级别|trust\\s*level)\\s*(\\d+)/i);
if (levelMatch && !level) level = levelMatch[1];
}
const subtitle = getText(section?.querySelector('.card-subtitle'));
if (!username && subtitle) {
const subtitleMatch = subtitle.match(/@([^@\\s·|]+)/);
if (subtitleMatch) username = subtitleMatch[1];
}
const metrics = {};
doc.querySelectorAll('.tl3-ring').forEach((ring) => {
const labelEl = ring.querySelector('.tl3-ring-label');
const currentEl = ring.querySelector('.tl3-ring-current');
const targetEl = ring.querySelector('.tl3-ring-target');
if (!labelEl || !currentEl || !targetEl) return;
const label = labelEl.textContent.trim();
const current = currentEl.textContent.trim();
const target = targetEl.textContent.replace('/', '').trim();
if (!label) return;
metrics[label] = { current, target };
});
const badgeEl = section?.querySelector('.badge, .status-met, .status-unmet, p[class*=\"status\"]')
|| doc.querySelector('.page-content .card .badge') || doc.querySelector('.card .badge');
const titleText = heading ? heading.replace('的要求', '').trim() : (level ? `信任级别 ${level}` : '');
const subtitleText = subtitle || userInfoText || (username ? `@${username}` : '');
const loggedIn = !!(level || username || subtitleText || Object.keys(metrics).length > 0);
return {
title: titleText,
subtitle: subtitleText,
badge: getText(badgeEl),
loggedIn,
metrics,
pageTitle
};
};
const applySummary = (summary) => {
if (!summary || typeof summary !== 'object') {
throw new Error('no_data');
}
const pageTitle = summary.pageTitle || '';
const metrics = summary.metrics || {};
const hasMetrics = Object.keys(metrics).length > 0;
const loggedIn = summary.loggedIn === true || hasMetrics;
const isLoginPage = /登录|Login|Sign in/i.test(pageTitle);
if (!loggedIn || isLoginPage) throw new Error('not_logged_in');
const rawTitle = (summary.title || '').replace('的要求', '').trim();
if (!rawTitle) throw new Error('no_data');
const titleMatch = rawTitle.match(/(信任级别)\s*(\d+)/);
if (titleMatch) {
titleEl.innerHTML = `<span class="level-title-label">${titleMatch[1]}</span><span class="level-title-value">${titleMatch[2]}</span>`;
if (heroValueEl) heroValueEl.textContent = titleMatch[2];
if (heroNameEl) heroNameEl.textContent = titleMatch[1];
} else {
titleEl.textContent = rawTitle;
if (heroValueEl) heroValueEl.textContent = '—';
}
const subtitleText = (summary.subtitle || '').trim();
const syncTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
metaEl.textContent = subtitleText ? `${subtitleText} · 同步 ${syncTime}` : `已同步 ${syncTime}`;
if (heroDescEl) heroDescEl.textContent = metaEl.textContent;
if (loginBtn) loginBtn.setAttribute('hidden', '');
if (bannerEl) {
bannerEl.dataset.loginNeeded = 'false';
bannerEl.classList.remove('is-login-needed');
bannerEl.classList.remove('is-empty');
}
const badgeText = (summary.badge || '—').trim();
badgeEl.textContent = badgeText || '—';
badgeEl.className = 'badge';
if (/已达|已达到/.test(badgeText)) {
badgeEl.classList.add('badge-success');
} else if (/未达|未达到/.test(badgeText)) {
badgeEl.classList.add('badge-warning');
}
const mapping = [
['访问天数', visitEl],
['浏览话题', topicsEl],
['浏览帖子', postsEl]
];
let updatedCount = 0;
const setMetricValue = (outputEl, value) => {
if (!outputEl) return;
const metricEl = outputEl.closest('.level-metric');
const match = String(value).match(/([\d.]+)\s*\/\s*([\d.]+)/);
if (match) {
const current = Number(match[1]);
const target = Number(match[2]);
outputEl.innerHTML = `<span class="level-metric__current">${match[1]}</span><span class="level-metric__target">/${match[2]}</span>`;
if (metricEl && target > 0) {
const progress = Math.min(1, current / target);
metricEl.style.setProperty('--progress', progress.toFixed(3));
metricEl.classList.toggle('is-met', current >= target);
}
updatedCount += 1;
} else {
outputEl.textContent = value;