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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const axios = require('axios');
|
| 2 |
+
const log = require('./utils/logger');
|
| 3 |
+
const queue = require('./utils/queue');
|
| 4 |
+
const { genresDb, providersDb, catalogDb } = require('./db');
|
| 5 |
+
const { getCache, setCache } = require('./cache');
|
| 6 |
+
const { TMDB_BEARER_TOKEN, TMDB_LANGUAGE, TMDB_WATCH_REGION } = process.env;
|
| 7 |
+
|
| 8 |
+
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';
|
| 9 |
+
|
| 10 |
+
const makeRequest = (url, tmdbApiKey = null) => {
|
| 11 |
+
const headers = {};
|
| 12 |
+
if (!tmdbApiKey && TMDB_BEARER_TOKEN) {
|
| 13 |
+
headers['Authorization'] = `Bearer ${TMDB_BEARER_TOKEN}`;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
return new Promise((resolve, reject) => {
|
| 17 |
+
queue.push({
|
| 18 |
+
fn: () => axios.get(url, { headers })
|
| 19 |
+
.then(response => {
|
| 20 |
+
log.debug(`API request successful for URL: ${url}`);
|
| 21 |
+
resolve(response.data);
|
| 22 |
+
})
|
| 23 |
+
.catch(error => {
|
| 24 |
+
log.error(`Error during API request for URL: ${url} - ${error.message}`);
|
| 25 |
+
reject(error);
|
| 26 |
+
})
|
| 27 |
+
});
|
| 28 |
+
});
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
const fetchData = async (endpoint, params = {}, tmdbApiKey = null) => {
|
| 32 |
+
if (tmdbApiKey) params.api_key = tmdbApiKey;
|
| 33 |
+
|
| 34 |
+
const queryString = new URLSearchParams(params).toString();
|
| 35 |
+
const url = `${TMDB_BASE_URL}${endpoint}?${queryString}`;
|
| 36 |
+
|
| 37 |
+
log.debug(`Request URL: ${url}`);
|
| 38 |
+
|
| 39 |
+
const cachedData = await getCache(url);
|
| 40 |
+
if (cachedData) return cachedData;
|
| 41 |
+
|
| 42 |
+
const data = await makeRequest(url, tmdbApiKey);
|
| 43 |
+
setCache(url, data);
|
| 44 |
+
return data;
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const fetchGenres = async (type, language, tmdbApiKey) => {
|
| 48 |
+
const mediaType = type === 'series' ? 'tv' : 'movie';
|
| 49 |
+
const endpoint = `/genre/${mediaType}/list`;
|
| 50 |
+
|
| 51 |
+
try {
|
| 52 |
+
const params = {
|
| 53 |
+
language: language || TMDB_LANGUAGE || 'en',
|
| 54 |
+
api_key: tmdbApiKey
|
| 55 |
+
};
|
| 56 |
+
|
| 57 |
+
const genresData = await fetchData(endpoint, params, tmdbApiKey);
|
| 58 |
+
log.debug(`Genres retrieved for ${type} (${language || 'en'})`);
|
| 59 |
+
return genresData.genres;
|
| 60 |
+
} catch (error) {
|
| 61 |
+
log.error(`Error fetching genres from TMDB: ${error.message}`);
|
| 62 |
+
throw error;
|
| 63 |
+
}
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
const storeGenresInDb = (genres, mediaType, language) =>
|
| 67 |
+
new Promise((resolve, reject) => {
|
| 68 |
+
genresDb.serialize(() => {
|
| 69 |
+
genresDb.run('BEGIN TRANSACTION');
|
| 70 |
+
const insertGenre = genresDb.prepare(`
|
| 71 |
+
INSERT INTO genres (genre_id, genre_name, media_type, language)
|
| 72 |
+
VALUES (?, ?, ?, ?)
|
| 73 |
+
ON CONFLICT(genre_id) DO NOTHING;
|
| 74 |
+
`);
|
| 75 |
+
|
| 76 |
+
genres.forEach((genre, index) => {
|
| 77 |
+
insertGenre.run(genre.id, genre.name, mediaType, language, (err) => {
|
| 78 |
+
if (err) {
|
| 79 |
+
log.error(`Error inserting genre: ${err.message}`);
|
| 80 |
+
genresDb.run('ROLLBACK');
|
| 81 |
+
reject(err);
|
| 82 |
+
return;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
if (index === genres.length - 1) {
|
| 86 |
+
insertGenre.finalize();
|
| 87 |
+
genresDb.run('COMMIT');
|
| 88 |
+
resolve();
|
| 89 |
+
}
|
| 90 |
+
});
|
| 91 |
+
});
|
| 92 |
+
});
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
const fetchAndStoreGenres = async (language, tmdbApiKey) => {
|
| 96 |
+
try {
|
| 97 |
+
const movieGenres = await fetchGenres('movie', language, tmdbApiKey);
|
| 98 |
+
const tvGenres = await fetchGenres('series', language, tmdbApiKey);
|
| 99 |
+
|
| 100 |
+
await storeGenresInDb(movieGenres, 'movie', language);
|
| 101 |
+
await storeGenresInDb(tvGenres, 'tv', language);
|
| 102 |
+
|
| 103 |
+
log.info(`Genres fetched and stored for ${language}`);
|
| 104 |
+
} catch (error) {
|
| 105 |
+
log.error(`Error fetching/storing genres: ${error.message}`);
|
| 106 |
+
}
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
const discoverContent = async (type, params = {}, tmdbApiKey) => {
|
| 110 |
+
const endpoint = `/discover/${type === 'series' ? 'tv' : 'movie'}`;
|
| 111 |
+
return await fetchData(endpoint, params, tmdbApiKey);
|
| 112 |
+
};
|
| 113 |
+
|
| 114 |
+
const fetchStreamingLinks = async (tmdbId, type, tmdbApiKey, region = 'US') => {
|
| 115 |
+
try {
|
| 116 |
+
const endpoint = `/${type}/${tmdbId}/watch/providers`;
|
| 117 |
+
const url = `${TMDB_BASE_URL}${endpoint}`;
|
| 118 |
+
|
| 119 |
+
const cachedData = await getCache(url);
|
| 120 |
+
if (cachedData) return cachedData;
|
| 121 |
+
|
| 122 |
+
const data = await makeRequest(url, tmdbApiKey);
|
| 123 |
+
const providers = data.results?.[region]?.flatrate || [];
|
| 124 |
+
await setCache(url, providers);
|
| 125 |
+
|
| 126 |
+
return providers;
|
| 127 |
+
} catch (error) {
|
| 128 |
+
log.error(`Failed to fetch streaming links for ${type} ID ${tmdbId}: ${error.message}`);
|
| 129 |
+
return [];
|
| 130 |
+
}
|
| 131 |
+
};
|
| 132 |
+
|
| 133 |
+
const updateProviders = async () => {
|
| 134 |
+
try {
|
| 135 |
+
const regions = TMDB_WATCH_REGION ? TMDB_WATCH_REGION.split(',') : [];
|
| 136 |
+
const movieEndpoint = `/watch/providers/movie`;
|
| 137 |
+
const tvEndpoint = `/watch/providers/tv`;
|
| 138 |
+
|
| 139 |
+
const fetchProvidersForRegion = async (region) => {
|
| 140 |
+
const params = { watch_region: region };
|
| 141 |
+
const [movieData, tvData] = await Promise.all([
|
| 142 |
+
fetchData(movieEndpoint, params),
|
| 143 |
+
fetchData(tvEndpoint, params)
|
| 144 |
+
]);
|
| 145 |
+
return [...movieData.results, ...tvData.results];
|
| 146 |
+
};
|
| 147 |
+
|
| 148 |
+
const results = await Promise.all(regions.map(region => fetchProvidersForRegion(region)));
|
| 149 |
+
const combinedProviders = mergeProviders(results.flat());
|
| 150 |
+
|
| 151 |
+
const insertOrUpdateProvider = providersDb.prepare(`
|
| 152 |
+
INSERT INTO providers (provider_id, provider_name, logo_path)
|
| 153 |
+
VALUES (?, ?, ?)
|
| 154 |
+
ON CONFLICT(provider_id) DO UPDATE SET
|
| 155 |
+
provider_name = excluded.provider_name,
|
| 156 |
+
logo_path = excluded.logo_path;
|
| 157 |
+
`);
|
| 158 |
+
|
| 159 |
+
combinedProviders.forEach(provider => {
|
| 160 |
+
insertOrUpdateProvider.run(provider.provider_id, provider.provider_name, provider.logo_path);
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
insertOrUpdateProvider.finalize();
|
| 164 |
+
log.info('Providers update completed.');
|
| 165 |
+
} catch (error) {
|
| 166 |
+
log.error(`Error during providers update: ${error.message}`);
|
| 167 |
+
}
|
| 168 |
+
};
|
| 169 |
+
|
| 170 |
+
module.exports = {
|
| 171 |
+
makeRequest,
|
| 172 |
+
fetchData,
|
| 173 |
+
fetchGenres,
|
| 174 |
+
fetchAndStoreGenres,
|
| 175 |
+
discoverContent,
|
| 176 |
+
fetchStreamingLinks,
|
| 177 |
+
updateProviders
|
| 178 |
+
};
|