no1b4me commited on
Commit
a0f2ddc
·
verified ·
1 Parent(s): f72b6d7

Upload 22 files

Browse files
index.js CHANGED
@@ -2,18 +2,20 @@ require('dotenv').config();
2
  const express = require('express');
3
  const cors = require('cors');
4
  const path = require('path');
5
- const log = require('./src/utils/logger');
6
- const routes = require('./src/routes');
7
 
8
- const PORT = process.env.PORT || 3000;
9
  const app = express();
10
 
11
  app.use(cors());
12
 
13
  app.use(express.static(path.join(__dirname, 'public')));
14
 
 
 
15
  app.use('/', routes);
16
 
17
  app.listen(PORT, () => {
18
- log.info(`Express server running on port ${PORT} in ${process.env.NODE_ENV || 'development'} mode.`);
19
  });
 
2
  const express = require('express');
3
  const cors = require('cors');
4
  const path = require('path');
5
+ const log = require('./src/helpers/logger');
6
+ const routes = require('./src/routes/index');
7
 
8
+ const PORT = process.env.PORT || 7000;
9
  const app = express();
10
 
11
  app.use(cors());
12
 
13
  app.use(express.static(path.join(__dirname, 'public')));
14
 
15
+ app.use(express.json());
16
+
17
  app.use('/', routes);
18
 
19
  app.listen(PORT, () => {
20
+ log.info(`Server running on port ${PORT} - Environment: ${process.env.NODE_ENV || 'development'}`);
21
  });
package-lock.json CHANGED
@@ -11,6 +11,7 @@
11
  "dependencies": {
12
  "async": "^3.2.6",
13
  "axios": "^1.7.5",
 
14
  "cors": "^2.8.5",
15
  "dotenv": "^16.4.5",
16
  "express": "^4.19.2",
@@ -305,6 +306,12 @@
305
  "npm": "1.2.8000 || >= 1.4.16"
306
  }
307
  },
 
 
 
 
 
 
308
  "node_modules/brace-expansion": {
309
  "version": "1.1.11",
310
  "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
 
11
  "dependencies": {
12
  "async": "^3.2.6",
13
  "axios": "^1.7.5",
14
+ "bottleneck": "^2.19.5",
15
  "cors": "^2.8.5",
16
  "dotenv": "^16.4.5",
17
  "express": "^4.19.2",
 
306
  "npm": "1.2.8000 || >= 1.4.16"
307
  }
308
  },
309
+ "node_modules/bottleneck": {
310
+ "version": "2.19.5",
311
+ "resolved": "https://registry.npmjs.org/bottleneck/-/bottleneck-2.19.5.tgz",
312
+ "integrity": "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==",
313
+ "license": "MIT"
314
+ },
315
  "node_modules/brace-expansion": {
316
  "version": "1.1.11",
317
  "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
package.json CHANGED
@@ -12,6 +12,7 @@
12
  "dependencies": {
13
  "async": "^3.2.6",
14
  "axios": "^1.7.5",
 
15
  "cors": "^2.8.5",
16
  "dotenv": "^16.4.5",
17
  "express": "^4.19.2",
 
12
  "dependencies": {
13
  "async": "^3.2.6",
14
  "axios": "^1.7.5",
15
+ "bottleneck": "^2.19.5",
16
  "cors": "^2.8.5",
17
  "dotenv": "^16.4.5",
18
  "express": "^4.19.2",
public/configure.html CHANGED
@@ -309,6 +309,14 @@
309
  transition: background-color 0.3s, transform 0.2s;
310
  }
311
 
 
 
 
 
 
 
 
 
312
  #installButton {
313
  background-color: #007aff;
314
  }
@@ -439,6 +447,194 @@
439
  color: #333;
440
  }
441
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  </style>
443
  </head>
444
  <html>
@@ -446,85 +642,118 @@
446
  <div id="addon">
447
  <div id="theme-toggle" class="theme-toggle" title="Toggle Dark/Light Mode"> 🌙 </div>
448
  <div class="logo">
449
- <img src="assets/logo.png" alt="Addon Logo" />
450
  </div>
451
  <h1 class="name">Streaming Catalog Providers</h1>
452
  <h2 class="version">1.0.0</h2>
453
- <h2 class="description">Choose your streaming providers below.</h2>
454
- <div class="separator"></div>
455
- <h3 class="providers-title">Available providers</h3>
456
- <div class="form-element">
457
- <input type="text" id="searchProviders" placeholder="Search providers..." />
458
- </div>
459
- <div id="providers" class="provider-container"></div>
460
- <div class="separator"></div>
461
- <form class="pure-form" id="mainForm">
462
  <div class="form-element">
463
- <label for="tmdbApiKey"> TMDB API key (<a href="https://www.themoviedb.org/settings/api" target="_blank" style="color: #007aff;">Get it here</a>) </label>
464
- <input type="text" id="tmdbApiKey" name="tmdbApiKey" />
465
- </div>
466
- <div class="form-element">
467
- <label for="language"> Language </label>
468
- <select id="language" name="language" required>
469
- <option value="">Select your language</option>
470
- </select>
471
- </div>
472
- <div class="form-element">
473
- <label for="ageRange"> Age range (content moderation) <span id="infoIcon" class="info-icon" title="Learn more">?</span>
474
- </label>
475
- <select id="ageRange" name="ageRange">
476
- <option value="">Select your age range</option>
477
- <option value="0-5">0-5 years</option>
478
- <option value="6-11">6-11 years</option>
479
- <option value="12-15">12-15 years</option>
480
- <option value="16-17">16-17 years</option>
481
- <option value="18+">18+ years</option>
482
- </select>
483
  </div>
 
 
 
 
 
484
  <div class="separator"></div>
 
 
 
 
 
 
485
  <div class="form-element">
486
- <label for="rpdbApiKey">RPDB API key (<a href="https://ratingposterdb.com/api-key/" target="_blank" style="color: #007aff;">Get it here</a>) </label>
487
- <input type="text" id="rpdbApiKey" name="rpdbApiKey">
488
  </div>
 
489
  <div class="separator"></div>
490
- <h3 class="selected-providers-title">Selected providers</h3>
491
- <div id="selectedProviders" class="provider-container"></div>
492
- <div class="separator"></div>
493
- <div class="button-container">
494
- <button type="button" id="installButton">INSTALL</button>
495
- <button type="button" id="copyButton">COPY LINK</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  </div>
497
- <div class="separator"></div>
498
- </form>
499
- <div id="popup" class="popup"></div>
500
- <div id="infoModal" class="modal">
501
- <span id="modalClose" class="modal-close">&times;</span>
502
- <h4>Age Range Content Moderation</h4>
503
- <p> The content moderation system filters media based on the selected age range to ensure suitability for viewers. Here's how it works: </p>
504
- <ul>
505
- <li>
506
- <strong>0-5 years:</strong> Uses the US certification 'G' (General Audience). Filters out content that is not suitable for very young children. This includes genres such as horror, drama, thriller, crime, war, western, erotic, war & politics, talk-show, soap-opera, reality-show, news, mystery, documentary, and history.
507
- </li>
508
- <li>
509
- <strong>6-11 years:</strong> Uses the US certification 'G' (General Audience). Filters out content unsuitable for young children, maintaining a focus on safe, family-friendly genres. The same genres as for 0-5 years are excluded.
510
- </li>
511
- <li>
512
- <strong>12-15 years:</strong> Uses the US certification 'PG' (Parental Guidance). Allows content with mild themes appropriate for older children and pre-teens. No specific genres are excluded for this age range.
513
- </li>
514
- <li>
515
- <strong>16-17 years:</strong> Uses the US certification 'PG-13' (Parents Strongly Cautioned). Permits content suitable for older teens, including more complex and mature themes but not adult content. No specific genres are excluded for this age range.
516
- </li>
517
- <li>
518
- <strong>18+ years:</strong> Includes all content, even those with adult themes and explicit material. For this age range, no genres are excluded.
519
- </li>
520
- </ul>
521
- <p>
522
- <p>
523
- <strong>Warning:</strong> Please note that the data for this content moderation system is sourced from TMDB (The Movie Database) and may contain inaccuracies. Viewer discretion is advised.
524
- </p>
525
- </p>
526
  </div>
527
- <script src="js/languages.js"></script>
 
 
528
  <script>
529
  document.addEventListener('DOMContentLoaded', () => {
530
  function populateLanguageDropdown() {
@@ -537,6 +766,7 @@
537
  });
538
  }
539
  populateLanguageDropdown();
 
540
  const mainForm = document.getElementById('mainForm');
541
  const installButton = document.getElementById('installButton');
542
  const copyButton = document.getElementById('copyButton');
@@ -546,8 +776,13 @@
546
  const infoModal = document.getElementById('infoModal');
547
  const modalClose = document.getElementById('modalClose');
548
  const selectedProvidersContainer = document.getElementById('selectedProviders');
 
 
 
 
549
  let selectedProviders = [];
550
  let providersMap = {};
 
551
  new Sortable(selectedProvidersContainer, {
552
  animation: 150,
553
  ghostClass: 'sortable-ghost',
@@ -555,12 +790,18 @@
555
  selectedProviders = Array.from(selectedProvidersContainer.querySelectorAll('.selected-provider')).map(div => div.getAttribute('data-id'));
556
  }
557
  });
 
558
  const renderSelectedProviders = () => {
559
- selectedProvidersContainer.innerHTML = selectedProviders.map(providerId => `
560
- <div class="selected-provider" data-id="${providerId}">
561
- <img src="https://image.tmdb.org/t/p/w500/${providersMap[providerId].logo_path}" alt="${providersMap[providerId].display_name}" title="${providersMap[providerId].display_name}" />
562
- <button class="remove-button" data-id="${providerId}">&times;</button>
563
- </div>`).join('');
 
 
 
 
 
564
  document.querySelectorAll('.remove-button').forEach(button => {
565
  button.addEventListener('click', (event) => {
566
  const providerId = event.target.getAttribute('data-id');
@@ -571,31 +812,91 @@
571
  });
572
  });
573
  };
574
- const fetchProviders = async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
  try {
576
- const response = await fetch('/providers');
 
 
 
 
 
 
 
577
  if (!response.ok) {
578
  throw new Error('Failed to fetch providers');
579
  }
 
580
  const providers = await response.json();
581
- providersMap = providers.reduce((map, provider) => {
582
- map[provider.id] = provider;
583
- return map;
584
- }, {});
585
  return providers;
586
  } catch (error) {
587
  console.error('Error fetching providers:', error);
 
588
  return [];
589
  }
590
  };
591
- const renderProviders = async () => {
592
- const providers = await fetchProviders();
593
- providers.sort((a, b) => a.display_name.localeCompare(b.display_name));
594
- providersContainer.innerHTML = providers.map(provider => `
595
- <div class="provider" data-id="${provider.id}">
596
- <img src="https://image.tmdb.org/t/p/w500/${provider.logo_path}" alt="${provider.display_name}" title="${provider.display_name}" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  </div>`).join('');
598
-
599
  document.querySelectorAll('.provider').forEach(provider => {
600
  provider.addEventListener('click', () => {
601
  const providerId = provider.getAttribute('data-id');
@@ -610,6 +911,26 @@
610
  });
611
  });
612
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  const showInfoModal = () => {
614
  infoModal.style.display = 'block';
615
  };
@@ -618,34 +939,133 @@
618
  };
619
  infoIcon.addEventListener('click', showInfoModal);
620
  modalClose.addEventListener('click', hideInfoModal);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
  const getStremioLink = () => {
622
  const config = Object.fromEntries(new FormData(mainForm));
623
  config.providers = selectedProviders;
624
  config.ageRange = document.getElementById('ageRange').value;
625
- return "stremio://" + window.location.host + "/" + encodeURIComponent(JSON.stringify(config)) + "/manifest.json";
 
 
 
 
 
626
  };
 
627
  const getHttpsLink = () => {
628
  const config = Object.fromEntries(new FormData(mainForm));
629
  config.providers = selectedProviders;
630
  config.ageRange = document.getElementById('ageRange').value;
631
- return "https://" + window.location.host + "/" + encodeURIComponent(JSON.stringify(config)) + "/manifest.json";
 
 
 
 
 
632
  };
 
633
  const showPopup = (message, type) => {
634
  popup.textContent = message;
635
  popup.className = `popup ${type}`;
636
  popup.style.display = 'block';
637
  setTimeout(() => {
638
  popup.style.display = 'none';
639
- }, 3000);
640
  };
 
641
  const validateForm = () => {
642
- const language = document.getElementById('language').value.trim();
643
- const ageRange = document.getElementById('ageRange').value.trim();
644
- return language && ageRange && selectedProviders.length > 0;
 
 
 
 
645
  };
 
646
  copyButton.onclick = () => {
647
  if (!validateForm()) {
648
- showPopup('Configuration incomplete: Please select a Language, an Age Range and choose at least one provider.', 'error');
649
  return;
650
  }
651
  const link = getHttpsLink();
@@ -656,28 +1076,110 @@
656
  showPopup('Failed to copy the link.', 'error');
657
  });
658
  };
 
659
  installButton.onclick = () => {
660
  if (!validateForm()) {
661
- showPopup('Configuration incomplete: Please select a Language, an Age Range and choose at least one provider.', 'error');
662
  return;
663
  }
664
  const link = getStremioLink();
665
  window.location.href = link;
666
  };
667
- renderProviders();
668
  document.getElementById('theme-toggle').addEventListener('click', () => {
669
  document.body.classList.toggle('dark-mode');
670
  const isDarkMode = document.body.classList.contains('dark-mode');
671
  document.getElementById('theme-toggle').textContent = isDarkMode ? '🌞' : '🌙';
672
  });
 
673
  document.getElementById('searchProviders').addEventListener('input', function(event) {
674
- const searchTerm = event.target.value.toLowerCase();
675
- document.querySelectorAll('#providers .provider').forEach(provider => {
676
- const providerName = providersMap[provider.getAttribute('data-id')].display_name.toLowerCase();
677
- provider.style.display = providerName.includes(searchTerm) ? 'flex' : 'none';
678
- });
 
 
 
 
 
 
 
679
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  });
681
- </script>
682
  </body>
683
  </html>
 
309
  transition: background-color 0.3s, transform 0.2s;
310
  }
311
 
312
+ #confirmButton {
313
+ background-color: #007aff;
314
+ }
315
+
316
+ #confirmButton:hover {
317
+ background-color: #007aff;
318
+ }
319
+
320
  #installButton {
321
  background-color: #007aff;
322
  }
 
447
  color: #333;
448
  }
449
  }
450
+
451
+ .custom-select-container {
452
+ position: relative;
453
+ width: 100%;
454
+ }
455
+
456
+ .tags-input {
457
+ display: flex;
458
+ flex-wrap: wrap;
459
+ align-items: center;
460
+ gap: 5px;
461
+ padding: 5px;
462
+ border: 1px solid #ccc;
463
+ border-radius: 8px;
464
+ position: relative;
465
+ }
466
+
467
+ #regionSearchInput {
468
+ border: none;
469
+ outline: none;
470
+ flex-grow: 1;
471
+ padding: 8px;
472
+ font-size: 1rem;
473
+ min-width: 100px;
474
+ }
475
+
476
+ .custom-dropdown {
477
+ position: absolute;
478
+ top: 100%;
479
+ left: 0;
480
+ width: 100%;
481
+ max-height: 350px;
482
+ overflow-y: auto;
483
+ background-color: #fff;
484
+ border: 1px solid #ccc;
485
+ border-radius: 0 0 8px 8px;
486
+ z-index: 100;
487
+ display: none;
488
+ }
489
+
490
+ .dropdown-option {
491
+ padding: 8px;
492
+ cursor: pointer;
493
+ }
494
+
495
+ .dropdown-option:hover {
496
+ background-color: #f0f0f5;
497
+ }
498
+
499
+ .tag {
500
+ display: inline-flex;
501
+ align-items: center;
502
+ background-color: #e9e9ed;
503
+ color: #333;
504
+ border-radius: 8px;
505
+ padding: 5px 10px;
506
+ font-size: 0.9rem;
507
+ margin-right: 5px;
508
+ margin-bottom: 5px;
509
+ }
510
+
511
+ .tag .flag {
512
+ margin-right: 5px;
513
+ }
514
+
515
+ .tag .country-name {
516
+ margin-right: 5px;
517
+ }
518
+
519
+ body.dark-mode .custom-select-container {
520
+ background-color: #555;
521
+ color: #f0f0f5;
522
+ border: 1px solid #666;
523
+ border-radius: 8px;
524
+ width: 100%;
525
+ position: relative;
526
+ }
527
+
528
+ body.dark-mode .tags-input {
529
+ display: flex;
530
+ flex-wrap: wrap;
531
+ align-items: center;
532
+ gap: 5px;
533
+ padding: 5px;
534
+ background-color: #555;
535
+ border: 1px solid #666;
536
+ border-radius: 8px;
537
+ position: relative;
538
+ color: #f0f0f5;
539
+ }
540
+
541
+ body.dark-mode #regionSearchInput {
542
+ background-color: #555;
543
+ color: #f0f0f5;
544
+ border: none;
545
+ outline: none;
546
+ flex-grow: 1;
547
+ padding: 8px;
548
+ font-size: 1rem;
549
+ min-width: 100px;
550
+ }
551
+
552
+ body.dark-mode .custom-dropdown {
553
+ background-color: #555;
554
+ border: 1px solid #666;
555
+ border-radius: 0 0 8px 8px;
556
+ z-index: 100;
557
+ max-height: 350px;
558
+ overflow-y: auto;
559
+ display: none;
560
+ }
561
+
562
+ body.dark-mode .dropdown-option {
563
+ padding: 8px;
564
+ background-color: #555;
565
+ color: #f0f0f5;
566
+ cursor: pointer;
567
+ transition: background-color 0.2s;
568
+ }
569
+
570
+ body.dark-mode .dropdown-option:hover {
571
+ background-color: #666;
572
+ }
573
+
574
+ body.dark-mode .tag {
575
+ display: inline-flex;
576
+ align-items: center;
577
+ background-color: #666;
578
+ color: #f0f0f5;
579
+ border-radius: 8px;
580
+ padding: 5px 10px;
581
+ font-size: 0.9rem;
582
+ margin-right: 5px;
583
+ margin-bottom: 5px;
584
+ }
585
+
586
+ body.dark-mode .tag .flag,
587
+ body.dark-mode .tag .country-name {
588
+ color: #f0f0f5;
589
+ }
590
+
591
+ .toggle-switch {
592
+ position: relative;
593
+ display: inline-block;
594
+ width: 40px;
595
+ height: 20px;
596
+ margin-left: 10px;
597
+ vertical-align: middle;
598
+ }
599
+
600
+ .toggle-switch input {
601
+ opacity: 0;
602
+ width: 0;
603
+ height: 0;
604
+ }
605
+
606
+ .slider {
607
+ position: absolute;
608
+ cursor: pointer;
609
+ top: 0;
610
+ left: 0;
611
+ right: 0;
612
+ bottom: 0;
613
+ background-color: #ccc;
614
+ transition: 0.4s;
615
+ border-radius: 34px;
616
+ }
617
+
618
+ .slider:before {
619
+ position: absolute;
620
+ content: "";
621
+ height: 14px;
622
+ width: 14px;
623
+ left: 3px;
624
+ bottom: 3px;
625
+ background-color: white;
626
+ transition: 0.4s;
627
+ border-radius: 50%;
628
+ }
629
+
630
+ input:checked + .slider {
631
+ background-color: #4caf50;
632
+ }
633
+
634
+ input:checked + .slider:before {
635
+ transform: translateX(20px);
636
+ }
637
+
638
  </style>
639
  </head>
640
  <html>
 
642
  <div id="addon">
643
  <div id="theme-toggle" class="theme-toggle" title="Toggle Dark/Light Mode"> 🌙 </div>
644
  <div class="logo">
645
+ <img src="/assets/logo.png" alt="Addon Logo" />
646
  </div>
647
  <h1 class="name">Streaming Catalog Providers</h1>
648
  <h2 class="version">1.0.0</h2>
649
+
650
+ <div id="interface1">
 
 
 
 
 
 
 
651
  <div class="form-element">
652
+ <label for="tmdbApiKey">TMDB API key (<a href="https://www.themoviedb.org/settings/api" target="_blank" style="color: #007aff;">Get it here</a>)</label>
653
+ <input type="text" id="tmdbApiKey" name="tmdbApiKey" required />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654
  </div>
655
+ <button type="button" id="confirmButton">CONFIRM</button>
656
+ </div>
657
+
658
+ <div id="interface2" style="display: none;">
659
+ <h2 class="description">Choose your streaming providers below.</h2>
660
  <div class="separator"></div>
661
+ <h3 class="providers-title">Available providers</h3>
662
+ <div class="form-element">
663
+ <label for="countrySelect">Select your country</label>
664
+ <select id="countrySelect" name="countrySelect">
665
+ </select>
666
+ </div>
667
  <div class="form-element">
668
+ <input type="text" id="searchProviders" placeholder="Search providers..." />
 
669
  </div>
670
+ <div id="providers" class="provider-container"></div>
671
  <div class="separator"></div>
672
+ <form class="pure-form" id="mainForm">
673
+ <div class="form-element">
674
+ <label for="regionSelect">Catalog regions</label>
675
+ <div class="custom-select-container" id="regionSelectContainer">
676
+ <div class="tags-input" id="tagsInput">
677
+ <input type="text" id="regionSearchInput" placeholder="Type or select a region..." />
678
+ </div>
679
+ <div id="regionDropdown" class="custom-dropdown"></div>
680
+ </div>
681
+ </div>
682
+ <div class="form-element">
683
+ <label for="language"> Language </label>
684
+ <select id="language" name="language" required>
685
+ <option value="">Select your language</option>
686
+ </select>
687
+ </div>
688
+ <div class="form-element">
689
+ <label for="ageRange"> Age range (content moderation) <span id="infoIcon" class="info-icon" title="Learn more">?</span>
690
+ </label>
691
+ <select id="ageRange" name="ageRange">
692
+ <option value="">Select your age range</option>
693
+ <option value="0-5">0-5 years</option>
694
+ <option value="6-11">6-11 years</option>
695
+ <option value="12-15">12-15 years</option>
696
+ <option value="16-17">16-17 years</option>
697
+ <option value="18+">18+ years</option>
698
+ </select>
699
+ </div>
700
+ <div class="separator"></div>
701
+ <div class="form-element">
702
+ <label for="rpdbApiKey">RPDB API key (<a href="https://ratingposterdb.com/api-key/" target="_blank" style="color: #007aff;">Get it here</a>) </label>
703
+ <input type="text" id="rpdbApiKey" name="rpdbApiKey">
704
+ </div>
705
+ <div class="separator"></div>
706
+ <div class="form-element">
707
+ <label for="filterContentWithoutPoster">
708
+ Do not display content that does not have a poster (often bad results)
709
+ <div class="toggle-switch">
710
+ <input type="checkbox" id="filterContentWithoutPoster" name="filterContentWithoutPoster" value="true">
711
+ <span class="slider"></span>
712
+ </div>
713
+ </label>
714
+ </div>
715
+ <div class="separator"></div>
716
+ <h3 class="selected-providers-title">Selected providers</h3>
717
+ <div id="selectedProviders" class="provider-container"></div>
718
+ <div class="separator"></div>
719
+ <div class="button-container">
720
+ <button type="button" id="installButton">INSTALL</button>
721
+ <button type="button" id="copyButton">COPY LINK</button>
722
+ </div>
723
+ <div class="separator"></div>
724
+ </form>
725
+ <div id="popup" class="popup"></div>
726
+ <div id="infoModal" class="modal">
727
+ <span id="modalClose" class="modal-close">&times;</span>
728
+ <h4>Age Range Content Moderation</h4>
729
+ <p> The content moderation system filters media based on the selected age range to ensure suitability for viewers. Here's how it works: </p>
730
+ <ul>
731
+ <li>
732
+ <strong>0-5 years:</strong> Uses the US certification 'G' (General Audience). Filters out content that is not suitable for very young children. This includes genres such as horror, drama, thriller, crime, war, western, erotic, war & politics, talk-show, soap-opera, reality-show, news, mystery, documentary, and history.
733
+ </li>
734
+ <li>
735
+ <strong>6-11 years:</strong> Uses the US certification 'G' (General Audience). Filters out content unsuitable for young children, maintaining a focus on safe, family-friendly genres. The same genres as for 0-5 years are excluded.
736
+ </li>
737
+ <li>
738
+ <strong>12-15 years:</strong> Uses the US certification 'PG' (Parental Guidance). Allows content with mild themes appropriate for older children and pre-teens. No specific genres are excluded for this age range.
739
+ </li>
740
+ <li>
741
+ <strong>16-17 years:</strong> Uses the US certification 'PG-13' (Parents Strongly Cautioned). Permits content suitable for older teens, including more complex and mature themes but not adult content. No specific genres are excluded for this age range.
742
+ </li>
743
+ <li>
744
+ <strong>18+ years:</strong> Includes all content, even those with adult themes and explicit material. For this age range, no genres are excluded.
745
+ </li>
746
+ </ul>
747
+ <p>
748
+ <p>
749
+ <strong>Warning:</strong> Please note that the data for this content moderation system is sourced from TMDB (The Movie Database) and may contain inaccuracies. Viewer discretion is advised.
750
+ </p>
751
+ </p>
752
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  </div>
754
+ </div>
755
+ <script src="/js/languages.js"></script>
756
+ <script src="/js/countries.js"></script>
757
  <script>
758
  document.addEventListener('DOMContentLoaded', () => {
759
  function populateLanguageDropdown() {
 
766
  });
767
  }
768
  populateLanguageDropdown();
769
+
770
  const mainForm = document.getElementById('mainForm');
771
  const installButton = document.getElementById('installButton');
772
  const copyButton = document.getElementById('copyButton');
 
776
  const infoModal = document.getElementById('infoModal');
777
  const modalClose = document.getElementById('modalClose');
778
  const selectedProvidersContainer = document.getElementById('selectedProviders');
779
+ const confirmButton = document.getElementById('confirmButton');
780
+ const interface1 = document.getElementById('interface1');
781
+ const interface2 = document.getElementById('interface2');
782
+ let providersData = [];
783
  let selectedProviders = [];
784
  let providersMap = {};
785
+
786
  new Sortable(selectedProvidersContainer, {
787
  animation: 150,
788
  ghostClass: 'sortable-ghost',
 
790
  selectedProviders = Array.from(selectedProvidersContainer.querySelectorAll('.selected-provider')).map(div => div.getAttribute('data-id'));
791
  }
792
  });
793
+
794
  const renderSelectedProviders = () => {
795
+ selectedProvidersContainer.innerHTML = selectedProviders.map(providerId => {
796
+ const provider = providersMap[providerId];
797
+ if (!provider) return '';
798
+ return `
799
+ <div class="selected-provider" data-id="${providerId}">
800
+ <img src="https://image.tmdb.org/t/p/w500/${provider.logo_path}" alt="${provider.provider_name}" title="${provider.provider_name}" />
801
+ <button class="remove-button" data-id="${providerId}">&times;</button>
802
+ </div>`;
803
+ }).join('');
804
+
805
  document.querySelectorAll('.remove-button').forEach(button => {
806
  button.addEventListener('click', (event) => {
807
  const providerId = event.target.getAttribute('data-id');
 
812
  });
813
  });
814
  };
815
+
816
+ const populateCountryDropdown = () => {
817
+ const countrySelect = document.getElementById('countrySelect');
818
+ const allOption = document.createElement('option');
819
+ allOption.value = 'ALL';
820
+ allOption.textContent = '🌍 Everywhere';
821
+ allOption.selected = true;
822
+ countrySelect.appendChild(allOption);
823
+
824
+ const sortedCountries = countries.sort((a, b) => a.english_name.localeCompare(b.english_name));
825
+ sortedCountries.forEach(country => {
826
+ const option = document.createElement('option');
827
+ option.value = country.iso_3166_1;
828
+
829
+ const flag = country.iso_3166_1
830
+ .toUpperCase()
831
+ .replace(/./g, char => String.fromCodePoint(127397 + char.charCodeAt()));
832
+ option.textContent = `${flag} ${country.english_name}`;
833
+ countrySelect.appendChild(option);
834
+ });
835
+ };
836
+
837
+ populateCountryDropdown();
838
+ document.getElementById('countrySelect').addEventListener('change', function() {
839
+ const selectedCountry = this.value;
840
+ renderProviders(selectedCountry);
841
+
842
+ const searchTerm = document.getElementById('searchProviders').value.toLowerCase();
843
+ document.querySelectorAll('#providers .provider').forEach(providerElement => {
844
+ const providerId = providerElement.getAttribute('data-id');
845
+ const providerName = providersMap[providerId].provider_name.toLowerCase();
846
+ providerElement.style.display = providerName.includes(searchTerm) ? 'flex' : 'none';
847
+ });
848
+ });
849
+
850
+ const fetchProviders = async (apiKey) => {
851
  try {
852
+ const response = await fetch('/fetch-providers', {
853
+ method: 'POST',
854
+ headers: {
855
+ 'Content-Type': 'application/json',
856
+ },
857
+ body: JSON.stringify({ apiKey }),
858
+ });
859
+
860
  if (!response.ok) {
861
  throw new Error('Failed to fetch providers');
862
  }
863
+
864
  const providers = await response.json();
 
 
 
 
865
  return providers;
866
  } catch (error) {
867
  console.error('Error fetching providers:', error);
868
+ showPopup('Failed to fetch providers. Please check your API key and try again.', 'error');
869
  return [];
870
  }
871
  };
872
+
873
+ const renderProviders = (countryCode) => {
874
+ let filteredProviders;
875
+
876
+ if (countryCode === 'ALL') {
877
+ filteredProviders = providersData;
878
+ } else {
879
+ filteredProviders = providersData.filter(provider => {
880
+ const displayPriorities = JSON.parse(provider.display_priorities || '{}');
881
+ return displayPriorities[countryCode] !== undefined;
882
+ });
883
+ }
884
+
885
+ filteredProviders = filteredProviders.filter(provider => {
886
+ const isSelected = selectedProviders.includes(provider.provider_id.toString());
887
+ return !isSelected;
888
+ });
889
+
890
+ filteredProviders.forEach(provider => {
891
+ providersMap[provider.provider_id] = provider;
892
+ });
893
+
894
+ filteredProviders.sort((a, b) => a.provider_name.localeCompare(b.provider_name));
895
+ providersContainer.innerHTML = filteredProviders.map(provider => `
896
+ <div class="provider" data-id="${provider.provider_id}">
897
+ <img src="https://image.tmdb.org/t/p/w500/${provider.logo_path}" alt="${provider.provider_name}" title="${provider.provider_name}" />
898
  </div>`).join('');
899
+
900
  document.querySelectorAll('.provider').forEach(provider => {
901
  provider.addEventListener('click', () => {
902
  const providerId = provider.getAttribute('data-id');
 
911
  });
912
  });
913
  };
914
+
915
+ confirmButton.addEventListener('click', async () => {
916
+ const apiKey = document.getElementById('tmdbApiKey').value.trim();
917
+ if (!apiKey) {
918
+ alert('Please enter your TMDB API key.');
919
+ return;
920
+ }
921
+
922
+ providersData = await fetchProviders(apiKey);
923
+ populateProvidersMap();
924
+
925
+ const event = new Event('providersLoaded');
926
+ confirmButton.dispatchEvent(event);
927
+
928
+ renderProviders('ALL');
929
+ interface1.style.display = 'none';
930
+ interface2.style.display = 'block';
931
+ });
932
+
933
+
934
  const showInfoModal = () => {
935
  infoModal.style.display = 'block';
936
  };
 
939
  };
940
  infoIcon.addEventListener('click', showInfoModal);
941
  modalClose.addEventListener('click', hideInfoModal);
942
+
943
+ let selectedRegions = [];
944
+
945
+ const populateRegionDropdown = () => {
946
+ const regionDropdown = document.getElementById('regionDropdown');
947
+ regionDropdown.innerHTML = '';
948
+
949
+ const sortedCountries = countries.sort((a, b) => a.english_name.localeCompare(b.english_name));
950
+
951
+ sortedCountries.forEach(country => {
952
+ const option = document.createElement('div');
953
+ option.className = 'dropdown-option';
954
+ option.setAttribute('data-value', country.iso_3166_1);
955
+
956
+ const flag = country.iso_3166_1
957
+ .toUpperCase()
958
+ .replace(/./g, char => String.fromCodePoint(127397 + char.charCodeAt()));
959
+ option.innerHTML = `${flag} ${country.english_name}`;
960
+ option.onclick = () => {
961
+ addSelectedRegion(country.iso_3166_1, flag, country.english_name);
962
+ filterRegionDropdown('');
963
+ document.getElementById('regionSearchInput').value = '';
964
+ regionDropdown.style.display = 'none';
965
+ };
966
+ regionDropdown.appendChild(option);
967
+ });
968
+ };
969
+
970
+ const filterRegionDropdown = (searchTerm) => {
971
+ const options = document.querySelectorAll('.dropdown-option');
972
+ options.forEach(option => {
973
+ const text = option.textContent.toLowerCase();
974
+ option.style.display = text.includes(searchTerm.toLowerCase()) ? 'block' : 'none';
975
+ });
976
+ document.getElementById('regionDropdown').style.display = 'block';
977
+ };
978
+
979
+ document.getElementById('regionSearchInput').addEventListener('input', function () {
980
+ const searchTerm = this.value;
981
+ filterRegionDropdown(searchTerm);
982
+ });
983
+
984
+ const addSelectedRegion = (regionCode, flag, countryName) => {
985
+ if (!selectedRegions.includes(regionCode)) {
986
+ selectedRegions.push(regionCode);
987
+ const tag = document.createElement('span');
988
+ tag.className = 'tag';
989
+ tag.setAttribute('data-id', regionCode);
990
+ tag.innerHTML = `
991
+ <span class="flag">${flag}</span>
992
+ <span class="country-name">${countryName}</span>
993
+ `;
994
+ tag.addEventListener('click', () => {
995
+ removeSelectedRegion(regionCode);
996
+ });
997
+ document.getElementById('regionSearchInput').parentNode.insertBefore(tag, document.getElementById('regionSearchInput'));
998
+ }
999
+ };
1000
+
1001
+ const removeSelectedRegion = (regionCode) => {
1002
+ selectedRegions = selectedRegions.filter(code => code !== regionCode);
1003
+ document.querySelector(`.tag[data-id='${regionCode}']`).remove();
1004
+ };
1005
+
1006
+ populateRegionDropdown();
1007
+
1008
+ document.getElementById('regionSearchInput').addEventListener('focus', function () {
1009
+ document.getElementById('regionDropdown').style.display = 'block';
1010
+ });
1011
+
1012
+ document.addEventListener('click', function (event) {
1013
+ const regionContainer = document.getElementById('regionSelectContainer');
1014
+ if (!regionContainer.contains(event.target)) {
1015
+ document.getElementById('regionDropdown').style.display = 'none';
1016
+ }
1017
+ });
1018
+
1019
+ const encodeToBase64 = (str) => {
1020
+ return btoa(unescape(encodeURIComponent(str)));
1021
+ };
1022
+
1023
  const getStremioLink = () => {
1024
  const config = Object.fromEntries(new FormData(mainForm));
1025
  config.providers = selectedProviders;
1026
  config.ageRange = document.getElementById('ageRange').value;
1027
+ config.tmdbApiKey = document.getElementById('tmdbApiKey').value.trim();
1028
+ config.regions = selectedRegions;
1029
+ config.filterContentWithoutPoster = document.getElementById('filterContentWithoutPoster').checked ? 'true' : '';
1030
+
1031
+ const encodedConfig = encodeToBase64(JSON.stringify(config));
1032
+ return "stremio://" + window.location.host + "/" + encodedConfig + "/manifest.json";
1033
  };
1034
+
1035
  const getHttpsLink = () => {
1036
  const config = Object.fromEntries(new FormData(mainForm));
1037
  config.providers = selectedProviders;
1038
  config.ageRange = document.getElementById('ageRange').value;
1039
+ config.tmdbApiKey = document.getElementById('tmdbApiKey').value.trim();
1040
+ config.regions = selectedRegions;
1041
+ config.filterContentWithoutPoster = document.getElementById('filterContentWithoutPoster').checked ? 'true' : '';
1042
+
1043
+ const encodedConfig = encodeToBase64(JSON.stringify(config));
1044
+ return "https://" + window.location.host + "/" + encodedConfig + "/manifest.json";
1045
  };
1046
+
1047
  const showPopup = (message, type) => {
1048
  popup.textContent = message;
1049
  popup.className = `popup ${type}`;
1050
  popup.style.display = 'block';
1051
  setTimeout(() => {
1052
  popup.style.display = 'none';
1053
+ }, 8000);
1054
  };
1055
+
1056
  const validateForm = () => {
1057
+ const language = document.getElementById('language').value.trim();
1058
+ const ageRange = document.getElementById('ageRange').value.trim();
1059
+ const regionSearchInput = document.getElementById('regionSearchInput').value.trim();
1060
+
1061
+ const isRegionSelected = selectedRegions.length > 0;
1062
+
1063
+ return isRegionSelected && language && ageRange && selectedProviders.length > 0;
1064
  };
1065
+
1066
  copyButton.onclick = () => {
1067
  if (!validateForm()) {
1068
+ showPopup('Configuration incomplete: Please select at least one Catalog regions, your Language, an Age Range and choose at least one provider.', 'error');
1069
  return;
1070
  }
1071
  const link = getHttpsLink();
 
1076
  showPopup('Failed to copy the link.', 'error');
1077
  });
1078
  };
1079
+
1080
  installButton.onclick = () => {
1081
  if (!validateForm()) {
1082
+ showPopup('Configuration incomplete: Please select at least one Catalog regions, your Language, an Age Range and choose at least one provider.', 'error');
1083
  return;
1084
  }
1085
  const link = getStremioLink();
1086
  window.location.href = link;
1087
  };
1088
+
1089
  document.getElementById('theme-toggle').addEventListener('click', () => {
1090
  document.body.classList.toggle('dark-mode');
1091
  const isDarkMode = document.body.classList.contains('dark-mode');
1092
  document.getElementById('theme-toggle').textContent = isDarkMode ? '🌞' : '🌙';
1093
  });
1094
+
1095
  document.getElementById('searchProviders').addEventListener('input', function(event) {
1096
+ const searchTerm = event.target.value.toLowerCase();
1097
+ document.querySelectorAll('#providers .provider').forEach(providerElement => {
1098
+ const providerId = providerElement.getAttribute('data-id');
1099
+ const providerName = providersMap[providerId].provider_name.toLowerCase();
1100
+ providerElement.style.display = providerName.includes(searchTerm) && !selectedProviders.includes(providerId) ? 'flex' : 'none';
1101
+ });
1102
+ if (searchTerm === '') {
1103
+ document.querySelectorAll('#providers .provider').forEach(providerElement => {
1104
+ const providerId = providerElement.getAttribute('data-id');
1105
+ providerElement.style.display = selectedProviders.includes(providerId) ? 'none' : 'flex';
1106
+ });
1107
+ }
1108
  });
1109
+ function getQueryParams() {
1110
+ const url = new URL(window.location.href);
1111
+ const path = url.pathname;
1112
+ const decodedPath = decodeURIComponent(path);
1113
+ const configMatch = decodedPath.match(/\{.*\}/);
1114
+ if (configMatch) {
1115
+ try {
1116
+ const config = JSON.parse(configMatch[0]);
1117
+ return config;
1118
+ } catch (error) {
1119
+ console.error('Error parsing configuration parameters:', error);
1120
+ showPopup('Error parsing configuration parameters. Please check your input and try again.', 'error');
1121
+ }
1122
+ }
1123
+ return {};
1124
+ }
1125
+
1126
+ function prefillFormFromUrlParams() {
1127
+ const params = getQueryParams();
1128
+
1129
+ if (params.tmdbApiKey) {
1130
+ document.getElementById('tmdbApiKey').value = params.tmdbApiKey;
1131
+ confirmButton.click();
1132
+ }
1133
+
1134
+ if (params.language) {
1135
+ document.getElementById('language').value = params.language;
1136
+ }
1137
+
1138
+ if (params.ageRange) {
1139
+ document.getElementById('ageRange').value = params.ageRange;
1140
+ }
1141
+
1142
+ if (params.rpdbApiKey) {
1143
+ document.getElementById('rpdbApiKey').value = params.rpdbApiKey;
1144
+ }
1145
+
1146
+ if (params.filterContentWithoutPoster === 'true') {
1147
+ document.getElementById('filterContentWithoutPoster').checked = true;
1148
+ }
1149
+
1150
+ if (params.providers) {
1151
+ selectedProviders = params.providers;
1152
+
1153
+ if (providersData.length > 0) {
1154
+ populateProvidersMap();
1155
+ renderSelectedProviders();
1156
+ } else {
1157
+ confirmButton.addEventListener('providersLoaded', () => {
1158
+ populateProvidersMap();
1159
+ renderSelectedProviders();
1160
+ }, { once: true });
1161
+ }
1162
+ }
1163
+
1164
+ if (params.regions) {
1165
+ params.regions.forEach(regionCode => {
1166
+ const country = countries.find(c => c.iso_3166_1 === regionCode);
1167
+ if (country) {
1168
+ const flag = country.iso_3166_1.toUpperCase().replace(/./g, char => String.fromCodePoint(127397 + char.charCodeAt()));
1169
+ addSelectedRegion(country.iso_3166_1, flag, country.english_name);
1170
+ }
1171
+ });
1172
+ }
1173
+ }
1174
+
1175
+ const populateProvidersMap = () => {
1176
+ providersData.forEach(provider => {
1177
+ providersMap[provider.provider_id] = provider;
1178
+ });
1179
+ };
1180
+
1181
+ prefillFormFromUrlParams();
1182
  });
1183
+ </script>
1184
  </body>
1185
  </html>
public/js/countries.js ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const countries = [
2
+ {
3
+ "iso_3166_1": "AD",
4
+ "english_name": "Andorra",
5
+ "native_name": "Andorra"
6
+ },
7
+ {
8
+ "iso_3166_1": "AE",
9
+ "english_name": "United Arab Emirates",
10
+ "native_name": "United Arab Emirates"
11
+ },
12
+ {
13
+ "iso_3166_1": "AG",
14
+ "english_name": "Antigua and Barbuda",
15
+ "native_name": "Antigua & Barbuda"
16
+ },
17
+ {
18
+ "iso_3166_1": "AL",
19
+ "english_name": "Albania",
20
+ "native_name": "Albania"
21
+ },
22
+ {
23
+ "iso_3166_1": "AO",
24
+ "english_name": "Angola",
25
+ "native_name": "Angola"
26
+ },
27
+ {
28
+ "iso_3166_1": "AR",
29
+ "english_name": "Argentina",
30
+ "native_name": "Argentina"
31
+ },
32
+ {
33
+ "iso_3166_1": "AT",
34
+ "english_name": "Austria",
35
+ "native_name": "Austria"
36
+ },
37
+ {
38
+ "iso_3166_1": "AU",
39
+ "english_name": "Australia",
40
+ "native_name": "Australia"
41
+ },
42
+ {
43
+ "iso_3166_1": "AZ",
44
+ "english_name": "Azerbaijan",
45
+ "native_name": "Azerbaijan"
46
+ },
47
+ {
48
+ "iso_3166_1": "BA",
49
+ "english_name": "Bosnia and Herzegovina",
50
+ "native_name": "Bosnia & Herzegovina"
51
+ },
52
+ {
53
+ "iso_3166_1": "BB",
54
+ "english_name": "Barbados",
55
+ "native_name": "Barbados"
56
+ },
57
+ {
58
+ "iso_3166_1": "BE",
59
+ "english_name": "Belgium",
60
+ "native_name": "Belgium"
61
+ },
62
+ {
63
+ "iso_3166_1": "BF",
64
+ "english_name": "Burkina Faso",
65
+ "native_name": "Burkina Faso"
66
+ },
67
+ {
68
+ "iso_3166_1": "BG",
69
+ "english_name": "Bulgaria",
70
+ "native_name": "Bulgaria"
71
+ },
72
+ {
73
+ "iso_3166_1": "BH",
74
+ "english_name": "Bahrain",
75
+ "native_name": "Bahrain"
76
+ },
77
+ {
78
+ "iso_3166_1": "BM",
79
+ "english_name": "Bermuda",
80
+ "native_name": "Bermuda"
81
+ },
82
+ {
83
+ "iso_3166_1": "BO",
84
+ "english_name": "Bolivia",
85
+ "native_name": "Bolivia"
86
+ },
87
+ {
88
+ "iso_3166_1": "BR",
89
+ "english_name": "Brazil",
90
+ "native_name": "Brazil"
91
+ },
92
+ {
93
+ "iso_3166_1": "BS",
94
+ "english_name": "Bahamas",
95
+ "native_name": "Bahamas"
96
+ },
97
+ {
98
+ "iso_3166_1": "BY",
99
+ "english_name": "Belarus",
100
+ "native_name": "Belarus"
101
+ },
102
+ {
103
+ "iso_3166_1": "BZ",
104
+ "english_name": "Belize",
105
+ "native_name": "Belize"
106
+ },
107
+ {
108
+ "iso_3166_1": "CA",
109
+ "english_name": "Canada",
110
+ "native_name": "Canada"
111
+ },
112
+ {
113
+ "iso_3166_1": "CD",
114
+ "english_name": "Congo",
115
+ "native_name": "Democratic Republic of the Congo (Kinshasa)"
116
+ },
117
+ {
118
+ "iso_3166_1": "CH",
119
+ "english_name": "Switzerland",
120
+ "native_name": "Switzerland"
121
+ },
122
+ {
123
+ "iso_3166_1": "CI",
124
+ "english_name": "Cote D'Ivoire",
125
+ "native_name": "Côte d’Ivoire"
126
+ },
127
+ {
128
+ "iso_3166_1": "CL",
129
+ "english_name": "Chile",
130
+ "native_name": "Chile"
131
+ },
132
+ {
133
+ "iso_3166_1": "CM",
134
+ "english_name": "Cameroon",
135
+ "native_name": "Cameroon"
136
+ },
137
+ {
138
+ "iso_3166_1": "CO",
139
+ "english_name": "Colombia",
140
+ "native_name": "Colombia"
141
+ },
142
+ {
143
+ "iso_3166_1": "CR",
144
+ "english_name": "Costa Rica",
145
+ "native_name": "Costa Rica"
146
+ },
147
+ {
148
+ "iso_3166_1": "CU",
149
+ "english_name": "Cuba",
150
+ "native_name": "Cuba"
151
+ },
152
+ {
153
+ "iso_3166_1": "CV",
154
+ "english_name": "Cape Verde",
155
+ "native_name": "Cape Verde"
156
+ },
157
+ {
158
+ "iso_3166_1": "CY",
159
+ "english_name": "Cyprus",
160
+ "native_name": "Cyprus"
161
+ },
162
+ {
163
+ "iso_3166_1": "CZ",
164
+ "english_name": "Czech Republic",
165
+ "native_name": "Czech Republic"
166
+ },
167
+ {
168
+ "iso_3166_1": "DE",
169
+ "english_name": "Germany",
170
+ "native_name": "Germany"
171
+ },
172
+ {
173
+ "iso_3166_1": "DK",
174
+ "english_name": "Denmark",
175
+ "native_name": "Denmark"
176
+ },
177
+ {
178
+ "iso_3166_1": "DO",
179
+ "english_name": "Dominican Republic",
180
+ "native_name": "Dominican Republic"
181
+ },
182
+ {
183
+ "iso_3166_1": "DZ",
184
+ "english_name": "Algeria",
185
+ "native_name": "Algeria"
186
+ },
187
+ {
188
+ "iso_3166_1": "EC",
189
+ "english_name": "Ecuador",
190
+ "native_name": "Ecuador"
191
+ },
192
+ {
193
+ "iso_3166_1": "EE",
194
+ "english_name": "Estonia",
195
+ "native_name": "Estonia"
196
+ },
197
+ {
198
+ "iso_3166_1": "EG",
199
+ "english_name": "Egypt",
200
+ "native_name": "Egypt"
201
+ },
202
+ {
203
+ "iso_3166_1": "ES",
204
+ "english_name": "Spain",
205
+ "native_name": "Spain"
206
+ },
207
+ {
208
+ "iso_3166_1": "FI",
209
+ "english_name": "Finland",
210
+ "native_name": "Finland"
211
+ },
212
+ {
213
+ "iso_3166_1": "FJ",
214
+ "english_name": "Fiji",
215
+ "native_name": "Fiji"
216
+ },
217
+ {
218
+ "iso_3166_1": "FR",
219
+ "english_name": "France",
220
+ "native_name": "France"
221
+ },
222
+ {
223
+ "iso_3166_1": "GB",
224
+ "english_name": "United Kingdom",
225
+ "native_name": "United Kingdom"
226
+ },
227
+ {
228
+ "iso_3166_1": "GF",
229
+ "english_name": "French Guiana",
230
+ "native_name": "French Guiana"
231
+ },
232
+ {
233
+ "iso_3166_1": "GH",
234
+ "english_name": "Ghana",
235
+ "native_name": "Ghana"
236
+ },
237
+ {
238
+ "iso_3166_1": "GI",
239
+ "english_name": "Gibraltar",
240
+ "native_name": "Gibraltar"
241
+ },
242
+ {
243
+ "iso_3166_1": "GP",
244
+ "english_name": "Guadaloupe",
245
+ "native_name": "Guadeloupe"
246
+ },
247
+ {
248
+ "iso_3166_1": "GQ",
249
+ "english_name": "Equatorial Guinea",
250
+ "native_name": "Equatorial Guinea"
251
+ },
252
+ {
253
+ "iso_3166_1": "GR",
254
+ "english_name": "Greece",
255
+ "native_name": "Greece"
256
+ },
257
+ {
258
+ "iso_3166_1": "GT",
259
+ "english_name": "Guatemala",
260
+ "native_name": "Guatemala"
261
+ },
262
+ {
263
+ "iso_3166_1": "GY",
264
+ "english_name": "Guyana",
265
+ "native_name": "Guyana"
266
+ },
267
+ {
268
+ "iso_3166_1": "HK",
269
+ "english_name": "Hong Kong",
270
+ "native_name": "Hong Kong SAR China"
271
+ },
272
+ {
273
+ "iso_3166_1": "HN",
274
+ "english_name": "Honduras",
275
+ "native_name": "Honduras"
276
+ },
277
+ {
278
+ "iso_3166_1": "HR",
279
+ "english_name": "Croatia",
280
+ "native_name": "Croatia"
281
+ },
282
+ {
283
+ "iso_3166_1": "HU",
284
+ "english_name": "Hungary",
285
+ "native_name": "Hungary"
286
+ },
287
+ {
288
+ "iso_3166_1": "ID",
289
+ "english_name": "Indonesia",
290
+ "native_name": "Indonesia"
291
+ },
292
+ {
293
+ "iso_3166_1": "IE",
294
+ "english_name": "Ireland",
295
+ "native_name": "Ireland"
296
+ },
297
+ {
298
+ "iso_3166_1": "IL",
299
+ "english_name": "Israel",
300
+ "native_name": "Israel"
301
+ },
302
+ {
303
+ "iso_3166_1": "IN",
304
+ "english_name": "India",
305
+ "native_name": "India"
306
+ },
307
+ {
308
+ "iso_3166_1": "IQ",
309
+ "english_name": "Iraq",
310
+ "native_name": "Iraq"
311
+ },
312
+ {
313
+ "iso_3166_1": "IS",
314
+ "english_name": "Iceland",
315
+ "native_name": "Iceland"
316
+ },
317
+ {
318
+ "iso_3166_1": "IT",
319
+ "english_name": "Italy",
320
+ "native_name": "Italy"
321
+ },
322
+ {
323
+ "iso_3166_1": "JM",
324
+ "english_name": "Jamaica",
325
+ "native_name": "Jamaica"
326
+ },
327
+ {
328
+ "iso_3166_1": "JO",
329
+ "english_name": "Jordan",
330
+ "native_name": "Jordan"
331
+ },
332
+ {
333
+ "iso_3166_1": "JP",
334
+ "english_name": "Japan",
335
+ "native_name": "Japan"
336
+ },
337
+ {
338
+ "iso_3166_1": "KE",
339
+ "english_name": "Kenya",
340
+ "native_name": "Kenya"
341
+ },
342
+ {
343
+ "iso_3166_1": "KR",
344
+ "english_name": "South Korea",
345
+ "native_name": "South Korea"
346
+ },
347
+ {
348
+ "iso_3166_1": "KW",
349
+ "english_name": "Kuwait",
350
+ "native_name": "Kuwait"
351
+ },
352
+ {
353
+ "iso_3166_1": "LB",
354
+ "english_name": "Lebanon",
355
+ "native_name": "Lebanon"
356
+ },
357
+ {
358
+ "iso_3166_1": "LC",
359
+ "english_name": "St. Lucia",
360
+ "native_name": "St. Lucia"
361
+ },
362
+ {
363
+ "iso_3166_1": "LI",
364
+ "english_name": "Liechtenstein",
365
+ "native_name": "Liechtenstein"
366
+ },
367
+ {
368
+ "iso_3166_1": "LT",
369
+ "english_name": "Lithuania",
370
+ "native_name": "Lithuania"
371
+ },
372
+ {
373
+ "iso_3166_1": "LU",
374
+ "english_name": "Luxembourg",
375
+ "native_name": "Luxembourg"
376
+ },
377
+ {
378
+ "iso_3166_1": "LV",
379
+ "english_name": "Latvia",
380
+ "native_name": "Latvia"
381
+ },
382
+ {
383
+ "iso_3166_1": "LY",
384
+ "english_name": "Libyan Arab Jamahiriya",
385
+ "native_name": "Libya"
386
+ },
387
+ {
388
+ "iso_3166_1": "MA",
389
+ "english_name": "Morocco",
390
+ "native_name": "Morocco"
391
+ },
392
+ {
393
+ "iso_3166_1": "MC",
394
+ "english_name": "Monaco",
395
+ "native_name": "Monaco"
396
+ },
397
+ {
398
+ "iso_3166_1": "MD",
399
+ "english_name": "Moldova",
400
+ "native_name": "Moldova"
401
+ },
402
+ {
403
+ "iso_3166_1": "ME",
404
+ "english_name": "Montenegro",
405
+ "native_name": "Montenegro"
406
+ },
407
+ {
408
+ "iso_3166_1": "MG",
409
+ "english_name": "Madagascar",
410
+ "native_name": "Madagascar"
411
+ },
412
+ {
413
+ "iso_3166_1": "MK",
414
+ "english_name": "Macedonia",
415
+ "native_name": "Macedonia"
416
+ },
417
+ {
418
+ "iso_3166_1": "ML",
419
+ "english_name": "Mali",
420
+ "native_name": "Mali"
421
+ },
422
+ {
423
+ "iso_3166_1": "MT",
424
+ "english_name": "Malta",
425
+ "native_name": "Malta"
426
+ },
427
+ {
428
+ "iso_3166_1": "MU",
429
+ "english_name": "Mauritius",
430
+ "native_name": "Mauritius"
431
+ },
432
+ {
433
+ "iso_3166_1": "MW",
434
+ "english_name": "Malawi",
435
+ "native_name": "Malawi"
436
+ },
437
+ {
438
+ "iso_3166_1": "MX",
439
+ "english_name": "Mexico",
440
+ "native_name": "Mexico"
441
+ },
442
+ {
443
+ "iso_3166_1": "MY",
444
+ "english_name": "Malaysia",
445
+ "native_name": "Malaysia"
446
+ },
447
+ {
448
+ "iso_3166_1": "MZ",
449
+ "english_name": "Mozambique",
450
+ "native_name": "Mozambique"
451
+ },
452
+ {
453
+ "iso_3166_1": "NE",
454
+ "english_name": "Niger",
455
+ "native_name": "Niger"
456
+ },
457
+ {
458
+ "iso_3166_1": "NG",
459
+ "english_name": "Nigeria",
460
+ "native_name": "Nigeria"
461
+ },
462
+ {
463
+ "iso_3166_1": "NI",
464
+ "english_name": "Nicaragua",
465
+ "native_name": "Nicaragua"
466
+ },
467
+ {
468
+ "iso_3166_1": "NL",
469
+ "english_name": "Netherlands",
470
+ "native_name": "Netherlands"
471
+ },
472
+ {
473
+ "iso_3166_1": "NO",
474
+ "english_name": "Norway",
475
+ "native_name": "Norway"
476
+ },
477
+ {
478
+ "iso_3166_1": "NZ",
479
+ "english_name": "New Zealand",
480
+ "native_name": "New Zealand"
481
+ },
482
+ {
483
+ "iso_3166_1": "OM",
484
+ "english_name": "Oman",
485
+ "native_name": "Oman"
486
+ },
487
+ {
488
+ "iso_3166_1": "PA",
489
+ "english_name": "Panama",
490
+ "native_name": "Panama"
491
+ },
492
+ {
493
+ "iso_3166_1": "PE",
494
+ "english_name": "Peru",
495
+ "native_name": "Peru"
496
+ },
497
+ {
498
+ "iso_3166_1": "PF",
499
+ "english_name": "French Polynesia",
500
+ "native_name": "French Polynesia"
501
+ },
502
+ {
503
+ "iso_3166_1": "PG",
504
+ "english_name": "Papua New Guinea",
505
+ "native_name": "Papua New Guinea"
506
+ },
507
+ {
508
+ "iso_3166_1": "PH",
509
+ "english_name": "Philippines",
510
+ "native_name": "Philippines"
511
+ },
512
+ {
513
+ "iso_3166_1": "PK",
514
+ "english_name": "Pakistan",
515
+ "native_name": "Pakistan"
516
+ },
517
+ {
518
+ "iso_3166_1": "PL",
519
+ "english_name": "Poland",
520
+ "native_name": "Poland"
521
+ },
522
+ {
523
+ "iso_3166_1": "PS",
524
+ "english_name": "Palestinian Territory",
525
+ "native_name": "Palestinian Territories"
526
+ },
527
+ {
528
+ "iso_3166_1": "PT",
529
+ "english_name": "Portugal",
530
+ "native_name": "Portugal"
531
+ },
532
+ {
533
+ "iso_3166_1": "PY",
534
+ "english_name": "Paraguay",
535
+ "native_name": "Paraguay"
536
+ },
537
+ {
538
+ "iso_3166_1": "QA",
539
+ "english_name": "Qatar",
540
+ "native_name": "Qatar"
541
+ },
542
+ {
543
+ "iso_3166_1": "RO",
544
+ "english_name": "Romania",
545
+ "native_name": "Romania"
546
+ },
547
+ {
548
+ "iso_3166_1": "RS",
549
+ "english_name": "Serbia",
550
+ "native_name": "Serbia"
551
+ },
552
+ {
553
+ "iso_3166_1": "RU",
554
+ "english_name": "Russia",
555
+ "native_name": "Russia"
556
+ },
557
+ {
558
+ "iso_3166_1": "SA",
559
+ "english_name": "Saudi Arabia",
560
+ "native_name": "Saudi Arabia"
561
+ },
562
+ {
563
+ "iso_3166_1": "SC",
564
+ "english_name": "Seychelles",
565
+ "native_name": "Seychelles"
566
+ },
567
+ {
568
+ "iso_3166_1": "SE",
569
+ "english_name": "Sweden",
570
+ "native_name": "Sweden"
571
+ },
572
+ {
573
+ "iso_3166_1": "SG",
574
+ "english_name": "Singapore",
575
+ "native_name": "Singapore"
576
+ },
577
+ {
578
+ "iso_3166_1": "SI",
579
+ "english_name": "Slovenia",
580
+ "native_name": "Slovenia"
581
+ },
582
+ {
583
+ "iso_3166_1": "SK",
584
+ "english_name": "Slovakia",
585
+ "native_name": "Slovakia"
586
+ },
587
+ {
588
+ "iso_3166_1": "SM",
589
+ "english_name": "San Marino",
590
+ "native_name": "San Marino"
591
+ },
592
+ {
593
+ "iso_3166_1": "SN",
594
+ "english_name": "Senegal",
595
+ "native_name": "Senegal"
596
+ },
597
+ {
598
+ "iso_3166_1": "SV",
599
+ "english_name": "El Salvador",
600
+ "native_name": "El Salvador"
601
+ },
602
+ {
603
+ "iso_3166_1": "TC",
604
+ "english_name": "Turks and Caicos Islands",
605
+ "native_name": "Turks & Caicos Islands"
606
+ },
607
+ {
608
+ "iso_3166_1": "TD",
609
+ "english_name": "Chad",
610
+ "native_name": "Chad"
611
+ },
612
+ {
613
+ "iso_3166_1": "TH",
614
+ "english_name": "Thailand",
615
+ "native_name": "Thailand"
616
+ },
617
+ {
618
+ "iso_3166_1": "TN",
619
+ "english_name": "Tunisia",
620
+ "native_name": "Tunisia"
621
+ },
622
+ {
623
+ "iso_3166_1": "TR",
624
+ "english_name": "Turkey",
625
+ "native_name": "Turkey"
626
+ },
627
+ {
628
+ "iso_3166_1": "TT",
629
+ "english_name": "Trinidad and Tobago",
630
+ "native_name": "Trinidad & Tobago"
631
+ },
632
+ {
633
+ "iso_3166_1": "TW",
634
+ "english_name": "Taiwan",
635
+ "native_name": "Taiwan"
636
+ },
637
+ {
638
+ "iso_3166_1": "TZ",
639
+ "english_name": "Tanzania",
640
+ "native_name": "Tanzania"
641
+ },
642
+ {
643
+ "iso_3166_1": "UA",
644
+ "english_name": "Ukraine",
645
+ "native_name": "Ukraine"
646
+ },
647
+ {
648
+ "iso_3166_1": "UG",
649
+ "english_name": "Uganda",
650
+ "native_name": "Uganda"
651
+ },
652
+ {
653
+ "iso_3166_1": "US",
654
+ "english_name": "United States of America",
655
+ "native_name": "United States"
656
+ },
657
+ {
658
+ "iso_3166_1": "UY",
659
+ "english_name": "Uruguay",
660
+ "native_name": "Uruguay"
661
+ },
662
+ {
663
+ "iso_3166_1": "VA",
664
+ "english_name": "Holy See",
665
+ "native_name": "Vatican City"
666
+ },
667
+ {
668
+ "iso_3166_1": "VE",
669
+ "english_name": "Venezuela",
670
+ "native_name": "Venezuela"
671
+ },
672
+ {
673
+ "iso_3166_1": "XK",
674
+ "english_name": "Kosovo",
675
+ "native_name": "Kosovo"
676
+ },
677
+ {
678
+ "iso_3166_1": "YE",
679
+ "english_name": "Yemen",
680
+ "native_name": "Yemen"
681
+ },
682
+ {
683
+ "iso_3166_1": "ZA",
684
+ "english_name": "South Africa",
685
+ "native_name": "South Africa"
686
+ },
687
+ {
688
+ "iso_3166_1": "ZM",
689
+ "english_name": "Zambia",
690
+ "native_name": "Zambia"
691
+ },
692
+ {
693
+ "iso_3166_1": "ZW",
694
+ "english_name": "Zimbabwe",
695
+ "native_name": "Zimbabwe"
696
+ }
697
+ ];
src/api/tmdb.js ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require('axios');
2
+ const log = require('../helpers/logger');
3
+ const addToQueue = require('../helpers/bottleneck');
4
+ const { genresDb, catalogDb } = require('../helpers/db');
5
+ const { getCache, setCache } = require('../helpers/cache');
6
+
7
+ const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
8
+
9
+ const PREFETCH_PAGE_COUNT = process.env.PREFETCH_PAGE_COUNT ? parseInt(process.env.PREFETCH_PAGE_COUNT, 10) : 5;
10
+
11
+ const makeRequest = (url, tmdbApiKey = null) => {
12
+ if (tmdbApiKey) {
13
+ url = `${url}${url.includes('?') ? '&' : '?'}api_key=${tmdbApiKey}`;
14
+ }
15
+
16
+ return new Promise((resolve, reject) => {
17
+ addToQueue({
18
+ fn: () => axios.get(url)
19
+ .then(response => {
20
+ log.debug(`API request successful for URL: ${url}`);
21
+ resolve(response.data);
22
+ })
23
+ .catch(error => {
24
+ log.error(`Error during API request for URL: ${url} - ${error.message}`);
25
+ reject(error);
26
+ })
27
+ });
28
+ });
29
+ };
30
+
31
+ const determinePageFromSkip = async (providerId, skip, catalogDb, type, sortBy, ageRange) => {
32
+ try {
33
+ const cachedEntry = await new Promise((resolve, reject) => {
34
+ catalogDb.get(
35
+ "SELECT page, skip FROM cache WHERE provider_id = ? AND skip <= ? AND type = ? AND sortBy = ? AND ageRange = ? ORDER BY skip DESC LIMIT 1",
36
+ [providerId, skip, type, sortBy, ageRange],
37
+ (err, row) => {
38
+ if (err) {
39
+ reject(err);
40
+ } else {
41
+ resolve(row);
42
+ }
43
+ }
44
+ );
45
+ });
46
+
47
+ if (cachedEntry) {
48
+ log.debug(`Cached Entry: Page ${cachedEntry.page}, Skip ${cachedEntry.skip}`);
49
+
50
+ const nextPage = Math.ceil((skip + 1) / 20);
51
+ log.debug(`Determined Page to Serve: ${nextPage}`);
52
+ return nextPage;
53
+ }
54
+
55
+ const lastEntry = await new Promise((resolve, reject) => {
56
+ catalogDb.get(
57
+ "SELECT page, skip FROM cache WHERE provider_id = ? AND type = ? AND sortBy = ? AND ageRange = ? ORDER BY skip DESC LIMIT 1",
58
+ [providerId, type, sortBy, ageRange],
59
+ (err, row) => {
60
+ if (err) {
61
+ reject(err);
62
+ } else {
63
+ resolve(row);
64
+ }
65
+ }
66
+ );
67
+ });
68
+
69
+ log.debug(`Last Entry in Cache: ${lastEntry ? `Page ${lastEntry.page}, Skip ${lastEntry.skip}` : 'None'}`);
70
+
71
+ if (lastEntry) {
72
+ return lastEntry.page + 1;
73
+ }
74
+
75
+ log.debug('Default to Page 1');
76
+ return 1;
77
+ } catch (error) {
78
+ log.error('Error in determinePageFromSkip:', error);
79
+ return 1;
80
+ }
81
+ };
82
+
83
+ const fetchData = async (endpoint, params = {}, tmdbApiKey = null, providerId = null, ageRange = null) => {
84
+ if (tmdbApiKey) {
85
+ params.api_key = tmdbApiKey;
86
+ }
87
+
88
+ const { skip, type, sort_by: sortBy, ...queryParams } = params;
89
+
90
+ const page = providerId ? await determinePageFromSkip(providerId, skip, catalogDb, type, sortBy, ageRange) : 1;
91
+
92
+ const queryParamsWithPage = {
93
+ ...queryParams,
94
+ page,
95
+ language: params.language,
96
+ type,
97
+ };
98
+
99
+ if (sortBy) {
100
+ queryParamsWithPage.sort_by = sortBy;
101
+ }
102
+
103
+ const queryString = new URLSearchParams(queryParamsWithPage).toString();
104
+
105
+ const url = `${TMDB_BASE_URL}${endpoint}?${queryString}`;
106
+
107
+ log.debug(`Request URL: ${url}`);
108
+
109
+ const cachedData = await getCache(url, skip);
110
+ if (cachedData) {
111
+ return cachedData;
112
+ }
113
+
114
+ const data = await makeRequest(url, tmdbApiKey);
115
+
116
+ if (data.total_pages >= page) {
117
+ setCache(url, data, page, skip, providerId, type, sortBy, ageRange);
118
+ log.debug(`Data stored in cache for URL: ${url} with page: ${page}, skip: ${skip}, providerId: ${providerId}, type: ${type}, sort_by: ${sortBy}, ageRange: ${ageRange}`);
119
+ } else {
120
+ log.debug(`Skipping cache: Page ${page} exceeds total_pages ${data.total_pages}`);
121
+ }
122
+
123
+ if (data.total_pages > page) {
124
+ prefetchNextPages(endpoint, queryParamsWithPage, page, data.total_pages, tmdbApiKey, providerId, ageRange);
125
+ }
126
+
127
+ return data;
128
+ };
129
+
130
+ const prefetchNextPages = async (endpoint, queryParamsWithPage, currentPage, totalPages, tmdbApiKey, providerId, ageRange) => {
131
+ const prefetchPromises = [];
132
+
133
+ for (let i = 1; i <= PREFETCH_PAGE_COUNT; i++) {
134
+ const nextPage = currentPage + i;
135
+
136
+ if (nextPage > totalPages) {
137
+ log.debug(`Stopping prefetch: nextPage (${nextPage}) exceeds totalPages (${totalPages})`);
138
+ break;
139
+ }
140
+
141
+ const nextQueryParamsWithPage = { ...queryParamsWithPage, page: nextPage };
142
+ const nextQueryString = new URLSearchParams(nextQueryParamsWithPage).toString();
143
+ const nextUrl = `${TMDB_BASE_URL}${endpoint}?${nextQueryString}`;
144
+
145
+ log.debug(`Preparing to prefetch URL: ${nextUrl}`);
146
+
147
+ prefetchPromises.push(
148
+ (async () => {
149
+ try {
150
+ const nextData = await makeRequest(nextUrl, tmdbApiKey);
151
+ setCache(nextUrl, nextData, nextPage, (currentPage - 1) * 20 + nextPage * 20, providerId, queryParamsWithPage.type, queryParamsWithPage.sort_by, ageRange);
152
+ log.debug(`Prefetched and stored data for URL: ${nextUrl} with page: ${nextPage}`);
153
+ } catch (error) {
154
+ log.warn(`Error prefetching URL: ${nextUrl} - ${error.message}`);
155
+ }
156
+ })()
157
+ );
158
+ }
159
+
160
+ Promise.all(prefetchPromises).then(() => log.debug(`Finished prefetching pages after ${currentPage}`));
161
+ };
162
+
163
+ const discoverContent = async (type, watchProviders = [], ageRange = null, sortBy = 'popularity.desc', genre = null, tmdbApiKey = null, language, skip = 0, regions = [], year = null, rating = null) => {
164
+ const mediaType = type === 'series' ? 'tv' : 'movie';
165
+ const endpoint = `/discover/${mediaType}`;
166
+
167
+ regions = regions && regions.length > 0 ? regions : [];
168
+
169
+ const providerId = watchProviders[0];
170
+
171
+ const params = {
172
+ with_watch_providers: watchProviders.join(','),
173
+ sort_by: sortBy,
174
+ language,
175
+ skip,
176
+ type
177
+ };
178
+
179
+ if (year) {
180
+ const [startYear, endYear] = year.split('-');
181
+ if (startYear && endYear) {
182
+ if (mediaType === 'movie') {
183
+ params['primary_release_date.gte'] = `${startYear}-01-01`;
184
+ params['primary_release_date.lte'] = `${endYear}-12-31`;
185
+ } else if (mediaType === 'tv') {
186
+ params['first_air_date.gte'] = `${startYear}-01-01`;
187
+ params['first_air_date.lte'] = `${endYear}-12-31`;
188
+ }
189
+ }
190
+ }
191
+
192
+ if (rating) {
193
+ const [minRating, maxRating] = rating.split('-');
194
+ if (minRating && maxRating) {
195
+ params['vote_average.gte'] = minRating;
196
+ params['vote_average.lte'] = maxRating;
197
+ }
198
+ }
199
+
200
+ if (ageRange) {
201
+ switch(ageRange) {
202
+ case '0-5':
203
+ if (mediaType === 'movie') {
204
+ params.certification_country = 'US';
205
+ params.certification = 'G';
206
+ params.without_genres = '27,18,53,80,10752,37,10749,10768,10767,10766,10764,10763,9648,99,36';
207
+ }
208
+ if (mediaType === 'tv') {
209
+ params.with_genres = '10762'; // Kids only
210
+ }
211
+ break;
212
+
213
+ case '6-11':
214
+ if (mediaType === 'movie') {
215
+ params.certification_country = 'US';
216
+ params.certification = 'G';
217
+ params.without_genres = '27,18,53,80,10752,37,10749,10768,10767,10766,10764,10763,9648,99,36';
218
+ }
219
+ if (mediaType === 'tv') {
220
+ params.with_genres = '10762'; // Kids only
221
+ }
222
+ break;
223
+
224
+ case '12-15':
225
+ if (mediaType === 'movie') {
226
+ params.certification_country = 'US';
227
+ params.certification = 'PG';
228
+ }
229
+ if (mediaType === 'tv') {
230
+ params.with_genres = '16'; // Animation only
231
+ }
232
+ break;
233
+
234
+ case '16-17':
235
+ if (mediaType === 'movie') {
236
+ params.certification_country = 'US';
237
+ params.certification = 'PG-13';
238
+ }
239
+ break;
240
+
241
+ case '18+':
242
+ if (mediaType === 'movie') {
243
+ params.include_adult = true;
244
+ }
245
+ break;
246
+
247
+ default:
248
+ log.warn(`Unknown ageRange: ${ageRange}`);
249
+ break;
250
+ }
251
+ }
252
+
253
+ if (genre) {
254
+ params.with_genres = genre;
255
+ }
256
+
257
+ const fetchForRegion = async (region) => {
258
+ if (region) {
259
+ params.watch_region = region;
260
+ } else {
261
+ delete params.watch_region;
262
+ }
263
+
264
+ return await fetchData(endpoint, params, tmdbApiKey, providerId, ageRange);
265
+ };
266
+
267
+ const results = await Promise.all(regions.map(region => fetchForRegion(region)));
268
+
269
+ const combinedResults = results.reduce((acc, result) => acc.concat(result.results), []);
270
+
271
+ const uniqueResults = Array.from(new Map(combinedResults.map(item => [item.id, item])).values());
272
+
273
+ return {
274
+ ...results[0],
275
+ results: uniqueResults
276
+ };
277
+ };
278
+
279
+ const fetchGenres = async (type, language, tmdbApiKey) => {
280
+ const mediaType = type === 'series' ? 'tv' : 'movie';
281
+ const endpoint = `/genre/${mediaType}/list`;
282
+
283
+ try {
284
+ const params = {
285
+ language,
286
+ api_key: tmdbApiKey
287
+ };
288
+
289
+ const genresData = await fetchData(endpoint, params, tmdbApiKey);
290
+ log.debug(`Genres retrieved for ${type} (${language})`);
291
+ return genresData.genres;
292
+ } catch (error) {
293
+ log.error(`Error fetching genres from TMDB: ${error.message}`);
294
+ throw error;
295
+ }
296
+ };
297
+
298
+ const storeGenresInDb = (genres, mediaType, language) =>
299
+ new Promise((resolve, reject) => {
300
+ genresDb.serialize(() => {
301
+ genresDb.run('BEGIN TRANSACTION');
302
+ const insertGenre = genresDb.prepare(`
303
+ INSERT INTO genres (genre_id, genre_name, media_type, language)
304
+ VALUES (?, ?, ?, ?)
305
+ ON CONFLICT DO NOTHING;
306
+ `);
307
+
308
+ genres.forEach((genre, index) => {
309
+ insertGenre.run(genre.id, genre.name, mediaType, language, (err) => {
310
+ if (err) {
311
+ log.error(`Error inserting genre: ${err.message}`);
312
+ genresDb.run('ROLLBACK');
313
+ reject(err);
314
+ return;
315
+ }
316
+
317
+ if (index === genres.length - 1) {
318
+ insertGenre.finalize();
319
+ genresDb.run('COMMIT');
320
+ log.info(`Genres stored for ${mediaType} (${language})`);
321
+ resolve();
322
+ }
323
+ });
324
+ });
325
+ });
326
+ });
327
+
328
+ const checkGenresExistForLanguage = async (language) =>
329
+ new Promise((resolve, reject) => {
330
+ log.debug(`Checking genres for ${language}`);
331
+ genresDb.get(
332
+ `SELECT 1 FROM genres WHERE language = ? LIMIT 1`,
333
+ [language],
334
+ (err, row) => err ? reject(err) : resolve(!!row)
335
+ );
336
+ });
337
+
338
+ const fetchAndStoreGenres = async (language, tmdbApiKey) => {
339
+ try {
340
+ const movieGenres = await fetchGenres('movie', language, tmdbApiKey);
341
+ const tvGenres = await fetchGenres('series', language, tmdbApiKey);
342
+
343
+ await storeGenresInDb(movieGenres, 'movie', language);
344
+ await storeGenresInDb(tvGenres, 'tv', language);
345
+
346
+ log.info(`Genres fetched and stored for ${language}`);
347
+ } catch (error) {
348
+ log.error(`Error fetching/storing genres: ${error.message}`);
349
+ }
350
+ };
351
+
352
+ module.exports = { makeRequest, fetchData, discoverContent, checkGenresExistForLanguage, fetchAndStoreGenres };
src/helpers/bottleneck.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const Bottleneck = require('bottleneck');
2
+
3
+ const limiter = new Bottleneck({
4
+ reservoir: 50,
5
+ reservoirRefreshAmount: 50,
6
+ reservoirRefreshInterval: 1000,
7
+ maxConcurrent: 20
8
+ });
9
+
10
+ const addToQueue = (task) => {
11
+ return limiter.schedule(task.fn);
12
+ };
13
+
14
+ module.exports = addToQueue;
src/helpers/cache.js ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { catalogDb, episodesDb } = require('./db');
2
+ const log = require('../helpers/logger');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const axios = require('axios');
6
+ const { CACHE_CATALOG_CONTENT_DURATION_DAYS, CACHE_POSTER_CONTENT_DURATION_DAYS } = process.env;
7
+ const baseUrl = process.env.BASE_URL || 'http://localhost:7000';
8
+
9
+ const defaultCacheDurationDays = 3;
10
+ const cacheCatalogDurationDays = parseInt(CACHE_CATALOG_CONTENT_DURATION_DAYS, 10) || defaultCacheDurationDays;
11
+ const cacheCatalogDurationMillis = cacheCatalogDurationDays * 24 * 60 * 60 * 1000;
12
+
13
+ const posterCacheDurationDays = parseInt(CACHE_POSTER_CONTENT_DURATION_DAYS, 10) || defaultCacheDurationDays;
14
+ const posterCacheDurationMillis = posterCacheDurationDays * 24 * 60 * 60 * 1000;
15
+
16
+ log.debug(`Cache duration for catalog: ${cacheCatalogDurationMillis} milliseconds (${cacheCatalogDurationDays} days)`);
17
+ log.debug(`Cache duration for posters: ${posterCacheDurationMillis} milliseconds (${posterCacheDurationDays} days)`);
18
+
19
+ const getCache = (key) => {
20
+ return new Promise((resolve, reject) => {
21
+ catalogDb.get("SELECT value, expiration FROM cache WHERE key = ?", [key], (err, row) => {
22
+ if (err) {
23
+ log.error(`Error fetching cache for key ${key}:`, err);
24
+ return reject(err);
25
+ }
26
+ if (row && row.expiration > Date.now()) {
27
+ log.info(`Cache hit for key ${key}`);
28
+ resolve(JSON.parse(row.value));
29
+ } else {
30
+ log.info(`Cache miss for key ${key}`);
31
+ resolve(null);
32
+ }
33
+ });
34
+ });
35
+ };
36
+
37
+ const setCache = (key, value, page = 1, skip = 0, providerId = null, type = null, sortBy = null, ageRange = null) => {
38
+ const expiration = Date.now() + cacheCatalogDurationMillis;
39
+ log.debug(`Setting cache with expiration: ${new Date(expiration).toUTCString()}`);
40
+
41
+ catalogDb.run(`
42
+ INSERT OR REPLACE INTO cache (key, value, expiration, page, skip, provider_id, type, sortBy, ageRange)
43
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
44
+ [key, JSON.stringify(value), expiration, page, skip, providerId, type, sortBy, ageRange],
45
+ (err) => {
46
+ if (err) {
47
+ log.error('Error setting cache:', err);
48
+ } else {
49
+ log.debug(`Cache set with page: ${page}, skip: ${skip}, providerId: ${providerId}, type: ${type}, sortBy: ${sortBy}, ageRange: ${ageRange}`);
50
+ }
51
+ }
52
+ );
53
+ };
54
+
55
+ const posterDirectory = path.join(__dirname, '../../db/rpdbPosters');
56
+
57
+ if (!fs.existsSync(posterDirectory)) {
58
+ fs.mkdirSync(posterDirectory, { recursive: true });
59
+ }
60
+
61
+ const formatFileName = (posterId) => {
62
+ return posterId.replace(/[^a-zA-Z0-9-_]/g, '_');
63
+ };
64
+
65
+ const getCachedPoster = async (posterId) => {
66
+ const formattedPosterId = formatFileName(posterId);
67
+ const filePath = path.join(posterDirectory, `${formattedPosterId}.jpg`);
68
+ const fileStats = fs.existsSync(filePath) ? fs.statSync(filePath) : null;
69
+
70
+ if (fileStats && (Date.now() - fileStats.mtimeMs < posterCacheDurationMillis)) {
71
+ const posterUrl = `${baseUrl}/poster/${formattedPosterId}.jpg`;
72
+ log.debug(`Cache hit for poster id ${posterId}, serving from ${posterUrl}`);
73
+ return { poster_url: posterUrl };
74
+ } else {
75
+ log.debug(`Cache miss or expired for poster id ${posterId}`);
76
+ return null;
77
+ }
78
+ };
79
+
80
+ const setCachedPoster = async (posterId, posterUrl) => {
81
+ const formattedPosterId = formatFileName(posterId);
82
+ const filePath = path.join(posterDirectory, `${formattedPosterId}.jpg`);
83
+
84
+ try {
85
+ const response = await axios.get(posterUrl, { responseType: 'arraybuffer' });
86
+ fs.writeFileSync(filePath, response.data);
87
+ log.debug(`Poster id ${posterId} cached at ${filePath}`);
88
+ } catch (error) {
89
+ log.error(`Error caching poster id ${posterId} from URL ${posterUrl}: ${error.message}`);
90
+ throw error;
91
+ }
92
+ };
93
+
94
+ const cleanUpCache = () => {
95
+ if (DISABLE_CACHE === 'true') {
96
+ log.info('Cache is disabled, skipping cache cleanup.');
97
+ return;
98
+ }
99
+
100
+ catalogDb.run("DELETE FROM cache WHERE expiration <= ?", [Date.now()], (err) => {
101
+ if (err) {
102
+ log.error('Failed to clean up cache:', err);
103
+ } else {
104
+ log.info('Cache cleanup completed successfully.');
105
+ }
106
+ });
107
+ };
108
+
109
+ const setEpisodeCache = (episodeData) => {
110
+ const { id, show_id, season_number, episode_number, air_date, name, overview, production_code, runtime, still_path, vote_average, vote_count } = episodeData;
111
+
112
+ const insertSQL = `INSERT OR REPLACE INTO episodes
113
+ (id, show_id, season_number, episode_number, air_date, name, overview, production_code, runtime, still_path, vote_average, vote_count)
114
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`;
115
+
116
+ episodesDb.run(insertSQL, [
117
+ id,
118
+ show_id,
119
+ season_number,
120
+ episode_number,
121
+ air_date,
122
+ name,
123
+ overview,
124
+ production_code,
125
+ runtime,
126
+ still_path,
127
+ vote_average,
128
+ vote_count
129
+ ], (err) => {
130
+ if (err) {
131
+ log.error(`Error inserting episode data into episodes.db for ID ${id}: ${err.message}`);
132
+ } else {
133
+ log.info(`Episode data inserted into episodes.db for ID ${id}`);
134
+ }
135
+ });
136
+ };
137
+
138
+ const getEpisodeCache = (show_id) => {
139
+ return new Promise((resolve, reject) => {
140
+ episodesDb.all("SELECT * FROM episodes WHERE show_id = ?", [show_id], (err, rows) => {
141
+ if (err) {
142
+ log.error(`Error fetching episodes data for show_id ${show_id}:`, err);
143
+ return reject(err);
144
+ }
145
+ if (rows && rows.length > 0) {
146
+ log.info(`Cache hit for all episodes of show_id ${show_id}`);
147
+ resolve(rows);
148
+ } else {
149
+ log.info(`Cache miss for all episodes of show_id ${show_id}`);
150
+ resolve(null);
151
+ }
152
+ });
153
+ });
154
+ };
155
+
156
+ setInterval(cleanUpCache, 24 * 60 * 60 * 1000);
157
+
158
+ module.exports = {
159
+ getCache,
160
+ setCache,
161
+ cleanUpCache,
162
+ getCachedPoster,
163
+ setCachedPoster,
164
+ getEpisodeCache,
165
+ setEpisodeCache
166
+ };
src/helpers/catalog.js ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require('axios');
2
+ const { genresDb } = require('../helpers/db');
3
+ const { discoverContent } = require('../api/tmdb');
4
+ const { getCachedPoster, setCachedPoster } = require('../helpers/cache');
5
+ const log = require('../helpers/logger');
6
+
7
+ async function parseConfigParameters(configParameters) {
8
+ let parsedConfig = {};
9
+ if (configParameters) {
10
+ try {
11
+ parsedConfig = JSON.parse(decodeURIComponent(configParameters));
12
+ } catch (error) {
13
+ log.error(`Error parsing configParameters: ${error.message}`);
14
+ }
15
+ }
16
+ return parsedConfig;
17
+ }
18
+
19
+ function extractCatalogInfo(id) {
20
+ const match = id.match(/^tmdb-discover-(movies|series)(-new|-popular)?-(\d+)$/);
21
+ if (!match) {
22
+ throw new Error('Invalid catalog id');
23
+ }
24
+ return {
25
+ catalogType: match[1],
26
+ providerId: parseInt(match[3], 10)
27
+ };
28
+ }
29
+
30
+ async function getGenreId(genreName, type) {
31
+ const genreRow = await new Promise((resolve, reject) => {
32
+ genresDb.get("SELECT genre_id FROM genres WHERE genre_name = ? AND media_type = ?", [genreName, type === 'series' ? 'tv' : 'movie'], (err, row) => {
33
+ if (err) reject(err);
34
+ else resolve(row);
35
+ });
36
+ });
37
+ return genreRow ? genreRow.genre_id : null;
38
+ }
39
+
40
+ async function fetchDiscoverContent(catalogType, providers, ageRange, sortBy, genre, tmdbApiKey, language, skip, regions, year = null, rating = null) {
41
+ return await discoverContent(catalogType, providers, ageRange, sortBy, genre, tmdbApiKey, language, skip, regions, year, rating);
42
+ }
43
+
44
+ function getRpdbPoster(type, id, language, rpdbkey) {
45
+ const tier = rpdbkey.split("-")[0];
46
+ const lang = language.split("-")[0];
47
+ const baseUrl = `https://api.ratingposterdb.com/${rpdbkey}/tmdb/poster-default/${type}-${id}.jpg?fallback=true`;
48
+ return (tier === "t0" || tier === "t1") ? baseUrl : `${baseUrl}&lang=${lang}`;
49
+ }
50
+
51
+ async function getPosterUrl(content, catalogType, language, rpdbApiKey) {
52
+ const posterId = `poster:${content.id}`;
53
+ let posterUrl;
54
+ if (rpdbApiKey) {
55
+ const cachedPoster = await getCachedPoster(posterId);
56
+ if (cachedPoster) {
57
+ log.debug(`Using cached poster URL for id ${posterId}`);
58
+ return cachedPoster.poster_url;
59
+ }
60
+
61
+ const rpdbImage = getRpdbPoster(catalogType, content.id, language, rpdbApiKey);
62
+ try {
63
+ const response = await axios.head(rpdbImage);
64
+ if (response.status === 200) {
65
+ log.debug(`RPDB poster found for id ${posterId}`);
66
+ await setCachedPoster(posterId, rpdbImage);
67
+ return rpdbImage;
68
+ }
69
+ } catch (error) {
70
+ log.warn(`Error fetching RPDB poster: ${error.message}. Falling back to TMDB poster.`);
71
+ }
72
+ }
73
+ posterUrl = `https://image.tmdb.org/t/p/w500${content.poster_path}`;
74
+ return posterUrl;
75
+ }
76
+
77
+ async function buildMetas(filteredResults, catalogType, language, rpdbApiKey) {
78
+ return await Promise.all(filteredResults.map(async (content) => {
79
+ const posterUrl = await getPosterUrl(content, catalogType, language, rpdbApiKey);
80
+
81
+
82
+ let releaseInfo = catalogType === 'movies'
83
+ ? content.release_date ? content.release_date.split('-')[0] : ''
84
+ : content.first_air_date
85
+ ? content.last_air_date
86
+ ? `${content.first_air_date.split('-')[0]}-${content.last_air_date.split('-')[0]}`
87
+ : content.first_air_date.split('-')[0]
88
+ : '';
89
+
90
+ const links = await buildLinks(content);
91
+
92
+ return {
93
+ id: `tmdb:${content.id}`,
94
+ type: catalogType === 'movies' ? 'movie' : 'series',
95
+ name: catalogType === 'movies' ? content.title : content.name,
96
+ poster: posterUrl,
97
+ background: `https://image.tmdb.org/t/p/w1280${content.backdrop_path}`,
98
+ description: content.overview,
99
+ releaseInfo: releaseInfo || null,
100
+ links
101
+ };
102
+ }));
103
+ }
104
+
105
+ async function buildLinks(content) {
106
+ const links = [];
107
+
108
+ if (content.genre_ids) {
109
+ for (const genreId of content.genre_ids) {
110
+ try {
111
+ const genreName = await getGenreName(genreId, content.type);
112
+ if (genreName) {
113
+ links.push({
114
+ name: genreName,
115
+ category: 'Genres',
116
+ url: `stremio:///discover`
117
+ });
118
+ }
119
+ } catch (error) {
120
+ console.error(`Error fetching genre name for ID ${genreId}: ${error.message}`);
121
+ }
122
+ }
123
+ }
124
+
125
+ if (content.vote_average && content.id) {
126
+ links.push({
127
+ name: content.vote_average.toFixed(1),
128
+ category: 'imdb',
129
+ url: `https://imdb.com/title/tt${content.id}`
130
+ });
131
+ }
132
+
133
+ return links;
134
+ }
135
+
136
+ async function getGenreName(genreId, type) {
137
+ return new Promise((resolve, reject) => {
138
+ genresDb.get("SELECT genre_name FROM genres WHERE genre_id = ? AND media_type = ?", [genreId, type === 'series' ? 'tv' : 'movie'], (err, row) => {
139
+ if (err) reject(err);
140
+ else resolve(row ? row.genre_name : null);
141
+ });
142
+ });
143
+ }
144
+
145
+ module.exports = {
146
+ parseConfigParameters,
147
+ extractCatalogInfo,
148
+ getGenreId,
149
+ fetchDiscoverContent,
150
+ getPosterUrl,
151
+ buildMetas
152
+ };
src/helpers/db.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const sqlite3 = require('sqlite3').verbose();
4
+ const log = require('../helpers/logger');
5
+
6
+ const dbDir = path.join(__dirname, '../../db');
7
+
8
+ if (!fs.existsSync(dbDir)) {
9
+ fs.mkdirSync(dbDir, { recursive: true });
10
+ log.debug('Created db directory');
11
+ }
12
+
13
+ const createDatabaseAndTable = (dbPath, tableName, createTableSQL) => {
14
+ const db = new sqlite3.Database(dbPath, (err) => {
15
+ if (err) {
16
+ log.error(`Failed to connect to ${tableName}:`, err);
17
+ } else {
18
+ log.debug(`Connected to ${tableName} successfully`);
19
+ }
20
+ });
21
+
22
+ db.serialize(() => {
23
+ db.run(createTableSQL, (err) => {
24
+ if (err) {
25
+ log.error(`Error creating ${tableName}:`, err);
26
+ } else {
27
+ log.debug(`${tableName} created or already exists`);
28
+ }
29
+ });
30
+ });
31
+
32
+ return db;
33
+ };
34
+
35
+ const providersDb = createDatabaseAndTable(
36
+ path.join(dbDir, 'providers.db'),
37
+ 'providers',
38
+ `CREATE TABLE IF NOT EXISTS providers (
39
+ provider_id INTEGER PRIMARY KEY,
40
+ provider_name TEXT,
41
+ logo_path TEXT,
42
+ display_priorities TEXT,
43
+ last_fetched DATETIME DEFAULT CURRENT_TIMESTAMP
44
+ )`
45
+ );
46
+
47
+ const catalogDb = createDatabaseAndTable(
48
+ path.join(dbDir, 'catalog.db'),
49
+ 'cache',
50
+ `CREATE TABLE IF NOT EXISTS cache (
51
+ key TEXT PRIMARY KEY,
52
+ value TEXT,
53
+ expiration INTEGER,
54
+ page INTEGER DEFAULT 1,
55
+ skip INTEGER DEFAULT 0,
56
+ provider_id INTEGER,
57
+ type TEXT,
58
+ sortBy TEXT,
59
+ ageRange TEXT
60
+ )`
61
+ );
62
+
63
+ const genresDb = createDatabaseAndTable(
64
+ path.join(dbDir, 'genres.db'),
65
+ 'genres',
66
+ `CREATE TABLE IF NOT EXISTS genres (
67
+ genre_id INTEGER,
68
+ genre_name TEXT,
69
+ media_type TEXT,
70
+ language TEXT,
71
+ PRIMARY KEY (genre_id, media_type, language),
72
+ UNIQUE (genre_id, media_type, language)
73
+ )`
74
+ );
75
+
76
+ module.exports = {
77
+ providersDb,
78
+ catalogDb,
79
+ genresDb
80
+ };
src/helpers/logger.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const winston = require('winston');
2
+ const DailyRotateFile = require('winston-daily-rotate-file');
3
+ const path = require('path');
4
+
5
+ winston.addColors({
6
+ error: 'red',
7
+ warn: 'yellow',
8
+ info: 'blue',
9
+ debug: 'green'
10
+ });
11
+
12
+ const uppercaseLevelFormat = winston.format((info) => {
13
+ info.level = info.level.toUpperCase();
14
+ return info;
15
+ })();
16
+
17
+ const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
18
+ const LOG_FILE_PATH = path.join(__dirname, '../../log/application-%DATE%.log');
19
+ const MAX_FILES = process.env.LOG_INTERVAL_DELETION || '3d';
20
+
21
+ const log = winston.createLogger({
22
+ level: LOG_LEVEL,
23
+ format: winston.format.combine(
24
+ uppercaseLevelFormat,
25
+ winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
26
+ winston.format.printf(({ level, message, timestamp }) => {
27
+ return `[${timestamp}] [${level}]: ${message}`;
28
+ })
29
+ ),
30
+ transports: [
31
+ new winston.transports.Console({
32
+ format: winston.format.combine(
33
+ winston.format.colorize(),
34
+ winston.format.printf(({ level, message, timestamp }) => {
35
+ return `[${timestamp}] [${level}]: ${message}`;
36
+ })
37
+ )
38
+ }),
39
+ new DailyRotateFile({
40
+ filename: LOG_FILE_PATH,
41
+ datePattern: 'YYYY-MM-DD',
42
+ maxSize: '20m',
43
+ maxFiles: MAX_FILES
44
+ })
45
+ ]
46
+ });
47
+
48
+ log.exceptions.handle(
49
+ new DailyRotateFile({
50
+ filename: path.join(__dirname, '../../log/exceptions-%DATE%.log'),
51
+ datePattern: 'YYYY-MM-DD',
52
+ maxSize: '20m',
53
+ maxFiles: '30d'
54
+ })
55
+ );
56
+
57
+ process.on('unhandledRejection', (reason, promise) => {
58
+ log.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
59
+ });
60
+
61
+ log.on('error', function (err) {
62
+ console.error('Erreur dans le logger:', err);
63
+ });
64
+
65
+ module.exports = log;
src/helpers/manifest.js ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { genresDb, providersDb } = require('./db');
2
+ const log = require('../helpers/logger');
3
+ const { checkGenresExistForLanguage, fetchAndStoreGenres } = require('../api/tmdb');
4
+
5
+ const manifestTemplate = {
6
+ id: 'community.tmdbstreamingcatalogproviders',
7
+ version: '0.3.0',
8
+ name: 'TMDB Streaming Catalog Providers',
9
+ description: 'Catalog from TMDB streaming providers.',
10
+ resources: ['catalog'],
11
+ types: ['movie', 'series'],
12
+ idPrefixes: ['tt'],
13
+ catalogs: [],
14
+ behaviorHints: {
15
+ configurable: true,
16
+ configurationRequired: false,
17
+ }
18
+ };
19
+
20
+ const getProvider = (providerId) => {
21
+ return new Promise((resolve, reject) => {
22
+ providersDb.get("SELECT * FROM providers WHERE provider_id = ?", [providerId], (err, row) => {
23
+ if (err) {
24
+ reject(err);
25
+ } else if (row) {
26
+ resolve(row);
27
+ } else {
28
+ resolve(null);
29
+ }
30
+ });
31
+ });
32
+ };
33
+
34
+ const getGenres = (type, language) =>
35
+ new Promise((resolve, reject) => {
36
+ const query = `SELECT genre_name FROM genres WHERE media_type = ? AND language = ?`;
37
+ genresDb.all(query, [type, language], (err, rows) => {
38
+ if (err) return reject(err);
39
+ resolve(rows.map(row => row.genre_name));
40
+ });
41
+ });
42
+
43
+ const getCurrentYear = () => new Date().getFullYear();
44
+
45
+ const generateYearIntervals = (startYear = 1880, endYear = getCurrentYear(), interval = 4) => {
46
+ const intervals = [];
47
+ endYear = Math.max(endYear, startYear);
48
+
49
+ for (let year = endYear; year >= startYear; year -= interval) {
50
+ const nextYear = Math.max(year - interval + 1, startYear);
51
+ intervals.push(`${nextYear}-${year}`);
52
+ }
53
+
54
+ const [firstStart, firstEnd] = intervals.length
55
+ ? intervals[intervals.length - 1].split('-').map(Number)
56
+ : [startYear, endYear];
57
+
58
+ if (firstStart > startYear) {
59
+ intervals[intervals.length - 1] = `${startYear}-${firstEnd}`;
60
+ }
61
+
62
+ return intervals.length ? intervals : [`${startYear}-${endYear}`];
63
+ };
64
+
65
+ const generateManifest = async (config) => {
66
+ try {
67
+ const { providers, language, tmdbApiKey, ageRange } = config;
68
+ if (!Array.isArray(providers) || !providers.length) throw new Error('No providers specified.');
69
+
70
+ if (language && !(await checkGenresExistForLanguage(language))) {
71
+ log.debug(`Fetching genres for language: ${language}`);
72
+ await fetchAndStoreGenres(language, tmdbApiKey);
73
+ }
74
+
75
+ const [movieGenres, seriesGenres] = await Promise.all([
76
+ getGenres('movie', language),
77
+ getGenres('tv', language)
78
+ ]);
79
+
80
+ const genreOptions = (genres) => genres.map(genre => genre);
81
+ const yearIntervals = generateYearIntervals();
82
+ const isKidsMode = ageRange && ageRange !== '18+';
83
+
84
+ const providerInfo = await Promise.all(providers.map(providerId => getProvider(providerId)));
85
+ const catalogs = providerInfo.flatMap(provider => {
86
+ if (!provider) return [];
87
+
88
+ const baseCatalogs = [
89
+ { type: 'movie', idSuffix: 'movies', namePrefix: 'Movies' },
90
+ { type: 'series', idSuffix: 'series', namePrefix: 'Series' }
91
+ ];
92
+
93
+ return baseCatalogs.flatMap(base => {
94
+ return ['Popular', 'New'].map(catalogType => ({
95
+ type: base.type,
96
+ id: `tmdb-discover-${base.idSuffix}-${catalogType.toLowerCase()}-${provider.provider_id}`,
97
+ name: `${catalogType} - ${provider.provider_name}`,
98
+ extra: [
99
+ { name: 'genre', isRequired: false, options: genreOptions(base.type === 'movie' ? movieGenres : seriesGenres) },
100
+ { name: "rating", options: ["8-10", "6-8", "4-6", "2-4", "0-2"], isRequired: false },
101
+ { name: "year", options: yearIntervals, isRequired: false },
102
+ { name: 'skip', isRequired: false },
103
+ { name: 'ageRange', value: isKidsMode ? ageRange : '18+' }
104
+ ]
105
+ }));
106
+ });
107
+ });
108
+
109
+ const manifest = {
110
+ ...manifestTemplate,
111
+ catalogs: catalogs
112
+ };
113
+
114
+ return manifest;
115
+ } catch (error) {
116
+ console.error('Error generating manifest:', error);
117
+ throw error;
118
+ }
119
+ };
120
+
121
+ module.exports = generateManifest;
src/helpers/providers.js ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const log = require('../helpers/logger');
2
+ const { providersDb } = require('../helpers/db');
3
+ const { makeRequest } = require('../api/tmdb');
4
+
5
+ async function fetchProvidersFromTMDB(apiKey) {
6
+ try {
7
+ const [movieData, tvData] = await Promise.all([
8
+ makeRequest(`https://api.themoviedb.org/3/watch/providers/movie`, apiKey),
9
+ makeRequest(`https://api.themoviedb.org/3/watch/providers/tv`, apiKey)
10
+ ]);
11
+
12
+ if (!movieData || !tvData) {
13
+ throw new Error('Failed to fetch providers from TMDB');
14
+ }
15
+
16
+ return [...movieData.results, ...tvData.results];
17
+ } catch (error) {
18
+ log.error(`Error fetching providers from TMDB: ${error.message}`);
19
+ throw error;
20
+ }
21
+ }
22
+
23
+ function fetchProvidersFromDatabase() {
24
+ return new Promise((resolve, reject) => {
25
+ providersDb.all(`SELECT * FROM providers`, (err, rows) => {
26
+ if (err) {
27
+ log.error(`Error fetching providers from the database: ${err.message}`);
28
+ return reject(err);
29
+ }
30
+
31
+ log.debug(`Fetched ${rows ? rows.length : 0} providers from the database.`);
32
+
33
+ if (rows && rows.length > 0) {
34
+ const now = new Date();
35
+ const lastFetched = new Date(rows[0].last_fetched);
36
+
37
+ log.debug(`Current time: ${now.toISOString()}, Last fetched: ${lastFetched.toISOString()}`);
38
+
39
+ if (!isNaN(lastFetched.getTime())) {
40
+ const timeDifference = now.getTime() - lastFetched.getTime();
41
+ const twentyFourHoursInMillis = 24 * 60 * 60 * 1000;
42
+
43
+ log.debug(`Time difference: ${timeDifference} ms (${(timeDifference / (1000 * 60)).toFixed(2)} minutes)`);
44
+
45
+ if (timeDifference < twentyFourHoursInMillis) {
46
+ log.info('Providers fetched from the database (less than 24 hours old).');
47
+ return resolve(rows);
48
+ } else {
49
+ log.info(`Providers are older than 24 hours. Time since last fetch: ${(timeDifference / (1000 * 60 * 60)).toFixed(2)} hours.`);
50
+ }
51
+ } else {
52
+ log.error('Invalid date format for last_fetched.');
53
+ }
54
+ } else {
55
+ log.info('No providers found in the database.');
56
+ }
57
+
58
+ resolve(null);
59
+ });
60
+ });
61
+ }
62
+
63
+ function updateProvidersInDatabase(providers) {
64
+ return new Promise((resolve, reject) => {
65
+ const mergedProviders = {};
66
+
67
+ providers.forEach(provider => {
68
+ const { provider_id, provider_name, logo_path, display_priorities } = provider;
69
+ if (!mergedProviders[provider_name]) {
70
+ mergedProviders[provider_name] = {
71
+ provider_id,
72
+ provider_name,
73
+ logo_path,
74
+ display_priorities: JSON.stringify(display_priorities)
75
+ };
76
+ }
77
+ });
78
+
79
+ const uniqueProviders = Object.values(mergedProviders);
80
+
81
+ const insertOrUpdateProvider = `
82
+ INSERT INTO providers (provider_id, provider_name, logo_path, display_priorities, last_fetched)
83
+ VALUES (?, ?, ?, ?, ?)
84
+ ON CONFLICT(provider_id) DO UPDATE SET
85
+ provider_name = excluded.provider_name,
86
+ logo_path = excluded.logo_path,
87
+ display_priorities = excluded.display_priorities,
88
+ last_fetched = excluded.last_fetched;
89
+ `;
90
+
91
+ const currentTimestamp = new Date().toISOString();
92
+ providersDb.serialize(() => {
93
+ const stmt = providersDb.prepare(insertOrUpdateProvider);
94
+ uniqueProviders.forEach(provider => {
95
+ stmt.run(
96
+ provider.provider_id,
97
+ provider.provider_name,
98
+ provider.logo_path,
99
+ provider.display_priorities,
100
+ currentTimestamp,
101
+ (err) => {
102
+ if (err) {
103
+ log.error('Error updating provider in database:', err.message);
104
+ return reject(err);
105
+ }
106
+ log.debug(`Inserted/Updated provider: ${provider.provider_name} (ID: ${provider.provider_id})`);
107
+ }
108
+ );
109
+ });
110
+ stmt.finalize();
111
+ });
112
+
113
+ log.info('Providers successfully updated in the database.');
114
+ resolve(uniqueProviders);
115
+ });
116
+ }
117
+
118
+ async function getProviders(apiKey) {
119
+ const providersFromDb = await fetchProvidersFromDatabase();
120
+ if (providersFromDb) {
121
+ return providersFromDb;
122
+ }
123
+
124
+ const providersFromApi = await fetchProvidersFromTMDB(apiKey);
125
+ const updatedProviders = await updateProvidersInDatabase(providersFromApi);
126
+ return updatedProviders;
127
+ }
128
+
129
+ module.exports = { getProviders };
src/routes/catalog.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const log = require('../helpers/logger');
3
+ const { parseConfigParameters, extractCatalogInfo, getGenreId, fetchDiscoverContent, buildMetas } = require('../helpers/catalog');
4
+
5
+ const router = express.Router();
6
+
7
+ router.get("/:configParameters?/catalog/:type/:id/:extra?.json", async (req, res, next) => {
8
+ const { id, configParameters, type, extra: extraParam } = req.params;
9
+ const extra = extraParam ? decodeURIComponent(extraParam) : '';
10
+ let skip = 0;
11
+
12
+ log.debug(`Received parameters: id=${id}, type=${type}, configParameters=${configParameters}, extra=${extra}`);
13
+
14
+ const parsedConfig = await parseConfigParameters(configParameters);
15
+ const { catalogType, providerId } = extractCatalogInfo(id);
16
+ const providers = [providerId.toString()];
17
+
18
+ if (extra.startsWith('skip=')) {
19
+ const skipValue = parseInt(extra.split('=')[1], 10);
20
+ skip = isNaN(skipValue) ? 0 : skipValue;
21
+ }
22
+
23
+ const yearMatch = extra.match(/year=([^&]+)/);
24
+ const ratingMatch = extra.match(/rating=([^&]+)/);
25
+ const genreMatch = extra.match(/genre=([^&]+)/);
26
+
27
+ let year = yearMatch ? yearMatch[1] : null;
28
+ let rating = ratingMatch ? ratingMatch[1] : null;
29
+ let genre = genreMatch ? genreMatch[1] : null;
30
+
31
+ if (genre) {
32
+ genre = await getGenreId(genre, type);
33
+ }
34
+
35
+ try {
36
+ const sortBy = catalogType === 'movies'
37
+ ? (id.includes('-new') ? 'primary_release_date.desc' : 'popularity.desc')
38
+ : (id.includes('-new') ? 'first_air_date.desc' : 'popularity.desc');
39
+
40
+ const discoverResults = await fetchDiscoverContent(
41
+ catalogType,
42
+ providers,
43
+ parsedConfig.ageRange,
44
+ sortBy,
45
+ genre,
46
+ parsedConfig.tmdbApiKey,
47
+ parsedConfig.language,
48
+ skip,
49
+ parsedConfig.regions,
50
+ year,
51
+ rating
52
+ );
53
+
54
+ let filteredResults = discoverResults.results;
55
+
56
+ if (parsedConfig.filterContentWithoutPoster === 'true') {
57
+ filteredResults = filteredResults.filter(content => content.poster_path);
58
+ }
59
+
60
+ const metas = await buildMetas(filteredResults, catalogType, parsedConfig.language, parsedConfig.rpdbApiKey);
61
+
62
+ res.json({ metas });
63
+ } catch (error) {
64
+ log.error(`Error processing request: ${error.message}`);
65
+ if (!res.headersSent) {
66
+ res.status(500).json({ error: 'Internal Server Error' });
67
+ }
68
+ }
69
+ });
70
+
71
+ module.exports = router;
src/routes/configure.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const path = require('path');
3
+ const log = require('../helpers/logger');
4
+
5
+ const router = express.Router();
6
+
7
+ router.use(express.static(path.join(__dirname, '../../public')));
8
+
9
+ router.get("/", (req, res) => {
10
+ log.info('Redirecting to /configure');
11
+ res.redirect("/configure");
12
+ });
13
+
14
+ router.get("/:configParameters?/configure", (req, res) => {
15
+ log.info(`Sending public/configure.html`);
16
+ res.sendFile(path.join(__dirname, `../../public/configure.html`));
17
+ });
18
+
19
+ module.exports = router;
src/routes/index.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const catalogRoutes = require('./catalog');
3
+ const configureRoutes = require('./configure');
4
+ const manifestRoutes = require('./manifest');
5
+ const posterRoutes = require('./poster');
6
+ const providersRoutes = require('./providers');
7
+ const log = require('../helpers/logger');
8
+
9
+ const router = express.Router();
10
+
11
+ const isBase64 = (str) => {
12
+ try {
13
+ return btoa(atob(str)) === str;
14
+ } catch (err) {
15
+ return false;
16
+ }
17
+ };
18
+
19
+ const decodeBase64Middleware = (req, res, next) => {
20
+ try {
21
+ const pathParts = req.path.split('/');
22
+
23
+ const decodedParts = pathParts.map(part => {
24
+ if (isBase64(part)) {
25
+ try {
26
+ return Buffer.from(part, 'base64').toString('utf8');
27
+ } catch (e) {
28
+ return part;
29
+ }
30
+ } else {
31
+ return part;
32
+ }
33
+ });
34
+
35
+ req.url = decodedParts.join('/');
36
+
37
+ next();
38
+ } catch (error) {
39
+ log.error('Base64 decoding error :', error);
40
+ res.status(400).send('Bad request: Invalid base64 encoding.');
41
+ }
42
+ };
43
+
44
+ router.use(decodeBase64Middleware);
45
+
46
+ router.use((req, res, next) => {
47
+ log.info(`--- Request received ---`);
48
+ log.info(`${req.method} ${req.originalUrl}`);
49
+ next();
50
+ });
51
+
52
+ router.use(catalogRoutes);
53
+ router.use(configureRoutes);
54
+ router.use(manifestRoutes);
55
+ router.use(posterRoutes);
56
+ router.use(providersRoutes);
57
+
58
+ router.use((err, req, res, next) => {
59
+ const errorTime = new Date().toISOString();
60
+ log.error(`${errorTime} - Error: ${err.stack}`);
61
+
62
+ res.status(500).send(`Something broke! If you need help, please provide this timestamp to the developer : ${errorTime}`);
63
+ });
64
+
65
+ module.exports = router;
src/routes/manifest.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const log = require('../helpers/logger');
3
+ const generateManifest = require('../helpers/manifest');
4
+
5
+ const router = express.Router();
6
+
7
+ router.get("/:configParameters?/manifest.json", async (req, res) => {
8
+ const { configParameters } = req.params;
9
+ let config = {};
10
+
11
+ if (configParameters) {
12
+ try {
13
+ config = JSON.parse(decodeURIComponent(configParameters));
14
+ } catch (error) {
15
+ log.error(`Failed to decode configParameters: ${error.message}`, error);
16
+ return res.status(400).json({ error: 'Invalid config parameters' });
17
+ }
18
+ }
19
+
20
+ log.debug(`Manifest request for language: ${config.language}`);
21
+
22
+ try {
23
+ const manifest = await generateManifest(config);
24
+ res.json(manifest);
25
+ } catch (error) {
26
+ log.error(`Error generating manifest: ${error.message}`);
27
+ res.status(500).json({ error: 'Error generating manifest' });
28
+ }
29
+ });
30
+
31
+ module.exports = router;
src/routes/poster.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const path = require('path');
3
+ const fs = require('fs');
4
+ const log = require('../helpers/logger');
5
+
6
+ const router = express.Router();
7
+
8
+ router.get('/poster/:filename', (req, res) => {
9
+ const filePath = path.join(__dirname, '../../db/rpdbPosters', req.params.filename);
10
+
11
+ fs.access(filePath, fs.constants.F_OK, (err) => {
12
+ if (err) {
13
+ log.error(`Poster not found: ${filePath}`);
14
+ res.status(404).send('Poster not found');
15
+ } else {
16
+ res.sendFile(filePath);
17
+ }
18
+ });
19
+ });
20
+
21
+ module.exports = router;
src/routes/providers.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const log = require('../helpers/logger');
3
+ const { getProviders } = require('../helpers/providers');
4
+
5
+ const router = express.Router();
6
+
7
+ router.post('/fetch-providers', async (req, res) => {
8
+ const { apiKey } = req.body;
9
+
10
+ if (!apiKey) {
11
+ return res.status(400).json({ error: 'API key is required' });
12
+ }
13
+
14
+ try {
15
+ const providers = await getProviders(apiKey);
16
+ return res.json(providers);
17
+ } catch (error) {
18
+ log.error(`Error fetching providers: ${error.message}`);
19
+ return res.status(500).json({ error: 'Failed to fetch providers' });
20
+ }
21
+ });
22
+
23
+ module.exports = router;