-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2264 lines (1977 loc) · 79 KB
/
Copy pathindex.js
File metadata and controls
2264 lines (1977 loc) · 79 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
#!/usr/bin/env node
// deletemytweets — Date-filtered tweet deletion tool for X (Twitter)
// Safely delete old tweets while protecting recent ones
// https://github.com/Kepners/deletemytweets
const fs = require("fs");
const path = require("path");
const { chromium, firefox } = require("playwright");
// Check if running in CLI mode (not embedded in Electron)
const IS_CLI = require.main === module;
// Modern UI libraries (only load for CLI mode)
let chalk, boxen, ora, cliProgress, figlet, gradient;
if (IS_CLI) {
chalk = require("chalk");
boxen = require("boxen");
ora = require("ora");
cliProgress = require("cli-progress");
figlet = require("figlet");
gradient = require("gradient-string");
} else {
// Stubs for embedded mode - recursive proxy to handle any chain like chalk.red.bold.underline(text)
const createChalkProxy = () => {
const handler = {
get: () => createChalkProxy(),
apply: (target, thisArg, args) => args[0] || ''
};
return new Proxy(function(s) { return s || ''; }, handler);
};
chalk = createChalkProxy();
// ora stub - returns spinner object with all methods
ora = () => {
const spinner = {
start: () => spinner,
stop: () => spinner,
succeed: () => spinner,
fail: () => spinner,
warn: () => spinner,
info: () => spinner,
text: ''
};
return spinner;
};
// boxen stub
boxen = (text) => text;
// cliProgress stub
cliProgress = {
SingleBar: class { start() {} stop() {} update() {} },
Presets: { shades_classic: {} }
};
// figlet stub
figlet = { textSync: (s) => s };
}
// ================= TERMINAL UI =================
// Only create gradients in CLI mode
let xGradient, deleteGradient, successGradient;
if (IS_CLI) {
xGradient = gradient(['#1DA1F2', '#14171A']); // Twitter blue to black
deleteGradient = gradient(['#ff6b6b', '#ee5a24']);
successGradient = gradient(['#2ecc71', '#27ae60']);
} else {
xGradient = deleteGradient = successGradient = { multiline: (s) => s };
}
// ================= BROWSER CHECK =================
// Check if Edge or Chrome is installed for Playwright to use
function getBrowserChannel() {
const edgePaths = [
path.join(process.env.PROGRAMFILES || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
path.join(process.env['PROGRAMFILES(X86)'] || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Microsoft', 'Edge', 'Application', 'msedge.exe')
];
const chromePaths = [
path.join(process.env.PROGRAMFILES || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
path.join(process.env['PROGRAMFILES(X86)'] || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Google', 'Chrome', 'Application', 'chrome.exe')
];
// Check for Edge first (preferred)
for (const p of edgePaths) {
if (fs.existsSync(p)) return 'msedge';
}
// Fallback to Chrome
for (const p of chromePaths) {
if (fs.existsSync(p)) return 'chrome';
}
return null; // No supported browser found
}
let BROWSER_CHANNEL = null; // Will be set at startup
function printHeader() {
if (!IS_CLI) return;
console.clear();
console.log("");
// ASCII art logo with gradient
const logo = figlet.textSync('DeleteMyTweets', {
font: 'Small',
horizontalLayout: 'default'
});
console.log(xGradient(logo));
// Tagline box
const tagline = boxen(
chalk.white.bold('Delete Old Tweets by Year') + '\n' +
chalk.gray('Safely clean your Twitter history'),
{
padding: { top: 0, bottom: 0, left: 2, right: 2 },
margin: { top: 0, bottom: 1, left: 0, right: 0 },
borderStyle: 'round',
borderColor: 'cyan',
textAlignment: 'center'
}
);
console.log(tagline);
}
function printConfig(config) {
if (!IS_CLI) return;
const { handle, target, posts, replies, reposts, speed } = config;
const bounds = resolveDateBounds(config);
const deleteDate = formatDate(bounds.deleteBefore);
const protectDate = formatDate(bounds.protectAfter);
const speedLabel = speed === 'aggressive' ? 'Aggressive' : speed === 'conservative' ? 'Conservative' : 'Normal';
const configBox = boxen(
chalk.bold.cyan(' CONFIGURATION\n') +
chalk.gray(' ─────────────────────────────────\n') +
` ${chalk.cyan('Profile')} ${chalk.white('@' + chalk.bold(handle))}\n` +
` ${chalk.cyan('Target')} ${chalk.bold.white(target)} tweets\n` +
` ${chalk.cyan('Mode')} ${chalk.white(describeDateBounds(config))}\n` +
` ${chalk.red('Delete')} Before ${deleteDate}\n` +
` ${chalk.green('Protect')} After ${protectDate}\n` +
` ${chalk.cyan('Speed')} ${speedLabel}\n` +
chalk.gray(' ─────────────────────────────────\n') +
` ${chalk.cyan('Posts')} ${posts ? chalk.green('✓ YES') : chalk.gray('✗ NO')}\n` +
` ${chalk.cyan('Replies')} ${replies ? chalk.green('✓ YES') : chalk.gray('✗ NO')}\n` +
` ${chalk.cyan('Reposts')} ${reposts ? chalk.green('✓ YES') : chalk.gray('✗ NO')}`,
{
padding: 1,
margin: { top: 0, bottom: 1, left: 0, right: 0 },
borderStyle: 'round',
borderColor: 'gray'
}
);
console.log(configBox);
}
// Callback for GUI mode logging
let onLogCallback = null;
// Abort controller for stopping cleanup
let abortController = null;
function isAborted() {
return abortController && abortController.signal.aborted;
}
function abortCleanup() {
if (abortController) {
abortController.abort();
}
}
function log(type, message, extra = "") {
const plainMessage = `${message}${extra ? ' ' + extra : ''}`;
// Send to GUI callback if set
if (onLogCallback) {
onLogCallback({ type, message: plainMessage });
}
// Only show in CLI mode
if (!IS_CLI) return;
const timestamp = chalk.gray(new Date().toLocaleTimeString("en-US", { hour12: false }));
const icons = {
info: chalk.blue('ℹ'),
success: chalk.green('✓'),
warn: chalk.yellow('⚠'),
error: chalk.red('✗'),
delete: chalk.red('🗑'),
protect: chalk.green('🛡'),
skip: chalk.gray('○'),
tab: chalk.magenta('→'),
};
const icon = icons[type] || chalk.gray('·');
const extraText = extra ? chalk.gray(` ${extra}`) : '';
console.log(`${timestamp} ${icon} ${message}${extraText}`);
}
function emitEvent(type, payload = {}) {
if (process.env.DMT_EMIT_EVENTS !== "true") return;
try {
console.log(`__DMT_EVENT__${JSON.stringify({ type, ...payload })}`);
} catch {}
}
function printSummary(removed, target, startTime) {
if (!IS_CLI) return;
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
const rate = removed > 0 ? (elapsed / removed).toFixed(1) : 0;
const percent = Math.round((removed / target) * 100);
console.log("");
const summaryBox = boxen(
successGradient.multiline(' COMPLETE!\n') +
chalk.gray(' ═══════════════════════════════\n') +
` ${chalk.cyan('Deleted')} ${chalk.bold.green(removed)} / ${target} (${percent}%)\n` +
` ${chalk.cyan('Time')} ${elapsed} seconds\n` +
` ${chalk.cyan('Speed')} ${rate}s per tweet\n` +
chalk.gray(' ═══════════════════════════════'),
{
padding: 1,
margin: 1,
borderStyle: 'double',
borderColor: 'green',
title: '✓ Summary',
titleAlignment: 'center'
}
);
console.log(summaryBox);
}
// Progress bar instance
let progressBar = null;
// Callback for GUI mode
let onProgressCallback = null;
function createProgressBar(total) {
if (!IS_CLI) return;
progressBar = new cliProgress.SingleBar({
format: ' {bar} | {percentage}% | {value}/{total} tweets | {tab}',
barCompleteChar: '█',
barIncompleteChar: '░',
hideCursor: true,
clearOnComplete: false,
barsize: 25,
forceRedraw: true
}, cliProgress.Presets.shades_classic);
progressBar.start(total, 0, { tab: '' });
}
function updateProgress(current, tab, total) {
if (IS_CLI && progressBar) {
progressBar.update(current, { tab });
}
if (onProgressCallback) {
onProgressCallback({ current, total, tab });
}
}
function stopProgress() {
if (!IS_CLI) return;
if (progressBar) {
progressBar.stop();
progressBar = null;
}
}
// ================= CONFIG FILE =================
const CONFIG_FILE = path.resolve(__dirname, "deletemytweets_config.json");
const SESSION_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours
const HANDLE_PATTERN = /^[A-Za-z0-9_]{1,15}$/;
const ARCHIVE_START = new Date(2006, 0, 1);
function normalizeHandle(rawHandle) {
if (typeof rawHandle !== "string") return null;
const trimmed = rawHandle.trim().replace(/^@+/, "");
if (!HANDLE_PATTERN.test(trimmed)) return null;
return trimmed.toLowerCase();
}
function toPositiveInt(value, fallback) {
const parsed = parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
function toBoolean(value, fallback = false) {
if (value === true || value === false) return value;
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
if (normalized === "true") return true;
if (normalized === "false") return false;
}
return fallback;
}
function normalizeSelectionMode(rawMode) {
const mode = typeof rawMode === "string" ? rawMode.trim().toLowerCase() : "";
if (
mode === "protect" ||
mode === "keep" ||
mode === "keep_recent" ||
mode === "keep-recent" ||
mode === "rolling-keep"
) {
return "protect";
}
if (
mode === "delete" ||
mode === "delete_recent" ||
mode === "delete-recent" ||
mode === "rolling-delete"
) {
return "delete";
}
return "delete";
}
function startOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
function shiftMonths(date, deltaMonths) {
return new Date(date.getFullYear(), date.getMonth() + deltaMonths, 1);
}
function resolveDateBounds(options = {}) {
const sliderMode = normalizeSelectionMode(options.sliderMode ?? SLIDER_MODE);
const rollingWindow = toBoolean(options.rollingWindow ?? ROLLING_WINDOW);
const rollingMonths = toPositiveInt(options.rollingMonths ?? ROLLING_MONTHS, 3);
const deleteMonth = toPositiveInt(options.deleteMonth ?? DELETE_MONTH, 12);
const deleteYear = toPositiveInt(options.deleteYear ?? DELETE_YEAR, 2014);
const protectMonth = toPositiveInt(options.protectMonth ?? PROTECT_MONTH, 1);
const protectYear = toPositiveInt(options.protectYear ?? PROTECT_YEAR, new Date().getFullYear());
if (rollingWindow) {
const currentMonth = startOfMonth(options.now || new Date());
const windowStart = shiftMonths(currentMonth, -(rollingMonths - 1));
const windowEndExclusive = shiftMonths(currentMonth, 1);
return {
sliderMode,
rollingWindow: true,
rollingMonths,
deleteBefore: sliderMode === "protect" ? ARCHIVE_START : windowStart,
protectAfter: sliderMode === "protect" ? windowStart : windowEndExclusive
};
}
return {
sliderMode,
rollingWindow: false,
rollingMonths,
deleteBefore: sliderMode === "protect"
? ARCHIVE_START
: new Date(deleteYear, deleteMonth - 1, 1),
protectAfter: new Date(protectYear, protectMonth - 1, 1)
};
}
function describeDateBounds(options = {}) {
const bounds = resolveDateBounds(options);
const { sliderMode, rollingWindow, rollingMonths, deleteBefore, protectAfter } = bounds;
if (rollingWindow) {
const displayStart = sliderMode === "protect" ? protectAfter : deleteBefore;
const displayEnd = sliderMode === "protect"
? shiftMonths(protectAfter, rollingMonths - 1)
: shiftMonths(protectAfter, -1);
if (sliderMode === "protect") {
return `Rolling keep recent ${rollingMonths} month${rollingMonths === 1 ? "" : "s"} (${formatDate(displayStart)} → ${formatDate(displayEnd)})`;
}
return `Rolling delete recent ${rollingMonths} month${rollingMonths === 1 ? "" : "s"} (${formatDate(displayStart)} → ${formatDate(displayEnd)})`;
}
if (sliderMode === "protect") {
return `Keep after ${formatDate(protectAfter)}`
}
return `Delete from ${formatDate(deleteBefore)} to ${formatDate(protectAfter)}`;
}
function loadConfig() {
try {
if (fs.existsSync(CONFIG_FILE)) {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
}
} catch {}
return {};
}
function saveConfig(config) {
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
} catch {}
}
// Get storage file path for specific handle
// Use app's userData folder in Electron, or __dirname for CLI
function getStoragePath(handle) {
const normalizedHandle = normalizeHandle(handle);
if (!normalizedHandle) return null;
// Check if running in Electron
let basePath = __dirname;
try {
const { app } = require('electron');
if (app && app.getPath) {
basePath = app.getPath('userData');
}
} catch {
// Not in Electron main process, check if we can get userData from env
if (process.env.ELECTRON_USER_DATA) {
basePath = process.env.ELECTRON_USER_DATA;
}
}
return path.resolve(basePath, `x_auth_${normalizedHandle}.json`);
}
// Check if session is valid (exists and not expired)
function isSessionValid(handle) {
const storagePath = getStoragePath(handle);
if (!storagePath) return false;
if (!fs.existsSync(storagePath)) return false;
try {
const stat = fs.statSync(storagePath);
const age = Date.now() - stat.mtimeMs;
if (age > SESSION_EXPIRY_MS) {
// Session expired, delete it
fs.unlinkSync(storagePath);
return false;
}
return true;
} catch {
return false;
}
}
// Clear session for a handle
function clearSession(handle) {
const storagePath = getStoragePath(handle);
if (!storagePath) return;
try {
if (fs.existsSync(storagePath)) {
fs.unlinkSync(storagePath);
}
} catch {}
}
const savedConfig = loadConfig();
// ================= CONFIG =================
// Speed presets for delay between deletions
const SPEED_PRESETS = {
aggressive: { min: 600, max: 1000 }, // Fast but risky
normal: { min: 1200, max: 2200 }, // Balanced (default)
conservative: { min: 2500, max: 4000 } // Slow but safe
};
const RETRY_PRESETS = {
aggressive: { unknownDate: 2, ownership: 2, action: 2 },
normal: { unknownDate: 3, ownership: 3, action: 3 },
conservative: { unknownDate: 5, ownership: 5, action: 4 }
};
let MAX_UNKNOWN_DATE_RETRIES = RETRY_PRESETS.normal.unknownDate;
let MAX_OWNERSHIP_RETRIES = RETRY_PRESETS.normal.ownership;
let MAX_ACTION_RETRIES = RETRY_PRESETS.normal.action;
const RETRYABLE_ACTION_REASONS = new Set([
"no-menu",
"menu-empty",
"card-not-found",
"no-delete-item",
"no-unretweet-btn",
"no-undo-item",
"menu-click-failed",
"delete-click-failed",
"confirm-click-failed",
"delete-not-confirmed",
"status-still-accessible",
"unretweet-click-failed",
"undo-click-failed",
"unrepost-not-confirmed"
]);
function parseRetryOverride(value) {
if (value === undefined || value === null || value === "") return null;
const n = Number(value);
if (!Number.isInteger(n) || n < 0) return null;
return n;
}
function applyRetryPreset(speed, overrides = {}) {
const preset = RETRY_PRESETS[speed] || RETRY_PRESETS.normal;
MAX_UNKNOWN_DATE_RETRIES = preset.unknownDate;
MAX_OWNERSHIP_RETRIES = preset.ownership;
MAX_ACTION_RETRIES = preset.action;
const unknownOverride = parseRetryOverride(overrides.unknownDate);
if (unknownOverride !== null) MAX_UNKNOWN_DATE_RETRIES = unknownOverride;
const ownershipOverride = parseRetryOverride(overrides.ownership);
if (ownershipOverride !== null) MAX_OWNERSHIP_RETRIES = ownershipOverride;
const actionOverride = parseRetryOverride(overrides.action);
if (actionOverride !== null) MAX_ACTION_RETRIES = actionOverride;
}
// Config variables (set by runCleanup or CLI)
let PROFILE_HANDLE = null;
let INCLUDE_POSTS = true;
let INCLUDE_REPLIES = true;
let HANDLE_REPOSTS = false;
let TARGET = 10000; // Default to large batch for "set and forget" usage
let HEADLESS = false;
let PRIVATE_MODE = false; // Use fresh browser instead of Edge profile
let USE_FIREFOX = false; // Use Firefox engine for anti-detection mode
let PROXY_SERVER = null; // Optional proxy server (http://host:port)
let SPEED = "normal";
let MIN_DELAY_MS = 1200;
let MAX_DELAY_MS = 2200;
let LOGIN_WAIT_MS = 3 * 60 * 1000;
let STORAGE = path.resolve(__dirname, "x_auth_storage.json");
let MAX_SCROLL_PASSES = 100; // Increased for large accounts (31K+ tweets)
let SCROLL_MIN_WAIT_MS = 200;
let SCROLL_MAX_WAIT_MS = 400;
let SCROLL_STEP_RATIO = 0.92;
let RETURN_TO_TOP = false;
let SLIDER_MODE = "delete";
let ROLLING_WINDOW = false;
let ROLLING_MONTHS = 3;
let DELETE_MONTH = 12;
let DELETE_YEAR = 2014;
let PROTECT_MONTH = new Date().getMonth() + 1;
let PROTECT_YEAR = new Date().getFullYear();
let DELETE_BEFORE = null;
let PROTECT_AFTER = null;
// Parse config from environment (CLI mode only)
function parseEnvConfig() {
const now = new Date();
// Support DMT_* env vars from Electron app, plus legacy names
const rawHandle = process.env.DMT_HANDLE || process.env.PROFILE_HANDLE || process.argv[2] || savedConfig.handle;
PROFILE_HANDLE = normalizeHandle(rawHandle);
if (!PROFILE_HANDLE) {
printHeader();
const errorBox = boxen(
chalk.red.bold('ERROR: Valid profile handle is required!\n\n') +
chalk.white.bold('Usage:\n') +
chalk.cyan(' node index.js ') + chalk.yellow('<your_handle>\n') +
chalk.cyan(' PROFILE_HANDLE=') + chalk.yellow('handle') + chalk.cyan(' node index.js\n\n') +
chalk.white('Handle rules: 1-15 characters, letters/numbers/underscore only\n\n') +
chalk.white.bold('Example:\n') +
chalk.gray(' node index.js johndoe\n') +
chalk.gray(' TARGET=100 DELETE_YEAR_AND_OLDER=2020 node index.js johndoe'),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'red',
title: '✗ Error',
titleAlignment: 'center'
}
);
console.log(errorBox);
process.exit(1);
}
// Save handle for next time
if (PROFILE_HANDLE !== savedConfig.handle) {
saveConfig({ ...savedConfig, handle: PROFILE_HANDLE });
}
INCLUDE_POSTS = (process.env.DMT_POSTS ?? process.env.INCLUDE_POSTS ?? "true") === "true";
INCLUDE_REPLIES = (process.env.DMT_REPLIES ?? process.env.INCLUDE_REPLIES ?? "true") === "true";
HANDLE_REPOSTS = (process.env.DMT_REPOSTS ?? process.env.HANDLE_REPOSTS ?? "false") === "true";
TARGET = parseInt(process.env.DMT_TARGET ?? process.env.TARGET ?? "10000", 10);
HEADLESS = (process.env.DMT_HEADLESS ?? process.env.HEADLESS ?? "false") === "true";
PRIVATE_MODE = (process.env.DMT_PRIVATE_MODE ?? process.env.PRIVATE_MODE ?? "false") === "true";
USE_FIREFOX = (process.env.DMT_USE_FIREFOX ?? process.env.USE_FIREFOX ?? "false") === "true";
PROXY_SERVER = normalizeProxy(process.env.DMT_PROXY ?? process.env.PROXY ?? "");
SPEED = process.env.DMT_SPEED ?? process.env.SPEED ?? "normal";
const delays = SPEED_PRESETS[SPEED] || SPEED_PRESETS.normal;
MIN_DELAY_MS = parseInt(process.env.MIN_DELAY_MS ?? String(delays.min), 10);
MAX_DELAY_MS = parseInt(process.env.MAX_DELAY_MS ?? String(delays.max), 10);
applyRetryPreset(SPEED, {
unknownDate: process.env.DMT_UNKNOWN_DATE_RETRIES ?? process.env.UNKNOWN_DATE_RETRIES,
ownership: process.env.DMT_OWNERSHIP_RETRIES ?? process.env.OWNERSHIP_RETRIES,
action: process.env.DMT_ACTION_RETRIES ?? process.env.ACTION_RETRIES
});
LOGIN_WAIT_MS = parseInt(process.env.LOGIN_WAIT_MS ?? String(3 * 60 * 1000), 10);
STORAGE = path.resolve(__dirname, "x_auth_storage.json");
MAX_SCROLL_PASSES = parseInt(process.env.MAX_SCROLL_PASSES ?? "5", 10);
SCROLL_MIN_WAIT_MS = parseInt(process.env.SCROLL_MIN_WAIT_MS ?? "300", 10);
SCROLL_MAX_WAIT_MS = parseInt(process.env.SCROLL_MAX_WAIT_MS ?? "600", 10);
SCROLL_STEP_RATIO = parseFloat(process.env.SCROLL_STEP_RATIO ?? "0.92");
RETURN_TO_TOP = (process.env.RETURN_TO_TOP ?? "false") === "true";
DELETE_MONTH = parseInt(process.env.DMT_DELETE_MONTH ?? process.env.DELETE_MONTH ?? "12", 10);
DELETE_YEAR = parseInt(process.env.DMT_DELETE_YEAR ?? process.env.DELETE_YEAR ?? process.env.DELETE_YEAR_AND_OLDER ?? "2014", 10);
PROTECT_MONTH = parseInt(process.env.DMT_PROTECT_MONTH ?? process.env.PROTECT_MONTH ?? String(now.getMonth() + 1), 10);
PROTECT_YEAR = parseInt(process.env.DMT_PROTECT_YEAR ?? process.env.PROTECT_YEAR ?? process.env.PROTECT_YEAR_AND_NEWER ?? String(now.getFullYear()), 10);
SLIDER_MODE = normalizeSelectionMode(process.env.DMT_SLIDER_MODE ?? process.env.SLIDER_MODE ?? "delete");
ROLLING_WINDOW = toBoolean(process.env.DMT_ROLLING_WINDOW ?? process.env.ROLLING_WINDOW ?? false);
ROLLING_MONTHS = toPositiveInt(process.env.DMT_ROLLING_MONTHS ?? process.env.ROLLING_MONTHS ?? "3", 3);
const bounds = resolveDateBounds({
sliderMode: SLIDER_MODE,
rollingWindow: ROLLING_WINDOW,
rollingMonths: ROLLING_MONTHS,
deleteMonth: DELETE_MONTH,
deleteYear: DELETE_YEAR,
protectMonth: PROTECT_MONTH,
protectYear: PROTECT_YEAR,
now
});
DELETE_BEFORE = bounds.deleteBefore;
PROTECT_AFTER = bounds.protectAfter;
}
const RE_DELETE = /(Delete|Eliminar|Supprimer|Löschen|Elimina|Excluir|Удалить|削除|삭제|刪除)/i;
const RE_UNDO_REPOST = /(Undo\s+(Repost|Retweet)|Unretweet|Deshacer\s+Repost|Annuler\s+Retweet|zurücknehmen|Desfazer|Отменить|취소|转推)/i;
// ================= UTILITIES =================
function rand(min, max) { return Math.floor(min + Math.random() * (max - min + 1)); }
async function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
async function pause(minMs, maxMs) { await sleep(rand(minMs, maxMs)); }
function getRetryEntry(retryState, key) {
let entry = retryState.get(key);
if (!entry) {
entry = { unknownDate: 0, ownership: 0, action: 0 };
retryState.set(key, entry);
}
return entry;
}
function normalizeProxy(rawProxy) {
if (typeof rawProxy !== "string") return null;
const trimmed = rawProxy.trim();
if (!trimmed) return null;
if (/^(http|https|socks4|socks5):\/\//i.test(trimmed)) return trimmed;
if (/^[^:\s]+:\d{2,5}$/.test(trimmed)) return `http://${trimmed}`;
return null;
}
function finalizeSeenKey(seen, retryState, key) {
seen.add(key);
retryState.delete(key);
}
function registerActionFailure(seen, retryState, key, reason, options = {}) {
const { forceRetry = false, label = "action failure" } = options;
if (!key) return false;
const retryable = forceRetry || RETRYABLE_ACTION_REASONS.has(reason);
if (!retryable) {
finalizeSeenKey(seen, retryState, key);
return false;
}
const retryEntry = getRetryEntry(retryState, key);
if (retryEntry.action < MAX_ACTION_RETRIES) {
retryEntry.action++;
seen.delete(key);
log("info", `Retrying ${label} (${reason}) (${retryEntry.action}/${MAX_ACTION_RETRIES})`);
return true;
}
finalizeSeenKey(seen, retryState, key);
return false;
}
async function pauseLikeHuman(page, removedCount, rhythmState) {
await pause(MIN_DELAY_MS, MAX_DELAY_MS);
if (removedCount > 0 && removedCount >= rhythmState.nextLongPauseAt) {
const longPauseMs = rand(4500, 11000);
log("info", `Natural pause (${(longPauseMs / 1000).toFixed(1)}s)`);
await page.waitForTimeout(longPauseMs);
rhythmState.nextLongPauseAt = removedCount + rand(28, 60);
return;
}
// Occasional hesitation to avoid perfectly periodic timing.
if (Math.random() < 0.14) {
await page.waitForTimeout(rand(450, 1400));
}
}
// Timeout wrapper to prevent hanging on video tweets
async function withTimeout(promise, ms = 3000, fallback = null) {
return Promise.race([
promise,
new Promise(resolve => setTimeout(() => resolve(fallback), ms))
]);
}
// Kill all videos on page - pause, remove source, prevent loading
async function pauseAllVideos(page) {
try {
await page.evaluate(() => {
document.querySelectorAll('video').forEach(v => {
v.pause();
v.currentTime = 0;
v.preload = 'none';
v.autoplay = false;
v.src = ''; // Remove source to stop network requests
v.load(); // Force reload with empty src
});
// Also kill any pending video network requests
document.querySelectorAll('source').forEach(s => s.remove());
});
} catch {}
}
// Dismiss common X/Twitter popups that can block interactions
async function dismissPopups(page) {
try {
// Cookie consent - "Accept all cookies" or close button
const cookieSelectors = [
'[data-testid="BottomBar"] button:has-text("Accept")',
'button:has-text("Accept all cookies")',
'button:has-text("Accept cookies")',
'[aria-label="Close"]'
];
// Premium/subscription prompts
const premiumSelectors = [
'[data-testid="sheetDialog"] [aria-label="Close"]',
'[role="dialog"] button[aria-label="Close"]',
'button:has-text("Not now")',
'button:has-text("Maybe later")'
];
// Notification prompts
const notificationSelectors = [
'button:has-text("Not now")',
'[data-testid="app-bar-close"]'
];
// General modal close buttons
const closeSelectors = [
'[data-testid="app-bar-close"]',
'[data-testid="xMigrationBottomBar"] button',
'[role="dialog"] [aria-label="Close"]',
'div[data-testid="confirmationSheetCancel"]'
];
const allSelectors = [...cookieSelectors, ...premiumSelectors, ...notificationSelectors, ...closeSelectors];
for (const selector of allSelectors) {
try {
const el = page.locator(selector).first();
const count = await el.count().catch(() => 0);
if (count > 0 && await el.isVisible().catch(() => false)) {
await el.click({ timeout: 1000 }).catch(() => {});
await page.waitForTimeout(300);
}
} catch {}
}
// Also try pressing Escape to close any modal
await page.keyboard.press('Escape').catch(() => {});
} catch {}
}
// ================= AUTH =================
async function isLoggedIn(context) {
try { return (await context.cookies()).some(c => c.name.toLowerCase() === "auth_token"); }
catch { return false; }
}
// Sign out of X/Twitter completely
async function signOut(page, context) {
log("info", "Signing out of X...");
try {
// Clear all cookies first
await context.clearCookies();
// Navigate to logout page
await page.goto('https://x.com/logout', { waitUntil: "domcontentloaded", timeout: 15000 }).catch(() => {});
await page.waitForTimeout(1500);
// Click the logout confirmation button if present
const confirmSelectors = [
'[data-testid="confirmationSheetConfirm"]',
'button:has-text("Log out")',
'[role="button"]:has-text("Log out")'
];
for (const selector of confirmSelectors) {
const btn = page.locator(selector);
const count = await btn.count().catch(() => 0);
if (count > 0) {
await btn.first().click({ timeout: 5000 }).catch(() => {});
await page.waitForTimeout(2000);
break;
}
}
// Clear cookies again after logout
await context.clearCookies();
// Verify we're logged out
const stillLoggedIn = await isLoggedIn(context);
if (stillLoggedIn) {
log("warn", "Cookies still present after logout - clearing again");
await context.clearCookies();
}
log("success", "Signed out successfully");
return true;
} catch (err) {
log("warn", `Sign out error: ${err?.message || err}`);
// Still try to clear cookies
await context.clearCookies().catch(() => {});
return false;
}
}
// Get the currently logged-in account handle from the sidebar
async function getLoggedInHandle(page) {
try {
// Look for the account switcher in the sidebar which shows current handle
const accountSelectors = [
'[data-testid="SideNav_AccountSwitcher_Button"] [dir="ltr"] span', // Sidebar account button
'[data-testid="AccountSwitcher"] span[dir="ltr"]',
'nav [data-testid="AppTabBar_Profile_Link"]', // Profile link in nav
'a[href*="/"][data-testid="AppTabBar_Profile_Link"]'
];
for (const selector of accountSelectors) {
const el = page.locator(selector);
const count = await el.count().catch(() => 0);
if (count > 0) {
const text = await el.first().innerText().catch(() => '');
// Extract handle (starts with @)
const match = text.match(/@(\w+)/);
if (match) return match[1].toLowerCase();
}
}
// Try to get from profile link href
const profileLink = page.locator('[data-testid="AppTabBar_Profile_Link"]');
const href = await profileLink.getAttribute('href').catch(() => null);
if (href) {
const match = href.match(/^\/(\w+)$/);
if (match) return match[1].toLowerCase();
}
return null;
} catch {
return null;
}
}
// Verify the logged-in account matches the expected handle
async function verifyAccount(page, expectedHandle) {
try {
// Check if we're on the right profile by looking at the URL or page content
log("info", `Navigating to profile @${expectedHandle}...`);
await page.goto(`https://x.com/${expectedHandle}`, { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(3000); // Give page time to fully load
// FIRST: Check who is actually logged in via sidebar
const loggedInAs = await getLoggedInHandle(page);
if (loggedInAs) {
if (loggedInAs === expectedHandle.toLowerCase()) {
log("success", `Confirmed logged in as @${loggedInAs}`);
} else {
log("error", `WRONG ACCOUNT! Logged in as @${loggedInAs}, but expected @${expectedHandle}`);
return false;
}
}
// Strategy 1: Look for "Edit profile" button (multiple possible selectors)
const editSelectors = [
'[data-testid="editProfileButton"]', // Most reliable - data-testid
'a[href="/settings/profile"]', // Direct link
'button:has-text("Edit profile")', // Button with text
'a:has-text("Edit profile")', // Link with text
'[aria-label="Edit profile"]' // Aria label
];
for (const selector of editSelectors) {
const el = page.locator(selector);
const count = await el.count().catch(() => 0);
if (count > 0) {
log("success", `Found edit profile button (${selector})`);
return true;
}
}
// Strategy 2: Check if there's NO "Follow" button (means it's our profile)
const followSelectors = [
'[data-testid="followButton"]',
'button:has-text("Follow")',
'[aria-label*="Follow @"]'
];
let hasFollowButton = false;
for (const selector of followSelectors) {
const el = page.locator(selector);
const count = await el.count().catch(() => 0);
if (count > 0) {
const text = await el.first().innerText().catch(() => '');
// "Following" is okay (we follow ourselves? no), but "Follow" means it's not our profile
if (text === 'Follow') {
log("warn", `Found Follow button - this is NOT our profile`);
hasFollowButton = true;
break;
}
}
}
if (hasFollowButton) {
return false;
}
// Strategy 3: If we confirmed logged-in handle matches, trust that
if (loggedInAs && loggedInAs === expectedHandle.toLowerCase()) {
return true;
}
// Strategy 4: Check URL matches expected handle (case-insensitive) - ONLY if edit button found
const currentUrl = page.url().toLowerCase();
if (currentUrl.includes(`x.com/${expectedHandle.toLowerCase()}`)) {
// Without Edit button AND without logged-in confirmation, this is NOT safe
log("warn", `On profile URL but could not confirm account ownership`);
log("warn", `Please ensure you are logged in as @${expectedHandle}`);
return false; // Changed from true - don't assume!
}
log("warn", `Could not verify profile ownership - URL: ${page.url()}`);
return false;
} catch (err) {
log("error", `verifyAccount error: ${err?.message || err}`);
return false;
}
}
async function waitForLogin(page, context, spinner, storagePath) {
const start = Date.now();
while (Date.now() - start < LOGIN_WAIT_MS) {
if (await isLoggedIn(context)) {
try { await context.storageState({ path: storagePath }); } catch {}
spinner.succeed(chalk.green('Session saved'));
return true;
}
await page.waitForTimeout(1000);
}
return false;
}
async function ensureLoggedIn(page, context) {
const storagePath = getStoragePath(PROFILE_HANDLE);
// Navigate to X first to pick up any existing Edge session cookies
log("info", "Checking X login status...");
try {
await page.goto('https://x.com/home', { waitUntil: "domcontentloaded", timeout: 30000 });
await page.waitForTimeout(2000); // Let cookies settle
} catch {
// Might redirect to login if not authenticated - that's fine
}
// Now check if logged in (from Edge profile or saved session)
if (await isLoggedIn(context)) {
log("info", `Verifying account is @${PROFILE_HANDLE}...`);
const isCorrectAccount = await verifyAccount(page, PROFILE_HANDLE);
if (isCorrectAccount) {
log("success", chalk.green(`Verified: logged in as @${PROFILE_HANDLE}`));
// Save/update session file for this handle
try { await context.storageState({ path: storagePath }); } catch {}
return true;
} else {
// Logged in but wrong account - sign out and force re-login
log("warn", chalk.yellow(`Logged in as wrong account! Need @${PROFILE_HANDLE}`));
clearSession(PROFILE_HANDLE);
// Use proper sign out
await signOut(page, context);
// Navigate to login page
await page.goto('https://x.com/login', { waitUntil: "domcontentloaded", timeout: 15000 }).catch(() => {});
}
} else {