-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontent.js
More file actions
1494 lines (1297 loc) · 47 KB
/
Copy pathcontent.js
File metadata and controls
1494 lines (1297 loc) · 47 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 自动浏览 - Content Script
// 使用持久化存储,支持页面跳转后继续运行
const STORAGE_KEY = 'linux_do_auto_state';
const DAILY_AUTO_KEY = 'linuxDoDailyAuto';
const INTERNAL_LOG_KEY = 'linuxDoInternalLogs';
const INTERNAL_LOG_LIMIT = 50;
const STOP_SIGNAL_KEY = 'linuxDoStopSignalAt';
const DEFAULT_DAILY_AUTO = {
// 固定:每日任务默认开启
enabled: true,
// 固定:每日执行 10 次(浏览 10 个新话题)
target: 10,
time: '01:00',
endTime: '11:00',
date: '',
count: 0,
running: false,
requireHidden: true
};
const DAILY_AUTO_IDLE_WAIT_MS = 10 * 60 * 1000;
const SITE_ACTIVITY_REPORT_INTERVAL_MS = 15 * 1000;
const DEFAULT_DAILY_AUTO_IDLE = {
lastActionAt: 0,
waitUntil: 0,
pending: false
};
const statsRecorder = typeof StatsRecorder === 'undefined' ? null : StatsRecorder;
class HumanBrowser {
constructor() {
this.currentUrl = window.location.href;
this.config = {
minScrollDelay: 800,
maxScrollDelay: 3000,
minPageStay: 5000,
maxPageStay: 15000,
minCommentRead: 1000,
maxCommentRead: 4000,
readDepth: 0.7,
mouseMoveProbability: 0.3,
clickProbability: 0.6,
quickMode: false,
skipDailyIdleWait: false
};
this.dailyAuto = { ...DEFAULT_DAILY_AUTO };
this.dailyAutoWaitTimer = null;
this.idleStateSaveTimer = null;
this.activityHandler = null;
this.lastActivityReportAt = 0;
this.lastVisibilityReported = null;
this.pendingSleeps = new Set();
this.lastStopSignalAt = 0;
this.storageChangeListenerAttached = false;
this.handleStorageChangedBound = this.handleStorageChanged.bind(this);
this.attachStorageChangeListener();
this.init().catch((error) => {
const messageText = error?.message || String(error);
this.recordInternalError('init_failed', messageText);
});
}
isContextValid() {
return !!chrome?.runtime?.id;
}
safeStorageGet(keys) {
if (!chrome?.storage?.local) return Promise.resolve({});
return new Promise((resolve) => {
try {
chrome.storage.local.get(keys, (result) => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
this.recordInternalError('storage_get_failed', lastError.message || 'unknown');
resolve({});
return;
}
resolve(result || {});
});
} catch (error) {
const messageText = error?.message || String(error);
this.recordInternalError('storage_get_threw', messageText);
resolve({});
}
});
}
safeStorageSet(payload) {
if (!chrome?.storage?.local) return Promise.resolve();
return new Promise((resolve) => {
try {
chrome.storage.local.set(payload, () => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
this.recordInternalError('storage_set_failed', lastError.message || 'unknown');
}
resolve();
});
} catch (error) {
const messageText = error?.message || String(error);
this.recordInternalError('storage_set_threw', messageText);
resolve();
}
});
}
safeStorageRemove(keys) {
if (!chrome?.storage?.local) return Promise.resolve();
return new Promise((resolve) => {
try {
chrome.storage.local.remove(keys, () => {
const lastError = chrome.runtime?.lastError;
if (lastError) {
this.recordInternalError('storage_remove_failed', lastError.message || 'unknown');
}
resolve();
});
} catch (error) {
const messageText = error?.message || String(error);
this.recordInternalError('storage_remove_threw', messageText);
resolve();
}
});
}
// 从存储加载状态
async loadState() {
const result = await this.safeStorageGet([STORAGE_KEY]);
return result[STORAGE_KEY] || {
isRunning: false,
browsedPosts: [],
stats: {
totalBrowsed: 0,
startTime: null,
errors: 0
},
accumulatedTime: 0,
lastStartTime: null,
config: this.config,
dailyAutoIdle: { ...DEFAULT_DAILY_AUTO_IDLE }
};
}
// 保存状态到存储
async saveState(state) {
await this.safeStorageSet({ [STORAGE_KEY]: state });
}
getTodayString() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
parseDateString(dateStr) {
if (!dateStr || typeof dateStr !== 'string') return null;
const parts = dateStr.split('-');
if (parts.length !== 3) return null;
const year = Number(parts[0]);
const month = Number(parts[1]);
const day = Number(parts[2]);
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) return null;
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
return new Date(year, month - 1, day, 0, 0, 0, 0);
}
parseDailyTime(time) {
if (!time || typeof time !== 'string') return { hour: 9, minute: 0, valid: false };
const parts = time.split(':');
if (parts.length !== 2) return { hour: 9, minute: 0, valid: false };
const hour = Number(parts[0]);
const minute = Number(parts[1]);
if (!Number.isInteger(hour) || !Number.isInteger(minute)) return { hour: 9, minute: 0, valid: false };
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return { hour: 9, minute: 0, valid: false };
return { hour, minute, valid: true };
}
formatDailyTime(hour, minute) {
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
}
normalizeDailyTime(time) {
const parsed = this.parseDailyTime(time);
return this.formatDailyTime(parsed.hour, parsed.minute);
}
defaultDailyEndTime(startTime) {
const parsed = this.parseDailyTime(startTime);
const totalMinutes = parsed.hour * 60 + parsed.minute + 600;
const normalizedMinutes = totalMinutes % (24 * 60);
return this.formatDailyTime(Math.floor(normalizedMinutes / 60), normalizedMinutes % 60);
}
getDailyAutoWindow(dateStr, startTime, endTime) {
const baseDate =
this.parseDateString(dateStr) || this.parseDateString(this.getTodayString()) || new Date();
const startParts = this.parseDailyTime(startTime);
const endParts = this.parseDailyTime(endTime);
const startDate = new Date(baseDate);
startDate.setHours(startParts.hour, startParts.minute, 0, 0);
const endDate = new Date(baseDate);
endDate.setHours(endParts.hour, endParts.minute, 0, 0);
if (endDate <= startDate) {
endDate.setDate(endDate.getDate() + 1);
}
return { startMs: startDate.getTime(), endMs: endDate.getTime() };
}
normalizeDailyAuto(raw) {
const today = this.getTodayString();
const config = { ...DEFAULT_DAILY_AUTO, ...(raw || {}) };
// 固定:不再暴露开关,始终开启
config.enabled = true;
config.time = DEFAULT_DAILY_AUTO.time;
config.endTime = this.defaultDailyEndTime(config.time);
config.requireHidden = config.requireHidden === true;
const normalizedDate = this.parseDateString(config.date) ? config.date : today;
config.date = normalizedDate;
const window = this.getDailyAutoWindow(config.date, config.time, config.endTime);
const now = Date.now();
if (config.date !== today && (!config.running || now >= window.endMs)) {
config.date = today;
config.count = 0;
config.running = false;
}
if (!config.target || config.target < 1) {
config.target = DEFAULT_DAILY_AUTO.target;
}
return config;
}
normalizeDailyAutoIdle(raw) {
const base = raw && typeof raw === 'object' ? raw : {};
return {
lastActionAt: Number.isFinite(base.lastActionAt) ? base.lastActionAt : 0,
waitUntil: Number.isFinite(base.waitUntil) ? base.waitUntil : 0,
pending: base.pending === true
};
}
getDailyAutoWaitMs() {
return this.config.skipDailyIdleWait ? 0 : DAILY_AUTO_IDLE_WAIT_MS;
}
async loadDailyAuto() {
const result = await this.safeStorageGet([DAILY_AUTO_KEY]);
const stored = result[DAILY_AUTO_KEY];
const normalized = this.normalizeDailyAuto(stored);
const shouldSave =
!stored ||
stored.time !== normalized.time ||
stored.endTime !== normalized.endTime ||
stored.date !== normalized.date ||
stored.enabled !== normalized.enabled ||
stored.target !== normalized.target ||
stored.requireHidden !== normalized.requireHidden;
if (shouldSave) {
await this.safeStorageSet({ [DAILY_AUTO_KEY]: normalized });
}
return normalized;
}
async saveDailyAuto(config) {
await this.safeStorageSet({ [DAILY_AUTO_KEY]: config });
}
isDailyAutoRunning() {
return this.dailyAuto?.running === true;
}
isQuickModeEnabled() {
return this.config.quickMode && !this.isDailyAutoRunning();
}
initUserActivityTracking() {
if (this.activityHandler) return;
this.activityHandler = () => this.recordUserActivity();
const events = ['pointerdown', 'keydown', 'wheel', 'scroll', 'touchstart', 'mousedown'];
events.forEach((eventName) => {
window.addEventListener(eventName, this.activityHandler, { passive: true, capture: true });
});
document.addEventListener('visibilitychange', () => {
this.reportVisibilityState();
if (document.visibilityState === 'visible') {
this.recordUserActivity();
}
});
this.reportVisibilityState(true);
}
recordUserActivity() {
if (!this.state?.dailyAutoIdle) return;
this.reportSiteActivity();
const now = Date.now();
this.state.dailyAutoIdle.lastActionAt = now;
if (this.state.dailyAutoIdle.pending) {
const waitMs = this.getDailyAutoWaitMs();
if (waitMs <= 0) {
this.tryStartPendingDailyAuto();
} else {
this.state.dailyAutoIdle.waitUntil = now + waitMs;
this.scheduleIdleStateSave();
this.scheduleDailyAutoWaitCheck();
}
}
}
reportVisibilityState(force = false) {
const visible = document.visibilityState === 'visible';
if (!force && this.lastVisibilityReported === visible) return;
this.lastVisibilityReported = visible;
this.sendMessage({ type: 'siteVisibility', visible, at: Date.now() });
}
reportSiteActivity() {
const now = Date.now();
if (now - this.lastActivityReportAt < SITE_ACTIVITY_REPORT_INTERVAL_MS) return;
this.lastActivityReportAt = now;
this.sendMessage({ type: 'siteActivity', at: now });
}
scheduleIdleStateSave() {
if (this.idleStateSaveTimer) return;
this.idleStateSaveTimer = setTimeout(() => {
this.idleStateSaveTimer = null;
if (this.state) {
this.saveState(this.state);
}
}, 500);
}
clearDailyAutoWaitTimer() {
if (this.dailyAutoWaitTimer) {
clearTimeout(this.dailyAutoWaitTimer);
this.dailyAutoWaitTimer = null;
}
}
scheduleDailyAutoWaitCheck() {
if (!this.state?.dailyAutoIdle?.pending) return;
const waitUntil = this.state.dailyAutoIdle.waitUntil;
if (!waitUntil) return;
this.clearDailyAutoWaitTimer();
const delay = Math.max(0, waitUntil - Date.now());
this.dailyAutoWaitTimer = setTimeout(() => {
this.tryStartPendingDailyAuto();
}, delay);
}
async tryStartPendingDailyAuto() {
if (!this.state?.dailyAutoIdle?.pending) return;
const waitMs = this.getDailyAutoWaitMs();
if (waitMs <= 0) {
await this.beginDailyAuto();
return;
}
const lastActionAt = this.state.dailyAutoIdle.lastActionAt || 0;
const waitUntil = Math.max(this.state.dailyAutoIdle.waitUntil || 0, lastActionAt + waitMs);
if (Date.now() < waitUntil) {
this.state.dailyAutoIdle.waitUntil = waitUntil;
this.scheduleIdleStateSave();
this.scheduleDailyAutoWaitCheck();
return;
}
await this.beginDailyAuto();
}
async beginDailyAuto() {
if (!this.state?.dailyAutoIdle) return;
this.state.dailyAutoIdle.pending = false;
this.state.dailyAutoIdle.waitUntil = 0;
this.clearDailyAutoWaitTimer();
await this.saveState(this.state);
if (!this.dailyAuto?.enabled) {
this.dailyAuto.running = false;
await this.saveDailyAuto(this.dailyAuto);
return;
}
if (await this.checkDailyAutoDeadline()) return;
if (!this.state.isRunning) {
await this.start();
}
}
async armDailyAutoWait(skipIdleWait = false) {
const waitMs = skipIdleWait ? 0 : this.getDailyAutoWaitMs();
if (waitMs <= 0) {
if (skipIdleWait) {
this.sendMessage({ type: 'log', message: '后台静置条件已满足,开始执行每日任务' });
}
await this.beginDailyAuto();
return;
}
if (!this.state?.dailyAutoIdle) return;
this.state.dailyAutoIdle.pending = true;
const now = Date.now();
const lastActionAt = this.state.dailyAutoIdle.lastActionAt || now;
if (!this.state.dailyAutoIdle.lastActionAt) {
this.state.dailyAutoIdle.lastActionAt = now;
}
const elapsed = now - lastActionAt;
if (elapsed >= waitMs) {
await this.beginDailyAuto();
return;
}
this.state.dailyAutoIdle.waitUntil = lastActionAt + waitMs;
await this.saveState(this.state);
this.scheduleDailyAutoWaitCheck();
this.sendMessage({ type: 'log', message: '等待 10 分钟无操作后执行每日任务' });
}
async resumePendingDailyAuto() {
if (!this.state?.dailyAutoIdle?.pending) return;
if (this.state.isRunning) {
this.state.dailyAutoIdle.pending = false;
this.state.dailyAutoIdle.waitUntil = 0;
this.scheduleIdleStateSave();
return;
}
await this.tryStartPendingDailyAuto();
}
async updateDailyAutoProgress(isNewPost) {
if (!this.isDailyAutoRunning()) return false;
if (await this.checkDailyAutoDeadline()) return true;
if (isNewPost) {
this.dailyAuto.count += 1;
await this.saveDailyAuto(this.dailyAuto);
const target = Number(this.dailyAuto.target) || 0;
if (target > 0 && this.dailyAuto.count >= target) {
await this.finishDailyAuto(`已完成每日任务(${target} 次),已停止`);
return true;
}
}
return false;
}
async finishDailyAuto(reason = '每日任务完成,已停止') {
this.dailyAuto.running = false;
await this.saveDailyAuto(this.dailyAuto);
this.state.isRunning = false;
this.releasePendingSleeps();
this.stopRunTimer();
if (this.state.dailyAutoIdle) {
this.state.dailyAutoIdle.pending = false;
this.state.dailyAutoIdle.waitUntil = 0;
}
this.clearDailyAutoWaitTimer();
await this.saveState(this.state);
this.sendMessage({ type: 'log', message: reason });
this.sendMessage({ type: 'stopped' });
}
async checkDailyAutoDeadline() {
if (!this.isDailyAutoRunning()) return false;
this.dailyAuto.endTime = this.defaultDailyEndTime(this.dailyAuto.time);
const window = this.getDailyAutoWindow(
this.dailyAuto.date || this.getTodayString(),
this.dailyAuto.time,
this.dailyAuto.endTime
);
if (Date.now() < window.endMs) return false;
await this.finishDailyAuto('已到每日结束时间,已停止');
return true;
}
startRunTimer() {
if (!this.state.lastStartTime) {
this.state.lastStartTime = Date.now();
}
}
stopRunTimer() {
if (this.state.lastStartTime) {
this.state.accumulatedTime += Date.now() - this.state.lastStartTime;
this.state.lastStartTime = null;
}
}
// 清除状态
async clearState() {
await this.safeStorageRemove([STORAGE_KEY]);
}
async init() {
console.log('[Linux DO Auto] 初始化', window.location.pathname);
// 加载保存的状态
const state = await this.loadState();
this.state = state;
const stopSignalResult = await this.safeStorageGet([STOP_SIGNAL_KEY]);
this.lastStopSignalAt = Number(stopSignalResult[STOP_SIGNAL_KEY]) || 0;
if (this.state.isRunning && this.lastStopSignalAt && this.state.lastStartTime && this.lastStopSignalAt >= this.state.lastStartTime) {
await this.stop();
}
this.state.dailyAutoIdle = this.normalizeDailyAutoIdle(this.state.dailyAutoIdle);
this.config = { ...this.config, ...(state.config || {}) };
this.dailyAuto = await this.loadDailyAuto();
this.initUserActivityTracking();
if (this.state.isRunning && !this.state.lastStartTime) {
this.state.lastStartTime = Date.now();
await this.saveState(this.state);
}
await this.checkDailyAutoDeadline();
await this.resumePendingDailyAuto();
console.log('[Linux DO Auto] 状态加载完成', {
isRunning: state.isRunning,
isPostPage: this.isPostPage(),
isListPage: this.isListPage()
});
// 如果正在运行,根据当前页面类型继续执行
if (this.state.isRunning) {
console.log('[Linux DO Auto] 检测到正在运行,继续执行');
if (this.isPostPage()) {
await this.handlePostPage();
} else if (this.isListPage()) {
await this.handleListPage();
}
}
this.sendMessage({ type: 'ready', url: this.currentUrl });
console.log('[Linux DO Auto] 初始化完成,等待指令');
}
// 判断是否是帖子页面
isPostPage() {
// 匹配 /t/topic/数字 或 /t/topic/数字/数字 格式
return window.location.pathname.match(/^\/t\/topic\/\d+(\/\d+)?$/);
}
// 判断是否是列表页面
isListPage() {
return window.location.pathname.match(/^\/(latest|top|hot)?$/);
}
random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomFloat(min, max) {
return Math.random() * (max - min) + min;
}
async humanScroll() {
const scrollHeight = document.body.scrollHeight;
const targetScroll = Math.floor(scrollHeight * this.config.readDepth);
let currentScroll = window.scrollY;
const scrollSteps = this.random(4, 8);
for (let i = 0; i < scrollSteps; i++) {
const stepSize = Math.floor((targetScroll - currentScroll) / (scrollSteps - i));
const randomStep = Math.floor(stepSize * this.randomFloat(0.6, 1.4));
currentScroll += randomStep;
window.scrollTo({
top: currentScroll,
behavior: 'smooth'
});
await this.sleep(this.random(this.config.minScrollDelay, this.config.maxScrollDelay));
if (Math.random() < this.config.mouseMoveProbability) {
this.randomMouseMove();
}
}
}
randomMouseMove() {
const x = this.random(100, window.innerWidth - 100);
const y = this.random(100, window.innerHeight - 100);
const event = new MouseEvent('mousemove', {
bubbles: true,
clientX: x,
clientY: y
});
document.dispatchEvent(event);
}
sleep(ms) {
return new Promise((resolve) => {
const sleepHandle = {
timerId: null,
resolve
};
sleepHandle.timerId = setTimeout(() => {
if (!this.pendingSleeps.delete(sleepHandle)) {
return;
}
resolve();
}, ms);
this.pendingSleeps.add(sleepHandle);
});
}
releasePendingSleeps() {
if (!this.pendingSleeps.size) return;
const pending = Array.from(this.pendingSleeps);
this.pendingSleeps.clear();
pending.forEach((sleepHandle) => {
clearTimeout(sleepHandle.timerId);
sleepHandle.resolve();
});
}
attachStorageChangeListener() {
if (this.storageChangeListenerAttached || !chrome?.storage?.onChanged) return;
chrome.storage.onChanged.addListener(this.handleStorageChangedBound);
this.storageChangeListenerAttached = true;
}
handleStorageChanged(changes, area) {
if (area !== 'local' || !changes?.[STOP_SIGNAL_KEY]) return;
const signal = Number(changes[STOP_SIGNAL_KEY].newValue) || 0;
if (!signal || signal <= this.lastStopSignalAt) return;
this.lastStopSignalAt = signal;
if (!this.state || (!this.state.isRunning && !this.isDailyAutoRunning())) return;
this.stop().catch((error) => {
const messageText = error?.message || String(error);
this.recordInternalError('stop_from_signal_failed', messageText);
});
}
getPostLinks() {
const links = new Set();
const topicLinks = document.querySelectorAll('a[href^="/t/topic/"]');
topicLinks.forEach(link => {
const href = link.getAttribute('href');
if (href && href.match(/^\/t\/topic\/\d+$/)) {
links.add(href);
}
});
return Array.from(links);
}
// 获取帖子内所有评论
getPostComments() {
// linux.do 使用 data-post-number 属性标识每个评论
const comments = document.querySelectorAll('[data-post-number]');
return Array.from(comments)
// 按 postNumber 升序排序,确保顺序处理
.sort((a, b) => {
const numA = parseInt(a.getAttribute('data-post-number') || '0');
const numB = parseInt(b.getAttribute('data-post-number') || '0');
return numA - numB;
});
}
// 检查评论是否有未读标记(小蓝点)
checkCommentUnread(commentElement) {
// linux.do 可能的未读标记位置:
// 1. 评论内部的 .new-indicator 元素
// 2. 评论本身的 .unread 类
// 3. data-unread 属性
// 4. 评论时间旁边的未读图标
// 5. Discourse 的 new-user-posts 或 new-posts
// 方法1: 检查评论内是否有 .new-indicator
const newIndicator = commentElement.querySelector('.new-indicator');
if (newIndicator) {
return true;
}
// 方法2: 检查评论本身是否有 .unread 类
if (commentElement.classList.contains('unread')) {
return true;
}
// 方法3: 检查 data-unread 属性
if (commentElement.hasAttribute('data-unread') &&
commentElement.getAttribute('data-unread') !== 'false') {
return true;
}
// 方法4: 检查常见的未读图标类名(Discourse 常见)
const unreadBadge = commentElement.querySelector('.badge-notification.unread, .new-posts, .new-user-posts');
if (unreadBadge) {
return true;
}
// 方法5: 检查评论的父级是否有未读标记(有时标记在容器上)
const parent = commentElement.closest('.topic-post, .post, article');
if (parent) {
const parentUnread = parent.querySelector('.new-indicator, .badge-notification.unread, .new-posts, .new-user-posts');
if (parentUnread) {
return true;
}
}
// 方法6: 检查时间戳附近是否有未读标记(常见 Discourse 结构)
const postInfo = commentElement.querySelector('.post-info, .topic-meta, .map');
if (postInfo) {
const infoUnread = postInfo.querySelector('.new-posts, .unread, .new-indicator');
if (infoUnread) {
return true;
}
}
// 方法7: 检查评论ID链接是否有未读类
const postLink = commentElement.querySelector('a[href*="/p/"], .post-number');
if (postLink && (postLink.classList.contains('unread') ||
postLink.querySelector('.unread, .new-indicator'))) {
return true;
}
return false;
}
// 逐个浏览评论(模拟人类阅读),支持动态加载
async browseCommentsSlowly() {
// 记录最后浏览的评论 postNumber,而不是 index(更可靠)
let lastPostNumber = this.state.lastPostNumber || null;
let lastCommentCount = 0;
let noNewCommentsCount = 0;
const maxNoNewComments = 2; // 连续2次没有新评论就停止(减少等待)
let sameLocationCount = 0; // 检测是否卡在同一位置
while (noNewCommentsCount < maxNoNewComments) {
if (await this.checkDailyAutoDeadline()) return;
// 检查是否已停止或切换到快速模式
if (!this.state.isRunning || this.isQuickModeEnabled()) {
if (this.isQuickModeEnabled()) {
this.sendMessage({ type: 'log', message: '检测到快速模式,停止浏览评论' });
} else {
this.sendMessage({ type: 'log', message: '浏览已停止' });
}
return;
}
// 检查是否离开了当前帖子(允许URL中添加页码,如 /t/topic/123 -> /t/topic/123/45)
const currentPath = window.location.pathname;
const currentTopicMatch = currentPath.match(/^\/t\/topic\/(\d+)/);
const originalTopicMatch = this.currentUrl.match(/^\/t\/topic\/(\d+)/);
if (currentTopicMatch && originalTopicMatch) {
// 都在帖子页面,检查帖子ID是否相同
if (currentTopicMatch[1] !== originalTopicMatch[1]) {
this.sendMessage({ type: 'log', message: `已切换到不同帖子 ${currentTopicMatch[1]},停止浏览` });
return;
}
// 帖子ID相同,更新当前URL(允许页码变化)
if (currentPath !== this.currentUrl) {
this.currentUrl = currentPath;
this.sendMessage({ type: 'log', message: `URL更新为: ${currentPath}` });
}
} else {
// 不在帖子页面了
if (!currentPath.match(/^\/t\/topic\//)) {
this.sendMessage({ type: 'log', message: '已离开帖子页面,停止浏览' });
return;
}
}
// 每次循环都重新获取评论(处理动态加载)
const comments = this.getPostComments();
const currentCount = comments.length;
if (currentCount > lastCommentCount) {
// 有新评论加载
this.sendMessage({ type: 'log', message: `发现新评论,总计 ${currentCount} 条` });
lastCommentCount = currentCount;
noNewCommentsCount = 0;
// 找到上次浏览位置的索引
let startIndex = 0;
if (lastPostNumber) {
for (let i = 0; i < comments.length; i++) {
if (comments[i].getAttribute('data-post-number') === lastPostNumber) {
startIndex = i + 1; // 从下一条开始
break;
}
}
}
this.sendMessage({ type: 'log', message: `从第 ${startIndex + 1} 条评论开始浏览` });
for (let i = startIndex; i < comments.length; i++) {
if (await this.checkDailyAutoDeadline()) return;
// 每次循环都检查状态和配置
if (!this.state.isRunning || this.isQuickModeEnabled()) {
if (this.isQuickModeEnabled()) {
this.sendMessage({ type: 'log', message: '检测到快速模式,停止浏览评论' });
} else {
this.sendMessage({ type: 'log', message: '浏览已停止' });
}
return;
}
const comment = comments[i];
const postNumber = comment.getAttribute('data-post-number');
// 检查是否已经处理过这条评论(防止倒退)
if (lastPostNumber && parseInt(postNumber) <= parseInt(lastPostNumber)) {
this.sendMessage({ type: 'log', message: `跳过评论 ${postNumber}` });
continue;
}
// 获取评论位置信息
const commentRect = comment.getBoundingClientRect();
const isVisible = commentRect.top < window.innerHeight && commentRect.bottom > 0;
this.sendMessage({ type: 'log', message: `浏览评论 ${postNumber}` });
// 只有当评论不可见时才滚动
if (!isVisible || commentRect.top < 100 || commentRect.top > window.innerHeight - 100) {
const targetY = window.scrollY + commentRect.top - window.innerHeight / 2;
window.scrollTo({
top: Math.max(0, targetY),
behavior: 'instant'
});
await this.sleep(300);
}
// 滚动后再次检查状态
if (!this.state.isRunning || this.isQuickModeEnabled()) {
if (this.isQuickModeEnabled()) {
this.sendMessage({ type: 'log', message: '检测到快速模式,停止浏览评论' });
} else {
this.sendMessage({ type: 'log', message: '浏览已停止' });
}
return;
}
// 等待未读标记渲染(关键修复:给页面时间渲染未读状态)
await this.sleep(1200);
// 再次检查状态(等待期间可能被停止)
if (!this.state.isRunning || this.isQuickModeEnabled()) {
if (this.isQuickModeEnabled()) {
this.sendMessage({ type: 'log', message: '检测到快速模式,停止浏览评论' });
} else {
this.sendMessage({ type: 'log', message: '浏览已停止' });
}
return;
}
// 检查是否有未读标记(小蓝点)
const hasUnreadMarker = this.checkCommentUnread(comment);
if (!hasUnreadMarker) {
// 已读评论,跳过等待但仍标记为已处理
this.sendMessage({ type: 'log', message: `评论 ${postNumber} 已读` });
lastPostNumber = postNumber;
this.state.lastPostNumber = lastPostNumber;
await this.saveState(this.state);
continue;
}
// 使用配置的阅读时间范围
const readTime = this.random(this.config.minCommentRead, this.config.maxCommentRead);
this.sendMessage({ type: 'log', message: `阅读评论 ${postNumber}/${currentCount} (${Math.round(readTime / 1000)}秒)` });
await this.sleep(readTime);
// 偶尔移动鼠标
if (Math.random() < this.config.mouseMoveProbability) {
this.randomMouseMove();
}
// 保存当前浏览位置
lastPostNumber = postNumber;
this.state.lastPostNumber = lastPostNumber;
await this.saveState(this.state);
}
// 浏览完当前所有评论后,尝试加载更多
this.sendMessage({ type: 'log', message: '尝试加载更多评论...' });
// 记录当前滚动位置
const beforeBottomScroll = window.scrollY;
const scrollHeight = document.body.scrollHeight;
// 小幅滚动到底部触发加载
window.scrollTo({
top: scrollHeight - window.innerHeight - 100,
behavior: 'instant'
});
// 等待可能的动态加载
await this.sleep(2000);
// 检查是否有新内容加载
const newComments = this.getPostComments();
if (newComments.length <= currentCount) {
// 没有新内容,检测是否卡在同一位置
const afterScrollY = window.scrollY;
if (Math.abs(afterScrollY - beforeBottomScroll) < 50) {
sameLocationCount++;
if (sameLocationCount >= 2) {
this.sendMessage({ type: 'log', message: '检测到无法加载更多,停止' });
break;
}
}
} else {
sameLocationCount = 0;
}
} else {
// 没有新评论
noNewCommentsCount++;
this.sendMessage({ type: 'log', message: `等待新评论... (${noNewCommentsCount}/${maxNoNewComments})` });
// 等待后再检查
await this.sleep(2000);
}
}
// 重置浏览位置
this.state.lastPostNumber = null;
this.state.lastCommentIndex = 0;
await this.saveState(this.state);
this.sendMessage({ type: 'log', message: '所有评论已浏览完毕' });
}
// 处理帖子页面
async handlePostPage() {
const postUrl = window.location.pathname;
this.sendMessage({ type: 'log', message: `正在浏览帖子: ${postUrl}` });
if (await this.checkDailyAutoDeadline()) return;
// 检查是否已浏览
if (this.state.browsedPosts.includes(postUrl)) {
this.sendMessage({ type: 'log', message: '已浏览过,返回列表' });
if (this.state.isRunning) {
this.navigateToLatest();
}
return;
}
// 新帖子:重置浏览位置,确保从头开始
this.state.lastPostNumber = null;
this.state.lastCommentIndex = 0;
await this.saveState(this.state);
// 添加到已浏览列表
const isNewPost = !this.state.browsedPosts.includes(postUrl);
if (isNewPost) {
this.state.browsedPosts.push(postUrl);
this.state.stats.totalBrowsed++;
}
// 等待页面稳定
await this.sleep(this.random(1500, 2500));
// 随机鼠标移动
this.randomMouseMove();
// 快速浏览模式:跳过评论,停留5-10秒
let stayTime = 0; // 用于统计记录
if (this.isQuickModeEnabled()) {
this.sendMessage({ type: 'log', message: '快速浏览模式:跳过评论' });
// 检查是否已停止(在输出日志后、sleep前检查)
if (!this.state.isRunning) {
this.sendMessage({ type: 'log', message: '已停止' });
return;
}
stayTime = this.random(5000, 10000);
this.sendMessage({ type: 'log', message: `停留阅读 ${Math.floor(stayTime / 1000)}秒` });
await this.sleep(stayTime);
} else {
// 正常模式:逐个浏览评论(模拟人类阅读)
await this.browseCommentsSlowly();
// 检查是否还在运行
if (!this.state.isRunning) {
this.sendMessage({ type: 'log', message: '已停止,不跳转' });
return;
}
// 停留阅读时间
stayTime = this.random(this.config.minPageStay, this.config.maxPageStay);
// 在输出日志和 sleep 前再次检查
if (!this.state.isRunning) {
this.sendMessage({ type: 'log', message: '已停止' });
return;
}
this.sendMessage({ type: 'log', message: `停留阅读 ${Math.floor(stayTime / 1000)}秒` });
await this.sleep(stayTime);
}
// 再次检查是否还在运行
if (!this.state.isRunning) {
this.sendMessage({ type: 'log', message: '已停止,不跳转' });
return;
}