Repository navigation
Expand file tree
/
Copy pathRLSBB_Userscript.user.js
More file actions
6164 lines (5294 loc) · 218 KB
/
Copy pathRLSBB_Userscript.user.js
File metadata and controls
6164 lines (5294 loc) · 218 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
// ==UserScript==
// @name RLSBB Prism
// @namespace https://chatgpt.local/rlsbb-clean-v11
// @version 2.8.23
// @description RLSBB media-card interface with artwork modes, quality filters, post lightbox, RapidGator/AllDebrid download buttons, protected.to helpers, homepage recommendations, infinite scroll, and a site-wide magnet-link helper.
// @author Personal
// @match https://rlsbb.in/*
// @match https://www.rlsbb.in/*
// @match https://post.rlsbb.in/*
// @match https://search.rlsbb.in/*
// @match https://rapidgator.net/file/*
// @match https://www.rapidgator.net/file/*
// @match http://protected.to/*
// @match https://protected.to/*
// @match *://*/*
// @connect rlsbb.in
// @connect www.rlsbb.in
// @connect post.rlsbb.in
// @connect search.rlsbb.in
// @connect api.alldebrid.com
// @connect api.themoviedb.org
// @connect 192.168.0.200
// @connect 127.0.0.1
// @resource rbbMoviePlaceholder https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/assets/placeholders/movie.png
// @resource rbbTvPlaceholder https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/assets/placeholders/tv.png
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_getResourceURL
// @grant GM_registerMenuCommand
// @grant GM_download
// @grant GM_info
// @grant GM_setClipboard
// @run-at document-end
// @downloadURL https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/RLSBB_Userscript.user.js?v=2.8.23
// @updateURL https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/RLSBB_Userscript.user.js?v=2.8.23
// ==/UserScript==
(function () {
'use strict';
// Sites that enforce a Trusted Types CSP (require-trusted-types-for 'script') block plain
// innerHTML assignment outright, which used to throw an uncaught TypeError and kill the rest
// of this script's execution on that page/frame -- including the magnet-link helper, which is
// meant to work everywhere (@match *://*/*), not just on RLSBB. Registering our own policy
// (createHTML is a no-op passthrough; we trust our own template strings) lets innerHTML keep
// working on those sites instead of silently no-opping the whole script.
let ttPolicy = null;
if (window.trustedTypes && typeof window.trustedTypes.createPolicy === 'function') {
try {
ttPolicy = window.trustedTypes.createPolicy('rbb-prism-html', { createHTML: html => html });
} catch {
// Policy name already taken (e.g. script ran twice) or default policy required elsewhere --
// fall through with ttPolicy left null, setHTML() below still degrades gracefully.
}
}
function setHTML(el, html) {
if (!el) return;
try {
el.innerHTML = ttPolicy ? ttPolicy.createHTML(html) : html;
} catch (err) {
console.warn('RLSBB Prism: innerHTML blocked on this page (CSP Trusted Types) --', err?.message || err);
}
}
const STORAGE_KEY = 'rbbCleanBoard.v11';
// v2 fixes the old TV cache identity, which omitted the episode number. That made every
// episode in one season reuse whichever display title populated the cache first (for
// example, S02E08/S02E09 both visibly became S02E10 even though their post data was right).
const TMDB_CACHE_KEY = 'tmdbArtworkCache.v2';
const TMDB_CACHE_MAX_AGE = 90 * 24 * 60 * 60 * 1000;
const TMDB_MISS_MAX_AGE = 14 * 24 * 60 * 60 * 1000;
const TMDB_POSTER_IMAGE_BASE = 'https://image.tmdb.org/t/p/w342';
const TMDB_BACKDROP_IMAGE_BASE = 'https://image.tmdb.org/t/p/w780';
const PLACEHOLDER_FALLBACKS = {
movie: 'https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/assets/placeholders/movie.png',
tv: 'https://raw.githubusercontent.com/PhadeDev/RLSBB_Userscript/main/assets/placeholders/tv.png'
};
const isPostPage = location.hostname.startsWith('post.') || document.body.classList.contains('single-post');
const isSearchPage = location.hostname.startsWith('search.');
// Recommended posters only make sense on the true homepage/archive browse view
const showRecommended = !isPostPage && !isSearchPage;
const seenIds = new Set();
let nextPageUrl = '';
let isLoading = false;
let rssDateMapPromise = null;
const state = loadState();
// ---- in-flight download-op tracking ----
// AllDebrid unlock (and, worse, magnet caching, which can poll for up to 10 minutes) only
// exists as JS running in this tab -- if the tab is closed or navigated away mid-unlock, that
// work is genuinely lost and has to be started over. Once a browser download or aria2 send-off
// has actually been kicked off, though, it keeps running independently (the browser's own
// download manager, or the aria2 daemon) and the tab is safe to close. This counter plus the
// beforeunload listener below turns "is it safe to close this?" from a guess into a real
// browser-native confirmation prompt during the risky window only.
let activeDownloadOps = 0;
function beginDownloadOp() { activeDownloadOps += 1; }
function endDownloadOp() { activeDownloadOps = Math.max(0, activeDownloadOps - 1); }
window.addEventListener('beforeunload', event => {
if (activeDownloadOps > 0) {
event.preventDefault();
event.returnValue = '';
}
});
// Ticks a status element every second with a live elapsed-seconds count instead of a single
// static "Unlocking..." label that never changes -- the actual complaint being answered here
// is "I can't tell if this is frozen or just slow." Returns a stop function.
function startElapsedTicker(statusEl, prefix) {
const startedAt = Date.now();
const tick = () => {
if (!statusEl) return;
const secs = Math.floor((Date.now() - startedAt) / 1000);
statusEl.textContent = `${prefix} ${secs}s`;
statusEl.title = secs < 8
? 'Unlocking via AllDebrid -- keep this tab open until it says Started/Sent.'
: 'Some hosts take 30s+ to unlock via AllDebrid. Keep this tab open -- check the console (F12) for live progress.';
};
tick();
const intervalId = setInterval(tick, 1000);
return () => clearInterval(intervalId);
}
function defaultState() {
return {
q: '',
categoryFilter: '',
sort: 'newest',
hideSupport: true,
hideApps: true,
hideLowQualityMovies: true,
hideTv: false,
hideGames: false,
hideMagazines: true,
rgOnly: false,
categoriesOpen: false,
recommendedOpen: true,
commentsOpen: true,
versionFilters: {
'1080p': false,
'4k': false,
'hdr': false,
'dv': false,
'x265': false,
'webdl': false
}
};
}
function loadState() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
const base = defaultState();
return {
...base,
...saved,
versionFilters: {
...base.versionFilters,
...(saved.versionFilters || {})
}
};
} catch {
return defaultState();
}
}
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
// Shown in the topbar so it's obvious from a screenshot whether Tampermonkey has actually
// picked up the latest version — its auto-update check isn't instant even with
// @updateURL/@downloadURL set correctly.
function scriptVersion() {
try {
return (typeof GM_info !== 'undefined' && GM_info.script && GM_info.script.version) || '?';
} catch {
return '?';
}
}
// ---- download settings: AllDebrid API key + aria2 RPC, stored via GM_setValue so they
// never touch the (public) GitHub repo — entered once through the Settings dialog ----
function getSetting(key, fallback) {
let gmValue = fallback;
try {
if (typeof GM_getValue === 'function') gmValue = GM_getValue(key, fallback);
} catch {}
const hasGmValue = gmValue !== fallback && gmValue !== undefined && gmValue !== null && gmValue !== '';
if (hasGmValue) {
// Keep this origin's localStorage mirror fresh on every read, so a real value stays
// recoverable here even if GM storage itself is ever wiped (e.g. a Tampermonkey reinstall).
try { localStorage.setItem('rbb_' + key, gmValue); } catch {}
return gmValue;
}
try {
const localValue = localStorage.getItem('rbb_' + key);
if (localValue !== null && localValue !== undefined && localValue !== '') {
// GM storage came back empty but this origin still remembers it -- restore it into GM
// storage right away instead of just limping along on the (more easily cleared) mirror.
try { if (typeof GM_setValue === 'function') GM_setValue(key, localValue); } catch {}
return localValue;
}
} catch {}
return gmValue ?? fallback;
}
function setSetting(key, value) {
if (typeof GM_setValue === 'function') GM_setValue(key, value);
try {
localStorage.setItem('rbb_' + key, value);
} catch {}
}
function getJsonSetting(key, fallback) {
const raw = getSetting(key, '');
if (!raw) return fallback;
try {
return typeof raw === 'string' ? JSON.parse(raw) : raw;
} catch {
return fallback;
}
}
function setJsonSetting(key, value) {
setSetting(key, JSON.stringify(value));
}
// Every key the Settings dialog's Backup/Restore controls round-trip. Keep in sync with the
// form fields in injectSettingsDialog().
const BACKUP_SETTING_KEYS = [
'movieArtworkMode', 'tvArtworkMode', 'tmdbApiKey',
'allDebridKey', 'aria2Rpc', 'aria2Secret',
'localAria2Rpc', 'localAria2Secret', 'localAria2Dir'
];
function buildSettingsBackupBlob() {
const payload = {};
BACKUP_SETTING_KEYS.forEach(key => { payload[key] = getSetting(key, ''); });
return 'RBBPRISM1:' + btoa(unescape(encodeURIComponent(JSON.stringify(payload))));
}
function restoreSettingsBackupBlob(blob) {
const trimmed = (blob || '').trim();
if (!trimmed.startsWith('RBBPRISM1:')) throw new Error('Not a recognised backup blob');
const payload = JSON.parse(decodeURIComponent(escape(atob(trimmed.slice('RBBPRISM1:'.length)))));
BACKUP_SETTING_KEYS.forEach(key => {
if (typeof payload[key] === 'string') setSetting(key, payload[key]);
});
}
function getDownloadSettings() {
return {
allDebridKey: getSetting('allDebridKey', ''),
aria2Rpc: getSetting('aria2Rpc', 'http://192.168.0.200:6800/jsonrpc'),
aria2Secret: getSetting('aria2Secret', ''),
// Separate local aria2 instance (runs on this PC, not the NAS) so magnet downloads can
// land in a folder you pick, rather than the NAS pipeline's fixed 2SORT path.
localAria2Rpc: getSetting('localAria2Rpc', 'http://127.0.0.1:6802/jsonrpc'),
localAria2Secret: getSetting('localAria2Secret', ''),
localAria2Dir: getSetting('localAria2Dir', '/home/Phaderon/Downloads')
};
}
function getArtworkSettings() {
const legacyMode = getSetting('artworkMode', 'rlsbb');
let movieMode = getSetting('movieArtworkMode', legacyMode);
if (movieMode === 'tmdb-backdrop') movieMode = 'tmdb';
// If the short-lived single global mode was set to TMDB, keep the useful part for movies
// but move TV back to RLSBB by default. TMDB TV posters are portrait, not banner art.
const tvFallback = legacyMode === 'placeholder' ? 'placeholder' : 'rlsbb';
const tvMode = getSetting('tvArtworkMode', tvFallback);
return {
movieArtworkMode: ['rlsbb', 'tmdb', 'placeholder'].includes(movieMode) ? movieMode : 'rlsbb',
tvArtworkMode: ['rlsbb', 'tmdb-poster', 'tmdb-backdrop', 'placeholder'].includes(tvMode) ? tvMode : 'rlsbb',
tmdbApiKey: getSetting('tmdbApiKey', '')
};
}
function init() {
const articles = [...document.querySelectorAll('#post-wrapper article, article.post')];
if (!articles.length) {
console.warn('RLSBB Prism: no posts found; leaving original page untouched.');
return;
}
const recommendedItems = showRecommended ? extractRecommendedItems(document) : [];
injectStyles();
if (!isPostPage) injectLightbox();
injectSettingsDialog();
bindDownloadButtons();
bindCategoryPills();
document.body.classList.add('rbb-clean-body', isPostPage ? 'rbb-post-mode' : 'rbb-feed-mode');
nextPageUrl = findNextPageUrl(document);
const originalMain = document.querySelector('#main') || document.body;
const originalSearch = document.querySelector('#HideSearch, form.search-form');
const categoryWidget = findCategoryWidget();
const app = document.createElement('section');
app.id = 'rbb-clean';
setHTML(app, makeShell());
originalMain.prepend(app);
mountSearch(app, originalSearch);
mountCategories(app, categoryWidget);
if (showRecommended) mountRecommended(app, recommendedItems);
const grid = app.querySelector('[data-grid]');
articles.forEach(article => appendArticle(article, grid));
if (!isPostPage) hydrateFeedCardDates(grid);
bindUi(app);
applyFiltersAndSort();
hideOriginalPageSafely();
if (showRecommended) {
refreshRecommendedRail();
watchRecommendedRail();
}
hidePosterWallsSafely();
if (isPostPage) {
autoExpandPostPageSections();
}
if (!isPostPage) setupInfiniteScroll(grid);
}
// ---- RapidGator file-page companion: adds its own Download/To NAS buttons directly on the
// page you land on after clicking through a protected.to link, since RapidGator's own free-
// download flow has no automatable button at all. Pre-fills a rename box with whichever
// release name was most recently clicked from RLSBB (see rememberPendingReleaseName()),
// since RapidGator's own filename is frequently a cryptic abbreviation. ----
function initRapidGatorPage() {
const fileLink = document.querySelector('.file-descr a');
if (!fileLink) return; // not an actual file page (login/premium/etc.) — leave it alone
injectStyles();
injectSettingsDialog();
const rawFilename = cleanText(fileLink.textContent) || document.title.replace(/^Download file\s*/i, '') || 'download';
const sizeMatch = document.body.textContent.match(/File size:\s*([\d.,]+\s*[KMGT]?B)/i);
const fileSize = sizeMatch ? sizeMatch[1] : '';
const recent = getRecentReleaseNames();
const suggestedName = recent[0]?.name || '';
const panel = document.createElement('div');
panel.id = 'rbb-rg-panel';
panel.className = 'rbb-card rbb-detail-card rbb-rg-page-panel';
setHTML(panel, `
<div class="rbb-content">
<h2 class="rbb-card-title">RLSBB Prism</h2>
<p class="rbb-description" style="max-width:none;">
Detected file: <strong>${esc(rawFilename)}</strong>${fileSize ? ` · ${esc(fileSize)}` : ''}
</p>
${suggestedName ? `<p class="rbb-description" style="max-width:none; color:#9ef0c8;">Guessed from a recent RLSBB click: <strong>${esc(suggestedName)}</strong></p>` : ''}
<label class="rbb-settings-field">
<span>Save as</span>
<input type="text" id="rbb-rg-filename" value="${escAttr(suggestedName || rawFilename)}">
</label>
<div class="rbb-settings-actions" style="justify-content:flex-start; gap:10px; margin-top:10px;">
<button type="button" class="rbb-dl-btn rbb-dl-browser" id="rbb-rg-download" style="width:auto; flex-direction:row; padding:8px 14px;">
<span class="rbb-dl-icon" aria-hidden="true">↓</span><span class="rbb-dl-label">Local aria2</span>
</button>
<button type="button" class="rbb-dl-btn rbb-dl-aria2" id="rbb-rg-tonas" style="width:auto; flex-direction:row; padding:8px 14px;">
<span class="rbb-dl-icon" aria-hidden="true">⇥</span><span class="rbb-dl-label">To NAS</span>
</button>
<button type="button" class="rbb-settings-btn" id="rbb-rg-settings" title="Download settings (AllDebrid + aria2)" style="height:auto; padding:6px 10px; font-size:14px;">⚙</button>
</div>
<span class="rbb-dl-status" id="rbb-rg-status" style="display:block; text-align:left; margin-top:8px;"></span>
<span class="rbb-dl-progress" id="rbb-rg-progress" style="max-width:260px;"></span>
</div>
`);
const anchor = document.querySelector('.file-descr') || document.body.firstElementChild;
anchor.parentNode.insertBefore(panel, anchor);
document.getElementById('rbb-rg-download').addEventListener('click', () => runRapidGatorDownload('browser'));
document.getElementById('rbb-rg-tonas').addEventListener('click', () => runRapidGatorDownload('aria2'));
document.getElementById('rbb-rg-settings').addEventListener('click', openSettingsDialog);
}
async function runRapidGatorDownload(mode) {
const input = document.getElementById('rbb-rg-filename');
const button = document.getElementById(mode === 'aria2' ? 'rbb-rg-tonas' : 'rbb-rg-download');
const status = document.getElementById('rbb-rg-status');
const progress = document.getElementById('rbb-rg-progress');
const chosenName = (input.value || '').trim() || 'download';
if (mode === 'browser') {
const { localAria2Dir } = getDownloadSettings();
status.textContent = 'Opening Windows folder picker...';
let destDir;
try {
destDir = await chooseLocalDownloadFolder(localAria2Dir);
} catch (error) {
status.textContent = error.message || 'Could not open folder picker';
status.classList.add('rbb-dl-error');
return;
}
if (!destDir) { status.textContent = ''; return; }
beginDownloadOp();
button.disabled = true;
button.classList.add('rbb-dl-busy');
status.classList.remove('rbb-dl-error');
status.textContent = 'Sending job to tray…';
status.title = 'The tray will own the AllDebrid unlock and local aria2 queue after this job is accepted.';
if (progress) progress.classList.add('rbb-dl-progress-active');
try {
const accepted = await submitLocalHandoffJob({
kind: 'link',
url: location.href,
suggestedName: chosenName,
downloadDir: destDir
});
status.textContent = `Sent to tray ✓ job ${accepted.job_id}`;
status.title = `Tray log: ${accepted.log || ''}`;
setSetting('localAria2Dir', destDir);
showLocalHandoffProgress(accepted, status);
} catch (error) {
logError('RapidGator tray handoff failed:', error);
status.textContent = error.message || 'Tray handoff failed';
status.classList.add('rbb-dl-error');
} finally {
endDownloadOp();
button.disabled = false;
button.classList.remove('rbb-dl-busy');
if (progress) progress.classList.remove('rbb-dl-progress-active');
}
return;
}
beginDownloadOp();
button.disabled = true;
button.classList.add('rbb-dl-busy');
status.classList.remove('rbb-dl-error');
if (progress) progress.classList.add('rbb-dl-progress-active');
const stopTicker = startElapsedTicker(status, 'Unlocking…');
try {
const unlocked = await allDebridUnlock(location.href);
stopTicker();
// preserve the real file extension even if the user's chosen name doesn't include one
const finalName = /\.[a-z0-9]{2,4}$/i.test(chosenName)
? chosenName
: chosenName + guessExtension(unlocked.filename);
const seconds = (unlocked.elapsedMs / 1000).toFixed(1);
if (mode === 'browser') {
await browserDownload(unlocked.link, finalName);
status.textContent = `Started ✓ ${seconds}s`;
status.title = 'Safe to close this tab now.';
} else {
await aria2AddUri(unlocked.link, finalName);
status.textContent = `Sent ✓ ${seconds}s`;
status.title = 'Safe to close this tab now.';
}
} catch (error) {
stopTicker();
logError('RapidGator page download failed:', error);
status.textContent = error.code === 'LINK_DOWN' ? '❌ File removed from host' : (error.message || 'Failed');
status.classList.add('rbb-dl-error');
} finally {
endDownloadOp();
button.disabled = false;
button.classList.remove('rbb-dl-busy');
if (progress) progress.classList.remove('rbb-dl-progress-active');
}
}
function guessExtension(filename) {
const match = /\.[a-z0-9]{2,4}$/i.exec(filename || '');
return match ? match[0] : '';
}
// ---- protected.to multi-part splitter page ("Ncrypt Application") ----
// Some protected.to releases (usually multi-part RARs) land you on a page listing every
// real rapidgator.net link directly instead of one link to click through. AllDebrid can't
// batch-unlock+extract these from the browser (that needs real filesystem/7z access), but
// the user's existing NAS pipeline (rlsbb-watcher.py --queue-direct-url, wired into the tray
// app's new Manual Import button) already does exactly that. This just detects the page and
// copies a ready-to-paste block (title + every link) to the clipboard for it.
function initProtectedToPage() {
const heading = document.querySelector('.Encrypted-folder');
const linkNodes = [...document.querySelectorAll('.Encrypted-box .links a[href]')];
if (!heading || !linkNodes.length) return; // not a splitter page at all — leave alone
const headingText = cleanText(heading.textContent);
const sizeMatch = headingText.match(/\[\s*([^\]]+?)\s*\]\s*$/);
const releaseName = cleanText(headingText.replace(/\[[^\]]*\]\s*$/, ''));
const size = sizeMatch ? sizeMatch[1] : '';
const links = linkNodes.map(a => a.href);
// same cross-page memory used for the RapidGator page's smart rename, in case the user
// clicks straight into a part instead of using the tray — worth doing even when there's
// only one link, since the name is already known regardless of how many hops follow
rememberPendingReleaseName(releaseName);
// A single link here is usually just another intermediate protected.to hop, not a real
// multi-part release — showing "split into 1 part" in that case was actively misleading
// (implied there was something to copy/paste when there wasn't). Only show the panel for
// genuine multi-part releases; for one link, stay out of the way and let the user click
// through normally.
if (links.length < 2) return;
injectStyles();
const panel = document.createElement('div');
panel.id = 'rbb-protected-panel';
panel.className = 'rbb-card rbb-detail-card rbb-rg-page-panel';
setHTML(panel, `
<div class="rbb-content">
<h2 class="rbb-card-title">RLSBB Prism</h2>
<p class="rbb-description" style="max-width:none;">
This release is split into <strong>${links.length}</strong> part${links.length === 1 ? '' : 's'}:
<strong>${esc(releaseName)}</strong>${size ? ` · ${esc(size)}` : ''}
</p>
<p class="rbb-description" style="max-width:none;">
AllDebrid can unlock each part, but auto-extracting a multi-part RAR needs real filesystem
access a browser doesn't have — your NAS pipeline already does this via the tray app's
<strong>Manual Import</strong> (paste icon next to Settings). Copy below, then paste there.
</p>
<div class="rbb-settings-actions" style="justify-content:flex-start; gap:10px; margin-top:6px;">
<button type="button" class="rbb-dl-btn rbb-dl-aria2" id="rbb-protected-copy" style="width:auto; flex-direction:row; padding:8px 14px;">
<span class="rbb-dl-icon" aria-hidden="true">📋</span><span class="rbb-dl-label">Copy for tray Manual Import</span>
</button>
</div>
<span class="rbb-dl-status" id="rbb-protected-status" style="display:block; text-align:left; margin-top:8px;"></span>
</div>
`);
const anchor = document.querySelector('.Encrypted-box')?.closest('.panel') || document.body.firstElementChild;
anchor.parentNode.insertBefore(panel, anchor);
document.getElementById('rbb-protected-copy').addEventListener('click', () => {
const status = document.getElementById('rbb-protected-status');
const clipboardText = [releaseName, ...links].join('\n');
if (typeof GM_setClipboard === 'function') {
GM_setClipboard(clipboardText);
status.textContent = 'Copied ✓ — paste into the tray\'s Manual Import';
status.classList.remove('rbb-dl-error');
} else {
status.textContent = 'Clipboard unavailable — copy the links manually';
status.classList.add('rbb-dl-error');
}
});
}
function makeShell() {
return `
<header class="rbb-topbar">
<a class="rbb-brand" href="https://rlsbb.in/" title="Back to the RLSBB homepage">
<div class="rbb-logo">RBB</div>
<div>
<div class="rbb-title">ReleaseBB</div>
<div class="rbb-subtitle">${isPostPage ? 'detail picker' : 'release picker'} · v${escAttr(scriptVersion())}</div>
</div>
</a>
<div class="rbb-search" data-search></div>
<details class="rbb-menu" ${state.categoriesOpen ? 'open' : ''}>
<summary>Categories</summary>
<div class="rbb-menu-panel" data-categories></div>
</details>
<button type="button" class="rbb-settings-btn" data-open-settings title="Download settings (AllDebrid + aria2)">⚙</button>
</header>
${isPostPage ? '' : `
<nav class="rbb-filters">
<input class="rbb-filter-input" data-filter="q" type="search" placeholder="Filter cards…" value="${escAttr(state.q)}">
<select class="rbb-sort" data-filter="sort">
<option value="newest" ${state.sort === 'newest' ? 'selected' : ''}>Newest first</option>
<option value="oldest" ${state.sort === 'oldest' ? 'selected' : ''}>Oldest first</option>
<option value="az" ${state.sort === 'az' ? 'selected' : ''}>Title A–Z</option>
<option value="za" ${state.sort === 'za' ? 'selected' : ''}>Title Z–A</option>
</select>
<span class="rbb-active-category" data-active-category ${state.categoryFilter ? '' : 'hidden'}>
<span data-active-category-label>${state.categoryFilter ? esc(activeCategoryLabel()) : ''}</span>
<button type="button" data-clear-category title="Clear category filter" aria-label="Clear category filter">×</button>
</span>
<div class="rbb-version-filter-group">
${versionToggle('1080p', '1080p')}
${versionToggle('4k', '4K')}
${versionToggle('hdr', 'HDR')}
${versionToggle('dv', 'DV')}
${versionToggle('x265', 'x265')}
${versionToggle('webdl', 'WEB-DL')}
</div>
${toggle('hideSupport', 'Hide support')}
${toggle('hideApps', 'Hide apps')}
${toggle('hideLowQualityMovies', 'Hide low movies')}
${toggle('hideTv', 'Hide TV')}
${toggle('hideGames', 'Hide games')}
${toggle('hideMagazines', 'Hide mags')}
${toggle('rgOnly', 'RG only')}
</nav>
`}
<div class="rbb-layout ${showRecommended ? '' : 'rbb-layout-full'}">
<main class="rbb-grid" data-grid></main>
${showRecommended ? '<aside class="rbb-side" data-side></aside>' : ''}
</div>
<div class="rbb-loader" data-loader hidden>Loading more…</div>
`;
}
function toggle(key, label) {
return `
<label class="rbb-toggle">
<input data-filter="${key}" type="checkbox" ${state[key] ? 'checked' : ''}>
<span>${label}</span>
</label>
`;
}
function versionToggle(key, label) {
return `
<label class="rbb-version-toggle rbb-version-${key}">
<input data-version-filter="${key}" type="checkbox" ${state.versionFilters[key] ? 'checked' : ''}>
<span>${label}</span>
</label>
`;
}
function activeCategoryLabel() {
return `Category: ${String(state.categoryFilter || '')
.split(/\s+/)
.filter(Boolean)
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')}`;
}
function mountSearch(app, originalSearch) {
const mount = app.querySelector('[data-search]');
if (!originalSearch) {
setHTML(mount, `
<form action="https://search.rlsbb.in/" method="get" class="rbb-site-search">
<input name="s" type="search" placeholder="Search title / keyword / IMDb ID">
<button type="submit">Search</button>
</form>
`);
return;
}
const clone = originalSearch.cloneNode(true);
clone.id = 'rbb-site-search';
clone.className = 'rbb-site-search';
const input = clone.querySelector('input[type="search"], input[name="s"]');
if (input) {
input.placeholder = 'Search title / keyword / IMDb ID';
input.autocomplete = 'off';
}
const button = clone.querySelector('button, input[type="submit"]');
if (button) {
button.textContent = 'Search';
button.value = 'Search';
}
mount.appendChild(clone);
}
function mountCategories(app, widget) {
const mount = app.querySelector('[data-categories]');
if (!mount) return;
if (!widget) {
setHTML(mount, `
<a href="https://rlsbb.in/category/movies/">Movies</a>
<a href="https://rlsbb.in/category/tv-shows/">TV Shows</a>
<a href="https://rlsbb.in/category/games/">Games</a>
<a href="https://rlsbb.in/category/applications/">Applications</a>
`);
return;
}
const clone = widget.cloneNode(true);
clone.querySelectorAll('h1,h2,h3,.widget-title,script,iframe,style').forEach(n => n.remove());
mount.appendChild(clone);
}
function mountRecommended(app, items) {
const side = app.querySelector('[data-side]');
if (!side) return;
setHTML(side, '');
const box = document.createElement('details');
box.className = 'rbb-recommended';
box.open = !!state.recommendedOpen;
setHTML(box, `
<summary>Recommended</summary>
<div class="rbb-recommended-scroll" data-recommended-scroll>
${items.length ? items.map(item => recommendedItemHtml(item)).join('') : ''}
</div>
<div class="rbb-recommended-empty" data-recommended-empty ${items.length ? 'hidden' : ''}>
Looking for posters…
</div>
`);
side.appendChild(box);
box.addEventListener('toggle', () => {
state.recommendedOpen = box.open;
saveState();
});
dedupeRecommendedRail();
}
function recommendedItemHtml(item) {
return `
<a class="rbb-rec-item" href="${escAttr(item.href)}" target="_blank" rel="noopener noreferrer" title="${escAttr(item.title)}">
<img src="${escAttr(item.src)}" alt="">
</a>
`;
}
function resourceUrl(name, fallback) {
try {
if (typeof GM_getResourceURL === 'function') return GM_getResourceURL(name) || fallback;
} catch {}
return fallback;
}
function mediaKindForData(data) {
const cats = (data.categories || []).join(' ').toLowerCase();
const title = String(data.title || '');
if (/\bgames?\b|\bpc\b|\bmac\b/.test(cats)) return 'game';
if (/tv|episode|foreign tv|tv packs/.test(cats) || /\bS\d{1,2}(?:E\d{1,3})?\b/i.test(title)) return 'tv';
return 'movie';
}
function artworkModeForKind(kind) {
const settings = getArtworkSettings();
if (kind === 'game') return 'rlsbb';
return kind === 'tv' ? settings.tvArtworkMode : settings.movieArtworkMode;
}
function placeholderForKind(kind) {
if (kind === 'game') return '';
return kind === 'tv'
? resourceUrl('rbbTvPlaceholder', PLACEHOLDER_FALLBACKS.tv)
: resourceUrl('rbbMoviePlaceholder', PLACEHOLDER_FALLBACKS.movie);
}
function artworkInitialUrl(data) {
const kind = mediaKindForData(data);
const placeholder = placeholderForKind(kind);
const artworkMode = artworkModeForKind(kind);
if (artworkMode === 'rlsbb') return data.image || placeholder;
return placeholder;
}
function imageHtmlForData(data) {
const kind = mediaKindForData(data);
const placeholder = placeholderForKind(kind);
const src = artworkInitialUrl(data);
if (!src) return `<div class="rbb-no-image">No image</div>`;
const mode = artworkModeForKind(kind);
const apiMode = mode !== 'rlsbb';
const fixedClass = 'rbb-fixed-backdrop-artwork';
const classes = [apiMode ? 'rbb-api-artwork' : '', fixedClass].filter(Boolean).join(' ');
return `<img src="${escAttr(src)}" alt="" data-rbb-artwork-img data-media-kind="${escAttr(kind)}" data-artwork-mode="${escAttr(mode)}" data-rlsbb-src="${escAttr(data.image || '')}" data-placeholder-src="${escAttr(placeholder)}"${classes ? ` class="${escAttr(classes)}"` : ''}>`;
}
function displayTitleForData(data, detail = false) {
if (detail) return data.title;
const cleaned = cleanMediaTitle(data.title, mediaKindForData(data));
return cleaned || data.title;
}
function cleanMediaTitle(title, kind) {
let text = String(title || '')
.replace(/[._]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) return '';
if (kind === 'game') {
return text
.replace(/\b(?:FLT|FCKDRM|RUNE|TENOKE|TiNYiSO|SKIDROW|CODEX|GOG)\b.*$/i, '')
.replace(/[-–—]\s*$/g, '')
.trim() || text;
}
const tvToken = kind === 'tv'
? (text.match(/\bS\d{1,2}E\d{1,3}\b/i)?.[0]?.toUpperCase() || text.match(/\bS\d{1,2}\b/i)?.[0]?.toUpperCase() || '')
: '';
const movieYear = kind === 'movie' ? (text.match(/\b(19\d{2}|20\d{2})\b/)?.[1] || '') : '';
text = text
.replace(/\bS\d{1,2}E\d{1,3}\b.*$/i, '')
.replace(/\bS\d{1,2}\b.*$/i, '')
.replace(/\b(19\d{2}|20\d{2})\b.*$/i, '')
.replace(/\b(?:4320p|2160p|1080p|720p|480p|8K|4K|UHD|HDR10P?|HDR|DV|BluRay|BRRip|WEB[-\s]?DL|WEBRip|HDTV|AMZN|NF|HMAX|DSNP|ATVP|iT|DDP?\d(?:\.\d)?|Atmos|TrueHD|AAC|AC3|H\.?26[45]|x26[45]|HEVC|AV1|Remux|MULTi)\b.*$/i, '')
.replace(/[-–—]\s*$/g, '')
.trim();
if (kind === 'movie' && movieYear && text) return `${text} (${movieYear})`;
return [text, tvToken].filter(Boolean).join(' ');
}
// Builds the card's inner HTML for either context: the compact feed-grid card (detail=false)
// or the full detail view -- the actual post page, and (via openLightbox) the lightbox modal
// triggered from a feed card (detail=true either way). `includeCommentsFooter` is kept
// separate from `detail` because the lightbox gets the full plot/ratings/release detail but
// has no live comments DOM to show (that only exists on the real post page itself).
function buildCardInnerHtml(data, detail, includeCommentsFooter) {
const bestRelease = chooseBestRelease(data.releases);
const otherReleases = data.releases.filter(r => r !== bestRelease);
const bestRow = bestRelease
? makeReleaseRow(bestRelease, true, detail)
: `<p class="rbb-muted">No RapidGator versions found.</p>`;
const allRows = otherReleases.length
? otherReleases.map(release => makeReleaseRow(release, false, detail)).join('')
: '';
// Feed-grid cards stay to a single "best" release row -- switching quality is a click
// away via the lightbox/post page, so listing every other version here was pure clutter.
// The detail view lists every other version too, but collapsed by default -- not worth
// auto-expanding a 5-10 release wall of text before anyone's asked for it.
const showAll = (detail && otherReleases.length)
? `
<details class="rbb-all-versions">
<summary>All other versions (${data.releases.length})</summary>
<div class="rbb-all-version-list">
${allRows}
</div>
</details>
`
: '';
const specStrip = releaseSpecStripHtml(bestRelease);
const displayTitle = displayTitleForData(data, detail);
return `
<a class="rbb-image" href="${escAttr(data.url)}" target="_blank" rel="noopener noreferrer">
${specStrip}
${imageHtmlForData(data)}
</a>
<div class="rbb-content">
<h2 class="rbb-card-title">
<a href="${escAttr(data.url)}" target="_blank" rel="noopener noreferrer" title="${escAttr(data.title)}">${esc(displayTitle)}</a>
</h2>
<div class="rbb-top-meta">
<div class="rbb-cats">
${data.categories.slice(0, 3).map(c => `<button type="button" class="rbb-cat-pill" data-category="${escAttr(c.toLowerCase())}" title="Filter to ${escAttr(c)}">${esc(c)}</button>`).join('')}
</div>
<div class="rbb-date-line" data-rbb-date-line>
<strong data-rbb-date-absolute>${data.postedAbsolute ? esc(data.postedAbsolute) : 'Date unknown'}</strong>
${data.postedRelative ? `<span class="rbb-relative" data-rbb-relative>${esc(data.postedRelative)}</span>` : ''}
${data.author ? `<span>by ${esc(data.author)}</span>` : ''}
</div>
</div>
${detail && data.notice ? `<div class="rbb-notice-card">⚠ ${esc(data.notice)}</div>` : ''}
${detail
? makeDetailSectionsHtml(data, bestRow, showAll)
: `
${data.description ? `<p class="rbb-description">${esc(data.description)}</p>` : ''}
<section class="rbb-release-list">
<div class="rbb-release-heading">
<h3>Best RapidGator version</h3>
<span>${data.releases.length} found</span>
</div>
${bestRow}
${showAll}
</section>
`}
${includeCommentsFooter ? `
<details class="rbb-comments" data-comments-url="${escAttr(data.commentsUrl || data.url + '#comments')}" open>
<summary>${esc(data.commentsText || 'Comments')}</summary>
<div class="rbb-comments-body">Loading original comments…</div>
</details>
<footer class="rbb-footer">
<span>${data.tag ? esc(data.tag) : ''}</span>
</footer>
` : ''}
</div>
<div class="rbb-extension-bridge" aria-hidden="true"></div>
`;
}
// The card image box used a single fixed aspect-ratio for every post, so wide banners
// (e.g. 520x170 TV-doc headers) got their edges cropped and tall posters got squashed
// down to a thin cropped sliver. Size the box from the real image ratio, but classify
// portrait art separately so CSS can keep posters compact instead of letting one tall
// image blow out the whole card row or lightbox.
function fitImageAspect(container, img) {
const apply = () => {
const w = img.naturalWidth;
const h = img.naturalHeight;
if (!w || !h) return;
const rawRatio = w / h;
const ratio = Math.min(3.4, Math.max(0.55, rawRatio));
const card = container.closest('.rbb-card');
const displayRatio = 16 / 6;
container.style.aspectRatio = `${displayRatio} / 1`;
container.style.setProperty('--rbb-img-ratio', `${displayRatio} / 1`);
container.classList.toggle('rbb-image-portrait', false);
container.classList.toggle('rbb-image-landscape', true);
container.classList.toggle('rbb-image-wide', true);
if (card) {
card.classList.toggle('rbb-card-portrait-media', false);
card.classList.toggle('rbb-card-landscape-media', true);
card.classList.toggle('rbb-card-wide-media', true);
}
};
if (img.complete && img.naturalWidth) apply();
else img.addEventListener('load', apply, { once: true });
}
let artworkObserver = null;
const artworkDataByCard = new WeakMap();
const activeArtworkFetches = new Set();
function observeArtworkCard(card, data, immediate = false) {
const { tmdbApiKey } = getArtworkSettings();
const mode = artworkModeForKind(mediaKindForData(data));
if (!mode.startsWith('tmdb') || !tmdbApiKey) return;
artworkDataByCard.set(card, data);
if (immediate || isPostPage) {
loadTmdbArtwork(card, data);
return;
}
if (!artworkObserver && typeof IntersectionObserver === 'function') {
artworkObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
artworkObserver.unobserve(entry.target);
const entryData = artworkDataByCard.get(entry.target);
if (entryData) loadTmdbArtwork(entry.target, entryData);
});
}, { rootMargin: '420px 0px' });
}
if (artworkObserver) artworkObserver.observe(card);
else loadTmdbArtwork(card, data);
}
function parseMediaSearch(data) {
const title = String(data.title || '').replace(/\s+/g, ' ').trim();
const yearMatch = title.match(/\b(19\d{2}|20\d{2})\b/);
const year = yearMatch ? yearMatch[1] : '';
const episodeMatch = title.match(/\bS(\d{1,2})E(\d{1,3})\b/i);
const seasonMatch = !episodeMatch ? title.match(/\bS(\d{1,2})\b/i) : null;
const scope = episodeMatch ? 'episode' : (seasonMatch ? 'season' : 'title');
const season = episodeMatch ? episodeMatch[1] : (seasonMatch ? seasonMatch[1] : '');
const episode = episodeMatch ? episodeMatch[2] : '';
let query = title
.replace(/\bS\d{1,2}E\d{1,3}\b.*$/i, '')
.replace(/\bS\d{1,2}\b.*$/i, '')
.replace(/\b(19\d{2}|20\d{2})\b.*$/i, '')
.replace(/\b(4320p|2160p|1080p|720p|480p|4k|8k|uhd|bluray|brrip|web[-.\s]?dl|webrip|hdr10p?|hdr|dv|h\.?26[45]|x26[45]|hevc|av1|remux|multi)\b.*$/i, '')
.replace(/[._-]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!query) query = title.replace(/\b(19\d{2}|20\d{2})\b.*$/i, '').trim() || title;
return { kind: mediaKindForData(data), query, year, scope, season, episode };
}
function tmdbCacheKey(data) {
const parsed = parseMediaSearch(data);