-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdashboard.html
More file actions
1943 lines (1797 loc) · 87.9 KB
/
Copy pathdashboard.html
File metadata and controls
1943 lines (1797 loc) · 87.9 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>LitterBox — dashboard</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body data-page="dashboard">
<header>
<h1><a href="/" class="logo-link">🐈⬛ LitterBox | ElfHosted</a> <span class="app-version" id="app-version"></span></h1>
<p class="tagline">Your Real-Debrid library, post-mortem.</p>
</header>
<main>
<!-- Compact detection-pattern strip — visible the whole time
(during scan + after). Mirrors RD_BLOCKED_FILENAME_REGEX
below; keep the two in sync when updating the regex. -->
<details class="detect-strip">
<summary>🔬 LitterBox detects these filename patterns out of the box <span class="muted small">(click to expand)</span></summary>
<div class="regex-chips">
<div class="chip-group">
<p class="chip-group-label">Source substrings (anywhere in filename)</p>
<span class="chip">web-dl</span>
<span class="chip">webrip</span>
<span class="chip">bdrip</span>
<span class="chip">hdrip</span>
<span class="chip">dvdrip</span>
</div>
<div class="chip-group">
<p class="chip-group-label">Source.Codec dot-adjacency</p>
<span class="chip">BluRay.x264</span>
<span class="chip">HDTV.x264</span>
<span class="chip">HDTV.XviD</span>
<span class="chip">WEB.x264</span>
<span class="chip">WEB.h264</span>
</div>
</div>
<p class="muted small">
Fast-pass detection — the exact 2-rule set RD's "infringing_file" filter blocks on,
<a href="https://www.patreon.com/posts/complete-list-of-158388927" target="_blank" rel="noopener">empirically mapped by the DMM developer</a>.
The deep-probe step below catches the long tail.
</p>
</details>
<section id="loading">
<p id="loading-status">👃 Sniffing your library…</p>
<progress id="scan-progress" max="100" value="0"></progress>
<p class="muted small" id="scan-detail"></p>
</section>
<section id="results" hidden>
<h2>🧹 The dirt has been audited</h2>
<!-- Headline stink rating: tongue-in-cheek 0-10 score driven by
the broken-bytes percentage. Surfaces the visceral "how bad
is it?" answer above the breakdown so users get the gut-
punch before the granular numbers. -->
<div class="stink" id="stink-card">
<p class="stink-prelude">your RD library smells:</p>
<p class="stink-rating" id="stink-rating">—</p>
<p class="stink-detail" id="stink-detail">—</p>
</div>
<!-- Composition pie + legend. The pie is a single conic-gradient
backed div — no charting library, no JS canvas. The legend
lists each segment with its swatch, count, and percentage. -->
<div class="pie-row">
<div class="pie" id="pie"></div>
<ul class="legend" id="pie-legend"></ul>
</div>
<div class="counts">
<div class="count-card"><p class="num" id="count-total">—</p><p class="label">total</p></div>
<div class="count-card healthy"><p class="num" id="count-healthy">—</p><p class="label">😺 healthy</p></div>
<div class="count-card broken"><p class="num" id="count-broken">—</p><p class="label">💀 broken</p></div>
</div>
<!-- Library statistics: size, broken weight, top broken cause. -->
<div class="stats">
<div class="stat-card">
<p class="stat-icon">📦</p>
<p class="stat-num" id="stat-library-size">—</p>
<p class="stat-label">library size</p>
</div>
<div class="stat-card warn">
<p class="stat-icon">🦨</p>
<p class="stat-num" id="stat-broken-size">—</p>
<p class="stat-label" id="stat-broken-pct">dead weight</p>
</div>
<div class="stat-card">
<p class="stat-icon">🏆</p>
<p class="stat-num" id="stat-top-status">—</p>
<p class="stat-label">stinkiest reason</p>
</div>
</div>
<!-- Filtered-class callout — only rendered when the May 2026
regex catches torrents RD's status field claims are healthy.
Tells the user "this isn't the old broken-statuses story —
this is the new rug-pull, and the official UI doesn't show
it". Most users will be discovering the May-2026 class for
the first time here so a sentence of context helps. -->
<div id="filtered-callout" class="filtered-callout" hidden>
<p>
<strong>🚫 <span id="filtered-callout-count">0</span> of those are <code>infringing_file</code> — Real-Debrid's May 2026 filter.</strong>
These appear <em>healthy</em> in Real-Debrid's UI — same status, same progress, same link — but the link is rejected with HTTP 451 the moment anyone tries to play them. LitterBox flags them by filename pattern so you don't have to per-torrent probe.
</p>
<p class="muted small">
<a href="https://rd-rug-pull.netlify.app/" target="_blank" rel="noopener">Background on what changed</a> (anonymous source, unconfirmed) ·
<a href="https://www.reddit.com/r/StremioAddons/comments/1t9qa96/elfhosteds_bandaid_fix_for_the_may_2026_rd/" target="_blank" rel="noopener">our server-side mitigation</a>
</p>
</div>
<!-- ============ Step 1: Quick wipe ============
Scoops everything the fast-pass detection (status field +
baked-in filename regex) already flagged as broken.
Instant value — no per-torrent probing required. -->
<section class="step" id="step-quickwipe" hidden>
<h3>① Quick wipe</h3>
<p class="muted small">
Scoop the torrents the fast pass already flagged
(<strong id="quickwipe-count">0</strong> rows) — broken
statuses RD admits to, plus filename-regex hits for the
May 2026 filter. No further probing needed.
</p>
<p>
<button id="delete-button" type="button" class="danger">🗑️ Quick wipe</button>
<label class="dryrun-toggle small muted">
<input type="checkbox" id="backup-toggle" checked>
💾 Download JSON backup before deleting (recommended)
</label>
<label class="dryrun-toggle small muted">
<input type="checkbox" id="dry-run-toggle">
🧪 Dry-run mode (no actual deletes — just for testing)
</label>
</p>
</section>
<!-- ============ Step 2: Deep clean ============
For each "healthy"-looking torrent (not flagged by Step 1),
POST /unrestrict/link and check for HTTP 451 + error_code 35.
Catches the May 2026 filter class that the filename regex
missed. Rate-limited client-side; abortable; cached in
localStorage per-hash so a re-scan doesn't re-probe. -->
<section class="step" id="step-deepclean" hidden>
<h3>② Deep clean (optional)</h3>
<p class="muted small" id="deepclean-intro">
Probe every healthy-looking torrent
(<strong id="deepclean-count">0</strong> rows) via
<code>/unrestrict/link</code> to catch May-2026 filtered
torrents the regex missed. Rate-limited at 250 req/min;
results cached per-hash so a re-scan picks up where you
left off. Estimated time:
<strong id="deepclean-eta">—</strong>.
</p>
<p id="deepclean-actions">
<button id="deepclean-button" type="button">🔍 Run deep clean</button>
<label class="dryrun-toggle small muted">
<input type="checkbox" id="deepclean-verify-toggle">
🧪 Verify mode — probe regex-flagged torrents too. Slower, but
confirms whether RD still filters the patterns we think they do
(and surfaces any that have been quietly reversed).
</label>
</p>
<div id="deepclean-progress" hidden>
<progress id="deepclean-bar" max="100" value="0"></progress>
<p class="muted small" id="deepclean-detail">starting…</p>
<p><button id="deepclean-abort" type="button" class="muted">Abort</button></p>
</div>
<div id="deepclean-result" hidden>
<p>
<strong id="deepclean-result-summary">—</strong>
</p>
<p id="deepclean-scoop-row" hidden>
<button id="deepclean-scoop-button" type="button" class="danger">🗑️ Scoop deep-clean catches</button>
</p>
</div>
</section>
<!-- ============ Discovery / Reddit report ============ -->
<section class="step" id="step-discovery" hidden>
<h3>📰 File a LitterBox report</h3>
<p class="muted small">
Post your library's results to the community — your
breakdown, your stink rating, and any candidate filter
patterns your library surfaced. One click copies the report
to your clipboard and opens the megathread; paste into the
comment box and submit. Every report helps refine the next
LitterBox release.
</p>
<p class="muted small">
<strong>Candidate filter patterns from your library:</strong>
</p>
<ul id="discovery-list" class="discovery-list"></ul>
<p>
<button id="discovery-reddit" type="button" hidden>🚀 Copy report + open r/StremioAddons →</button>
<button id="discovery-copy" type="button" class="muted">📋 Copy report only</button>
</p>
</section>
<p id="all-clean" hidden class="ok">🧼 Nothing to clean up — your library is spotless.</p>
<!-- Share-the-news buttons. Three tones; each generates the
text from the stats just computed. Twitter intent URL +
clipboard copy for cross-platform reach without us managing
per-platform OAuth or instance picking. -->
<section class="share">
<h3>📣 Share the carnage</h3>
<p class="muted small">Three pre-canned posts you can fire off in one click. We don't track anything — these just open Twitter/X or copy to your clipboard.</p>
<div class="share-card">
<p class="share-tone">😤 Vent</p>
<p class="share-text" id="share-shame">…</p>
<p class="share-actions">
<button type="button" class="muted" data-share-copy="share-shame">📋 Copy</button>
<button type="button" data-share-tweet="share-shame">𝕏 Tweet</button>
<button type="button" class="share-reroll" data-share-reroll="share-shame">🎲 Reroll</button>
</p>
</div>
<div class="share-card">
<p class="share-tone">🐈⬛ Brag</p>
<p class="share-text" id="share-tool">…</p>
<p class="share-actions">
<button type="button" class="muted" data-share-copy="share-tool">📋 Copy</button>
<button type="button" data-share-tweet="share-tool">𝕏 Tweet</button>
<button type="button" class="share-reroll" data-share-reroll="share-tool">🎲 Reroll</button>
</p>
</div>
<div class="share-card">
<p class="share-tone">🚪 Plot escape</p>
<p class="share-text" id="share-elfhosted">…</p>
<p class="share-actions">
<button type="button" class="muted" data-share-copy="share-elfhosted">📋 Copy</button>
<button type="button" data-share-tweet="share-elfhosted">𝕏 Tweet</button>
<button type="button" class="share-reroll" data-share-reroll="share-elfhosted">🎲 Reroll</button>
</p>
</div>
</section>
</section>
<section id="confirm" hidden>
<h2>🚨 Confirm bulk scoop</h2>
<p>
You're about to delete <strong id="confirm-count">0</strong> broken torrents
from your Real-Debrid library. This <strong>cannot be undone</strong> via LitterBox —
you'd need to re-add each magnet manually.
</p>
<p id="confirm-dry-banner" hidden class="ok small">🧪 Dry-run mode is ON — no actual deletes will be sent.</p>
<p>Type <code>delete</code> to confirm:</p>
<input type="text" id="confirm-input" class="confirm-input" autocomplete="off" autocapitalize="off">
<p>
<button id="confirm-button" type="button" class="danger" disabled>Scoop 'em</button>
<button id="cancel-button" type="button" class="muted">Cancel</button>
</p>
</section>
<section id="deleting" hidden>
<h2>🧹 Scooping…</h2>
<progress id="delete-progress" max="100" value="0"></progress>
<p class="muted small" id="delete-detail"></p>
</section>
<section id="done" hidden>
<h2 id="done-title">🐈⬛ Done</h2>
<!-- Before/after stink comparison — same rating function as the
scan headline, computed once with pre-delete stats, once with
post-delete stats (broken bytes/count subtracted off). -->
<div class="before-after" id="before-after">
<div class="ba-cell">
<p class="ba-label">before</p>
<p class="ba-rating" id="ba-before-rating">—</p>
<p class="ba-detail muted small" id="ba-before-detail">—</p>
</div>
<div class="ba-arrow">→</div>
<div class="ba-cell">
<p class="ba-label">after</p>
<p class="ba-rating" id="ba-after-rating">—</p>
<p class="ba-detail muted small" id="ba-after-detail">—</p>
</div>
</div>
<p id="done-detail" class="muted small"></p>
<p>
<button id="rescan-button" type="button">🔄 Re-scan library</button>
<button id="signout-button" type="button" class="muted">Sign out</button>
</p>
</section>
</main>
<footer>
<p class="muted small">
Built by <a href="https://elfhosted.com">ElfHosted</a>.
Tired of broken Real-Debrid torrents?
<a href="https://store.elfhosted.com/product-category/personal-stacks/personal-media-stacks/?utm_source=litterbox&utm_medium=dashboard&utm_campaign=rd-migration">
Our CatBox personal media stacks run on TorBox</a> — lazy-materialise so nothing
ever sits broken in your library.
</p>
</footer>
<script src="/static/app.js"></script>
<script>
// Dashboard logic. Depends on /static/app.js for the rate-limited
// proxiedFetch + localStorage helpers (exported on window.litterbox).
(function () {
"use strict";
// BROKEN_STATUSES — torrents RD itself admits are broken via the
// `status` field. Four categories taken from RD's documented enum.
// Mirrors catbox's BrokenRDStatuses (internal/rdimport/rd_client.go)
// so the taxonomy stays consistent across our tools.
const BROKEN_STATUSES = {
error: "⚠️ error",
virus: "🦠 virus-flagged",
dead: "💀 dead",
magnet_error: "🧲❌ bad magnet",
};
// FILTERED_STATUS — synthesized client-side, NOT a real RD status.
// RD's May 2026 "infringing_file" filter doesn't surface on the
// /torrents list (we confirmed against a live filtered torrent:
// status reports "downloaded", progress 100, link present — only
// /unrestrict/link returns HTTP 451 + error_code 35). Probing every
// torrent via /unrestrict/link is correct but takes ~14h for a 10k
// library at RD's 250-req/min ceiling.
//
// The regex below is the same pattern ElfHosted's server-side band-
// aid uses to predict filter hits from the filename alone. It's a
// heuristic — fast, free, no API calls — that catches the bulk of
// the May 2026 class with near-zero false negatives on the affected
// population. False positives are possible (legitimate WEB-DL
// releases that still work) and the user can always untick those
// before scooping.
//
// Encodes the two empirical rules mapped by the Debrid Media
// Manager developer (yowmamasita) against several thousand scene
// releases — the canonical reference for which filenames RD's
// May-2026 "infringing_file" filter rejects:
// https://www.patreon.com/posts/complete-list-of-158388927
//
// Rule 1 — substring (case-insensitive, anywhere):
// web-dl, webrip, bdrip, hdrip, dvdrip
// Rule 2 — Source.Codec dot-adjacency (literal dot, case-insensitive,
// asymmetric — HDTV.h264 is NOT blocked, Blu-Ray.x264 is NOT blocked):
// BluRay.x264, HDTV.x264, HDTV.XviD, WEB.x264, WEB.h264
//
// Server's main.go ships the same fallback; this constant only
// applies if /api/config never lands.
//
// Operator can override via the RD_BLOCKED_FILENAME_REGEX env var
// (exposed through /api/config) to track future RD rule changes
// without rebuilding.
const RD_BLOCKED_FILENAME_FALLBACK =
"web-dl|webrip|bdrip|hdrip|dvdrip|BluRay\\.x264|HDTV\\.x264|HDTV\\.XviD|WEB\\.x264|WEB\\.h264";
let _rdRegex = null, _rdRegexSource = null;
function rdBlockedFilenameRegex() {
const src = (window.litterbox && window.litterbox.cfg && window.litterbox.cfg.rdBlockedFilenameRegex)
|| RD_BLOCKED_FILENAME_FALLBACK;
if (src !== _rdRegexSource) {
_rdRegex = new RegExp(src, "i");
_rdRegexSource = src;
}
return _rdRegex;
}
// The synthesized status key + label. Pretends to be just another
// entry in the broken set from the consumer's POV. Two variants:
// a long label for the legend + callout where there's room for
// the full descriptor, and a short label for tight UI slots like
// the "worst offender" stat card.
// Labels mirror RD's actual error_code literal ("infringing_file")
// so the term in the UI matches what users see in /unrestrict/link
// responses, forum posts, and the verbatim "infringing_file errors
// everywhere" complaints across r/StremioAddons and X. The May-2026
// timeline context lives in the surrounding narrative copy, not in
// the status label itself.
const FILTERED_STATUS_KEY = "filtered";
const FILTERED_STATUS_LABEL = "🚫 infringing_file";
const FILTERED_STATUS_SHORT = "🚫 infringing_file";
// Combined view: which RD status (real or synthesized) is broken.
// Order matters when both could apply — RD's own status takes
// precedence so the user understands the most-explicit signal first.
function classifyStatus(torrent) {
if (BROKEN_STATUSES.hasOwnProperty(torrent.status)) return torrent.status;
if (rdBlockedFilenameRegex().test(torrent.filename || "")) {
return FILTERED_STATUS_KEY;
}
return null; // healthy / in-flight
}
const isBroken = (t) => classifyStatus(t) !== null;
// Friendly label dispatch — consumes the synthesized + real labels
// through one entry point. The `short` variant is for tight slots
// (stat-card titles) that can't fit the full descriptor; falls
// back to the long label for statuses that don't have a short
// form (the four real RD statuses are already short).
function labelFor(status, opts) {
if (status === FILTERED_STATUS_KEY) {
return (opts && opts.short) ? FILTERED_STATUS_SHORT : FILTERED_STATUS_LABEL;
}
return BROKEN_STATUSES[status] || status;
}
// Dry-run flag persisted in localStorage so a refresh keeps the
// local-testing posture across reloads. Default OFF — real deletes
// are the production case.
const DRY_RUN_KEY = "litterbox:dryRun";
const isDryRun = () => localStorage.getItem(DRY_RUN_KEY) === "1";
function $(id) { return document.getElementById(id); }
function show(id) { $(id).hidden = false; }
function hide(id) { $(id).hidden = true; }
// Guard: redirect to sign-in if no token.
if (!localStorage.getItem("rd:accessToken")) {
window.location.href = "/";
return;
}
// Wire the dry-run toggle to localStorage on page load.
const dryToggle = $("dry-run-toggle");
dryToggle.checked = isDryRun();
dryToggle.addEventListener("change", (e) => {
if (e.target.checked) localStorage.setItem(DRY_RUN_KEY, "1");
else localStorage.removeItem(DRY_RUN_KEY);
});
// _allTorrents holds the full /torrents response from the most
// recent scan, used for the backup download. Captured at scan time
// so the backup represents what the user actually saw when they
// clicked apply, not whatever RD's state looks like at apply time.
let _allTorrents = [];
// _deepCatchIds is populated by runDeepClean — the subset of
// torrents that LOOKED healthy on the fast pass but came back
// 451 + error_code 35 from /unrestrict/link.
let _deepCatchIds = [];
// _activeScoopMode tracks which step's results the current
// delete-flow is consuming — "quickwipe" or "deepclean". Used by
// the delete loop to look up the right id set, and by the done-
// screen copy to say "scooped via X". Pre-set to "quickwipe" so
// the historical single-button flow stays correct.
let _activeScoopMode = "quickwipe";
// ============================================================
// localStorage keys for the discovery layer. All client-side —
// no server ever sees any of this data.
// ============================================================
// Per-hash probe outcome cache. Survives across scan sessions so
// a refresh doesn't redo a 30-minute probe walk. Shape:
// { "<hash>": { outcome: "filtered"|"healthy", at: <unix-ms> } }
// Reads tolerate missing keys; writes happen as the probe runs.
const PROBE_CACHE_KEY = "litterbox:probeCache";
// Append-only release-field aggregates across all probe sessions.
// Shape: { "<field>:<value>": { f: <n>, h: <n> } } — e.g.
// "group:flux", "source:webdl", "codec:x264". Feeds the discovery
// analysis; never sent anywhere.
const RELEASE_AGG_KEY = "litterbox:releaseAggregates";
// Community megathread the "Post to Reddit" button opens. Auto-
// copies the report to the clipboard so the user can paste into
// the megathread's comment box. URL comes from REDDIT_MEGATHREAD_URL
// env var via /api/config — when unset, the button is hidden so
// users don't get bounced to a 404. Operator rotates the URL via
// configmap edit; stakater reloader bounces the pods.
function getRedditMegathreadUrl() {
return window.litterbox && window.litterbox.cfg && window.litterbox.cfg.redditMegathreadUrl;
}
function updateRedditButtonVisibility() {
const btn = $("discovery-reddit");
if (!btn) return;
if (getRedditMegathreadUrl()) {
btn.hidden = false;
} else {
btn.hidden = true;
}
}
window.addEventListener("litterbox:config", updateRedditButtonVisibility);
function loadProbeCache() {
try { return JSON.parse(localStorage.getItem(PROBE_CACHE_KEY) || "{}"); }
catch { return {}; }
}
function saveProbeCache(cache) {
localStorage.setItem(PROBE_CACHE_KEY, JSON.stringify(cache));
}
function loadReleaseAgg() {
try { return JSON.parse(localStorage.getItem(RELEASE_AGG_KEY) || "{}"); }
catch { return {}; }
}
function saveReleaseAgg(agg) {
localStorage.setItem(RELEASE_AGG_KEY, JSON.stringify(agg));
}
// maybeRebuildAggregates — on first scan after upgrade, populate
// releaseAggregates by re-parsing every cached probe verdict's
// filename. Lets users carry forward signal from prior probe
// sessions without re-paying the /unrestrict cost.
function maybeRebuildAggregates(torrents) {
const agg = loadReleaseAgg();
if (Object.keys(agg).length > 0) return;
const cache = loadProbeCache();
if (Object.keys(cache).length === 0) return;
let dirty = false;
for (const t of torrents) {
const v = cache[t.hash];
if (!v) continue;
if (v.outcome !== "filtered" && v.outcome !== "healthy") continue;
const parsed = parseRelease(t.filename);
for (const [field, value] of Object.entries(parsed)) {
if (!value) continue;
const key = `${field}:${value}`;
if (!agg[key]) agg[key] = { f: 0, h: 0 };
if (v.outcome === "filtered") agg[key].f++;
else agg[key].h++;
dirty = true;
}
}
if (dirty) saveReleaseAgg(agg);
}
// ============================================================
// parseRelease — structured field extraction from a torrent
// filename. Returns a subset of {group, source, codec,
// resolution, audio}; absent fields are undefined. Targets the
// common scene/p2p naming conventions. Output values are
// lowercased for canonical aggregation keys.
// ============================================================
function parseRelease(filename) {
if (!filename) return {};
let base = filename.replace(/\.(mkv|mp4|avi|m4v|mov|wmv|flv|webm|ts)$/i, "");
while (/\[[^\]]*\]$/.test(base)) {
base = base.replace(/\[[^\]]*\]$/, "").trim();
}
const text = base.replace(/[._]/g, " ");
const out = {};
const res = text.match(/\b(2160p|1080p|720p|480p|4k|uhd)\b/i);
if (res) out.resolution = res[1].toLowerCase();
const codec = text.match(/\b(x265|x264|h\.?265|h\.?264|hevc|avc|vp9|av1|xvid|divx)\b/i);
if (codec) out.codec = codec[1].toLowerCase().replace(/\./g, "");
const source = text.match(/\b(WEB-?DL|WEB-?Rip|BD-?Rip|BR-?Rip|DVD-?Rip|HD-?Rip|HDTV|HD-?CAM|HD-?TC|HD-?TS|BluRay|BD-?Remux|REMUX|AMZN|DSNP|NFLX|HMAX|MAX|ATVP|HULU|PCOK|PMTP)\b/i);
if (source) out.source = source[1].toLowerCase().replace(/-/g, "");
const audio = text.match(/\b(DDP?\d(\.\d)?|AAC\d?(\.\d)?|AC-?3|E?AC-?3|DTS(-HD)?(-MA)?|FLAC|MP3|Opus|TrueHD|Atmos)\b/i);
if (audio) out.audio = audio[0].toLowerCase().replace(/[.-]/g, "");
// Release group — last hyphen-separated fragment in the base.
// Defensively skip values that are clearly codec/channel
// markers rather than groups.
const groupMatch = base.match(/-([A-Za-z0-9_.]+)$/);
if (groupMatch) {
const candidate = groupMatch[1].toLowerCase();
const looksLikeGroup =
!/^[xh]\.?\d{3}$/.test(candidate) &&
!/^\d+\.\d+$/.test(candidate) &&
!/^(aac|ac3|ddp?|dts(-?hd)?(-?ma)?|flac|mp3|opus|truehd|atmos)\d?(\.\d)?$/i.test(candidate);
if (looksLikeGroup) out.group = candidate;
}
return out;
}
// bakedInRegexTokens is the set of tokens already covered by
// RD_BLOCKED_FILENAME_REGEX — used by the discovery analysis to
// filter OUT candidates that wouldn't actually be a new pattern.
// Kept in sync manually with the regex above. The dot-adjacency
// rule's tokens (BluRay/HDTV/WEB/x264/h264/XviD) are intentionally
// omitted — they're not blocked individually, only in specific
// pairings; discovery should still surface them if they correlate
// outside those pairings.
const bakedInRegexTokens = new Set([
"web-dl", "webrip", "bdrip", "hdrip", "dvdrip",
]);
// ============================================================
// Deep probe: POST /unrestrict/link for every "healthy"-looking
// torrent, surface HTTP 451 + error_code 35 as ground-truth
// filtered. Rate-limited by the existing proxiedFetch wrapper
// (240ms / 250 req/min); abortable via the AbortController
// pattern; per-hash results cached to localStorage so a refresh
// mid-probe picks up where it left off.
// ============================================================
// Holds an in-flight abort signal so the abort button can cancel
// the probe loop mid-flight. AbortError percolates up and the
// loop unwinds cleanly.
let _probeAbort = null;
async function runDeepProbe(toProbe, onProgress) {
const cache = loadProbeCache();
const releaseAgg = loadReleaseAgg();
let probedNow = 0, filtered = 0, healthy = 0, deadLink = 0, cached = 0, errored = 0;
const filteredTorrents = [];
const healthyTorrents = [];
const deadLinkTorrents = [];
const abortCtl = new AbortController();
_probeAbort = abortCtl;
// dead-link cache TTL — these outcomes are "the hoster CDN was
// down at probe time" which CAN recover. We re-check after 24h
// so a re-scan picks up resurrected items. Filtered / healthy
// never expire (filter is permanent; healthy stays healthy).
const DEAD_LINK_TTL_MS = 24 * 60 * 60 * 1000;
// Batched cache flush — write every CACHE_FLUSH_EVERY probes
// instead of after every iteration. localStorage.setItem is
// synchronous and JSON.stringify is O(n) over the entire cache,
// so flushing per-row burns visible CPU on a multi-hundred
// probe run. Worst case on abort/crash, we lose the last <25
// verdicts — acceptable, the user will just re-probe them.
const CACHE_FLUSH_EVERY = 25;
let dirty = 0;
const flushCache = () => {
if (dirty === 0) return;
saveProbeCache(cache);
dirty = 0;
};
try {
for (let i = 0; i < toProbe.length; i++) {
if (abortCtl.signal.aborted) throw new DOMException("aborted", "AbortError");
const t = toProbe[i];
let outcome = (cache[t.hash] && cache[t.hash].outcome) || null;
// Honor TTL on dead-link cache entries — those can recover,
// unlike filtered/healthy which are stable. After the TTL
// expires we drop the cached verdict and re-probe.
if (outcome === "dead-link" && cache[t.hash] && (Date.now() - cache[t.hash].at) > DEAD_LINK_TTL_MS) {
outcome = null;
}
// Track whether this row's outcome came from cache vs a
// fresh probe, so we can keep the counters mutually
// exclusive (cached items used to also be counted in
// filtered/healthy, which made the running tally exceed the
// bar position).
let fromCache = !!outcome;
if (!outcome) {
// Not cached — actually call RD.
if (!t.links || t.links.length === 0) {
// No link to probe — treat as inconclusive, skip.
errored++;
onProgress({ i, total: toProbe.length, filtered, healthy, cached, errored });
continue;
}
const link = t.links[0];
try {
const body = new URLSearchParams({ link }).toString();
const r = await window.litterbox.proxiedFetch(
`/rest/1.0/unrestrict/link`,
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body,
// onRetry hook lets us surface mid-retry backoff
// to the UI so a long 429 wait doesn't read as
// "stuck" (field report on first deep probe).
onRetry: ({ reason, attempt, backoffMs }) => {
onProgress({
i, total: toProbe.length, filtered, healthy, cached, errored,
retry: { reason, attempt, backoffMs },
});
},
}
);
if (r.status === 451) {
outcome = "filtered";
} else if (r.status === 503) {
// 503 with a known RD stable-error body — hoster
// unavailable / in maintenance. doProxied already
// skipped retry on these, so we get here fast. Treat
// as a third outcome category alongside filtered and
// healthy — different cause, but equally "this torrent
// doesn't work" from the user's POV. Scooping is up to
// the user.
let isDeadLink = false;
try {
const j = await r.clone().json();
if (j.error_code === 19 || j.error_code === 23) isDeadLink = true;
} catch { /* unexpected 503 body — fall through to errored */ }
if (isDeadLink) {
outcome = "dead-link";
} else {
errored++;
onProgress({ i, total: toProbe.length, filtered, healthy, deadLink, cached, errored });
continue;
}
} else if (r.status === 401 || r.status === 403) {
// Token rejected mid-probe — flush whatever we have
// before bouncing so the user's progress isn't lost.
flushCache();
localStorage.clear();
window.location.href = "/";
return null;
} else if (r.ok) {
// 200 means the unrestrict succeeded — torrent is
// genuinely playable. Mark healthy.
outcome = "healthy";
} else {
// Other errors (429 with retry budget exhausted, other
// 5xx without a known stable-error body, etc.) —
// inconclusive. DON'T cache; a future probe can retry.
errored++;
onProgress({ i, total: toProbe.length, filtered, healthy, deadLink, cached, errored });
continue;
}
cache[t.hash] = { outcome, at: Date.now() };
dirty++;
if (dirty >= CACHE_FLUSH_EVERY) flushCache();
probedNow++;
} catch (e) {
if (e.name === "AbortError") throw e;
errored++;
onProgress({ i, total: toProbe.length, filtered, healthy, deadLink, cached, errored });
continue;
}
}
// Field aggregation: every probed torrent's parsed release
// fields get counted against the outcome. Filtered (May-2026)
// and healthy contribute to the discovery signal. Dead-link
// is excluded — those correlate with a hoster CDN problem,
// not with release naming.
if (outcome === "filtered" || outcome === "healthy") {
const parsed = parseRelease(t.filename);
for (const [field, value] of Object.entries(parsed)) {
if (!value) continue;
const key = `${field}:${value}`;
if (!releaseAgg[key]) releaseAgg[key] = { f: 0, h: 0 };
if (outcome === "filtered") releaseAgg[key].f++;
else releaseAgg[key].h++;
}
}
// Per-row counter bookkeeping: each row increments EXACTLY
// ONE of {cached, filtered, healthy, deadLink, errored} so
// the running tally always equals i+1.
if (fromCache) {
cached++;
} else if (outcome === "filtered") {
filtered++;
filteredTorrents.push(t);
} else if (outcome === "dead-link") {
deadLink++;
deadLinkTorrents.push(t);
} else {
healthy++;
healthyTorrents.push(t);
}
onProgress({ i, total: toProbe.length, filtered, healthy, deadLink, cached, errored });
}
} finally {
_probeAbort = null;
// Final flushes on the way out — completion OR abort path.
flushCache();
saveReleaseAgg(releaseAgg);
}
return { probedNow, filtered, healthy, deadLink, cached, errored, filteredTorrents, healthyTorrents, deadLinkTorrents };
}
// ============================================================
// Discovery analysis: find (field, value) pairs strongly
// correlated with filtering. Only release-tag fields (group,
// source) are surfaced — title / resolution / audio carry no
// filter signal.
// ============================================================
const DISCOVERY_FIELDS = new Set(["group", "source"]);
// annotateCoOccurrence — for each candidate, list the OTHER
// (field, value) pairs that appear in *every* filtered torrent
// containing the candidate AND are themselves strongly filter-
// correlated. Without this filter the list floods with
// universally-common attributes (resolution:1080p, codec:h264)
// that co-occur trivially because most releases use them.
//
// Tightened to 90% ratio + 10-observation floor after seeing
// codec:h264 surface at 77% from a small probed subset — that's
// "h264 is popular", not "h264 is filtered". The stricter cutoff
// keeps the list to fields a curator would consider load-bearing.
const COOCCUR_MIN_RATIO = 0.90;
const COOCCUR_MIN_FILTERED = 10;
function annotateCoOccurrence(candidates, torrents) {
const cache = loadProbeCache();
const releaseAgg = loadReleaseAgg();
const filteredParsed = [];
for (const t of torrents) {
const v = cache[t.hash];
if (!v || v.outcome !== "filtered") continue;
filteredParsed.push(parseRelease(t.filename));
}
for (const c of candidates) {
const matches = filteredParsed.filter(p => p[c.field] === c.value);
if (matches.length === 0) { c.cooccurs = []; continue; }
const counts = {};
for (const p of matches) {
for (const [f, v] of Object.entries(p)) {
if (!v || f === c.field) continue;
const k = `${f}:${v}`;
counts[k] = (counts[k] || 0) + 1;
}
}
c.cooccurs = Object.entries(counts)
.filter(([, n]) => n === matches.length)
.map(([k]) => {
const agg = releaseAgg[k] || { f: 0, h: 0 };
const total = agg.f + agg.h;
const ratio = total > 0 ? agg.f / total : 0;
const value = k.slice(k.indexOf(":") + 1);
return { key: k, ratio, value, filtered: agg.f };
})
.filter(co => co.ratio >= COOCCUR_MIN_RATIO)
.filter(co => co.filtered >= COOCCUR_MIN_FILTERED)
// Skip values already covered by the baked-in regex —
// surfacing them as co-occurrence is redundant noise.
.filter(co => !bakedInRegexTokens.has(co.value))
.sort((a, b) => b.ratio - a.ratio);
}
}
function findDiscoveryCandidates(releaseAgg, minFiltered, minRatio) {
const out = [];
for (const [key, counts] of Object.entries(releaseAgg)) {
const colon = key.indexOf(":");
if (colon < 0) continue; // legacy bare-token entries: skip
const field = key.slice(0, colon);
const value = key.slice(colon + 1);
if (!DISCOVERY_FIELDS.has(field)) continue;
const total = counts.f + counts.h;
if (counts.f < minFiltered) continue;
const ratio = total > 0 ? counts.f / total : 0;
if (ratio < minRatio) continue;
if (bakedInRegexTokens.has(value)) continue;
out.push({ field, value, filtered: counts.f, healthy: counts.h, ratio });
}
out.sort((a, b) => b.filtered - a.filtered || b.ratio - a.ratio);
return out;
}
// _lastProbeResult — populated by the deep-clean handler after a
// successful probe run. Captured so the Reddit report can include
// the deep-clean breakdown (filtered + dead-link counts found via
// /unrestrict/link) even if the user clicks the report button
// after navigating around the page. Null until the first probe.
let _lastProbeResult = null;
const DISCOVERY_DISPLAY_LIMIT = 15;
function renderDiscovery(candidates) {
const ul = $("discovery-list");
ul.innerHTML = "";
if (candidates.length === 0) {
const li = document.createElement("li");
li.className = "muted small";
li.textContent = "No new pattern candidates from your library — the baked-in regex covered everything we saw.";
ul.appendChild(li);
} else {
const shown = candidates.slice(0, DISCOVERY_DISPLAY_LIMIT);
for (const c of shown) {
const li = document.createElement("li");
const label = `${window.litterbox.escapeHTML(c.field)}:${window.litterbox.escapeHTML(c.value)}`;
let html = `<code>${label}</code> — ` +
`<strong>${c.filtered}</strong> filtered, ${c.healthy} healthy ` +
`<span class="muted small">(${(c.ratio * 100).toFixed(1)}% filter-correlated)</span>`;
if (c.cooccurs && c.cooccurs.length > 0) {
const co = c.cooccurs
.map(o => `<code>${window.litterbox.escapeHTML(o.key)}</code> (${(o.ratio * 100).toFixed(0)}%, ${o.filtered} filtered)`)
.join(", ");
html += `<br><span class="muted small">always co-occurs with: ${co}</span>`;
}
li.innerHTML = html;
ul.appendChild(li);
}
if (candidates.length > DISCOVERY_DISPLAY_LIMIT) {
const li = document.createElement("li");
li.className = "muted small";
li.textContent = `…and ${candidates.length - DISCOVERY_DISPLAY_LIMIT} more weaker correlations (not shown).`;
ul.appendChild(li);
}
}
show("step-discovery");
}
// pickRandom — uniform random pick from an array.
function pickRandom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
// Reddit-report headlines — picked at random per render.
// ctx fields: { total, brokenBytes, libraryBytes, pct, stink }
const REDDIT_HEADLINES = [
(c) => `**LitterBox cleaned ${c.pct}% of my ${c.libraryBytes} Real-Debrid library (that RD broke)**`,
(c) => `**${c.pct}% of my ${c.libraryBytes} Real-Debrid library was broken. LitterBox scooped it.**`,
(c) => `**Real-Debrid broke ${c.brokenBytes} of my ${c.libraryBytes} library (${c.pct}%). LitterBox cleaned it up.**`,
(c) => `**LitterBox audit of my ${c.libraryBytes} Real-Debrid library: ${c.brokenBytes} broken (${c.pct}%)**`,
(c) => `**Found ${c.brokenBytes} of dead weight in my ${c.libraryBytes} Real-Debrid library — ${c.pct}% gone, LitterBox cleaned the rest up**`,
(c) => `**My Real-Debrid library was ${c.pct}% rot (${c.brokenBytes} of ${c.libraryBytes}). LitterBox scooped it.**`,
];
// buildRedditReport returns the markdown the user pastes into the
// community megathread comment box.
function buildRedditReport(stats, stink, probeResult, candidates) {
const filteredViaRegex = stats.brokenByStatus[FILTERED_STATUS_KEY] || 0;
const probeFiltered = (probeResult && probeResult.filtered) || 0;
const probeDeadLink = (probeResult && probeResult.deadLink) || 0;
const probeBytes = (probeResult && ((probeResult.filteredBytes || 0) + (probeResult.deadLinkBytes || 0))) || 0;
const adminBroken = (stats.brokenByStatus.error || 0)
+ (stats.brokenByStatus.virus || 0)
+ (stats.brokenByStatus.dead || 0)
+ (stats.brokenByStatus.magnet_error || 0);
const totalScooped = stats.broken + probeFiltered + probeDeadLink;
// Headline / stink reflect EVERYTHING the scan + probe surfaced,
// not just regex hits. Without this, a library with 0 regex hits
// but 72 probe-found infringing_file torrents would render
// "0 B broken (0.0%)" — technically true of the fast-pass, but
// wildly misleading next to the breakdown that mentions the 72.
const totalBrokenBytes = stats.brokenBytes + probeBytes;
const totalBrokenStink = stinkRating(totalBrokenBytes, stats.libraryBytes);
// Projected after-state: assume everything broken got cleaned.
const remainingLibBytes = Math.max(0, stats.libraryBytes - totalBrokenBytes);
const afterStink = stinkRating(0, remainingLibBytes);
// Inline-comma breakdown — one line vs a 5-row table. Plain-
// language labels — no "(regex)" / "(hoster_unavailable)" /
// "/unrestrict probe" jargon. Average Redditor needs to read
// these and grok them at a glance.
const parts = [];
if (filteredViaRegex > 0) parts.push(`${filteredViaRegex} caught by filename pattern`);
if (probeFiltered > 0) parts.push(`${probeFiltered} more caught by per-torrent probe`);
if (probeDeadLink > 0) parts.push(`${probeDeadLink} dead-link errors`);
if (adminBroken > 0) parts.push(`${adminBroken} flagged broken by RD`);
const breakdown = parts.length > 0
? parts.join(" · ")
: "_nothing flagged yet — run the deep-clean step to surface probe-only filters_";
const headline = pickRandom(REDDIT_HEADLINES)({
total: totalScooped,
brokenBytes: fmtBytesRounded(totalBrokenBytes),
libraryBytes: fmtBytesRounded(stats.libraryBytes),
pct: totalBrokenStink.pct.toFixed(1),
stink: totalBrokenStink,
});
const lines = [
headline,
"",
`Stink rating: **${totalBrokenStink.label} (${totalBrokenStink.score}/10)** → **${afterStink.label} (${afterStink.score}/10)** ✨`,
"",
`**Breakdown:** ${breakdown}`,
"",
];
if (candidates && candidates.length > 0) {
const shown = candidates.slice(0, DISCOVERY_DISPLAY_LIMIT);
// Drop the "Co-occurs with" column when no candidate has any
// co-occurrence data — saves explaining what "co-occurs" means
// for the common case where the column would just be "—" rows.
const hasCooccurs = shown.some(c => c.cooccurs && c.cooccurs.length > 0);
lines.push("**Tags not yet in LitterBox's built-in filter list, found in 100%-filtered torrents in my library:**");
lines.push("");
if (hasCooccurs) {
lines.push("| Field | Value | Filtered | Healthy | % filtered | Co-occurs with |");
lines.push("|---|---|---:|---:|---:|---|");
} else {
lines.push("| Field | Value | Filtered | Healthy | % filtered |");
lines.push("|---|---|---:|---:|---:|");
}
for (const c of shown) {
const baseRow = `| \`${c.field}\` | \`${c.value}\` | ${c.filtered} | ${c.healthy} | ${(c.ratio * 100).toFixed(1)}% |`;
if (hasCooccurs) {
const co = (c.cooccurs && c.cooccurs.length > 0)
? c.cooccurs.map(o => `\`${o.key}\` (${(o.ratio * 100).toFixed(0)}%, ${o.filtered} filtered)`).join(", ")
: "—";
lines.push(`${baseRow} ${co} |`);
} else {
lines.push(baseRow);
}
}
if (candidates.length > DISCOVERY_DISPLAY_LIMIT) {
const fill = hasCooccurs ? " | | | | | |" : " | | | | |";
lines.push(`| _…and ${candidates.length - DISCOVERY_DISPLAY_LIMIT} more_${fill}`);
}
lines.push("");
}
lines.push("---");
lines.push("");
lines.push("Tool: [LitterBox](https://litterbox.elfhosted.com) — open-source, runs in-browser, signs in with your RD account.");
lines.push("");
lines.push("Migrating from Real-Debrid to TorBox with the catalog intact: [ElfHosted's CatBox personal media stacks](https://store.elfhosted.com/product-category/personal-stacks/personal-media-stacks/?utm_source=litterbox&utm_medium=reddit&utm_campaign=rd-migration) — API and policy compliant, TorBox-endorsed.");