-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathptp-upcoming-releases.js
1644 lines (1439 loc) · 74.3 KB
/
ptp-upcoming-releases.js
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 PTP upcoming releases
// @namespace https://github.com/Audionut/add-trackers
// @version 1.1.7
// @description Get a list of upcoming releases from IMDB and TMDb and integrate with site search form.
// @author Audionut
// @match https://passthepopcorn.me/upcoming.php*
// @icon https://passthepopcorn.me/favicon.ico
// @downloadURL https://github.com/Audionut/add-trackers/raw/main/ptp-upcoming-releases.js
// @updateURL https://github.com/Audionut/add-trackers/raw/main/ptp-upcoming-releases.js
// @grant GM_xmlhttpRequest
// @connect api.graphql.imdb.com
// @connect api.themoviedb.org
// @grant GM_setValue
// @grant GM_getValue
// @require https://code.jquery.com/jquery-3.6.0.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/lz-string/1.4.4/lz-string.min.js
// ==/UserScript==
(function () {
'use strict';
const CACHE_KEY_IMDB = 'comingSoonData';
const CACHE_KEY_TMDB = 'digitalReleasesData';
const CACHE_EXPIRATION_KEY_IMDB = 'comingSoonDataExpiration';
const CACHE_EXPIRATION_KEY_TMDB = 'digitalReleasesDataExpiration';
const NAME_IMAGES_CACHE_KEY = 'nameImagesData';
const CURRENT_PAGE_KEY = 'currentPage';
const RESULTS_PER_PAGE_KEY = 'resultsPerPage';
const RESULTS_PER_PAGE_DEFAULT = 20;
const MAX_RESULTS = 45; // per API call - Maximum 45 per call
const ALLOWED_GENRES = new Set([]); // Define your allowed genres here. ["Crime", "Drama", "Thriller"] for example.
const LAYOUT_KEY = 'displayLayout';
const LAYOUT_ORIGINAL = 'Original';
const LAYOUT_CONDENSED = 'Condensed';
const FILTERED_CACHE_KEY = 'filterALLData';
const API_KEY_TMDB = 'tmdbApiKey';
const RESULT_TYPE_KEY = 'resultType';
const radarrSignal = new CustomEvent('UpcomingReleasesDisplayChanged');
const container = document.querySelector("#torrents-movie-view > div");
let digitalReleases = [];
const setCache = (key, data) => {
try {
const stringData = JSON.stringify(data);
const compressedData = LZString.compress(stringData);
GM_setValue(key, compressedData);
console.log(`Data compressed and cached under key: ${key}`);
} catch (e) {
console.error(`Failed to compress and cache data for key: ${key}`, e);
}
};
const getCache = (key) => {
const compressedData = GM_getValue(key, null);
if (compressedData && typeof compressedData === 'string') {
try {
const decompressedData = LZString.decompress(compressedData);
if (decompressedData) {
return JSON.parse(decompressedData);
} else {
console.warn(`Data for key ${key} was not properly compressed or decompressed.`);
return null;
}
} catch (e) {
console.error(`Failed to decompress data for key: ${key}`, e);
return null;
}
} else {
// Return null when no valid data is found
console.warn(`No valid data found for key ${key}.`);
return null;
}
};
let aCacheWasCleared = 0;
const clearCache = (cacheType) => {
switch (cacheType) {
case 'IMDb':
GM_setValue(CACHE_KEY_IMDB, null);
GM_setValue(CACHE_EXPIRATION_KEY_IMDB, 0);
GM_setValue(NAME_IMAGES_CACHE_KEY, null);
console.log("IMDb cache cleared");
break;
case 'TMDb':
GM_setValue(CACHE_KEY_TMDB, null);
GM_setValue(CACHE_EXPIRATION_KEY_TMDB, 0);
console.log("TMDb cache cleared");
break;
case 'All':
clearCache('IMDb');
clearCache('TMDb');
GM_setValue(CURRENT_PAGE_KEY, 1);
GM_setValue(FILTERED_CACHE_KEY, null);
console.log("All caches cleared");
break;
}
aCacheWasCleared = 1;
};
// Function to format date to YYYY-MM-DD
function formatDate(date) {
const d = new Date(date);
const month = ('0' + (d.getMonth() + 1)).slice(-2);
const day = ('0' + d.getDate()).slice(-2);
const year = d.getFullYear();
return `${year}-${month}-${day}`;
}
// Helper function to deduplicate results by movie ID
const deduplicateResults = (results) => {
const uniqueData = [];
const seenIds = new Set();
results.forEach(edge => {
// Handle cases where the structure has a node property (IMDb) or not (TMDb)
const movie = edge.node || edge; // Fallback to `edge` if `node` doesn't exist (for TMDb data)
if (!movie || !movie.id) {
console.warn("Skipping edge without valid movie ID during deduplication:", edge);
return; // Skip if no valid movie ID is found
}
const id = movie.id; // Use only the movie ID as the unique key
if (!seenIds.has(id)) {
// If this ID has not been seen, add it to the uniqueData
seenIds.add(id);
uniqueData.push(edge);
}
});
return uniqueData;
};
const fetchDetailsWithRetry = (movie, retries, callback) => {
//const container = document.querySelector("#torrents-movie-view > div");
container.innerHTML = `
<div class="loading-container">
<div class="spinner"></div>
<p>Loading upcoming releases...</p>
</div>
`;
const apiKey = GM_getValue(API_KEY_TMDB, '');
const url = `https://api.themoviedb.org/3/movie/${movie.id}?api_key=${apiKey}&append_to_response=credits,external_ids,images`;
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: function (response) {
if (response.status === 200) {
const data = JSON.parse(response.responseText);
movie.details = data;
} else if (retries > 0) {
console.warn(`Retrying fetch for movie ID ${movie.id}. Remaining retries: ${retries - 1}`);
fetchDetailsWithRetry(movie, retries - 1, callback);
} else {
console.error(`Failed to fetch details for movie ID ${movie.id} after multiple attempts`);
}
callback();
},
onerror: function () {
if (retries > 0) {
console.warn(`Retrying fetch for movie ID ${movie.id}. Remaining retries: ${retries - 1}`);
fetchDetailsWithRetry(movie, retries - 1, callback);
} else {
console.error(`Error occurred while fetching details for movie ID ${movie.id} after multiple attempts`);
callback();
}
}
});
};
const sortAndFilterTmdbData = (data) => {
const today = new Date();
today.setHours(0, 0, 0, 0); // Set today's date to midnight for accurate comparison
//console.log("Today's date:", today);
// Filter out movies that are not future releases and movies with a release date before today
const filteredDateData = data.filter(movie => {
const releaseDate = new Date(movie.release_date); // Ensure release_date is a valid date object
if (isNaN(releaseDate)) {
console.warn("Invalid release date for movie:", movie.title, movie.release_date);
return false;
}
// Check if the movie is in the future (isFuture should be true)
const isFuture = releaseDate >= today;
if (!isFuture) {
//console.log(`Excluding movie: ${movie.title} | Release Date: ${releaseDate} | Is Future: ${isFuture}`);
return false;
}
//console.log(`Including movie: ${movie.title} | Release Date: ${releaseDate} | Is Future: ${isFuture}`);
return true;
});
// Sort the remaining movies by release date in ascending order
filteredDateData.sort((a, b) => new Date(a.release_date) - new Date(b.release_date));
//console.log("Filtered and sorted TMDB data:", filteredDateData);
return filteredDateData;
};
const fetchMovieDetails = async () => {
const apiKey = GM_getValue(API_KEY_TMDB, '');
if (!apiKey) {
console.error('TMDb API key is not set.');
return;
}
let remainingRequests = digitalReleases.length;
return new Promise((resolve) => {
digitalReleases.forEach(movie => {
fetchDetailsWithRetry(movie, 3, () => {
if (--remainingRequests === 0) {
//console.log("Digital releases before filtering:", digitalReleases);
// Filter and sort the TMDb data before caching and displaying
const filteredData = sortAndFilterTmdbData(digitalReleases);
resolve(filteredData); // Resolve the filtered data correctly
}
});
});
});
};
const fetchComingSoonDataWithRetry = async (afterDate = null, retries = 3) => {
const url = `https://api.graphql.imdb.com/`;
const today = new Date().toISOString().split('T')[0];
const dateFilter = afterDate ? afterDate : today;
const comingSoonQuery = {
query: `
query {
comingSoon(
comingSoonType: MOVIE,
first: ${MAX_RESULTS},
releasingOnOrAfter: "${dateFilter}",
sort: {sortBy: RELEASE_DATE, sortOrder: ASC}
) {
edges {
node {
id
titleText {
text
}
releaseDate {
day
month
year
}
plot {
plotText {
plainText
}
}
genres {
genres {
text
}
}
primaryImage {
url
width
height
caption {
plainText
}
}
credits(first: 20) {
edges {
node {
name {
id
nameText {
text
}
}
category {
id
text
}
title {
id
titleText {
text
}
}
}
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
`
};
return new Promise((resolve, reject) => {
const attemptFetch = (remainingRetries) => {
GM_xmlhttpRequest({
method: "POST",
url: url,
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify(comingSoonQuery),
onload: function (response) {
if (response.status >= 200 && response.status < 300) {
const comingSoonData = JSON.parse(response.responseText);
if (!comingSoonData.data || !comingSoonData.data.comingSoon || comingSoonData.data.comingSoon.edges.length === 0) {
resolve([]);
return;
}
const edges = comingSoonData.data.comingSoon.edges;
resolve(edges);
} else if (remainingRetries > 0) {
console.warn(`Retrying fetch from IMDb API. Remaining retries: ${remainingRetries - 1}`);
attemptFetch(remainingRetries - 1);
} else {
console.error("Failed to fetch coming soon data after multiple attempts", response);
reject(response);
}
},
onerror: function (response) {
if (remainingRetries > 0) {
console.warn(`Retrying fetch from IMDb API. Remaining retries: ${remainingRetries - 1}`);
attemptFetch(remainingRetries - 1);
} else {
console.error("Request error after multiple attempts", response);
reject(response);
}
}
});
};
attemptFetch(retries);
});
};
const fetchPrimaryImageUrls = async (nameIds) => {
const url = `https://api.graphql.imdb.com/`;
const queries = [];
for (let i = 0; i < nameIds.length; i += 250) {
const chunk = nameIds.slice(i, i + 250);
queries.push({
query: `
query {
names(ids: ${JSON.stringify(chunk)}) {
id
nameText {
text
}
primaryImage {
url
}
}
}
`
});
}
const results = await Promise.all(queries.map(query =>
new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "POST",
url: url,
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify(query),
onload: function (response) {
if (response.status >= 200 && response.status < 300) {
const data = JSON.parse(response.responseText);
if (data && data.data && data.data.names) {
resolve(data.data.names);
} else {
reject(new Error("Invalid response structure for primary image URLs"));
}
} else {
reject(new Error("Failed to fetch primary image URLs"));
}
},
onerror: function (response) {
reject(new Error("Request error"));
}
});
})
));
return results.flat();
};
const fetchAllComingSoonData = async () => {
//const container = document.querySelector("#torrents-movie-view > div");
container.innerHTML = `
<div class="loading-container">
<div class="spinner"></div>
<p>Loading upcoming releases...</p>
</div>
`;
let allEdges = [];
let lastReleaseDate = null;
while (true) {
const newEdges = await fetchComingSoonDataWithRetry(lastReleaseDate ? lastReleaseDate : null);
if (newEdges.length === 0) break;
allEdges = allEdges.concat(newEdges);
const lastEdge = newEdges[newEdges.length - 1];
lastReleaseDate = `${lastEdge.node.releaseDate.year}-${String(lastEdge.node.releaseDate.month).padStart(2, '0')}-${String(lastEdge.node.releaseDate.day).padStart(2, '0')}`;
if (newEdges.length < MAX_RESULTS) break;
}
const cachedData = { edges: allEdges };
//console.log('IMDb Data before deduplication:', cachedData);
// Deduplicate before caching
const deduplicatedIMDbData = deduplicateResults(cachedData.edges);
//console.log('IMDb Data after deduplication:', deduplicatedIMDbData);
setCache(CACHE_KEY_IMDB, { edges: deduplicatedIMDbData }); // Cache deduplicated IMDb data
const nameIds = [];
cachedData.edges.forEach(edge => {
edge.node.credits.edges.forEach(credit => {
nameIds.push(credit.node.name.id);
});
});
const primaryImageUrls = await fetchPrimaryImageUrls(nameIds);
setCache(NAME_IMAGES_CACHE_KEY, primaryImageUrls);
container.innerHTML = "";
//displayResults(1);
};
const fetchUpcomingDigitalMovies = async (page = 1) => {
const apiKey = GM_getValue(API_KEY_TMDB, '');
if (!apiKey) {
console.error('TMDb API key is not set.');
return;
}
const today = new Date();
const fourMonthsFromNow = new Date();
fourMonthsFromNow.setMonth(today.getMonth() + 4);
const url = `https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&language=en-US®ion=US&sort_by=release_date.desc&release_date.gte=${formatDate(today)}&release_date.lte=${formatDate(fourMonthsFromNow)}&with_release_type=4&page=${page}`;
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: function (response) {
if (response.status === 200) {
const data = JSON.parse(response.responseText);
digitalReleases = digitalReleases.concat(data.results);
if (data.page < data.total_pages) {
fetchUpcomingDigitalMovies(data.page + 1).then(resolve).catch(reject);
} else {
fetchMovieDetails().then((filteredData) => {
//console.log('Filtered Data before deduplication:', filteredData);
// Deduplicate before caching
const deduplicatedTMDBData = deduplicateResults(filteredData);
//console.log('TMDB Data after deduplication:', deduplicatedTMDBData);
setCache(CACHE_KEY_TMDB, deduplicatedTMDBData); // Cache only deduplicated data
resolve(deduplicatedTMDBData); // Resolve only the deduplicated data
}).catch(reject);
}
} else {
console.error('Failed to fetch data from TMDb API', response); // Debugging log for errors
reject(new Error('Failed to fetch data from TMDb API'));
}
},
onerror: function (response) {
console.error('Error occurred while fetching data from TMDb API', response); // Debugging log for errors
reject(new Error('Error occurred while fetching data from TMDb API'));
}
});
});
};
const sortCombinedDataByDate = (data) => {
return data.sort((a, b) => {
const dateA = a.node.releaseDate ?
new Date(`${a.node.releaseDate.year}-${String(a.node.releaseDate.month || 1).padStart(2, '0')}-${String(a.node.releaseDate.day || 1).padStart(2, '0')}`) :
(a.node && a.node.release_date ? new Date(a.node.release_date) : null);
const dateB = b.node.releaseDate ?
new Date(`${b.node.releaseDate.year}-${String(b.node.releaseDate.month || 1).padStart(2, '0')}-${String(b.node.releaseDate.day || 1).padStart(2, '0')}`) :
(b.node && b.node.release_date ? new Date(b.node.release_date) : null);
if (!dateA || !dateB || isNaN(dateA) || isNaN(dateB)) {
return 0; // Consider them equal if either date is invalid
}
return dateA - dateB;
});
};
const addLightboxStyles = () => {
const style = document.createElement('style');
style.innerHTML = `
.lightbox {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: none;
align-items: center;
justify-content: center;
z-index: 1000;
cursor: pointer;
}
.lightbox img {
max-width: 90%;
max-height: 90%;
}
`;
document.head.appendChild(style);
};
const createLightbox = () => {
const lightbox = document.createElement('div');
lightbox.classList.add('lightbox');
lightbox.innerHTML = '<img src="" alt="lightbox image">';
document.body.appendChild(lightbox);
lightbox.addEventListener('click', () => {
lightbox.style.display = 'none';
});
return lightbox;
};
const initLightbox = () => {
const lightbox = createLightbox();
document.addEventListener('click', (event) => {
if (event.target.tagName === 'IMG' && event.target.classList.contains('lightbox-trigger')) {
lightbox.querySelector('img').src = event.target.src;
lightbox.style.display = 'flex';
}
});
};
const createImageElement = (node, size, source) => {
const image = document.createElement("img");
if (source === 'IMDb') {
// IMDb image handling
image.src = node.primaryImage && node.primaryImage.url ? node.primaryImage.url : 'https://ptpimg.me/w6l4kj.png';
image.alt = node.primaryImage && node.primaryImage.caption ? node.primaryImage.caption.plainText : 'No image available';
} else if (source === 'TMDb') {
// TMDb image handling for both wrapped and unwrapped data
const posterPath = node.details?.poster_path || node.poster_path || (node.primaryImage && node.primaryImage.url);
const titleText = node.details?.title || node.title;
// Use direct URL if primaryImage is available, otherwise construct the URL
image.src = posterPath && node.primaryImage ? posterPath : (posterPath ? `https://image.tmdb.org/t/p/original${posterPath}` : 'https://ptpimg.me/w6l4kj.png');
image.alt = titleText ? titleText : 'No image available';
}
image.style.maxWidth = size;
//image.style.aspectRatio = "2 / 3";
image.style.marginRight = "10px";
image.classList.add('lightbox-trigger');
image.loading = "lazy";
return image;
};
const displayResultsOriginal = (page, data, source) => {
const nameImagesData = getCache(NAME_IMAGES_CACHE_KEY);
const resultsPerPage = GM_getValue(RESULTS_PER_PAGE_KEY, RESULTS_PER_PAGE_DEFAULT);
const resultType = GM_getValue(RESULT_TYPE_KEY, 'All');
const totalResults = data.edges.length;
const totalPages = Math.ceil(totalResults / resultsPerPage);
page = Math.max(1, Math.min(page, totalPages));
const startIndex = (page - 1) * resultsPerPage;
const endIndex = startIndex + resultsPerPage;
let pageData = data.edges.slice(startIndex, endIndex);
if (ALLOWED_GENRES.size > 0) {
pageData = pageData.filter(movie => {
return movie.node && movie.node.genres && movie.node.genres.genres.some(genre => ALLOWED_GENRES.has(genre.text || genre.name));
});
}
//const container = document.querySelector("#torrents-movie-view > div");
container.innerHTML = "";
const groupedByDate = pageData.reduce((acc, movie) => {
const node = movie.node;
if (!node) return acc;
const releaseDate = node.releaseDate ? `${node.releaseDate.year}-${String(node.releaseDate.month).padStart(2, '0')}-${String(node.releaseDate.day).padStart(2, '0')}` : node.release_date;
if (!releaseDate) return acc;
const dateStr = new Date(releaseDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
if (!acc[dateStr]) acc[dateStr] = [];
acc[dateStr].push(movie);
return acc;
}, {});
for (const [date, movies] of Object.entries(groupedByDate)) {
const dateHeader = document.createElement("h2");
dateHeader.textContent = date;
dateHeader.style.fontSize = "1.5em";
dateHeader.style.color = "white";
container.appendChild(dateHeader);
movies.forEach(movie => {
const node = movie.node;
const movieDiv = document.createElement("div");
movieDiv.setAttribute('class', 'huge-movie-list__movie');
movieDiv.style.border = "1px solid #ccc";
movieDiv.style.padding = "10px";
movieDiv.style.marginBottom = "10px";
movieDiv.style.display = "flex";
movieDiv.style.position = "relative";
const image = createImageElement(node, "200px", movie.source);
movieDiv.appendChild(image);
const infoDiv = document.createElement("div");
infoDiv.setAttribute('class', 'site-link');
infoDiv.style.flex = "1";
infoDiv.style.display = "flex";
infoDiv.style.flexDirection = "column";
infoDiv.style.whiteSpace = "nowrap"; // Prevent wrapping
infoDiv.style.overflow = "hidden"; // Hide overflowed content
infoDiv.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
const titleLinkDiv = document.createElement("div");
titleLinkDiv.style.display = "flex";
titleLinkDiv.style.justifyContent = "space-between";
titleLinkDiv.style.alignItems = "center";
const titleLink = document.createElement("a");
titleLink.href = movie.source === 'IMDb' ? `https://www.imdb.com/title/${node.id}/` : `https://www.themoviedb.org/movie/${node.id}`;
titleLink.target = "_blank";
titleLink.rel = "noreferrer";
titleLink.setAttribute('class', 'title-link');
titleLink.textContent = node.titleText?.text || node.details?.title || node.title || node.original_title;
titleLink.style.fontWeight = "bold";
titleLink.style.fontSize = "1.2em";
titleLink.style.textDecoration = "none";
titleLink.style.color = "white";
titleLink.style.display = "block";
titleLink.style.marginBottom = "10px";
titleLink.style.whiteSpace = "nowrap"; // Prevent wrapping
titleLink.style.overflow = "hidden"; // Hide overflowed content
titleLink.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
if (movie.source === 'TMDb' && resultType === "All") {
const digitalLabel = document.createElement('span');
digitalLabel.textContent = 'Digital';
digitalLabel.style.color = 'teal';
digitalLabel.style.marginLeft = '10px';
titleLink.appendChild(digitalLabel);
}
if (movie.source === 'IMDb' && resultType === "All") {
const digitalLabel = document.createElement('span');
digitalLabel.textContent = 'Theatrical';
digitalLabel.style.color = 'orange';
digitalLabel.style.marginLeft = '10px';
titleLink.appendChild(digitalLabel);
}
const radarLink = document.createElement("a");
radarLink.setAttribute('class', 'radarLink');
radarLink.style.float = "left";
const ptpLink = document.createElement("a");
if(movie.source === 'IMDb') {
ptpLink.href = `https://passthepopcorn.me/requests.php?search=${node.id || node.titleText?.text}`;
}
if(movie.source === 'TMDb') {
ptpLink.href = `https://passthepopcorn.me/requests.php?search=${node.title || node.details?.title || node.titleText?.text}`;
}
ptpLink.target = "_blank";
ptpLink.setAttribute('class', 'request-link');
ptpLink.textContent = "(Search PTP requests)";
ptpLink.style.float = "right";
ptpLink.style.fontSize = "0.9em";
titleLinkDiv.appendChild(titleLink);
titleLinkDiv.appendChild(radarLink);
titleLinkDiv.appendChild(ptpLink);
infoDiv.appendChild(titleLinkDiv);
const plot = document.createElement("p");
plot.textContent = node.plot?.plotText?.plainText || node.details?.overview || "No plot available.";
infoDiv.appendChild(plot);
const genres = document.createElement("p");
const genresList = node.genres?.genres || (node.details?.genres?.length ? node.details.genres : []);
genresList.forEach(genre => {
const genreLink = document.createElement("a");
genreLink.setAttribute('class', 'genres');
genreLink.href = `https://passthepopcorn.me/torrents.php?action=advanced&taglist=${genre.text || genre.name}`;
genreLink.textContent = genre.text || genre.name;
genreLink.style.color = "white";
genreLink.style.marginRight = "5px";
genreLink.style.whiteSpace = "nowrap"; // Prevent wrapping
genreLink.style.overflow = "hidden"; // Hide overflowed content
genreLink.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
genres.appendChild(genreLink);
});
infoDiv.appendChild(genres);
const castContainer = document.createElement("div");
castContainer.style.display = "flex";
castContainer.style.flexWrap = "nowrap"; // Prevent wrapping
castContainer.style.overflow = "auto"; // Allow horizontal scrolling if needed
castContainer.style.gap = "10px";
let castCount = 0;
const creditsList = movie.source === 'IMDb'
? (node.cast || node.credits?.edges || []) // IMDb: Handle wrapped and unwrapped data
: (node.cast || node.details?.credits?.cast || []); // TMDb: Handle wrapped (node.cast) and unwrapped (node.details.credits.cast)
creditsList.forEach(credit => {
// IMDb case: Check if it's wrapped (node.cast) or unwrapped (credits.edges)
const castMember = movie.source === 'IMDb'
? (node.cast ? credit : nameImagesData.find(name => name.id === credit.node.name.id)) // IMDb: Handle wrapped and unwrapped
: (node.cast ? credit : credit); // TMDb: Handle wrapped (node.cast) and unwrapped (credit)
// Check for valid images
const hasValidImage = movie.source === 'IMDb'
? (node.cast ? castMember?.profilePath : castMember?.primaryImage?.url) // IMDb: Wrapped uses profilePath, unwrapped uses primaryImage.url
: (movie.source === 'TMDb' && castMember?.profilePath) // TMDb: Wrapped data (node.cast)
|| (movie.source === 'TMDb' && castMember?.profile_path); // TMDb: Unwrapped data (credits.cast)
if (castMember && hasValidImage && castCount < 5) {
castCount++;
const castDiv = document.createElement("div");
castDiv.style.textAlign = "center";
castDiv.style.width = "auto";
castDiv.style.whiteSpace = "nowrap";
const castImageLink = document.createElement("a");
let test = "test";
castImageLink.href = movie.source === 'IMDb'
? (node.cast ? `https://www.imdb.com/name/${castMember.id}/` : `https://www.imdb.com/name/${credit.node.name.id}/`) // IMDb: Wrapped (castMember.id), Unwrapped (credit.node.name.id)
: (node.cast ? `https://www.themoviedb.org/person/${castMember.id}` : `https://www.themoviedb.org/person/${credit.id}`); // TMDb: Wrapped (castMember.id), Unwrapped (credit.id)
castImageLink.target = "_blank";
castImageLink.rel = "noreferrer";
const castImage = document.createElement("img");
castImage.src = movie.source === 'IMDb'
? (node.cast ? castMember.profilePath : castMember.primaryImage.url) // IMDb: Wrapped (profilePath), Unwrapped (primaryImage.url)
: (node.cast ? castMember.profilePath : `https://image.tmdb.org/t/p/w185${castMember.profile_path}`); // TMDb: Wrapped (profilePath), Unwrapped (profile_path)
//castImage.alt = movie.source === 'IMDb' ? credit.node.name.nameText.text : credit.name;
castImage.style.maxHeight = "150px";
castImage.style.width = "auto";
castImage.style.display = "block";
castImageLink.appendChild(castImage);
castDiv.appendChild(castImageLink);
const castNameLink = document.createElement("a");
const castName = movie.source === 'IMDb'
? (node.cast ? credit.name : credit.node.name.nameText.text) // IMDb: Wrapped or unwrapped
: (node.cast ? credit.name : credit.name); // TMDb: Handle both wrapped and unwrapped
castNameLink.href = `https://passthepopcorn.me/artist.php?artistname=${encodeURIComponent(castName)}`;
castNameLink.target = "_blank";
castNameLink.rel = "noreferrer";
castNameLink.textContent = castName;
castNameLink.style.display = "block";
castNameLink.style.textDecoration = "none";
castNameLink.style.color = "white";
castNameLink.style.marginTop = "10px";
castNameLink.style.whiteSpace = "nowrap";
castDiv.appendChild(castNameLink);
castContainer.appendChild(castDiv);
}
});
infoDiv.appendChild(castContainer);
movieDiv.appendChild(infoDiv);
container.appendChild(movieDiv);
});
}
createPagination(page, totalResults);
};
const displayResultsCondensed = (page, data, source) => {
const nameImagesData = getCache(NAME_IMAGES_CACHE_KEY);
const resultsPerPage = GM_getValue(RESULTS_PER_PAGE_KEY, RESULTS_PER_PAGE_DEFAULT);
const resultType = GM_getValue(RESULT_TYPE_KEY, 'All');
const totalResults = data.edges.length;
const totalPages = Math.ceil(totalResults / resultsPerPage);
page = Math.max(1, Math.min(page, totalPages));
const startIndex = (page - 1) * resultsPerPage;
const endIndex = startIndex + resultsPerPage;
let pageData = data.edges.slice(startIndex, endIndex);
if (ALLOWED_GENRES.size > 0) {
pageData = pageData.filter(movie => {
return movie.node && movie.node.genres && movie.node.genres.genres.some(genre => ALLOWED_GENRES.has(genre.text || genre.name));
});
}
const container = document.querySelector("#torrents-movie-view > div");
container.innerHTML = "";
const groupedByDate = pageData.reduce((acc, movie) => {
const node = movie.node;
if (!node) return acc;
const releaseDate = node.releaseDate ? `${node.releaseDate.year}-${String(node.releaseDate.month).padStart(2, '0')}-${String(node.releaseDate.day).padStart(2, '0')}` : node.release_date;
if (!releaseDate) return acc;
const dateStr = new Date(releaseDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
if (!acc[dateStr]) acc[dateStr] = [];
acc[dateStr].push(movie);
return acc;
}, {});
const table = document.createElement("table");
table.setAttribute('id', 'torrent-table');
table.style.width = "100%";
table.style.borderCollapse = "collapse";
for (const [date, movies] of Object.entries(groupedByDate)) {
const dateHeaderRow = document.createElement("tr");
const dateHeader = document.createElement("th");
dateHeader.colSpan = 2;
dateHeader.textContent = date;
dateHeader.style.fontSize = "1.5em";
dateHeader.style.color = "white";
dateHeader.style.padding = "10px";
dateHeaderRow.appendChild(dateHeader);
table.appendChild(dateHeaderRow);
for (let i = 0; i < movies.length; i += 2) {
const row = document.createElement("tr");
for (let j = 0; j < 2; j++) {
const movie = movies[i + j];
if (!movie || !movie.node) continue;
const node = movie.node;
const cell = document.createElement("td");
cell.setAttribute('class', 'basic-movie-list');
cell.style.border = "1px solid #525252";
cell.style.padding = "10px";
cell.style.verticalAlign = "top";
cell.style.width = "50%";
const movieDiv = document.createElement("div");
movieDiv.style.display = "flex";
movieDiv.style.position = "relative";
const image = createImageElement(node, "60px", movie.source); // Pass source to distinguish between IMDb and TMDb
movieDiv.appendChild(image);
const infoDiv = document.createElement("div");
infoDiv.style.flex = "1";
infoDiv.setAttribute('class', 'site-link');
infoDiv.style.whiteSpace = "nowrap"; // Prevent wrapping
infoDiv.style.overflow = "hidden"; // Hide overflowed content
infoDiv.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
const titleLink = document.createElement("a");
titleLink.href = movie.source === 'IMDb'
? `https://www.imdb.com/title/${node.id}/`
: `https://www.themoviedb.org/movie/${node.id}`;
titleLink.target = "_blank";
titleLink.rel = "noreferrer";
titleLink.textContent = node.titleText?.text || node.details?.title || node.title || node.original_title;
titleLink.style.fontWeight = "bold";
titleLink.style.fontSize = "1.2em";
titleLink.style.textDecoration = "none";
titleLink.style.color = "white";
titleLink.style.marginBottom = "2px";
titleLink.style.whiteSpace = "nowrap"; // Prevent wrapping
titleLink.style.overflow = "hidden"; // Hide overflowed content
titleLink.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
infoDiv.appendChild(titleLink);
if (movie.source === 'TMDb' && resultType === "All") {
const digitalLabel = document.createElement('span');
digitalLabel.textContent = 'Digital';
digitalLabel.style.color = 'teal';
digitalLabel.style.marginLeft = '10px';
titleLink.appendChild(digitalLabel);
}
if (movie.source === 'IMDb' && resultType === "All") {
const digitalLabel = document.createElement('span');
digitalLabel.textContent = 'Theatrical';
digitalLabel.style.color = 'orange';
digitalLabel.style.marginLeft = '10px';
titleLink.appendChild(digitalLabel);
}
const ptpLink = document.createElement("a");
if(movie.source === 'IMDb') {
ptpLink.href = `https://passthepopcorn.me/requests.php?search=${node.id || node.details?.title}`;
}
if(movie.source === 'TMDb') {
ptpLink.href = `https://passthepopcorn.me/requests.php?search=${node.details?.title || node.titleText?.text}`;
}
ptpLink.target = "_blank";
ptpLink.textContent = "(Search PTP requests)";
ptpLink.style.float = "right";
ptpLink.style.fontSize = "0.9em";
infoDiv.appendChild(ptpLink);
const genres = document.createElement("p");
const genresList = node.genres?.genres || node.details?.genres || [];
genresList.forEach(genre => {
const genreLink = document.createElement("a");
genreLink.href = `https://passthepopcorn.me/torrents.php?action=advanced&taglist=${genre.text || genre.name}`;
genreLink.textContent = genre.text || genre.name;
genreLink.style.color = "white";
genreLink.style.marginRight = "10px";
genreLink.style.whiteSpace = "nowrap"; // Prevent wrapping
genreLink.style.overflow = "hidden"; // Hide overflowed content
genreLink.style.textOverflow = "ellipsis"; // Add ellipsis for overflowed content
genres.appendChild(genreLink);
});
infoDiv.appendChild(genres);
const castContainer = document.createElement("div");
castContainer.setAttribute('class', 'cast-list');
castContainer.style.display = "flex";
castContainer.style.flexWrap = "nowrap"; // Prevent wrapping
castContainer.style.overflow = "auto"; // Allow horizontal scrolling if needed
castContainer.style.gap = "10px";
let castCount = 0;
// Handle IMDb or TMDb cast lists for both wrapped and unwrapped data
const creditsList = movie.source === 'IMDb'
? (node.cast || node.credits?.edges || []) // IMDb: Handle wrapped and unwrapped data
: (node.cast || node.details?.credits?.cast || []); // TMDb: Handle wrapped (node.cast) and unwrapped (node.details.credits.cast)
creditsList.forEach(credit => {
// IMDb case: Check if it's wrapped (node.cast) or unwrapped (credits.edges)
const castMember = movie.source === 'IMDb'
? (node.cast ? credit : nameImagesData.find(name => name.id === credit.node.name.id)) // IMDb: Handle wrapped and unwrapped
: (node.cast ? credit : credit); // TMDb: Handle wrapped (node.cast) and unwrapped (credit)
if (castMember && castCount < 5) {
castCount++;
// Create a div to hold the cast member details
const castDiv = document.createElement("div");
castDiv.style.textAlign = "center";
castDiv.style.width = "auto";
castDiv.style.whiteSpace = "nowrap";
// Create a clickable link for the cast member
const castNameLink = document.createElement("a");
// Get the cast name based on whether the data is wrapped or not for both IMDb and TMDb
const castName = movie.source === 'IMDb'
? (node.cast ? credit.name : credit.node.name.nameText.text) // IMDb: Wrapped or unwrapped
: (node.cast ? credit.name : credit.name); // TMDb: Handle both wrapped and unwrapped
castNameLink.href = `https://passthepopcorn.me/artist.php?artistname=${encodeURIComponent(castName)}`;
castNameLink.target = "_blank";
castNameLink.textContent = castName;
castNameLink.style.display = "block";
castNameLink.style.textDecoration = "none";
castNameLink.style.color = "white";
castNameLink.style.marginTop = "10px";
castNameLink.style.whiteSpace = "nowrap";
// Append the cast name link to the div
castDiv.appendChild(castNameLink);
// Append the cast div to the container
castContainer.appendChild(castDiv);
}
});
infoDiv.appendChild(castContainer);
movieDiv.appendChild(infoDiv);
cell.appendChild(movieDiv);
row.appendChild(cell);