Delete src
Browse files- src/api/fanart.js +0 -40
- src/api/rpdb.js +0 -35
- src/api/tmdb.js +0 -68
- src/api/trakt.js +0 -594
- src/helpers/bottleneck.js +0 -14
- src/helpers/bottleneck_tmdb.js +0 -14
- src/helpers/bottleneck_trakt.js +0 -23
- src/helpers/cache.js +0 -68
- src/helpers/catalog.js +0 -196
- src/helpers/db.js +0 -65
- src/helpers/logger.js +0 -65
- src/helpers/manifest.js +0 -145
- src/helpers/providers.js +0 -122
- src/helpers/redis.js +0 -68
- src/helpers/stream.js +0 -72
- src/helpers/trakt.js +0 -56
- src/routes/catalog.js +0 -303
- src/routes/configure.js +0 -26
- src/routes/index.js +0 -82
- src/routes/manifest.js +0 -123
- src/routes/poster.js +0 -21
- src/routes/providers.js +0 -23
- src/routes/stream.js +0 -74
- src/routes/trakt.js +0 -115
src/api/fanart.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
const axios = require('axios');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
|
| 4 |
-
const getFanartLogo = async (tmdbId, preferredLang, fanartApiKey) => {
|
| 5 |
-
try {
|
| 6 |
-
const url = `https://webservice.fanart.tv/v3/movies/${tmdbId}/?api_key=${fanartApiKey}`;
|
| 7 |
-
|
| 8 |
-
log.debug(`Fetching Fanart logos from: ${url}`);
|
| 9 |
-
|
| 10 |
-
const response = await axios.get(url);
|
| 11 |
-
const logos = response.data.hdmovielogo || [];
|
| 12 |
-
|
| 13 |
-
log.debug(`Logos fetched: ${JSON.stringify(logos)}`);
|
| 14 |
-
|
| 15 |
-
const preferredLangLogos = logos.filter(logo => logo.lang === preferredLang);
|
| 16 |
-
log.debug(`Logos in preferred language (${preferredLang}): ${JSON.stringify(preferredLangLogos)}`);
|
| 17 |
-
|
| 18 |
-
const bestLogoInPreferredLang = preferredLangLogos.sort((a, b) => b.likes - a.likes)[0];
|
| 19 |
-
log.debug(`Best logo in preferred language: ${JSON.stringify(bestLogoInPreferredLang)}`);
|
| 20 |
-
|
| 21 |
-
if (!bestLogoInPreferredLang) {
|
| 22 |
-
const englishLogos = logos.filter(logo => logo.lang === 'en');
|
| 23 |
-
log.debug(`Logos in English: ${JSON.stringify(englishLogos)}`);
|
| 24 |
-
|
| 25 |
-
const bestLogoInEnglish = englishLogos.sort((a, b) => b.likes - a.likes)[0];
|
| 26 |
-
log.debug(`Best logo in English: ${JSON.stringify(bestLogoInEnglish)}`);
|
| 27 |
-
|
| 28 |
-
return bestLogoInEnglish ? bestLogoInEnglish.url.replace('http://', 'https://') : '';
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
const bestLogoUrl = bestLogoInPreferredLang.url.replace('http://', 'https://');
|
| 32 |
-
log.debug(`Best logo URL: ${bestLogoUrl}`);
|
| 33 |
-
return bestLogoUrl;
|
| 34 |
-
} catch (error) {
|
| 35 |
-
log.error(`Error fetching logos from Fanart.tv for TMDB ID ${tmdbId}:`, error.message);
|
| 36 |
-
return '';
|
| 37 |
-
}
|
| 38 |
-
};
|
| 39 |
-
|
| 40 |
-
module.exports = { getFanartLogo };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/api/rpdb.js
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
const axios = require('axios');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const { getCachedPoster, setCachedPoster } = require('../helpers/cache');
|
| 4 |
-
|
| 5 |
-
async function getRpdbPosterUrl(type, id, language, rpdbApiKey) {
|
| 6 |
-
const posterId = `poster:${id}`;
|
| 7 |
-
const tier = rpdbApiKey.split("-")[0];
|
| 8 |
-
const lang = language.split("-")[0];
|
| 9 |
-
const baseUrl = `https://api.ratingposterdb.com/${rpdbApiKey}/tmdb/poster-default/${type}-${id}.jpg?fallback=true`;
|
| 10 |
-
const rpdbImageUrl = (tier === "t0" || tier === "t1") ? baseUrl : `${baseUrl}&lang=${lang}`;
|
| 11 |
-
|
| 12 |
-
const cachedPoster = await getCachedPoster(posterId);
|
| 13 |
-
if (cachedPoster) {
|
| 14 |
-
log.debug(`Using cached RPDB poster for ID ${posterId}`);
|
| 15 |
-
return cachedPoster.poster_url;
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
try {
|
| 19 |
-
const response = await axios.head(rpdbImageUrl);
|
| 20 |
-
if (response.status === 200) {
|
| 21 |
-
log.debug(`RPDB poster found for ID ${posterId}`);
|
| 22 |
-
await setCachedPoster(posterId, rpdbImageUrl);
|
| 23 |
-
return rpdbImageUrl;
|
| 24 |
-
}
|
| 25 |
-
} catch (error) {
|
| 26 |
-
log.warn(`RPDB poster not found for ID ${posterId}, falling back to TMDB: ${error.message}`);
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
return null;
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
module.exports = {
|
| 34 |
-
getRpdbPosterUrl
|
| 35 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/api/tmdb.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
| 1 |
-
const axios = require('axios');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const addToQueueTMDB = require('../helpers/bottleneck_tmdb');
|
| 4 |
-
const { safeRedisCall } = require('../helpers/redis');
|
| 5 |
-
const { parseCacheDuration } = require('../helpers/cache');
|
| 6 |
-
|
| 7 |
-
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
|
| 8 |
-
|
| 9 |
-
const generateRedisKey = (tmdbId, type, language) => {
|
| 10 |
-
return `tmdb:${type}:${tmdbId}:${language}`;
|
| 11 |
-
};
|
| 12 |
-
|
| 13 |
-
const formatRuntime = (runtime) => {
|
| 14 |
-
if (!runtime) return null;
|
| 15 |
-
|
| 16 |
-
const hours = Math.floor(runtime / 60);
|
| 17 |
-
const minutes = runtime % 60;
|
| 18 |
-
|
| 19 |
-
if (hours > 0 && minutes > 0) {
|
| 20 |
-
return `${hours}h${minutes.toString().padStart(2, '0')}`;
|
| 21 |
-
} else if (hours > 0) {
|
| 22 |
-
return `${hours}h`;
|
| 23 |
-
} else {
|
| 24 |
-
return `${minutes}m`;
|
| 25 |
-
}
|
| 26 |
-
};
|
| 27 |
-
|
| 28 |
-
const getMetadataByTmdbId = async (tmdbId, type, tmdbApiKey, language = 'en-US') => {
|
| 29 |
-
const redisKey = generateRedisKey(tmdbId, type, language);
|
| 30 |
-
const endpoint = `${TMDB_BASE_URL}/${type}/${tmdbId}?language=${language}&api_key=${tmdbApiKey}`;
|
| 31 |
-
|
| 32 |
-
try {
|
| 33 |
-
const cachedData = await safeRedisCall('get', redisKey);
|
| 34 |
-
if (cachedData) {
|
| 35 |
-
log.debug(`TMDB data for ${type} with ID ${tmdbId} in language ${language} found in cache.`);
|
| 36 |
-
return JSON.parse(cachedData);
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
const response = await addToQueueTMDB({
|
| 40 |
-
fn: () => axios.get(endpoint)
|
| 41 |
-
});
|
| 42 |
-
|
| 43 |
-
const data = response.data;
|
| 44 |
-
|
| 45 |
-
const result = {
|
| 46 |
-
title: data.title || data.name,
|
| 47 |
-
poster: data.poster_path ? `https://image.tmdb.org/t/p/w500${data.poster_path}` : null,
|
| 48 |
-
description: data.overview,
|
| 49 |
-
releaseDate: (data.release_date || data.first_air_date || '').slice(0, 4),
|
| 50 |
-
lastAirDate: data.last_air_date ? data.last_air_date.slice(0, 4) : null,
|
| 51 |
-
imdbRating: data.vote_average ? data.vote_average.toFixed(1) : null,
|
| 52 |
-
genres: data.genres ? data.genres.map(genre => genre.name) : [],
|
| 53 |
-
runtime: formatRuntime(data.runtime)
|
| 54 |
-
};
|
| 55 |
-
|
| 56 |
-
const cacheDuration = parseCacheDuration(process.env.TMDB_CACHE_DURATION || '1d');
|
| 57 |
-
await safeRedisCall('set', redisKey, JSON.stringify(result), 'EX', cacheDuration);
|
| 58 |
-
|
| 59 |
-
log.debug(`TMDB API request successful for ${type} with ID ${tmdbId} in language ${language}. Data cached.`);
|
| 60 |
-
|
| 61 |
-
return result;
|
| 62 |
-
} catch (error) {
|
| 63 |
-
log.error(`Error fetching TMDB details for ${type} with ID ${tmdbId}: ${error.message}`);
|
| 64 |
-
throw error;
|
| 65 |
-
}
|
| 66 |
-
};
|
| 67 |
-
|
| 68 |
-
module.exports = { getMetadataByTmdbId };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/api/trakt.js
DELETED
|
@@ -1,594 +0,0 @@
|
|
| 1 |
-
const axios = require('axios');
|
| 2 |
-
const { pool } = require('../helpers/db');
|
| 3 |
-
const log = require('../helpers/logger');
|
| 4 |
-
const { addToQueueGET, addToQueuePOST } = require('../helpers/bottleneck_trakt');
|
| 5 |
-
const { safeRedisCall } = require('../helpers/redis');
|
| 6 |
-
const { parseCacheDuration } = require('../helpers/cache');
|
| 7 |
-
|
| 8 |
-
const TRAKT_BASE_URL = 'https://api.trakt.tv';
|
| 9 |
-
const TRAKT_API_VERSION = '2';
|
| 10 |
-
const TRAKT_API_KEY = process.env.TRAKT_CLIENT_ID;
|
| 11 |
-
const TRAKT_CLIENT_SECRET = process.env.TRAKT_CLIENT_SECRET;
|
| 12 |
-
const TRAKT_REDIRECT_URI = `${process.env.BASE_URL}/callback`;
|
| 13 |
-
|
| 14 |
-
const makeGetRequest = (url, accessToken = null) => {
|
| 15 |
-
const headers = {
|
| 16 |
-
'trakt-api-version': TRAKT_API_VERSION,
|
| 17 |
-
'trakt-api-key': TRAKT_API_KEY,
|
| 18 |
-
};
|
| 19 |
-
|
| 20 |
-
if (accessToken) {
|
| 21 |
-
headers.Authorization = `Bearer ${accessToken}`;
|
| 22 |
-
} else {
|
| 23 |
-
log.debug(`No access token provided, making unauthenticated request.`);
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
const cacheKey = `trakt:GET:${accessToken || 'public'}:${url}`;
|
| 27 |
-
|
| 28 |
-
return new Promise(async (resolve, reject) => {
|
| 29 |
-
const cachedData = await safeRedisCall('get', cacheKey);
|
| 30 |
-
if (cachedData) {
|
| 31 |
-
log.debug(`Cache hit for URL: ${url}`);
|
| 32 |
-
return resolve(JSON.parse(cachedData));
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
addToQueueGET({
|
| 36 |
-
fn: () => axios.get(url, { headers })
|
| 37 |
-
.then(async (response) => {
|
| 38 |
-
log.debug(`API GET request successful for URL: ${url}`);
|
| 39 |
-
|
| 40 |
-
const cacheDuration = parseCacheDuration(process.env.TRAKT_CACHE_DURATION || '1d');
|
| 41 |
-
await safeRedisCall('set', cacheKey, JSON.stringify(response.data), 'EX', cacheDuration);
|
| 42 |
-
|
| 43 |
-
resolve(response.data);
|
| 44 |
-
})
|
| 45 |
-
.catch(error => {
|
| 46 |
-
if (error.response && error.response.status === 401) {
|
| 47 |
-
log.warn(`Unauthorized request (401) during API GET request for URL: ${url} - ${error.message}`);
|
| 48 |
-
} else {
|
| 49 |
-
log.error(`Error during API GET request for URL: ${url} - ${error.message}`);
|
| 50 |
-
}
|
| 51 |
-
reject(error);
|
| 52 |
-
})
|
| 53 |
-
});
|
| 54 |
-
});
|
| 55 |
-
};
|
| 56 |
-
|
| 57 |
-
const makePostRequest = (url, data, accessToken = null) => {
|
| 58 |
-
const headers = {
|
| 59 |
-
'trakt-api-version': TRAKT_API_VERSION,
|
| 60 |
-
'trakt-api-key': TRAKT_API_KEY,
|
| 61 |
-
'Content-Type': 'application/json',
|
| 62 |
-
};
|
| 63 |
-
|
| 64 |
-
if (accessToken) {
|
| 65 |
-
headers.Authorization = `Bearer ${accessToken}`;
|
| 66 |
-
}
|
| 67 |
-
|
| 68 |
-
const cacheKey = `trakt:POST:${accessToken || 'public'}:${url}:${JSON.stringify(data)}`;
|
| 69 |
-
|
| 70 |
-
return new Promise(async (resolve, reject) => {
|
| 71 |
-
const cachedData = await safeRedisCall('get', cacheKey);
|
| 72 |
-
if (cachedData) {
|
| 73 |
-
log.debug(`Cache hit for POST URL: ${url}`);
|
| 74 |
-
return resolve(JSON.parse(cachedData));
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
addToQueuePOST({
|
| 78 |
-
fn: () => axios.post(url, data, { headers })
|
| 79 |
-
.then(async (response) => {
|
| 80 |
-
log.debug(`API POST request successful for URL: ${url}`);
|
| 81 |
-
|
| 82 |
-
const cacheDuration = parseCacheDuration(process.env.TRAKT_CACHE_DURATION || '1d');
|
| 83 |
-
await safeRedisCall('set', cacheKey, JSON.stringify(response.data), 'EX', cacheDuration);
|
| 84 |
-
|
| 85 |
-
resolve(response.data);
|
| 86 |
-
})
|
| 87 |
-
.catch(error => {
|
| 88 |
-
log.error(`Error during API POST request for URL: ${url} - ${error.message}`);
|
| 89 |
-
reject(error);
|
| 90 |
-
})
|
| 91 |
-
});
|
| 92 |
-
});
|
| 93 |
-
};
|
| 94 |
-
|
| 95 |
-
const exchangeCodeForToken = async (code) => {
|
| 96 |
-
try {
|
| 97 |
-
const response = await makePostRequest(`${TRAKT_BASE_URL}/oauth/token`, {
|
| 98 |
-
code: code,
|
| 99 |
-
client_id: TRAKT_API_KEY,
|
| 100 |
-
client_secret: TRAKT_CLIENT_SECRET,
|
| 101 |
-
redirect_uri: TRAKT_REDIRECT_URI,
|
| 102 |
-
grant_type: 'authorization_code',
|
| 103 |
-
});
|
| 104 |
-
|
| 105 |
-
return response;
|
| 106 |
-
} catch (error) {
|
| 107 |
-
log.error(`Error exchanging authorization code for token: ${error.message}`);
|
| 108 |
-
throw error;
|
| 109 |
-
}
|
| 110 |
-
};
|
| 111 |
-
|
| 112 |
-
const fetchData = async (endpoint, params = {}, accessToken = null) => {
|
| 113 |
-
const queryString = new URLSearchParams(params).toString();
|
| 114 |
-
const url = `${TRAKT_BASE_URL}${endpoint}?${queryString}`;
|
| 115 |
-
|
| 116 |
-
try {
|
| 117 |
-
const data = await makeGetRequest(url, accessToken);
|
| 118 |
-
log.debug(`Data successfully retrieved from URL: ${url}`);
|
| 119 |
-
return data;
|
| 120 |
-
} catch (error) {
|
| 121 |
-
throw error;
|
| 122 |
-
}
|
| 123 |
-
};
|
| 124 |
-
|
| 125 |
-
const refreshTraktToken = async (refreshToken) => {
|
| 126 |
-
const payload = {
|
| 127 |
-
refresh_token: refreshToken,
|
| 128 |
-
client_id: TRAKT_API_KEY,
|
| 129 |
-
client_secret: TRAKT_CLIENT_SECRET,
|
| 130 |
-
redirect_uri: TRAKT_REDIRECT_URI,
|
| 131 |
-
grant_type: 'refresh_token'
|
| 132 |
-
};
|
| 133 |
-
|
| 134 |
-
try {
|
| 135 |
-
const data = await makePostRequest('https://api.trakt.tv/oauth/token', payload);
|
| 136 |
-
log.debug('Token refreshed successfully');
|
| 137 |
-
return data;
|
| 138 |
-
} catch (error) {
|
| 139 |
-
if (error.response) {
|
| 140 |
-
log.error(`Failed to refresh token: ${JSON.stringify(error.response.data)}`);
|
| 141 |
-
} else {
|
| 142 |
-
log.error(`Failed to refresh token: ${error.message}`);
|
| 143 |
-
}
|
| 144 |
-
throw error;
|
| 145 |
-
}
|
| 146 |
-
};
|
| 147 |
-
|
| 148 |
-
const updateTokensInDb = async (username, newAccessToken, newRefreshToken) => {
|
| 149 |
-
await pool.query(
|
| 150 |
-
'UPDATE trakt_tokens SET access_token = $1, refresh_token = $2 WHERE username = $3',
|
| 151 |
-
[newAccessToken, newRefreshToken, username]
|
| 152 |
-
);
|
| 153 |
-
};
|
| 154 |
-
|
| 155 |
-
const fetchUserHistory = async (username, type, accessToken) => {
|
| 156 |
-
const endpoint = `/users/${username}/watched/${type}`;
|
| 157 |
-
|
| 158 |
-
try {
|
| 159 |
-
return await fetchData(endpoint, {}, accessToken);
|
| 160 |
-
} catch (error) {
|
| 161 |
-
if (error.response && error.response.status === 401) {
|
| 162 |
-
throw new Error('token_expired');
|
| 163 |
-
} else {
|
| 164 |
-
throw error;
|
| 165 |
-
}
|
| 166 |
-
}
|
| 167 |
-
};
|
| 168 |
-
|
| 169 |
-
async function handleTraktHistory(parsedConfig, filteredResults, type) {
|
| 170 |
-
const traktUsername = parsedConfig.traktUsername;
|
| 171 |
-
const watchedEmoji = parsedConfig.watchedEmoji || '✔️';
|
| 172 |
-
const fetchInterval = process.env.TRAKT_HISTORY_FETCH_INTERVAL || '24h';
|
| 173 |
-
|
| 174 |
-
const dbType = type === 'movies' ? 'movie' : type === 'series' ? 'show' : type;
|
| 175 |
-
|
| 176 |
-
const intervalInMs = (() => {
|
| 177 |
-
const intervalValue = parseInt(fetchInterval.slice(0, -1), 10);
|
| 178 |
-
const intervalUnit = fetchInterval.slice(-1);
|
| 179 |
-
|
| 180 |
-
switch (intervalUnit) {
|
| 181 |
-
case 'h':
|
| 182 |
-
return intervalValue * 60 * 60 * 1000;
|
| 183 |
-
case 'd':
|
| 184 |
-
return intervalValue * 24 * 60 * 60 * 1000;
|
| 185 |
-
default:
|
| 186 |
-
throw new Error(`Invalid time unit in TRAKT_HISTORY_FETCH_INTERVAL: ${fetchInterval}`);
|
| 187 |
-
}
|
| 188 |
-
})();
|
| 189 |
-
|
| 190 |
-
const result = await pool.query(
|
| 191 |
-
`SELECT last_fetched_at FROM trakt_tokens WHERE username = $1`,
|
| 192 |
-
[traktUsername]
|
| 193 |
-
);
|
| 194 |
-
|
| 195 |
-
const lastFetchedRow = result.rows[0];
|
| 196 |
-
const lastFetchedAt = lastFetchedRow ? new Date(lastFetchedRow.last_fetched_at) : null;
|
| 197 |
-
const now = new Date();
|
| 198 |
-
|
| 199 |
-
if (!lastFetchedAt || (now - lastFetchedAt) >= intervalInMs) {
|
| 200 |
-
try {
|
| 201 |
-
const tokensResult = await pool.query(
|
| 202 |
-
`SELECT access_token, refresh_token FROM trakt_tokens WHERE username = $1`,
|
| 203 |
-
[traktUsername]
|
| 204 |
-
);
|
| 205 |
-
|
| 206 |
-
const tokensRow = tokensResult.rows[0];
|
| 207 |
-
if (tokensRow) {
|
| 208 |
-
let { access_token, refresh_token } = tokensRow;
|
| 209 |
-
|
| 210 |
-
try {
|
| 211 |
-
const [movieHistory, showHistory] = await Promise.all([
|
| 212 |
-
fetchUserHistory(traktUsername, 'movies', access_token),
|
| 213 |
-
fetchUserHistory(traktUsername, 'shows', access_token)
|
| 214 |
-
]);
|
| 215 |
-
|
| 216 |
-
await Promise.all([
|
| 217 |
-
saveUserWatchedHistory(traktUsername, movieHistory),
|
| 218 |
-
saveUserWatchedHistory(traktUsername, showHistory)
|
| 219 |
-
]);
|
| 220 |
-
} catch (error) {
|
| 221 |
-
if (error.message === 'token_expired') {
|
| 222 |
-
log.warn(`Token expired for user ${traktUsername}, refreshing token...`);
|
| 223 |
-
|
| 224 |
-
const newTokens = await refreshTraktToken(refresh_token);
|
| 225 |
-
access_token = newTokens.access_token;
|
| 226 |
-
refresh_token = newTokens.refresh_token;
|
| 227 |
-
|
| 228 |
-
await updateTokensInDb(traktUsername, newTokens.access_token, newTokens.refresh_token);
|
| 229 |
-
|
| 230 |
-
const [movieHistory, showHistory] = await Promise.all([
|
| 231 |
-
fetchUserHistory(traktUsername, 'movies', newTokens.access_token),
|
| 232 |
-
fetchUserHistory(traktUsername, 'shows', newTokens.access_token)
|
| 233 |
-
]);
|
| 234 |
-
|
| 235 |
-
await Promise.all([
|
| 236 |
-
saveUserWatchedHistory(traktUsername, movieHistory),
|
| 237 |
-
saveUserWatchedHistory(traktUsername, showHistory)
|
| 238 |
-
]);
|
| 239 |
-
} else {
|
| 240 |
-
throw error;
|
| 241 |
-
}
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
-
await pool.query(
|
| 245 |
-
`UPDATE trakt_tokens SET last_fetched_at = $1 WHERE username = $2`,
|
| 246 |
-
[now.toISOString(), traktUsername]
|
| 247 |
-
);
|
| 248 |
-
}
|
| 249 |
-
} catch (error) {
|
| 250 |
-
log.error(`Error fetching Trakt history for user ${traktUsername}: ${error.message}`);
|
| 251 |
-
}
|
| 252 |
-
}
|
| 253 |
-
|
| 254 |
-
const traktIdsResult = await pool.query(
|
| 255 |
-
`SELECT imdb_id FROM trakt_history WHERE username = $1 AND type = $2 AND imdb_id IS NOT NULL`,
|
| 256 |
-
[traktUsername, dbType]
|
| 257 |
-
);
|
| 258 |
-
|
| 259 |
-
log.debug(`Fetching Trakt history for user ${traktUsername} with type ${dbType}. Result: ${traktIdsResult.rows.length} items found.`);
|
| 260 |
-
const traktIds = traktIdsResult.rows.map(row => `${row.imdb_id}`);
|
| 261 |
-
|
| 262 |
-
return filteredResults.map(content => {
|
| 263 |
-
const contentId = `${content.id}`;
|
| 264 |
-
if (traktIds.includes(contentId)) {
|
| 265 |
-
content.name = `${watchedEmoji} ${content.name || content.title}`;
|
| 266 |
-
}
|
| 267 |
-
return content;
|
| 268 |
-
});
|
| 269 |
-
}
|
| 270 |
-
|
| 271 |
-
const saveUserWatchedHistory = async (username, history) => {
|
| 272 |
-
if (!history || history.length === 0) {
|
| 273 |
-
log.warn(`No history to save for user ${username}.`);
|
| 274 |
-
return;
|
| 275 |
-
}
|
| 276 |
-
|
| 277 |
-
const client = await pool.connect();
|
| 278 |
-
try {
|
| 279 |
-
await client.query('BEGIN');
|
| 280 |
-
|
| 281 |
-
for (const item of history) {
|
| 282 |
-
const media = item.movie || item.show;
|
| 283 |
-
const mediaId = media.ids.imdb || media.ids.tmdb;
|
| 284 |
-
const mediaType = item.movie ? 'movie' : 'show';
|
| 285 |
-
const watchedAt = item.last_watched_at;
|
| 286 |
-
const title = media.title;
|
| 287 |
-
|
| 288 |
-
const historyResult = await client.query(
|
| 289 |
-
`SELECT id FROM trakt_history WHERE username = $1 AND imdb_id = $2`,
|
| 290 |
-
[username, media.ids.imdb]
|
| 291 |
-
);
|
| 292 |
-
|
| 293 |
-
if (historyResult.rows.length > 0) {
|
| 294 |
-
await client.query(
|
| 295 |
-
`UPDATE trakt_history
|
| 296 |
-
SET watched_at = $1, title = $2, tmdb_id = $3, type = $4
|
| 297 |
-
WHERE id = $5`,
|
| 298 |
-
[watchedAt, title, media.ids.tmdb, mediaType, historyResult.rows[0].id]
|
| 299 |
-
);
|
| 300 |
-
} else {
|
| 301 |
-
await client.query(
|
| 302 |
-
`INSERT INTO trakt_history (username, imdb_id, tmdb_id, type, watched_at, title)
|
| 303 |
-
VALUES ($1, $2, $3, $4, $5, $6)`,
|
| 304 |
-
[username, media.ids.imdb, media.ids.tmdb, mediaType, watchedAt, title]
|
| 305 |
-
);
|
| 306 |
-
}
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
await client.query('COMMIT');
|
| 310 |
-
log.info(`History saved for user ${username}`);
|
| 311 |
-
} catch (err) {
|
| 312 |
-
await client.query('ROLLBACK');
|
| 313 |
-
log.error(`Error committing transaction for user ${username}: ${err.message}`);
|
| 314 |
-
throw err;
|
| 315 |
-
} finally {
|
| 316 |
-
client.release();
|
| 317 |
-
}
|
| 318 |
-
};
|
| 319 |
-
|
| 320 |
-
const fetchUserProfile = async (accessToken) => {
|
| 321 |
-
const endpoint = '/users/me';
|
| 322 |
-
return await fetchData(endpoint, {}, accessToken);
|
| 323 |
-
};
|
| 324 |
-
|
| 325 |
-
async function lookupTraktId(tmdbId, type, accessToken) {
|
| 326 |
-
const url = `${TRAKT_BASE_URL}/search/tmdb/${tmdbId}?type=${type}`;
|
| 327 |
-
|
| 328 |
-
try {
|
| 329 |
-
const response = await makeGetRequest(url, accessToken);
|
| 330 |
-
if (response.length > 0 && response[0].type === type && response[0][type]) {
|
| 331 |
-
const traktId = response[0][type].ids.trakt;
|
| 332 |
-
return traktId;
|
| 333 |
-
} else {
|
| 334 |
-
throw new Error(`No Trakt ID found for TMDB ID ${tmdbId}`);
|
| 335 |
-
}
|
| 336 |
-
} catch (error) {
|
| 337 |
-
log.error(`Error fetching Trakt ID for TMDB ID ${tmdbId}: ${error.message}`);
|
| 338 |
-
throw error;
|
| 339 |
-
}
|
| 340 |
-
}
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
const markContentAsWatched = async (access_token, type, id, watched_at) => {
|
| 344 |
-
const url = `${TRAKT_BASE_URL}/sync/history`;
|
| 345 |
-
|
| 346 |
-
let data = {};
|
| 347 |
-
if (type === 'movies') {
|
| 348 |
-
data = {
|
| 349 |
-
movies: [{ ids: { trakt: id }, watched_at }]
|
| 350 |
-
};
|
| 351 |
-
} else if (type === 'series') {
|
| 352 |
-
data = {
|
| 353 |
-
shows: [{ ids: { trakt: id }, watched_at }]
|
| 354 |
-
};
|
| 355 |
-
}
|
| 356 |
-
|
| 357 |
-
try {
|
| 358 |
-
const response = await makePostRequest(url, data, access_token);
|
| 359 |
-
return response;
|
| 360 |
-
} catch (error) {
|
| 361 |
-
log.error(`Error marking content as watched: ${error.message}`);
|
| 362 |
-
throw error;
|
| 363 |
-
}
|
| 364 |
-
};
|
| 365 |
-
|
| 366 |
-
const fetchTrendingLists = async (page = 1, limit = 10, accessToken = null) => {
|
| 367 |
-
const endpoint = `/lists/trending?page=${page}&limit=${limit}`;
|
| 368 |
-
const response = await fetchData(endpoint, {}, accessToken);
|
| 369 |
-
return response;
|
| 370 |
-
};
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
const fetchPopularLists = async (page = 1, limit = 10, accessToken = null) => {
|
| 374 |
-
const endpoint = `/lists/popular?page=${page}&limit=${limit}`;
|
| 375 |
-
return await fetchData(endpoint, {}, accessToken);
|
| 376 |
-
};
|
| 377 |
-
|
| 378 |
-
const searchLists = async (query, page = 1, limit = 10, accessToken = null) => {
|
| 379 |
-
const endpoint = `/search/list?query=${encodeURIComponent(query)}&page=${page}&limit=${limit}`;
|
| 380 |
-
return await fetchData(endpoint, {}, accessToken);
|
| 381 |
-
};
|
| 382 |
-
|
| 383 |
-
const fetchListById = async (listId, accessToken = null) => {
|
| 384 |
-
const endpoint = `/lists/${listId}`;
|
| 385 |
-
return await fetchData(endpoint, {}, accessToken);
|
| 386 |
-
};
|
| 387 |
-
|
| 388 |
-
const fetchListItems = async (listId, type, page = 1, limit = 20, sortBy = null, sortHow = 'asc', accessToken = null) => {
|
| 389 |
-
const endpoint = `/lists/${listId}/items/movies,shows`;
|
| 390 |
-
|
| 391 |
-
let params = {};
|
| 392 |
-
if (!sortBy) {
|
| 393 |
-
params = { page, limit };
|
| 394 |
-
}
|
| 395 |
-
|
| 396 |
-
log.debug(`Fetching list items from Trakt API with listId: ${listId}, type: ${type}, page: ${page}, limit: ${limit}, sortBy: ${sortBy}, sortHow: ${sortHow}`);
|
| 397 |
-
|
| 398 |
-
try {
|
| 399 |
-
const data = await fetchData(endpoint, params, accessToken);
|
| 400 |
-
|
| 401 |
-
log.debug(`Data successfully retrieved from Trakt API: ${endpoint}`);
|
| 402 |
-
|
| 403 |
-
if (sortBy) {
|
| 404 |
-
data.sort((a, b) => {
|
| 405 |
-
let valueA, valueB;
|
| 406 |
-
|
| 407 |
-
switch (sortBy) {
|
| 408 |
-
case 'rank':
|
| 409 |
-
valueA = a.rank;
|
| 410 |
-
valueB = b.rank;
|
| 411 |
-
break;
|
| 412 |
-
case 'listed_at':
|
| 413 |
-
valueA = new Date(a.listed_at);
|
| 414 |
-
valueB = new Date(b.listed_at);
|
| 415 |
-
break;
|
| 416 |
-
case 'title':
|
| 417 |
-
valueA = (a.movie?.title || a.show?.title || '').toLowerCase();
|
| 418 |
-
valueB = (b.movie?.title || b.show?.title || '').toLowerCase();
|
| 419 |
-
break;
|
| 420 |
-
case 'year':
|
| 421 |
-
valueA = a.movie?.year || a.show?.year || 0;
|
| 422 |
-
valueB = b.movie?.year || b.show?.year || 0;
|
| 423 |
-
break;
|
| 424 |
-
default:
|
| 425 |
-
return 0;
|
| 426 |
-
}
|
| 427 |
-
|
| 428 |
-
if (sortHow === 'desc') {
|
| 429 |
-
return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
|
| 430 |
-
} else {
|
| 431 |
-
return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
|
| 432 |
-
}
|
| 433 |
-
});
|
| 434 |
-
}
|
| 435 |
-
|
| 436 |
-
return data;
|
| 437 |
-
} catch (error) {
|
| 438 |
-
log.error(`Error fetching list items from Trakt API: ${endpoint} - ${error.message}`);
|
| 439 |
-
throw error;
|
| 440 |
-
}
|
| 441 |
-
};
|
| 442 |
-
|
| 443 |
-
const fetchTrendingItems = async (type, page = 1, limit = 20, genre = null) => {
|
| 444 |
-
const convertedType = type === 'movie' ? 'movies' : type === 'series' ? 'shows' : type;
|
| 445 |
-
const endpoint = `/${convertedType}/trending`;
|
| 446 |
-
const params = { page, limit };
|
| 447 |
-
if (genre) {
|
| 448 |
-
params.genres = genre;
|
| 449 |
-
}
|
| 450 |
-
|
| 451 |
-
try {
|
| 452 |
-
log.debug(`Fetching trending items for type: ${type} (converted to ${convertedType}), page: ${page}, limit: ${limit}, genre: ${genre}`);
|
| 453 |
-
const data = await fetchData(endpoint, params);
|
| 454 |
-
log.debug(`Data successfully retrieved for trending ${convertedType}: ${endpoint}`);
|
| 455 |
-
return data;
|
| 456 |
-
} catch (error) {
|
| 457 |
-
log.error(`Error fetching trending ${convertedType}: ${error.message}`);
|
| 458 |
-
throw error;
|
| 459 |
-
}
|
| 460 |
-
};
|
| 461 |
-
|
| 462 |
-
const fetchPopularItems = async (type, page = 1, limit = 20, genre = null) => {
|
| 463 |
-
const convertedType = type === 'movie' ? 'movies' : type === 'series' ? 'shows' : type;
|
| 464 |
-
const endpoint = `/${convertedType}/popular`;
|
| 465 |
-
const params = { page, limit };
|
| 466 |
-
if (genre) {
|
| 467 |
-
params.genres = genre;
|
| 468 |
-
}
|
| 469 |
-
|
| 470 |
-
try {
|
| 471 |
-
log.debug(`Fetching popular items for type: ${type} (converted to ${convertedType}), page: ${page}, limit: ${limit}, genre: ${genre}`);
|
| 472 |
-
const data = await fetchData(endpoint, params);
|
| 473 |
-
log.debug(`Data successfully retrieved for popular ${convertedType}: ${endpoint}`);
|
| 474 |
-
return data;
|
| 475 |
-
} catch (error) {
|
| 476 |
-
log.error(`Error fetching popular ${convertedType}: ${error.message}`);
|
| 477 |
-
throw error;
|
| 478 |
-
}
|
| 479 |
-
};
|
| 480 |
-
|
| 481 |
-
const getAccessTokenForUser = async (username) => {
|
| 482 |
-
try {
|
| 483 |
-
const query = 'SELECT access_token FROM trakt_tokens WHERE username = $1';
|
| 484 |
-
const result = await pool.query(query, [username]);
|
| 485 |
-
|
| 486 |
-
if (result.rows.length === 0) {
|
| 487 |
-
throw new Error(`No access token found for user ${username}`);
|
| 488 |
-
}
|
| 489 |
-
|
| 490 |
-
return result.rows[0].access_token;
|
| 491 |
-
} catch (error) {
|
| 492 |
-
log.error(`Error fetching access token for user ${username}: ${error.message}`);
|
| 493 |
-
throw error;
|
| 494 |
-
}
|
| 495 |
-
};
|
| 496 |
-
|
| 497 |
-
const fetchWatchlistItems = async (username, type = 'movie', page = 1, limit = 20) => {
|
| 498 |
-
try {
|
| 499 |
-
const accessToken = await getAccessTokenForUser(username);
|
| 500 |
-
|
| 501 |
-
const convertedType = type === 'movie' ? 'movies' : type === 'series' ? 'shows' : type;
|
| 502 |
-
const endpoint = `/users/${username}/watchlist/${convertedType}`;
|
| 503 |
-
const params = { page, limit };
|
| 504 |
-
|
| 505 |
-
log.debug(`Fetching watchlist items for user: ${username}, type: ${type} (converted to ${convertedType}), page: ${page}, limit: ${limit}`);
|
| 506 |
-
|
| 507 |
-
const data = await fetchData(endpoint, params, accessToken);
|
| 508 |
-
|
| 509 |
-
log.debug(`Data successfully retrieved for watchlist: ${endpoint}`);
|
| 510 |
-
return data;
|
| 511 |
-
} catch (error) {
|
| 512 |
-
log.error(`Error fetching watchlist for user ${username}: ${error.message}`);
|
| 513 |
-
throw error;
|
| 514 |
-
}
|
| 515 |
-
};
|
| 516 |
-
|
| 517 |
-
const fetchRecommendations = async (username, type = 'movies', ignoreCollected = true, ignoreWatchlisted = true) => {
|
| 518 |
-
try {
|
| 519 |
-
const accessToken = await getAccessTokenForUser(username);
|
| 520 |
-
|
| 521 |
-
const convertedType = type === 'movie' ? 'movies' : type === 'series' ? 'shows' : type;
|
| 522 |
-
const endpoint = `/recommendations/${convertedType}`;
|
| 523 |
-
const params = {
|
| 524 |
-
ignore_collected: ignoreCollected,
|
| 525 |
-
ignore_watchlisted: ignoreWatchlisted,
|
| 526 |
-
limit: 100
|
| 527 |
-
};
|
| 528 |
-
|
| 529 |
-
log.debug(`Fetching recommendations for user: ${username}, type: ${type} (converted to ${convertedType}), limit: 100`);
|
| 530 |
-
|
| 531 |
-
const data = await fetchData(endpoint, params, accessToken);
|
| 532 |
-
|
| 533 |
-
log.debug(`Data successfully retrieved for recommendations: ${endpoint}`);
|
| 534 |
-
return data;
|
| 535 |
-
} catch (error) {
|
| 536 |
-
log.error(`Error fetching recommendations for user ${username}: ${error.message}`);
|
| 537 |
-
throw error;
|
| 538 |
-
}
|
| 539 |
-
};
|
| 540 |
-
|
| 541 |
-
const fetchGenres = async (type) => {
|
| 542 |
-
const endpoint = `/genres/${type}`;
|
| 543 |
-
|
| 544 |
-
try {
|
| 545 |
-
const genresData = await fetchData(endpoint);
|
| 546 |
-
log.debug(`Genres retrieved for ${type}`);
|
| 547 |
-
return genresData;
|
| 548 |
-
} catch (error) {
|
| 549 |
-
log.error(`Error fetching genres from Trakt: ${error.message}`);
|
| 550 |
-
throw error;
|
| 551 |
-
}
|
| 552 |
-
};
|
| 553 |
-
|
| 554 |
-
const storeGenresInDb = async (genres, mediaType) => {
|
| 555 |
-
const client = await pool.connect();
|
| 556 |
-
try {
|
| 557 |
-
await client.query('BEGIN');
|
| 558 |
-
|
| 559 |
-
const insertGenreText = `
|
| 560 |
-
INSERT INTO genres (genre_slug, genre_name, media_type)
|
| 561 |
-
VALUES ($1, $2, $3)
|
| 562 |
-
ON CONFLICT DO NOTHING
|
| 563 |
-
`;
|
| 564 |
-
|
| 565 |
-
for (const genre of genres) {
|
| 566 |
-
await client.query(insertGenreText, [genre.slug, genre.name, mediaType]);
|
| 567 |
-
}
|
| 568 |
-
|
| 569 |
-
await client.query('COMMIT');
|
| 570 |
-
log.info(`Genres stored for ${mediaType}`);
|
| 571 |
-
} catch (err) {
|
| 572 |
-
await client.query('ROLLBACK');
|
| 573 |
-
log.error(`Error inserting genre: ${err.message}`);
|
| 574 |
-
throw err;
|
| 575 |
-
} finally {
|
| 576 |
-
client.release();
|
| 577 |
-
}
|
| 578 |
-
};
|
| 579 |
-
|
| 580 |
-
const fetchAndStoreGenres = async () => {
|
| 581 |
-
try {
|
| 582 |
-
const movieGenres = await fetchGenres('movies');
|
| 583 |
-
const showGenres = await fetchGenres('shows');
|
| 584 |
-
|
| 585 |
-
await storeGenresInDb(movieGenres, 'movie');
|
| 586 |
-
await storeGenresInDb(showGenres, 'series');
|
| 587 |
-
|
| 588 |
-
log.info(`Genres fetched and stored`);
|
| 589 |
-
} catch (error) {
|
| 590 |
-
log.error(`Error fetching/storing genres: ${error.message}`);
|
| 591 |
-
}
|
| 592 |
-
};
|
| 593 |
-
|
| 594 |
-
module.exports = { makeGetRequest, makePostRequest, fetchUserHistory, fetchUserProfile, exchangeCodeForToken, handleTraktHistory, markContentAsWatched, lookupTraktId, saveUserWatchedHistory, fetchTrendingLists, fetchPopularLists, searchLists, fetchListById, fetchListItems, fetchTrendingItems, fetchPopularItems, fetchWatchlistItems, fetchRecommendations, fetchAndStoreGenres };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/bottleneck.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 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/bottleneck_tmdb.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 1 |
-
const Bottleneck = require('bottleneck');
|
| 2 |
-
|
| 3 |
-
const tmdbLimiter = new Bottleneck({
|
| 4 |
-
reservoir: 50,
|
| 5 |
-
reservoirRefreshAmount: 50,
|
| 6 |
-
reservoirRefreshInterval: 1000,
|
| 7 |
-
maxConcurrent: 20
|
| 8 |
-
});
|
| 9 |
-
|
| 10 |
-
const addToQueueTMDB = (task) => {
|
| 11 |
-
return tmdbLimiter.schedule(task.fn);
|
| 12 |
-
};
|
| 13 |
-
|
| 14 |
-
module.exports = addToQueueTMDB;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/bottleneck_trakt.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
| 1 |
-
const Bottleneck = require('bottleneck');
|
| 2 |
-
|
| 3 |
-
const traktLimiterGET = new Bottleneck({
|
| 4 |
-
reservoir: 1000,
|
| 5 |
-
reservoirRefreshAmount: 1000,
|
| 6 |
-
reservoirRefreshInterval: 300 * 1000,
|
| 7 |
-
maxConcurrent: 10
|
| 8 |
-
});
|
| 9 |
-
|
| 10 |
-
const traktLimiterPOST = new Bottleneck({
|
| 11 |
-
minTime: 1000,
|
| 12 |
-
maxConcurrent: 1
|
| 13 |
-
});
|
| 14 |
-
|
| 15 |
-
const addToQueueGET = (task) => {
|
| 16 |
-
return traktLimiterGET.schedule(task.fn);
|
| 17 |
-
};
|
| 18 |
-
|
| 19 |
-
const addToQueuePOST = (task) => {
|
| 20 |
-
return traktLimiterPOST.schedule(task.fn);
|
| 21 |
-
};
|
| 22 |
-
|
| 23 |
-
module.exports = { addToQueueGET, addToQueuePOST };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/cache.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
| 1 |
-
const log = require('../helpers/logger');
|
| 2 |
-
const fs = require('fs');
|
| 3 |
-
const path = require('path');
|
| 4 |
-
const axios = require('axios');
|
| 5 |
-
const { CACHE_POSTER_CONTENT_DURATION_DAYS } = process.env;
|
| 6 |
-
const baseUrl = process.env.BASE_URL || 'http://localhost:7000';
|
| 7 |
-
|
| 8 |
-
const defaultCacheDurationDays = 3;
|
| 9 |
-
|
| 10 |
-
const posterCacheDurationDays = parseInt(CACHE_POSTER_CONTENT_DURATION_DAYS, 10) || defaultCacheDurationDays;
|
| 11 |
-
const posterCacheDurationMillis = posterCacheDurationDays * 24 * 60 * 60 * 1000;
|
| 12 |
-
|
| 13 |
-
log.debug(`Cache duration for posters: ${posterCacheDurationMillis} milliseconds (${posterCacheDurationDays} days)`);
|
| 14 |
-
|
| 15 |
-
const posterDirectory = path.join(__dirname, '../../cache/rpdbPosters');
|
| 16 |
-
|
| 17 |
-
if (!fs.existsSync(posterDirectory)) {
|
| 18 |
-
fs.mkdirSync(posterDirectory, { recursive: true });
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
const formatFileName = (posterId) => {
|
| 22 |
-
return posterId.replace(/[^a-zA-Z0-9-_]/g, '_');
|
| 23 |
-
};
|
| 24 |
-
|
| 25 |
-
const getCachedPoster = async (posterId) => {
|
| 26 |
-
const formattedPosterId = formatFileName(posterId);
|
| 27 |
-
const filePath = path.join(posterDirectory, `${formattedPosterId}.jpg`);
|
| 28 |
-
const fileStats = fs.existsSync(filePath) ? fs.statSync(filePath) : null;
|
| 29 |
-
|
| 30 |
-
if (fileStats && (Date.now() - fileStats.mtimeMs < posterCacheDurationMillis)) {
|
| 31 |
-
const posterUrl = `${baseUrl}/poster/${formattedPosterId}.jpg`;
|
| 32 |
-
log.debug(`Cache hit for poster id ${posterId}, serving from ${posterUrl}`);
|
| 33 |
-
return { poster_url: posterUrl };
|
| 34 |
-
} else {
|
| 35 |
-
log.debug(`Cache miss or expired for poster id ${posterId}`);
|
| 36 |
-
return null;
|
| 37 |
-
}
|
| 38 |
-
};
|
| 39 |
-
|
| 40 |
-
const setCachedPoster = async (posterId, posterUrl) => {
|
| 41 |
-
const formattedPosterId = formatFileName(posterId);
|
| 42 |
-
const filePath = path.join(posterDirectory, `${formattedPosterId}.jpg`);
|
| 43 |
-
|
| 44 |
-
try {
|
| 45 |
-
const response = await axios.get(posterUrl, { responseType: 'arraybuffer' });
|
| 46 |
-
fs.writeFileSync(filePath, response.data);
|
| 47 |
-
log.debug(`Poster id ${posterId} cached at ${filePath}`);
|
| 48 |
-
} catch (error) {
|
| 49 |
-
log.error(`Error caching poster id ${posterId} from URL ${posterUrl}: ${error.message}`);
|
| 50 |
-
throw error;
|
| 51 |
-
}
|
| 52 |
-
};
|
| 53 |
-
|
| 54 |
-
const parseCacheDuration = (duration) => {
|
| 55 |
-
const match = duration.match(/^(\d+)([dh])$/);
|
| 56 |
-
if (!match) {
|
| 57 |
-
throw new Error("Invalid cache duration format. Use '<number>d' for days or '<number>h' for hours.");
|
| 58 |
-
}
|
| 59 |
-
const value = parseInt(match[1], 10);
|
| 60 |
-
const unit = match[2];
|
| 61 |
-
return unit === 'd' ? value * 86400 : value * 3600;
|
| 62 |
-
};
|
| 63 |
-
|
| 64 |
-
module.exports = {
|
| 65 |
-
getCachedPoster,
|
| 66 |
-
setCachedPoster,
|
| 67 |
-
parseCacheDuration
|
| 68 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/catalog.js
DELETED
|
@@ -1,196 +0,0 @@
|
|
| 1 |
-
const axios = require('axios');
|
| 2 |
-
const { pool } = require('./db');
|
| 3 |
-
const { discoverContent } = require('../api/tmdb');
|
| 4 |
-
const { getFanartPoster } = require('../api/fanart');
|
| 5 |
-
const { getCachedPoster, setCachedPoster } = require('../helpers/cache');
|
| 6 |
-
const log = require('../helpers/logger');
|
| 7 |
-
|
| 8 |
-
const baseUrl = process.env.BASE_URL || 'http://localhost:7000';
|
| 9 |
-
|
| 10 |
-
async function parseConfigParameters(configParameters) {
|
| 11 |
-
let parsedConfig = {};
|
| 12 |
-
if (configParameters) {
|
| 13 |
-
try {
|
| 14 |
-
parsedConfig = JSON.parse(decodeURIComponent(configParameters));
|
| 15 |
-
} catch (error) {
|
| 16 |
-
log.error(`Error parsing configParameters: ${error.message}`);
|
| 17 |
-
}
|
| 18 |
-
}
|
| 19 |
-
return parsedConfig;
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
function extractCatalogInfo(id) {
|
| 23 |
-
const match = id.match(/^tmdb-discover-(movies|series)(-new|-popular)?-(\d+)$/);
|
| 24 |
-
if (!match) {
|
| 25 |
-
throw new Error('Invalid catalog id');
|
| 26 |
-
}
|
| 27 |
-
return {
|
| 28 |
-
catalogType: match[1],
|
| 29 |
-
providerId: parseInt(match[3], 10)
|
| 30 |
-
};
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
async function getGenreId(genreName, type) {
|
| 34 |
-
try {
|
| 35 |
-
const result = await pool.query(
|
| 36 |
-
"SELECT genre_id FROM genres WHERE genre_name = $1 AND media_type = $2",
|
| 37 |
-
[genreName, type === 'series' ? 'tv' : 'movie']
|
| 38 |
-
);
|
| 39 |
-
const row = result.rows[0];
|
| 40 |
-
return row ? row.genre_id : null;
|
| 41 |
-
} catch (err) {
|
| 42 |
-
throw err;
|
| 43 |
-
}
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
async function fetchDiscoverContent(catalogType, providers, ageRange, sortBy, genre, tmdbApiKey, language, skip, regions, year = null, rating = null) {
|
| 47 |
-
return await discoverContent(catalogType, providers, ageRange, sortBy, genre, tmdbApiKey, language, skip, regions, year, rating);
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
function getRpdbPoster(type, id, language, rpdbkey) {
|
| 51 |
-
const tier = rpdbkey.split("-")[0];
|
| 52 |
-
const lang = language.split("-")[0];
|
| 53 |
-
const baseUrl = `https://api.ratingposterdb.com/${rpdbkey}/tmdb/poster-default/${type}-${id}.jpg?fallback=true`;
|
| 54 |
-
return (tier === "t0" || tier === "t1") ? baseUrl : `${baseUrl}&lang=${lang}`;
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
async function getPosterUrl(content, catalogType, language, rpdbApiKey) {
|
| 58 |
-
const posterId = `poster:${content.id}`;
|
| 59 |
-
let posterUrl;
|
| 60 |
-
if (rpdbApiKey) {
|
| 61 |
-
const cachedPoster = await getCachedPoster(posterId);
|
| 62 |
-
if (cachedPoster) {
|
| 63 |
-
log.debug(`Using cached poster URL for id ${posterId}`);
|
| 64 |
-
return cachedPoster.poster_url;
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
const rpdbImage = getRpdbPoster(catalogType, content.id, language, rpdbApiKey);
|
| 68 |
-
try {
|
| 69 |
-
const response = await axios.head(rpdbImage);
|
| 70 |
-
if (response.status === 200) {
|
| 71 |
-
log.debug(`RPDB poster found for id ${posterId}`);
|
| 72 |
-
await setCachedPoster(posterId, rpdbImage);
|
| 73 |
-
return rpdbImage;
|
| 74 |
-
}
|
| 75 |
-
} catch (error) {
|
| 76 |
-
log.warn(`Error fetching RPDB poster: ${error.message}. Falling back to TMDB poster.`);
|
| 77 |
-
}
|
| 78 |
-
}
|
| 79 |
-
posterUrl = `https://image.tmdb.org/t/p/w500${content.poster_path}`;
|
| 80 |
-
return posterUrl;
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
async function buildMetas(filteredResults, catalogType, language, rpdbApiKey, fanartApiKey, addWatchedTraktBtn, hideTraktHistory, traktUsername, origin) {
|
| 84 |
-
return await Promise.all(filteredResults.map(async (content) => {
|
| 85 |
-
const posterUrl = await getPosterUrl(content, catalogType, language, rpdbApiKey);
|
| 86 |
-
|
| 87 |
-
let releaseInfo = catalogType === 'movies'
|
| 88 |
-
? content.release_date ? content.release_date.split('-')[0] : ''
|
| 89 |
-
: content.first_air_date
|
| 90 |
-
? content.last_air_date
|
| 91 |
-
? `${content.first_air_date.split('-')[0]}-${content.last_air_date.split('-')[0]}`
|
| 92 |
-
: content.first_air_date.split('-')[0]
|
| 93 |
-
: '';
|
| 94 |
-
|
| 95 |
-
let links = null;
|
| 96 |
-
let imdbRating = null;
|
| 97 |
-
let genres = null;
|
| 98 |
-
let logo = null;
|
| 99 |
-
|
| 100 |
-
if (fanartApiKey) {
|
| 101 |
-
logo = await getFanartPoster(content.id, language, fanartApiKey);
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
if (origin === 'https://web.stremio.com') {
|
| 105 |
-
|
| 106 |
-
links = await buildLinks(content, catalogType, addWatchedTraktBtn, hideTraktHistory, traktUsername, language);
|
| 107 |
-
} else {
|
| 108 |
-
imdbRating = content.vote_average ? content.vote_average.toFixed(1) : null;
|
| 109 |
-
|
| 110 |
-
genres = await Promise.all(
|
| 111 |
-
content.genre_ids.map(async (genreId) => {
|
| 112 |
-
|
| 113 |
-
const genreName = await getGenreName(genreId, catalogType, language);
|
| 114 |
-
return genreName;
|
| 115 |
-
})
|
| 116 |
-
);
|
| 117 |
-
|
| 118 |
-
genres = genres.filter(Boolean);
|
| 119 |
-
}
|
| 120 |
-
|
| 121 |
-
return {
|
| 122 |
-
id: `tmdb:${content.id}`,
|
| 123 |
-
type: catalogType === 'movies' ? 'movie' : 'series',
|
| 124 |
-
name: catalogType === 'movies' ? content.title : content.name,
|
| 125 |
-
poster: posterUrl,
|
| 126 |
-
logo: logo || null,
|
| 127 |
-
background: `https://image.tmdb.org/t/p/w1280${content.backdrop_path}`,
|
| 128 |
-
description: content.overview,
|
| 129 |
-
releaseInfo: releaseInfo || null,
|
| 130 |
-
...(links && { links }),
|
| 131 |
-
...(imdbRating && { imdbRating }),
|
| 132 |
-
...(genres && genres.length > 0 && { genres })
|
| 133 |
-
};
|
| 134 |
-
}));
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
async function buildLinks(content, catalogType, addWatchedTraktBtn, hideTraktHistory, traktUsername, language) {
|
| 138 |
-
const links = [];
|
| 139 |
-
|
| 140 |
-
if (content.genre_ids) {
|
| 141 |
-
for (const genreId of content.genre_ids) {
|
| 142 |
-
try {
|
| 143 |
-
const genreName = await getGenreName(genreId, content.type, language);
|
| 144 |
-
if (genreName) {
|
| 145 |
-
links.push({
|
| 146 |
-
name: genreName,
|
| 147 |
-
category: 'Genres',
|
| 148 |
-
url: `stremio:///discover`
|
| 149 |
-
});
|
| 150 |
-
}
|
| 151 |
-
} catch (error) {
|
| 152 |
-
console.error(`Error fetching genre name for ID ${genreId}: ${error.message}`);
|
| 153 |
-
}
|
| 154 |
-
}
|
| 155 |
-
}
|
| 156 |
-
|
| 157 |
-
if (content.vote_average && content.id) {
|
| 158 |
-
links.push({
|
| 159 |
-
name: content.vote_average.toFixed(1),
|
| 160 |
-
category: 'imdb',
|
| 161 |
-
url: `https://imdb.com/title/tt${content.id}`
|
| 162 |
-
});
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
if (addWatchedTraktBtn && addWatchedTraktBtn.trim() !== '' && hideTraktHistory === 'true' && traktUsername) {
|
| 166 |
-
links.push({
|
| 167 |
-
name: addWatchedTraktBtn,
|
| 168 |
-
category: 'Trakt',
|
| 169 |
-
url: `${baseUrl}/updateWatched/${traktUsername}/${catalogType}/${content.id}`
|
| 170 |
-
});
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
return links;
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
async function getGenreName(genreId, type, language) {
|
| 177 |
-
try {
|
| 178 |
-
const result = await pool.query(
|
| 179 |
-
"SELECT genre_name FROM genres WHERE genre_id = $1 AND media_type = $2 AND language = $3",
|
| 180 |
-
[genreId, type === 'series' ? 'tv' : 'movie', language]
|
| 181 |
-
);
|
| 182 |
-
const row = result.rows[0];
|
| 183 |
-
return row ? row.genre_name : null;
|
| 184 |
-
} catch (err) {
|
| 185 |
-
throw err;
|
| 186 |
-
}
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
module.exports = {
|
| 190 |
-
parseConfigParameters,
|
| 191 |
-
extractCatalogInfo,
|
| 192 |
-
getGenreId,
|
| 193 |
-
fetchDiscoverContent,
|
| 194 |
-
getPosterUrl,
|
| 195 |
-
buildMetas
|
| 196 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/db.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
| 1 |
-
const { Pool } = require('pg');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
|
| 4 |
-
const pool = new Pool({
|
| 5 |
-
user: process.env.DB_USER,
|
| 6 |
-
host: process.env.DB_HOST,
|
| 7 |
-
database: process.env.DB_NAME,
|
| 8 |
-
password: process.env.DB_PASSWORD,
|
| 9 |
-
port: process.env.DB_PORT,
|
| 10 |
-
max: process.env.DB_MAX_CONNECTIONS,
|
| 11 |
-
idleTimeoutMillis: process.env.DB_IDLE_TIMEOUT,
|
| 12 |
-
connectionTimeoutMillis: process.env.DB_CONNECTION_TIMEOUT,
|
| 13 |
-
});
|
| 14 |
-
|
| 15 |
-
const createDatabaseAndTable = async (createTableSQL) => {
|
| 16 |
-
let client;
|
| 17 |
-
try {
|
| 18 |
-
client = await pool.connect();
|
| 19 |
-
const commands = createTableSQL.split(';');
|
| 20 |
-
for (let command of commands) {
|
| 21 |
-
if (command.trim()) {
|
| 22 |
-
await client.query(command);
|
| 23 |
-
log.debug('Table created or already exists');
|
| 24 |
-
}
|
| 25 |
-
}
|
| 26 |
-
} catch (err) {
|
| 27 |
-
log.error('Error executing query', err.stack);
|
| 28 |
-
} finally {
|
| 29 |
-
if (client) client.release();
|
| 30 |
-
}
|
| 31 |
-
};
|
| 32 |
-
|
| 33 |
-
const traktDb = createDatabaseAndTable(
|
| 34 |
-
`CREATE TABLE IF NOT EXISTS trakt_tokens (
|
| 35 |
-
id SERIAL PRIMARY KEY,
|
| 36 |
-
username TEXT UNIQUE,
|
| 37 |
-
access_token TEXT NOT NULL,
|
| 38 |
-
refresh_token TEXT NOT NULL,
|
| 39 |
-
last_fetched_at TIMESTAMP DEFAULT NULL
|
| 40 |
-
);
|
| 41 |
-
CREATE TABLE IF NOT EXISTS trakt_history (
|
| 42 |
-
id SERIAL PRIMARY KEY,
|
| 43 |
-
username TEXT,
|
| 44 |
-
watched_at TIMESTAMP,
|
| 45 |
-
type TEXT,
|
| 46 |
-
title TEXT,
|
| 47 |
-
imdb_id TEXT,
|
| 48 |
-
tmdb_id INTEGER,
|
| 49 |
-
FOREIGN KEY (username) REFERENCES trakt_tokens(username) ON DELETE CASCADE
|
| 50 |
-
);
|
| 51 |
-
CREATE INDEX IF NOT EXISTS idx_trakt_history_username ON trakt_history(username);
|
| 52 |
-
`
|
| 53 |
-
);
|
| 54 |
-
|
| 55 |
-
const genresDb = createDatabaseAndTable(
|
| 56 |
-
`CREATE TABLE IF NOT EXISTS genres (
|
| 57 |
-
genre_slug TEXT,
|
| 58 |
-
genre_name TEXT,
|
| 59 |
-
media_type TEXT,
|
| 60 |
-
PRIMARY KEY (genre_slug, media_type),
|
| 61 |
-
UNIQUE (genre_slug, media_type)
|
| 62 |
-
);`
|
| 63 |
-
);
|
| 64 |
-
|
| 65 |
-
module.exports = { pool };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/logger.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,145 +0,0 @@
|
|
| 1 |
-
const { pool } = require('./db');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const { checkGenresExistForLanguage, fetchAndStoreGenres } = require('../api/tmdb');
|
| 4 |
-
|
| 5 |
-
const addonLogoUrl = `${process.env.BASE_URL}/assets/logo.png`;
|
| 6 |
-
|
| 7 |
-
const manifestTemplate = {
|
| 8 |
-
id: 'community.streamingcatalogproviders',
|
| 9 |
-
version: '1.3.0',
|
| 10 |
-
logo: addonLogoUrl,
|
| 11 |
-
name: 'Streaming Catalog Providers',
|
| 12 |
-
description: 'Catalog from TMDB streaming providers.',
|
| 13 |
-
resources: ['catalog'],
|
| 14 |
-
types: ['movie', 'series'],
|
| 15 |
-
idPrefixes: ['tt'],
|
| 16 |
-
catalogs: [],
|
| 17 |
-
behaviorHints: {
|
| 18 |
-
configurable: true,
|
| 19 |
-
configurationRequired: false,
|
| 20 |
-
}
|
| 21 |
-
};
|
| 22 |
-
|
| 23 |
-
const getProvider = async (providerId) => {
|
| 24 |
-
try {
|
| 25 |
-
const result = await pool.query("SELECT * FROM providers WHERE provider_id = $1", [providerId]);
|
| 26 |
-
const row = result.rows[0];
|
| 27 |
-
return row || null;
|
| 28 |
-
} catch (err) {
|
| 29 |
-
throw err;
|
| 30 |
-
}
|
| 31 |
-
};
|
| 32 |
-
|
| 33 |
-
const getGenres = async (type, language) => {
|
| 34 |
-
try {
|
| 35 |
-
const result = await pool.query(
|
| 36 |
-
"SELECT genre_name FROM genres WHERE media_type = $1 AND language = $2",
|
| 37 |
-
[type, language]
|
| 38 |
-
);
|
| 39 |
-
return result.rows.map(row => row.genre_name);
|
| 40 |
-
} catch (err) {
|
| 41 |
-
throw err;
|
| 42 |
-
}
|
| 43 |
-
};
|
| 44 |
-
|
| 45 |
-
const getCurrentYear = () => new Date().getFullYear();
|
| 46 |
-
|
| 47 |
-
const generateYearIntervals = (startYear = 1880, endYear = getCurrentYear(), interval = 4) => {
|
| 48 |
-
const intervals = [];
|
| 49 |
-
endYear = Math.max(endYear, startYear);
|
| 50 |
-
|
| 51 |
-
for (let year = endYear; year >= startYear; year -= interval) {
|
| 52 |
-
const nextYear = Math.max(year - interval + 1, startYear);
|
| 53 |
-
intervals.push(`${nextYear}-${year}`);
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
const [firstStart, firstEnd] = intervals.length
|
| 57 |
-
? intervals[intervals.length - 1].split('-').map(Number)
|
| 58 |
-
: [startYear, endYear];
|
| 59 |
-
|
| 60 |
-
if (firstStart > startYear) {
|
| 61 |
-
intervals[intervals.length - 1] = `${startYear}-${firstEnd}`;
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
return intervals.length ? intervals : [`${startYear}-${endYear}`];
|
| 65 |
-
};
|
| 66 |
-
|
| 67 |
-
const generateManifest = async (config) => {
|
| 68 |
-
try {
|
| 69 |
-
const { providers, language, tmdbApiKey, ageRange, additionalContent, popularCatalogTitle, newCatalogTitle } = config;
|
| 70 |
-
|
| 71 |
-
if (!Array.isArray(providers) || !providers.length) throw new Error('No providers specified.');
|
| 72 |
-
|
| 73 |
-
if (language && !(await checkGenresExistForLanguage(language))) {
|
| 74 |
-
log.debug(`Fetching genres for language: ${language}`);
|
| 75 |
-
await fetchAndStoreGenres(language, tmdbApiKey);
|
| 76 |
-
}
|
| 77 |
-
|
| 78 |
-
const [movieGenres, seriesGenres] = await Promise.all([
|
| 79 |
-
getGenres('movie', language),
|
| 80 |
-
getGenres('tv', language)
|
| 81 |
-
]);
|
| 82 |
-
|
| 83 |
-
const genreOptions = (genres) => genres.map(genre => genre);
|
| 84 |
-
const yearIntervals = generateYearIntervals();
|
| 85 |
-
const isKidsMode = ageRange && ageRange !== '18+';
|
| 86 |
-
|
| 87 |
-
const providerInfo = await Promise.all(providers.map(providerId => getProvider(providerId)));
|
| 88 |
-
const catalogs = providerInfo.flatMap(provider => {
|
| 89 |
-
if (!provider) return [];
|
| 90 |
-
|
| 91 |
-
const baseCatalogs = [
|
| 92 |
-
{ type: 'movie', idSuffix: 'movies', namePrefix: 'Movies' },
|
| 93 |
-
{ type: 'series', idSuffix: 'series', namePrefix: 'Series' }
|
| 94 |
-
];
|
| 95 |
-
|
| 96 |
-
return baseCatalogs.flatMap(base => {
|
| 97 |
-
return [
|
| 98 |
-
{
|
| 99 |
-
type: base.type,
|
| 100 |
-
id: `tmdb-discover-${base.idSuffix}-popular-${provider.provider_id}`,
|
| 101 |
-
name: `${popularCatalogTitle || 'Popular'} - ${provider.provider_name}`,
|
| 102 |
-
extra: [
|
| 103 |
-
{ name: 'genre', isRequired: false, options: genreOptions(base.type === 'movie' ? movieGenres : seriesGenres) },
|
| 104 |
-
{ name: "rating", options: ["8-10", "6-8", "4-6", "2-4", "0-2"], isRequired: false },
|
| 105 |
-
{ name: "year", options: yearIntervals, isRequired: false },
|
| 106 |
-
{ name: 'skip', isRequired: false },
|
| 107 |
-
{ name: 'ageRange', value: isKidsMode ? ageRange : '18+' }
|
| 108 |
-
]
|
| 109 |
-
},
|
| 110 |
-
{
|
| 111 |
-
type: base.type,
|
| 112 |
-
id: `tmdb-discover-${base.idSuffix}-new-${provider.provider_id}`,
|
| 113 |
-
name: `${newCatalogTitle || 'New'} - ${provider.provider_name}`,
|
| 114 |
-
extra: [
|
| 115 |
-
{ name: 'genre', isRequired: false, options: genreOptions(base.type === 'movie' ? movieGenres : seriesGenres) },
|
| 116 |
-
{ name: "rating", options: ["8-10", "6-8", "4-6", "2-4", "0-2"], isRequired: false },
|
| 117 |
-
{ name: "year", options: yearIntervals, isRequired: false },
|
| 118 |
-
{ name: 'skip', isRequired: false },
|
| 119 |
-
{ name: 'ageRange', value: isKidsMode ? ageRange : '18+' }
|
| 120 |
-
]
|
| 121 |
-
}
|
| 122 |
-
];
|
| 123 |
-
});
|
| 124 |
-
});
|
| 125 |
-
|
| 126 |
-
const resources = ['catalog'];
|
| 127 |
-
if (additionalContent && additionalContent.trim() !== '') {
|
| 128 |
-
resources.push('stream');
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
const manifest = {
|
| 132 |
-
...manifestTemplate,
|
| 133 |
-
catalogs: catalogs,
|
| 134 |
-
resources: resources
|
| 135 |
-
};
|
| 136 |
-
|
| 137 |
-
return manifest;
|
| 138 |
-
} catch (error) {
|
| 139 |
-
console.error('Error generating manifest:', error);
|
| 140 |
-
throw error;
|
| 141 |
-
}
|
| 142 |
-
};
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
module.exports = generateManifest;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/providers.js
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 1 |
-
const log = require('../helpers/logger');
|
| 2 |
-
const { pool } = 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 |
-
async function fetchProvidersFromDatabase() {
|
| 24 |
-
try {
|
| 25 |
-
const result = await pool.query(`SELECT * FROM providers`);
|
| 26 |
-
const rows = result.rows;
|
| 27 |
-
|
| 28 |
-
log.debug(`Fetched ${rows.length} providers from the database.`);
|
| 29 |
-
|
| 30 |
-
if (rows.length > 0) {
|
| 31 |
-
const now = new Date();
|
| 32 |
-
const lastFetched = new Date(rows[0].last_fetched);
|
| 33 |
-
|
| 34 |
-
log.debug(`Current time: ${now.toISOString()}, Last fetched: ${lastFetched.toISOString()}`);
|
| 35 |
-
|
| 36 |
-
if (!isNaN(lastFetched.getTime())) {
|
| 37 |
-
const timeDifference = now.getTime() - lastFetched.getTime();
|
| 38 |
-
const twentyFourHoursInMillis = 24 * 60 * 60 * 1000;
|
| 39 |
-
|
| 40 |
-
log.debug(`Time difference: ${timeDifference} ms (${(timeDifference / (1000 * 60)).toFixed(2)} minutes)`);
|
| 41 |
-
|
| 42 |
-
if (timeDifference < twentyFourHoursInMillis) {
|
| 43 |
-
log.info('Providers fetched from the database (less than 24 hours old).');
|
| 44 |
-
return rows;
|
| 45 |
-
} else {
|
| 46 |
-
log.info(`Providers are older than 24 hours. Time since last fetch: ${(timeDifference / (1000 * 60 * 60)).toFixed(2)} hours.`);
|
| 47 |
-
}
|
| 48 |
-
} else {
|
| 49 |
-
log.error('Invalid date format for last_fetched.');
|
| 50 |
-
}
|
| 51 |
-
} else {
|
| 52 |
-
log.info('No providers found in the database.');
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
return null;
|
| 56 |
-
} catch (err) {
|
| 57 |
-
log.error(`Error fetching providers from the database: ${err.message}`);
|
| 58 |
-
throw err;
|
| 59 |
-
}
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
async function updateProvidersInDatabase(providers) {
|
| 63 |
-
const mergedProviders = {};
|
| 64 |
-
|
| 65 |
-
providers.forEach(provider => {
|
| 66 |
-
const { provider_id, provider_name, logo_path, display_priorities } = provider;
|
| 67 |
-
if (!mergedProviders[provider_name]) {
|
| 68 |
-
mergedProviders[provider_name] = {
|
| 69 |
-
provider_id,
|
| 70 |
-
provider_name,
|
| 71 |
-
logo_path,
|
| 72 |
-
display_priorities: JSON.stringify(display_priorities)
|
| 73 |
-
};
|
| 74 |
-
}
|
| 75 |
-
});
|
| 76 |
-
|
| 77 |
-
const uniqueProviders = Object.values(mergedProviders);
|
| 78 |
-
|
| 79 |
-
const insertOrUpdateProvider = `
|
| 80 |
-
INSERT INTO providers (provider_id, provider_name, logo_path, display_priorities, last_fetched)
|
| 81 |
-
VALUES ($1, $2, $3, $4, $5)
|
| 82 |
-
ON CONFLICT(provider_id) DO UPDATE SET
|
| 83 |
-
provider_name = EXCLUDED.provider_name,
|
| 84 |
-
logo_path = EXCLUDED.logo_path,
|
| 85 |
-
display_priorities = EXCLUDED.display_priorities,
|
| 86 |
-
last_fetched = EXCLUDED.last_fetched;
|
| 87 |
-
`;
|
| 88 |
-
|
| 89 |
-
const currentTimestamp = new Date().toISOString();
|
| 90 |
-
|
| 91 |
-
try {
|
| 92 |
-
for (const provider of uniqueProviders) {
|
| 93 |
-
await pool.query(insertOrUpdateProvider, [
|
| 94 |
-
provider.provider_id,
|
| 95 |
-
provider.provider_name,
|
| 96 |
-
provider.logo_path,
|
| 97 |
-
provider.display_priorities,
|
| 98 |
-
currentTimestamp
|
| 99 |
-
]);
|
| 100 |
-
log.debug(`Inserted/Updated provider: ${provider.provider_name} (ID: ${provider.provider_id})`);
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
log.info('Providers successfully updated in the database.');
|
| 104 |
-
return uniqueProviders;
|
| 105 |
-
} catch (err) {
|
| 106 |
-
log.error('Error updating providers in the database:', err.message);
|
| 107 |
-
throw err;
|
| 108 |
-
}
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
async function getProviders(apiKey) {
|
| 112 |
-
const providersFromDb = await fetchProvidersFromDatabase();
|
| 113 |
-
if (providersFromDb) {
|
| 114 |
-
return providersFromDb;
|
| 115 |
-
}
|
| 116 |
-
|
| 117 |
-
const providersFromApi = await fetchProvidersFromTMDB(apiKey);
|
| 118 |
-
const updatedProviders = await updateProvidersInDatabase(providersFromApi);
|
| 119 |
-
return updatedProviders;
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
module.exports = { getProviders };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/redis.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
| 1 |
-
const { createClient } = require('redis');
|
| 2 |
-
const log = require('./logger');
|
| 3 |
-
|
| 4 |
-
let redisUnavailable = false;
|
| 5 |
-
let hasLoggedError = false;
|
| 6 |
-
|
| 7 |
-
const redisClient = createClient({
|
| 8 |
-
socket: {
|
| 9 |
-
host: process.env.REDIS_HOST || 'localhost',
|
| 10 |
-
port: process.env.REDIS_PORT || 6379,
|
| 11 |
-
},
|
| 12 |
-
password: process.env.REDIS_PASSWORD || null,
|
| 13 |
-
});
|
| 14 |
-
|
| 15 |
-
redisClient.on('ready', () => {
|
| 16 |
-
if (redisUnavailable) {
|
| 17 |
-
redisUnavailable = false;
|
| 18 |
-
hasLoggedError = false;
|
| 19 |
-
log.info('Redis is ready and connected.');
|
| 20 |
-
}
|
| 21 |
-
});
|
| 22 |
-
|
| 23 |
-
redisClient.on('end', () => {
|
| 24 |
-
if (!redisUnavailable) {
|
| 25 |
-
redisUnavailable = true;
|
| 26 |
-
log.warn('Redis connection closed. Marking as unavailable.');
|
| 27 |
-
}
|
| 28 |
-
});
|
| 29 |
-
|
| 30 |
-
redisClient.on('error', (err) => {
|
| 31 |
-
if (!redisUnavailable) {
|
| 32 |
-
redisUnavailable = true;
|
| 33 |
-
}
|
| 34 |
-
if (!hasLoggedError) {
|
| 35 |
-
log.error(`Redis error: ${err}. Marking Redis as unavailable.`);
|
| 36 |
-
hasLoggedError = true;
|
| 37 |
-
}
|
| 38 |
-
});
|
| 39 |
-
|
| 40 |
-
redisClient.connect().catch((err) => {
|
| 41 |
-
if (!hasLoggedError) {
|
| 42 |
-
log.error(`Failed to connect to Redis: ${err}. Disabling Redis cache temporarily.`);
|
| 43 |
-
hasLoggedError = true;
|
| 44 |
-
}
|
| 45 |
-
redisUnavailable = true;
|
| 46 |
-
});
|
| 47 |
-
|
| 48 |
-
const safeRedisCall = async (operation, ...args) => {
|
| 49 |
-
if (redisUnavailable) {
|
| 50 |
-
log.warn('Redis is unavailable, skipping cache operation.');
|
| 51 |
-
return null;
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
try {
|
| 55 |
-
return await redisClient[operation](...args);
|
| 56 |
-
} catch (err) {
|
| 57 |
-
if (!redisUnavailable) {
|
| 58 |
-
redisUnavailable = true;
|
| 59 |
-
log.error(`Redis operation failed: ${err}. Marking Redis as unavailable.`);
|
| 60 |
-
}
|
| 61 |
-
return null;
|
| 62 |
-
}
|
| 63 |
-
};
|
| 64 |
-
|
| 65 |
-
module.exports = {
|
| 66 |
-
redisClient,
|
| 67 |
-
safeRedisCall
|
| 68 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/stream.js
DELETED
|
@@ -1,72 +0,0 @@
|
|
| 1 |
-
const log = require('./logger');
|
| 2 |
-
const { getContentDetailsById, getImdbId } = require('../api/tmdb');
|
| 3 |
-
|
| 4 |
-
const prepareStreams = async (content, apiKey, language, showRating, showTagline, userAgent = '', type) => {
|
| 5 |
-
const today = new Date();
|
| 6 |
-
|
| 7 |
-
if (!Array.isArray(content)) {
|
| 8 |
-
throw new TypeError('Expected content to be an array');
|
| 9 |
-
}
|
| 10 |
-
|
| 11 |
-
const contentDetails = await Promise.all(
|
| 12 |
-
content.map(item => getContentDetailsById(item, type, apiKey, language))
|
| 13 |
-
);
|
| 14 |
-
|
| 15 |
-
const imdbIdResults = await Promise.all(contentDetails.map(async item => {
|
| 16 |
-
return (new Date(item.released) <= today) ? getImdbId(item.id, type, apiKey, language) : null;
|
| 17 |
-
}));
|
| 18 |
-
|
| 19 |
-
const preparedContent = contentDetails.map((item, index) => {
|
| 20 |
-
const rating = showRating ? (item.rating?.toFixed(1) || 'N/A') : '';
|
| 21 |
-
const ratingValue = parseFloat(rating);
|
| 22 |
-
const emoji = ratingValue > 0 ? ratingToEmoji(ratingValue) : '';
|
| 23 |
-
const ratingText = ratingValue > 0 ? `${rating} ${emoji}` : '';
|
| 24 |
-
const voteCountText = showRating && item.vote_count ? ` (${formatVoteCount(item.vote_count)} 👥)` : '';
|
| 25 |
-
|
| 26 |
-
const externalUrl = item.released
|
| 27 |
-
? (new Date(item.released) > today
|
| 28 |
-
? `https://www.themoviedb.org/${type}/${item.id}`
|
| 29 |
-
: userAgent.includes('Stremio')
|
| 30 |
-
? `stremio:///detail/${type}/${imdbIdResults[index] || ''}`
|
| 31 |
-
: `https://web.stremio.com/#/detail/${type}/${imdbIdResults[index] || ''}`)
|
| 32 |
-
: `https://www.themoviedb.org/${type}/${item.id}`;
|
| 33 |
-
|
| 34 |
-
const newLine = '\n';
|
| 35 |
-
const title = `${item.title}${ratingText ? `${newLine}${ratingText}` : ''}${voteCountText ? `${voteCountText}` : ''}${showTagline && item.tagline ? `${newLine}${item.tagline}` : ''}`;
|
| 36 |
-
|
| 37 |
-
return {
|
| 38 |
-
name: item.released ? item.released.match(/^\d{4}/)?.[0] || 'TMDB' : 'TMDB',
|
| 39 |
-
title: title,
|
| 40 |
-
externalUrl: externalUrl,
|
| 41 |
-
rating: rating,
|
| 42 |
-
ratingValue: ratingValue,
|
| 43 |
-
emoji: emoji,
|
| 44 |
-
ratingText: ratingText,
|
| 45 |
-
voteCountText: voteCountText
|
| 46 |
-
};
|
| 47 |
-
});
|
| 48 |
-
|
| 49 |
-
return preparedContent;
|
| 50 |
-
};
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
const formatVoteCount = (voteCount) => {
|
| 54 |
-
if (voteCount >= 1000000) {
|
| 55 |
-
return `${Math.round(voteCount / 1000000)}M`;
|
| 56 |
-
} else if (voteCount >= 1000) {
|
| 57 |
-
return `${Math.round(voteCount / 1000)}k`;
|
| 58 |
-
}
|
| 59 |
-
return voteCount.toString();
|
| 60 |
-
};
|
| 61 |
-
|
| 62 |
-
const ratingToEmoji = (rating) => {
|
| 63 |
-
if (rating >= 9) return '🏆';
|
| 64 |
-
if (rating >= 8) return '🔥';
|
| 65 |
-
if (rating >= 6) return '⭐';
|
| 66 |
-
if (rating >= 5) return '😐';
|
| 67 |
-
return '🥱';
|
| 68 |
-
};
|
| 69 |
-
|
| 70 |
-
module.exports = {
|
| 71 |
-
prepareStreams
|
| 72 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/helpers/trakt.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
| 1 |
-
const { fetchUserHistory } = require('../api/trakt');
|
| 2 |
-
const { pool } = require('./db');
|
| 3 |
-
const log = require('./logger');
|
| 4 |
-
|
| 5 |
-
const saveUserTokens = async (username, accessToken, refreshToken) => {
|
| 6 |
-
try {
|
| 7 |
-
await pool.query(
|
| 8 |
-
`INSERT INTO trakt_tokens (username, access_token, refresh_token)
|
| 9 |
-
VALUES ($1, $2, $3)
|
| 10 |
-
ON CONFLICT (username) DO UPDATE SET access_token = $2, refresh_token = $3`,
|
| 11 |
-
[username, accessToken, refreshToken]
|
| 12 |
-
);
|
| 13 |
-
log.info(`Tokens saved for user ${username}`);
|
| 14 |
-
} catch (err) {
|
| 15 |
-
log.error(`Error saving tokens for user ${username}: ${err.message}`);
|
| 16 |
-
throw err;
|
| 17 |
-
}
|
| 18 |
-
};
|
| 19 |
-
|
| 20 |
-
const fetchUserTokens = async (username) => {
|
| 21 |
-
try {
|
| 22 |
-
const result = await pool.query(
|
| 23 |
-
`SELECT access_token, refresh_token FROM trakt_tokens WHERE username = $1`,
|
| 24 |
-
[username]
|
| 25 |
-
);
|
| 26 |
-
const row = result.rows[0];
|
| 27 |
-
|
| 28 |
-
if (!row) {
|
| 29 |
-
log.warn(`No tokens found for user ${username}`);
|
| 30 |
-
throw new Error(`No tokens found for user ${username}`);
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
return {
|
| 34 |
-
access_token: row.access_token,
|
| 35 |
-
refresh_token: row.refresh_token,
|
| 36 |
-
};
|
| 37 |
-
} catch (err) {
|
| 38 |
-
log.error(`Error fetching tokens for user ${username}: ${err.message}`);
|
| 39 |
-
throw err;
|
| 40 |
-
}
|
| 41 |
-
};
|
| 42 |
-
|
| 43 |
-
const fetchUserWatchedMovies = async (username, accessToken) => {
|
| 44 |
-
return fetchUserHistory(username, 'movies', accessToken);
|
| 45 |
-
};
|
| 46 |
-
|
| 47 |
-
const fetchUserWatchedShows = async (username, accessToken) => {
|
| 48 |
-
return fetchUserHistory(username, 'shows', accessToken);
|
| 49 |
-
};
|
| 50 |
-
|
| 51 |
-
module.exports = {
|
| 52 |
-
saveUserTokens,
|
| 53 |
-
fetchUserWatchedMovies,
|
| 54 |
-
fetchUserWatchedShows,
|
| 55 |
-
fetchUserTokens
|
| 56 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/catalog.js
DELETED
|
@@ -1,303 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const { pool } = require('../helpers/db');
|
| 3 |
-
const log = require('../helpers/logger');
|
| 4 |
-
const { fetchListItems, fetchWatchlistItems, fetchRecommendations, fetchTrendingItems, fetchPopularItems, handleTraktHistory } = require('../api/trakt');
|
| 5 |
-
const { getMetadataByTmdbId } = require('../api/tmdb');
|
| 6 |
-
const { getFanartLogo } = require('../api/fanart');
|
| 7 |
-
const { getRpdbPosterUrl } = require('../api/rpdb');
|
| 8 |
-
|
| 9 |
-
const getGenreSlug = async (genreName, mediaType) => {
|
| 10 |
-
try {
|
| 11 |
-
const result = await pool.query(
|
| 12 |
-
"SELECT genre_slug FROM genres WHERE genre_name = $1 AND media_type = $2",
|
| 13 |
-
[genreName, mediaType]
|
| 14 |
-
);
|
| 15 |
-
return result.rows.length ? result.rows[0].genre_slug : null;
|
| 16 |
-
} catch (err) {
|
| 17 |
-
throw err;
|
| 18 |
-
}
|
| 19 |
-
};
|
| 20 |
-
|
| 21 |
-
const router = express.Router();
|
| 22 |
-
|
| 23 |
-
router.get("/:configParameters?/catalog/:type/:id/:extra?.json", async (req, res, next) => {
|
| 24 |
-
const { type, id, extra } = req.params;
|
| 25 |
-
let cleanId = id.startsWith('trakt_') ? id.replace('trakt_', '') : id;
|
| 26 |
-
|
| 27 |
-
log.debug(`Type before processing: ${type}`);
|
| 28 |
-
log.debug(`ID before processing: ${cleanId}`);
|
| 29 |
-
|
| 30 |
-
const { configParameters } = req.params;
|
| 31 |
-
let config = {};
|
| 32 |
-
|
| 33 |
-
try {
|
| 34 |
-
if (configParameters) {
|
| 35 |
-
const decodedConfig = decodeURIComponent(configParameters);
|
| 36 |
-
config = JSON.parse(decodedConfig);
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
const tmdbApiKey = config.tmdbApiKey;
|
| 40 |
-
const fanartApiKey = config.fanartApiKey;
|
| 41 |
-
const rpdbApiKey = config.rpdbApiKey;
|
| 42 |
-
const language = config.language || 'en-US';
|
| 43 |
-
const traktUsername = config.traktUsername;
|
| 44 |
-
|
| 45 |
-
if (!tmdbApiKey) {
|
| 46 |
-
return res.status(400).json({ error: 'TMDB API key is required' });
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
if (cleanId === 'watchlist_movies' || cleanId === 'watchlist_series') {
|
| 50 |
-
if (!traktUsername) {
|
| 51 |
-
return res.status(400).json({ error: 'Trakt username is required for fetching watchlist' });
|
| 52 |
-
}
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
let skip = 0;
|
| 56 |
-
let genre = null;
|
| 57 |
-
let sortBy = null;
|
| 58 |
-
let sortHow = 'asc';
|
| 59 |
-
|
| 60 |
-
if (extra) {
|
| 61 |
-
const extraParams = extra.split('&');
|
| 62 |
-
for (const param of extraParams) {
|
| 63 |
-
const [key, value] = param.split('=');
|
| 64 |
-
if (key === 'skip' && !isNaN(value)) {
|
| 65 |
-
skip = parseInt(value);
|
| 66 |
-
} else if (key === 'genre') {
|
| 67 |
-
genre = value;
|
| 68 |
-
} else if (key === 'sortBy') {
|
| 69 |
-
const lastUnderscore = value.lastIndexOf('_');
|
| 70 |
-
if (lastUnderscore !== -1) {
|
| 71 |
-
sortBy = value.slice(0, lastUnderscore);
|
| 72 |
-
sortHow = value.slice(lastUnderscore + 1);
|
| 73 |
-
}
|
| 74 |
-
}
|
| 75 |
-
}
|
| 76 |
-
}
|
| 77 |
-
|
| 78 |
-
const limit = 20;
|
| 79 |
-
const page = Math.floor(skip / limit) + 1;
|
| 80 |
-
|
| 81 |
-
let genreSlug = null;
|
| 82 |
-
if (genre) {
|
| 83 |
-
genreSlug = await getGenreSlug(genre, type);
|
| 84 |
-
if (!genreSlug) {
|
| 85 |
-
return res.status(400).json({ error: `Genre '${genre}' not found for type '${type}'` });
|
| 86 |
-
}
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
log.debug(`Fetching list items with skip: ${skip}, limit: ${limit}, page: ${page}, genre: ${genre}, genreSlug: ${genreSlug}, sortBy: ${sortBy}, sortHow: ${sortHow}`);
|
| 90 |
-
|
| 91 |
-
let allItems = [];
|
| 92 |
-
|
| 93 |
-
switch (cleanId) {
|
| 94 |
-
case 'watchlist_movies':
|
| 95 |
-
case 'watchlist_series':
|
| 96 |
-
log.debug(`Fetching watchlist for ${type} and user: ${traktUsername}`);
|
| 97 |
-
allItems = await fetchWatchlistItems(traktUsername, type, page, limit);
|
| 98 |
-
break;
|
| 99 |
-
case 'recommendations_movies':
|
| 100 |
-
case 'recommendations_series':
|
| 101 |
-
log.debug(`Fetching recommendations for ${type} and user: ${traktUsername}`);
|
| 102 |
-
allItems = await fetchRecommendations(traktUsername, type, true, true);
|
| 103 |
-
break;
|
| 104 |
-
case 'trending_movies':
|
| 105 |
-
case 'trending_series':
|
| 106 |
-
log.debug(`Fetching trending items for ${type}`);
|
| 107 |
-
allItems = await fetchTrendingItems(type, page, limit, genreSlug);
|
| 108 |
-
break;
|
| 109 |
-
case 'popular_movies':
|
| 110 |
-
case 'popular_series':
|
| 111 |
-
log.debug(`Fetching popular items for ${type}`);
|
| 112 |
-
allItems = await fetchPopularItems(type, page, limit, genreSlug);
|
| 113 |
-
break;
|
| 114 |
-
default:
|
| 115 |
-
log.debug(`Fetching list items from Trakt API for list ${cleanId}`);
|
| 116 |
-
if (sortBy) {
|
| 117 |
-
log.debug(`Sorting provided: ignoring pagination, using sortBy: ${sortBy} and sortHow: ${sortHow}`);
|
| 118 |
-
allItems = await fetchListItems(cleanId, type, null, null, sortBy, sortHow);
|
| 119 |
-
} else {
|
| 120 |
-
log.debug(`No sorting provided: using pagination with page: ${page}, limit: ${limit}`);
|
| 121 |
-
allItems = await fetchListItems(cleanId, type, page, limit);
|
| 122 |
-
}
|
| 123 |
-
break;
|
| 124 |
-
}
|
| 125 |
-
|
| 126 |
-
log.debug(`Items fetched for list ${cleanId}: ${allItems.length} items`);
|
| 127 |
-
|
| 128 |
-
const paginatedItems = sortBy ? allItems.slice(skip, skip + limit) : allItems;
|
| 129 |
-
|
| 130 |
-
const metas = await Promise.all(paginatedItems.map(async (item) => {
|
| 131 |
-
let logoUrl = '';
|
| 132 |
-
let posterUrl = '';
|
| 133 |
-
|
| 134 |
-
if (type === 'movie' || type === 'movies') {
|
| 135 |
-
const movie = item.movie || item;
|
| 136 |
-
if (movie && movie.ids && movie.ids.tmdb) {
|
| 137 |
-
try {
|
| 138 |
-
const tmdbDetails = await getMetadataByTmdbId(movie.ids.tmdb, 'movie', tmdbApiKey, language);
|
| 139 |
-
if (rpdbApiKey) {
|
| 140 |
-
const rpdbPosterUrl = await getRpdbPosterUrl('movie', movie.ids.tmdb, language, rpdbApiKey);
|
| 141 |
-
posterUrl = rpdbPosterUrl || tmdbDetails.poster;
|
| 142 |
-
} else {
|
| 143 |
-
posterUrl = tmdbDetails.poster;
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
if (fanartApiKey) {
|
| 147 |
-
logoUrl = await getFanartLogo(movie.ids.tmdb, language, fanartApiKey);
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
return {
|
| 151 |
-
id: `${movie.ids.imdb}`,
|
| 152 |
-
type: 'movie',
|
| 153 |
-
name: tmdbDetails.title,
|
| 154 |
-
poster: posterUrl,
|
| 155 |
-
logo: logoUrl,
|
| 156 |
-
description: tmdbDetails.description,
|
| 157 |
-
releaseInfo: tmdbDetails.releaseDate,
|
| 158 |
-
posterShape: 'poster',
|
| 159 |
-
imdbRating: tmdbDetails.imdbRating,
|
| 160 |
-
genres: tmdbDetails.genres,
|
| 161 |
-
runtime: tmdbDetails.runtime
|
| 162 |
-
};
|
| 163 |
-
} catch (error) {
|
| 164 |
-
log.error(`Error fetching TMDB details for movie: ${movie.title}, TMDB ID: ${movie.ids.tmdb} - ${error.message}`);
|
| 165 |
-
return null;
|
| 166 |
-
}
|
| 167 |
-
}
|
| 168 |
-
}
|
| 169 |
-
else if (type === 'series' || type === 'tv') {
|
| 170 |
-
const show = item.show || item;
|
| 171 |
-
if (show && show.ids && show.ids.tmdb) {
|
| 172 |
-
try {
|
| 173 |
-
const tmdbDetails = await getMetadataByTmdbId(show.ids.tmdb, 'tv', tmdbApiKey, language);
|
| 174 |
-
if (rpdbApiKey) {
|
| 175 |
-
const rpdbPosterUrl = await getRpdbPosterUrl('series', show.ids.tmdb, language, rpdbApiKey);
|
| 176 |
-
posterUrl = rpdbPosterUrl || tmdbDetails.poster;
|
| 177 |
-
} else {
|
| 178 |
-
posterUrl = tmdbDetails.poster;
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
if (fanartApiKey) {
|
| 182 |
-
logoUrl = await getFanartLogo(show.ids.tmdb, language, fanartApiKey);
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
-
const releaseInfo = tmdbDetails.releaseDate === tmdbDetails.lastAirDate
|
| 186 |
-
? tmdbDetails.releaseDate
|
| 187 |
-
: `${tmdbDetails.releaseDate}-${tmdbDetails.lastAirDate}`;
|
| 188 |
-
|
| 189 |
-
return {
|
| 190 |
-
id: `${show.ids.imdb}`,
|
| 191 |
-
type: 'series',
|
| 192 |
-
name: tmdbDetails.title,
|
| 193 |
-
poster: posterUrl,
|
| 194 |
-
logo: logoUrl,
|
| 195 |
-
description: tmdbDetails.description,
|
| 196 |
-
releaseInfo,
|
| 197 |
-
posterShape: 'poster',
|
| 198 |
-
imdbRating: tmdbDetails.imdbRating,
|
| 199 |
-
genres: tmdbDetails.genres,
|
| 200 |
-
runtime: tmdbDetails.runtime
|
| 201 |
-
};
|
| 202 |
-
} catch (error) {
|
| 203 |
-
log.error(`Error fetching TMDB details for show: ${show.title}, TMDB ID: ${show.ids.tmdb} - ${error.message}`);
|
| 204 |
-
return null;
|
| 205 |
-
}
|
| 206 |
-
}
|
| 207 |
-
}
|
| 208 |
-
else if (type === 'list') {
|
| 209 |
-
const listItem = item;
|
| 210 |
-
|
| 211 |
-
if (listItem && listItem.movie && listItem.movie.ids && listItem.movie.ids.tmdb) {
|
| 212 |
-
try {
|
| 213 |
-
const tmdbDetails = await getMetadataByTmdbId(listItem.movie.ids.tmdb, 'movie', tmdbApiKey, language);
|
| 214 |
-
if (rpdbApiKey) {
|
| 215 |
-
const rpdbPosterUrl = await getRpdbPosterUrl('movie', listItem.movie.ids.tmdb, language, rpdbApiKey);
|
| 216 |
-
posterUrl = rpdbPosterUrl || tmdbDetails.poster;
|
| 217 |
-
} else {
|
| 218 |
-
posterUrl = tmdbDetails.poster;
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
if (fanartApiKey) {
|
| 222 |
-
logoUrl = await getFanartLogo(listItem.movie.ids.tmdb, language, fanartApiKey);
|
| 223 |
-
}
|
| 224 |
-
|
| 225 |
-
return {
|
| 226 |
-
id: `${listItem.movie.ids.imdb}`,
|
| 227 |
-
type: 'movie',
|
| 228 |
-
name: listItem.movie.title,
|
| 229 |
-
poster: posterUrl,
|
| 230 |
-
logo: logoUrl,
|
| 231 |
-
description: tmdbDetails.description,
|
| 232 |
-
releaseInfo: tmdbDetails.releaseDate,
|
| 233 |
-
posterShape: 'poster',
|
| 234 |
-
imdbRating: tmdbDetails.imdbRating,
|
| 235 |
-
genres: tmdbDetails.genres,
|
| 236 |
-
runtime: tmdbDetails.runtime
|
| 237 |
-
};
|
| 238 |
-
} catch (error) {
|
| 239 |
-
log.error(`Error fetching TMDB details for list item: ${listItem.movie.title}, TMDB ID: ${listItem.movie.ids.tmdb} - ${error.message}`);
|
| 240 |
-
return null;
|
| 241 |
-
}
|
| 242 |
-
}
|
| 243 |
-
else if (listItem && listItem.show && listItem.show.ids && listItem.show.ids.tmdb) {
|
| 244 |
-
try {
|
| 245 |
-
const tmdbDetails = await getMetadataByTmdbId(listItem.show.ids.tmdb, 'tv', tmdbApiKey, language);
|
| 246 |
-
if (rpdbApiKey) {
|
| 247 |
-
const rpdbPosterUrl = await getRpdbPosterUrl('series', listItem.show.ids.tmdb, language, rpdbApiKey);
|
| 248 |
-
posterUrl = rpdbPosterUrl || tmdbDetails.poster;
|
| 249 |
-
} else {
|
| 250 |
-
posterUrl = tmdbDetails.poster;
|
| 251 |
-
}
|
| 252 |
-
|
| 253 |
-
if (fanartApiKey) {
|
| 254 |
-
logoUrl = await getFanartLogo(listItem.show.ids.tmdb, language, fanartApiKey);
|
| 255 |
-
}
|
| 256 |
-
|
| 257 |
-
const releaseInfo = tmdbDetails.releaseDate === tmdbDetails.lastAirDate
|
| 258 |
-
? tmdbDetails.releaseDate
|
| 259 |
-
: `${tmdbDetails.releaseDate}-${tmdbDetails.lastAirDate}`;
|
| 260 |
-
|
| 261 |
-
return {
|
| 262 |
-
id: `${listItem.show.ids.imdb}`,
|
| 263 |
-
type: 'series',
|
| 264 |
-
name: listItem.show.title,
|
| 265 |
-
poster: posterUrl,
|
| 266 |
-
logo: logoUrl,
|
| 267 |
-
description: tmdbDetails.description,
|
| 268 |
-
releaseInfo,
|
| 269 |
-
posterShape: 'poster',
|
| 270 |
-
imdbRating: tmdbDetails.imdbRating,
|
| 271 |
-
genres: tmdbDetails.genres,
|
| 272 |
-
runtime: tmdbDetails.runtime
|
| 273 |
-
};
|
| 274 |
-
} catch (error) {
|
| 275 |
-
log.error(`Error fetching TMDB details for list item: ${listItem.show.title}, TMDB ID: ${listItem.show.ids.tmdb} - ${error.message}`);
|
| 276 |
-
return null;
|
| 277 |
-
}
|
| 278 |
-
}
|
| 279 |
-
}
|
| 280 |
-
else {
|
| 281 |
-
log.warn(`Unknown type in route: ${type}`);
|
| 282 |
-
return null;
|
| 283 |
-
}
|
| 284 |
-
}).filter(Boolean));
|
| 285 |
-
try {
|
| 286 |
-
let updatedMetas = metas;
|
| 287 |
-
|
| 288 |
-
if (config.markContentHistory) {
|
| 289 |
-
updatedMetas = await handleTraktHistory(config, metas, type);
|
| 290 |
-
}
|
| 291 |
-
|
| 292 |
-
res.json({ metas: updatedMetas });
|
| 293 |
-
} catch (error) {
|
| 294 |
-
log.error(`Error handling Trakt history: ${error.message}`);
|
| 295 |
-
res.status(500).json({ error: "Error handling Trakt history." });
|
| 296 |
-
}
|
| 297 |
-
} catch (error) {
|
| 298 |
-
log.error('Error in /catalog route:', error);
|
| 299 |
-
return res.status(500).json({ error: "Invalid configParameters or server error." });
|
| 300 |
-
}
|
| 301 |
-
});
|
| 302 |
-
|
| 303 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/configure.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
| 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 |
-
router.get('/env', (req, res) => {
|
| 20 |
-
log.info('Sending environment variable TRAKT_CLIENT_ID to client');
|
| 21 |
-
res.json({
|
| 22 |
-
TRAKT_CLIENT_ID: process.env.TRAKT_CLIENT_ID
|
| 23 |
-
});
|
| 24 |
-
});
|
| 25 |
-
|
| 26 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/index.js
DELETED
|
@@ -1,82 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const catalogRoutes = require('./catalog');
|
| 4 |
-
const configureRoutes = require('./configure');
|
| 5 |
-
const manifestRoutes = require('./manifest');
|
| 6 |
-
const posterRoutes = require('./poster');
|
| 7 |
-
const traktRoutes = require('./trakt');
|
| 8 |
-
|
| 9 |
-
const router = express.Router();
|
| 10 |
-
|
| 11 |
-
const isBase64 = (str) => {
|
| 12 |
-
const base64Regex = /^[A-Za-z0-9+/=]+$/;
|
| 13 |
-
if (!str || str.length % 4 !== 0 || !base64Regex.test(str)) {
|
| 14 |
-
return false;
|
| 15 |
-
}
|
| 16 |
-
try {
|
| 17 |
-
Buffer.from(str, 'base64').toString('utf8');
|
| 18 |
-
return true;
|
| 19 |
-
} catch (err) {
|
| 20 |
-
return false;
|
| 21 |
-
}
|
| 22 |
-
};
|
| 23 |
-
|
| 24 |
-
const IGNORE_PATHS = ['/catalog', '/list', '/configure', '/manifest', '/poster'];
|
| 25 |
-
|
| 26 |
-
const decodeBase64Middleware = (req, res, next) => {
|
| 27 |
-
if (req.path.startsWith('/callback') || req.path.startsWith('/lists')) {
|
| 28 |
-
return next();
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
try {
|
| 32 |
-
const pathParts = req.path.split('/');
|
| 33 |
-
|
| 34 |
-
const decodedParts = pathParts.map(part => {
|
| 35 |
-
if (IGNORE_PATHS.includes(`/${part}`)) {
|
| 36 |
-
return part;
|
| 37 |
-
}
|
| 38 |
-
if (isBase64(part)) {
|
| 39 |
-
try {
|
| 40 |
-
return Buffer.from(part, 'base64').toString('utf8');
|
| 41 |
-
} catch (e) {
|
| 42 |
-
log.error(`Error decoding part: ${e.message}`);
|
| 43 |
-
return part;
|
| 44 |
-
}
|
| 45 |
-
} else {
|
| 46 |
-
return part;
|
| 47 |
-
}
|
| 48 |
-
});
|
| 49 |
-
|
| 50 |
-
req.url = decodedParts.join('/');
|
| 51 |
-
|
| 52 |
-
log.info(`URL after Base64 decoding: ${req.url}`);
|
| 53 |
-
|
| 54 |
-
next();
|
| 55 |
-
} catch (error) {
|
| 56 |
-
log.error('Base64 decoding error:', error);
|
| 57 |
-
res.status(400).send('Bad request: Invalid Base64 encoding.');
|
| 58 |
-
}
|
| 59 |
-
};
|
| 60 |
-
|
| 61 |
-
router.use(decodeBase64Middleware);
|
| 62 |
-
|
| 63 |
-
router.use((req, res, next) => {
|
| 64 |
-
log.info(`--- Request received ---`);
|
| 65 |
-
log.info(`${req.method} ${req.originalUrl}`);
|
| 66 |
-
next();
|
| 67 |
-
});
|
| 68 |
-
|
| 69 |
-
router.use(catalogRoutes);
|
| 70 |
-
router.use(configureRoutes);
|
| 71 |
-
router.use(manifestRoutes);
|
| 72 |
-
router.use(posterRoutes);
|
| 73 |
-
router.use(traktRoutes);
|
| 74 |
-
|
| 75 |
-
router.use((err, req, res, next) => {
|
| 76 |
-
const errorTime = new Date().toISOString();
|
| 77 |
-
log.error(`${errorTime} - Error: ${err.stack}`);
|
| 78 |
-
|
| 79 |
-
res.status(500).send(`Something broke! If you need help, please provide this timestamp to the developer : ${errorTime}`);
|
| 80 |
-
});
|
| 81 |
-
|
| 82 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/manifest.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const { pool } = require('../helpers/db');
|
| 4 |
-
const { fetchAndStoreGenres } = require('../api/trakt');
|
| 5 |
-
|
| 6 |
-
const getGenres = async (type) => {
|
| 7 |
-
try {
|
| 8 |
-
const result = await pool.query(
|
| 9 |
-
"SELECT genre_name FROM genres WHERE media_type = $1",
|
| 10 |
-
[type]
|
| 11 |
-
);
|
| 12 |
-
return result.rows.map(row => row.genre_name);
|
| 13 |
-
} catch (err) {
|
| 14 |
-
throw err;
|
| 15 |
-
}
|
| 16 |
-
};
|
| 17 |
-
|
| 18 |
-
const router = express.Router();
|
| 19 |
-
|
| 20 |
-
router.get("/:configParameters?/manifest.json", async (req, res) => {
|
| 21 |
-
const { configParameters } = req.params;
|
| 22 |
-
|
| 23 |
-
let config = {};
|
| 24 |
-
|
| 25 |
-
try {
|
| 26 |
-
if (configParameters) {
|
| 27 |
-
const decodedConfig = decodeURIComponent(configParameters);
|
| 28 |
-
config = JSON.parse(decodedConfig);
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
if (!(await pool.query("SELECT 1 FROM genres LIMIT 1")).rows.length) {
|
| 32 |
-
log.debug(`Fetching genres`);
|
| 33 |
-
await fetchAndStoreGenres();
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
const movieGenres = await getGenres('movie');
|
| 37 |
-
const seriesGenres = await getGenres('series');
|
| 38 |
-
|
| 39 |
-
const manifest = {
|
| 40 |
-
"id": "com.stremio.stremiotraktaddon",
|
| 41 |
-
"version": "0.3.0",
|
| 42 |
-
"name": "Trakt Addon",
|
| 43 |
-
"description": "Addon that generates dynamic catalogs based on Trakt lists & catalogs in your language.",
|
| 44 |
-
"resources": [ "catalog" ],
|
| 45 |
-
"types": [
|
| 46 |
-
"movie",
|
| 47 |
-
"series"
|
| 48 |
-
],
|
| 49 |
-
"catalogs": [],
|
| 50 |
-
"idPrefixes": ["tt"],
|
| 51 |
-
"behaviorHints": {
|
| 52 |
-
"configurable": true,
|
| 53 |
-
"configurationRequired": false
|
| 54 |
-
}
|
| 55 |
-
};
|
| 56 |
-
|
| 57 |
-
const createCatalog = (type, id, name, genres = [], addSortingOptions = false) => ({
|
| 58 |
-
type,
|
| 59 |
-
id,
|
| 60 |
-
name,
|
| 61 |
-
"extra": [
|
| 62 |
-
...(genres.length ? [{ name: 'genre', isRequired: false, options: genres }] : []),
|
| 63 |
-
{ name: "skip", isRequired: false },
|
| 64 |
-
...(addSortingOptions ? [
|
| 65 |
-
{
|
| 66 |
-
name: 'sortBy',
|
| 67 |
-
isRequired: false,
|
| 68 |
-
options: [
|
| 69 |
-
'rank_asc', 'rank_desc',
|
| 70 |
-
'listed_at_asc', 'listed_at_desc',
|
| 71 |
-
'title_asc', 'title_desc',
|
| 72 |
-
'year_asc', 'year_desc'
|
| 73 |
-
]
|
| 74 |
-
}
|
| 75 |
-
] : [])
|
| 76 |
-
]
|
| 77 |
-
});
|
| 78 |
-
|
| 79 |
-
if (config.traktLists && Array.isArray(config.traktLists)) {
|
| 80 |
-
config.traktLists.forEach(list => {
|
| 81 |
-
manifest.catalogs.push(createCatalog('list', `trakt_${list.id}`, list.name, [], true));
|
| 82 |
-
});
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
-
const toggles = config.toggles || {};
|
| 86 |
-
|
| 87 |
-
if (toggles.watchlist) {
|
| 88 |
-
manifest.catalogs.push(
|
| 89 |
-
createCatalog('movie', 'watchlist_movies', 'Watchlist Movies', movieGenres),
|
| 90 |
-
createCatalog('series', 'watchlist_series', 'Watchlist Series', seriesGenres)
|
| 91 |
-
);
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
if (toggles.recommendations) {
|
| 95 |
-
manifest.catalogs.push(
|
| 96 |
-
createCatalog('movie', 'recommendations_movies', 'Recommended Movies', movieGenres),
|
| 97 |
-
createCatalog('series', 'recommendations_series', 'Recommended Series', seriesGenres)
|
| 98 |
-
);
|
| 99 |
-
}
|
| 100 |
-
|
| 101 |
-
if (toggles.trending) {
|
| 102 |
-
manifest.catalogs.push(
|
| 103 |
-
createCatalog('movie', 'trending_movies', 'Trending Movies', movieGenres),
|
| 104 |
-
createCatalog('series', 'trending_series', 'Trending Series', seriesGenres)
|
| 105 |
-
);
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
if (toggles.popular) {
|
| 109 |
-
manifest.catalogs.push(
|
| 110 |
-
createCatalog('movie', 'popular_movies', 'Popular Movies', movieGenres),
|
| 111 |
-
createCatalog('series', 'popular_series', 'Popular Series', seriesGenres)
|
| 112 |
-
);
|
| 113 |
-
}
|
| 114 |
-
|
| 115 |
-
res.setHeader('Content-Type', 'application/json');
|
| 116 |
-
return res.status(200).json(manifest);
|
| 117 |
-
} catch (error) {
|
| 118 |
-
log.error('Error in /manifest.json route:', error);
|
| 119 |
-
return res.status(500).json({ error: "Invalid configParameters or server error." });
|
| 120 |
-
}
|
| 121 |
-
});
|
| 122 |
-
|
| 123 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/poster.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 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, '../../cache/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
DELETED
|
@@ -1,23 +0,0 @@
|
|
| 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;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/stream.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const log = require('../helpers/logger');
|
| 3 |
-
const { parseConfigParameters } = require('../helpers/catalog');
|
| 4 |
-
const { prepareStreams } = require('../helpers/stream');
|
| 5 |
-
const { getRecommendationsFromTmdb, getSimilarContentFromTmdb, getContentFromImdbId } = require('../api/tmdb');
|
| 6 |
-
|
| 7 |
-
const router = express.Router();
|
| 8 |
-
|
| 9 |
-
router.get("/:configParameters?/stream/:type/:id.json", async (req, res, next) => {
|
| 10 |
-
const { id, configParameters, type } = req.params;
|
| 11 |
-
|
| 12 |
-
const origin = req.get('origin');
|
| 13 |
-
const userAgent = req.headers['user-agent'] || '';
|
| 14 |
-
log.debug(`Request Origin: ${origin}`);
|
| 15 |
-
|
| 16 |
-
log.debug(`Received parameters: id=${id}, type=${type}, configParameters=${configParameters}`);
|
| 17 |
-
|
| 18 |
-
const parsedConfig = await parseConfigParameters(configParameters);
|
| 19 |
-
const additionalContent = parsedConfig.additionalContent || '';
|
| 20 |
-
|
| 21 |
-
const recommendationsTitle = parsedConfig.recommendationsTitle || 'Recommendations';
|
| 22 |
-
const similarTitle = parsedConfig.similarTitle || 'Similar';
|
| 23 |
-
|
| 24 |
-
try {
|
| 25 |
-
const content = await getContentFromImdbId(id, parsedConfig.tmdbApiKey, parsedConfig.language);
|
| 26 |
-
if (!content) {
|
| 27 |
-
log.warn(`Content not found for IMDb ID: ${id}`);
|
| 28 |
-
return res.json({ streams: [] });
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
let recommendations = [];
|
| 32 |
-
let similar = [];
|
| 33 |
-
|
| 34 |
-
if (additionalContent === 'recommendations-similar') {
|
| 35 |
-
recommendations = await getRecommendationsFromTmdb(content.tmdbId, type, parsedConfig.tmdbApiKey, parsedConfig.language);
|
| 36 |
-
similar = await getSimilarContentFromTmdb(content.tmdbId, type, parsedConfig.tmdbApiKey, parsedConfig.language);
|
| 37 |
-
} else if (additionalContent === 'recommendations') {
|
| 38 |
-
recommendations = await getRecommendationsFromTmdb(content.tmdbId, type, parsedConfig.tmdbApiKey, parsedConfig.language);
|
| 39 |
-
} else if (additionalContent === 'similar') {
|
| 40 |
-
similar = await getSimilarContentFromTmdb(content.tmdbId, type, parsedConfig.tmdbApiKey, parsedConfig.language);
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
let streams = [];
|
| 44 |
-
|
| 45 |
-
if (recommendations.length > 0) {
|
| 46 |
-
streams.push({
|
| 47 |
-
name: '📢',
|
| 48 |
-
title: recommendationsTitle,
|
| 49 |
-
externalUrl: 'https://web.stremio.com'
|
| 50 |
-
});
|
| 51 |
-
const recommendationStreams = await prepareStreams(recommendations, parsedConfig.tmdbApiKey, parsedConfig.language, true, true, userAgent, type);
|
| 52 |
-
streams = streams.concat(recommendationStreams);
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
if (similar.length > 0) {
|
| 56 |
-
streams.push({
|
| 57 |
-
name: '🔍',
|
| 58 |
-
title: similarTitle,
|
| 59 |
-
externalUrl: 'https://web.stremio.com'
|
| 60 |
-
});
|
| 61 |
-
const similarStreams = await prepareStreams(similar, parsedConfig.tmdbApiKey, parsedConfig.language, true, true, userAgent, type);
|
| 62 |
-
streams = streams.concat(similarStreams);
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
res.json({ streams });
|
| 66 |
-
} catch (error) {
|
| 67 |
-
log.error(`Error processing request: ${error.message}`, error);
|
| 68 |
-
if (!res.headersSent) {
|
| 69 |
-
res.status(500).json({ error: 'Internal Server Error' });
|
| 70 |
-
}
|
| 71 |
-
}
|
| 72 |
-
});
|
| 73 |
-
|
| 74 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/routes/trakt.js
DELETED
|
@@ -1,115 +0,0 @@
|
|
| 1 |
-
const express = require('express');
|
| 2 |
-
const { saveUserTokens, fetchUserWatchedMovies, fetchUserWatchedShows, fetchUserTokens } = require('../helpers/trakt');
|
| 3 |
-
const { fetchUserProfile, exchangeCodeForToken, markContentAsWatched, saveUserWatchedHistory, lookupTraktId, fetchTrendingLists, fetchPopularLists, searchLists, fetchListById } = require('../api/trakt');
|
| 4 |
-
const log = require('../helpers/logger');
|
| 5 |
-
const router = express.Router();
|
| 6 |
-
|
| 7 |
-
const { TRAKT_CLIENT_ID } = process.env;
|
| 8 |
-
|
| 9 |
-
if (!TRAKT_CLIENT_ID) {
|
| 10 |
-
log.warn('Environment variables TRAKT_CLIENT_ID is not set.');
|
| 11 |
-
}
|
| 12 |
-
|
| 13 |
-
router.get('/callback', async (req, res) => {
|
| 14 |
-
const code = req.query.code;
|
| 15 |
-
|
| 16 |
-
if (!code) {
|
| 17 |
-
log.error('Authorization code is missing.');
|
| 18 |
-
return res.status(400).send('Error: Authorization code is missing.');
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
try {
|
| 22 |
-
const { access_token, refresh_token } = await exchangeCodeForToken(code);
|
| 23 |
-
|
| 24 |
-
if (!access_token || !refresh_token) {
|
| 25 |
-
log.error('Received tokens are invalid or missing.');
|
| 26 |
-
return res.status(500).send('Error receiving tokens.');
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
const userProfile = await fetchUserProfile(access_token);
|
| 30 |
-
const username = userProfile.username;
|
| 31 |
-
|
| 32 |
-
if (!username) {
|
| 33 |
-
log.error('Received username is invalid or missing.');
|
| 34 |
-
return res.status(500).send('Error receiving username.');
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
const now = new Date();
|
| 38 |
-
|
| 39 |
-
await saveUserTokens(username, access_token, refresh_token);
|
| 40 |
-
log.info(`Successfully saved tokens and username for user ${username}.`);
|
| 41 |
-
|
| 42 |
-
const [movieHistory, showHistory] = await Promise.all([
|
| 43 |
-
fetchUserWatchedMovies(username, access_token),
|
| 44 |
-
fetchUserWatchedShows(username, access_token)
|
| 45 |
-
]);
|
| 46 |
-
|
| 47 |
-
log.info(`Successfully fetched watched movies and shows for user ${username}.`);
|
| 48 |
-
|
| 49 |
-
await Promise.all([
|
| 50 |
-
saveUserWatchedHistory(username, movieHistory),
|
| 51 |
-
saveUserWatchedHistory(username, showHistory)
|
| 52 |
-
]);
|
| 53 |
-
|
| 54 |
-
log.info(`Successfully saved watched history for user ${username} in the database.`);
|
| 55 |
-
|
| 56 |
-
res.redirect(`/configure?username=${encodeURIComponent(username)}`);
|
| 57 |
-
} catch (error) {
|
| 58 |
-
log.error(`Error during token exchange: ${error.response ? error.response.data : error.message}`);
|
| 59 |
-
res.status(500).send('Error connecting to Trakt');
|
| 60 |
-
}
|
| 61 |
-
});
|
| 62 |
-
|
| 63 |
-
router.get('/lists/trending', async (req, res) => {
|
| 64 |
-
const { page = 1, limit = 10 } = req.query;
|
| 65 |
-
|
| 66 |
-
try {
|
| 67 |
-
const trendingLists = await fetchTrendingLists(page, limit);
|
| 68 |
-
res.json(trendingLists);
|
| 69 |
-
} catch (error) {
|
| 70 |
-
log.error(`Error fetching trending lists: ${error.message}`);
|
| 71 |
-
res.status(500).send('Error fetching trending lists');
|
| 72 |
-
}
|
| 73 |
-
});
|
| 74 |
-
|
| 75 |
-
router.get('/lists/popular', async (req, res) => {
|
| 76 |
-
const { page = 1, limit = 10 } = req.query;
|
| 77 |
-
|
| 78 |
-
try {
|
| 79 |
-
const popularLists = await fetchPopularLists(page, limit);
|
| 80 |
-
res.json(popularLists);
|
| 81 |
-
} catch (error) {
|
| 82 |
-
log.error(`Error fetching popular lists: ${error.message}`);
|
| 83 |
-
res.status(500).send('Error fetching popular lists');
|
| 84 |
-
}
|
| 85 |
-
});
|
| 86 |
-
|
| 87 |
-
router.get('/lists/search', async (req, res) => {
|
| 88 |
-
const { query, page = 1, limit = 10 } = req.query;
|
| 89 |
-
|
| 90 |
-
if (!query) {
|
| 91 |
-
return res.status(400).send('Query parameter is required');
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
try {
|
| 95 |
-
const searchResults = await searchLists(query, page, limit);
|
| 96 |
-
res.json(searchResults);
|
| 97 |
-
} catch (error) {
|
| 98 |
-
log.error(`Error searching for lists: ${error.message}`);
|
| 99 |
-
res.status(500).send('Error searching for lists');
|
| 100 |
-
}
|
| 101 |
-
});
|
| 102 |
-
|
| 103 |
-
router.get('/lists/:id', async (req, res) => {
|
| 104 |
-
const { id } = req.params;
|
| 105 |
-
|
| 106 |
-
try {
|
| 107 |
-
const listData = await fetchListById(id);
|
| 108 |
-
res.json(listData);
|
| 109 |
-
} catch (error) {
|
| 110 |
-
log.error(`Error fetching list with ID ${id}: ${error.message}`);
|
| 111 |
-
res.status(500).send('Error fetching list');
|
| 112 |
-
}
|
| 113 |
-
});
|
| 114 |
-
|
| 115 |
-
module.exports = router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|