Spaces:
Paused
Paused
Download src/api/tmdb.js from mikmc/catalogs-test: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/spaces/mikmc/catalogs-test/resolve/main/src/api/tmdb.js
- Command line
-
hf download hf://spaces/mikmc/catalogs-test/src/api/tmdb.js
-
curl -L -o tmdb.js https://huggingface.co/spaces/mikmc/catalogs-test/resolve/main/src/api/tmdb.js
5.95 kB
| const axios = require('axios'); | |
| const log = require('../helpers/logger'); | |
| const { genresDb, cacheDb } = require('../helpers/db'); | |
| const { getCatalogCache, setCatalogCache } = require('../helpers/cache'); | |
| const queue = require('../helpers/ratelimit'); | |
| const { getFanartPoster } = require('./fanart'); | |
| const { getPosterUrl, cachePosters } = require('./rpdb'); | |
| const TMDB_BASE_URL = 'https://api.themoviedb.org/3'; | |
| // Function to verify a stream link | |
| const verifyStream = async (url, authHeader) => { | |
| try { | |
| const headers = { | |
| Range: 'bytes=0-8191', | |
| Authorization: authHeader, | |
| 'User-Agent': 'Stremio', | |
| }; | |
| const response = await axios.head(url, { headers }); | |
| return response.status === 206 || response.status === 200; | |
| } catch (error) { | |
| log.error(`Stream verification failed: ${url} - ${error.message}`); | |
| return false; | |
| } | |
| }; | |
| // Function to fetch streaming sources from TMDb Watch Providers API | |
| const getStreamingSources = async (tmdbId, mediaType, tmdbApiKey, language = 'en') => { | |
| try { | |
| const url = `${TMDB_BASE_URL}/${mediaType}/${tmdbId}/watch/providers?api_key=${tmdbApiKey}`; | |
| const response = await axios.get(url); | |
| const sources = response.data.results?.[language]?.flatrate || []; | |
| log.debug(`Streaming sources for TMDB ID ${tmdbId}: ${sources.length} found`); | |
| return sources.map(source => ({ | |
| name: source.provider_name, | |
| url: `https://www.themoviedb.org/${mediaType}/${tmdbId}`, | |
| logo: source.logo_path ? `https://image.tmdb.org/t/p/w500${source.logo_path}` : null, | |
| })); | |
| } catch (error) { | |
| log.error(`Failed to fetch streaming sources for TMDB ID: ${tmdbId} - ${error.message}`); | |
| return []; | |
| } | |
| }; | |
| // Function to build query parameters for TMDb API | |
| const buildQueryParams = (params, mediaType) => { | |
| const queryParams = []; | |
| if (params.year) { | |
| const [startYear, endYear] = params.year.split('-'); | |
| if (startYear && endYear) { | |
| if (mediaType === 'movie') { | |
| queryParams.push(`primary_release_date.gte=${startYear}-01-01`); | |
| queryParams.push(`primary_release_date.lte=${endYear}-12-31`); | |
| } else if (mediaType === 'tv') { | |
| queryParams.push(`first_air_date.gte=${startYear}-01-01`); | |
| queryParams.push(`first_air_date.lte=${endYear}-12-31`); | |
| } | |
| } | |
| } | |
| if (params.rating) { | |
| const [minRating, maxRating] = params.rating.split('-'); | |
| if (minRating && maxRating) { | |
| queryParams.push(`vote_average.gte=${minRating}`); | |
| queryParams.push(`vote_average.lte=${maxRating}`); | |
| } | |
| } | |
| Object.entries(params).forEach(([key, value]) => { | |
| if (value && !['year', 'rating', 'genre'].includes(key)) { | |
| queryParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); | |
| } | |
| }); | |
| return queryParams.join('&'); | |
| }; | |
| // Function to fetch data and metadata from TMDb | |
| const fetchData = async (type, id, extra, cacheDuration = '3d', tmdbApiKey, rpdbApiKey, fanartApiKey) => { | |
| try { | |
| const mediaType = type === 'series' ? 'tv' : type; | |
| const cacheKey = `catalog_${type}_${id}_${JSON.stringify(extra)}`; | |
| const cached = await getCatalogCache(cacheKey, cacheDuration); | |
| if (cached) { | |
| log.info(`Using cached data for key: ${cacheKey}`); | |
| return cached.value; | |
| } | |
| // Build the API URL | |
| const queryParams = buildQueryParams(extra, mediaType); | |
| const url = `${TMDB_BASE_URL}/discover/${mediaType}?api_key=${tmdbApiKey}&${queryParams}`; | |
| log.debug(`Fetching TMDb data from: ${url}`); | |
| // Fetch data from TMDb | |
| const response = await axios.get(url); | |
| const results = response.data.results || []; | |
| // Process metadata | |
| const metas = await Promise.all(results.map(async item => { | |
| const genres = await getGenreNames(item.genre_ids, mediaType, extra.language); | |
| const poster = await getPosterUrl(item, rpdbApiKey); | |
| const streams = await getStreamingSources(item.id, mediaType, tmdbApiKey, extra.language); | |
| const verifiedStreams = await Promise.all( | |
| streams.map(async stream => { | |
| const verified = await verifyStream(stream.url, 'Bearer your-auth-token'); | |
| return verified ? stream : null; | |
| }) | |
| ); | |
| return { | |
| id: item.id.toString(), | |
| type: mediaType, | |
| name: item.title || item.name, | |
| poster, | |
| description: item.overview, | |
| releaseInfo: item.release_date || item.first_air_date, | |
| genres, | |
| streams: verifiedStreams.filter(Boolean), // Only include verified streams | |
| }; | |
| })); | |
| // Cache the result and return | |
| await setCatalogCache(cacheKey, metas, cacheDuration); | |
| return metas; | |
| } catch (error) { | |
| log.error(`Error in fetchData: ${error.message}`); | |
| throw new Error('Failed to fetch data'); | |
| } | |
| }; | |
| // Fetch genres by genre IDs | |
| const getGenreNames = (genreIds, mediaType, language) => | |
| new Promise(resolve => { | |
| if (!genreIds || genreIds.length === 0) { | |
| return resolve([]); | |
| } | |
| const placeholders = genreIds.map(() => '?').join(','); | |
| const sql = `SELECT genre_name FROM genres WHERE genre_id IN (${placeholders}) AND media_type = ? AND language = ?`; | |
| genresDb.all(sql, [...genreIds, mediaType, language], (err, rows) => { | |
| if (err) { | |
| log.error(`Error fetching genres: ${err.message}`); | |
| return resolve([]); | |
| } | |
| resolve(rows.map(row => row.genre_name)); | |
| }); | |
| }); | |
| module.exports = { | |
| fetchData, | |
| }; | |