const { addonBuilder } = require("stremio-addon-sdk"); const { google } = require("googleapis"); const NodeCache = require("node-cache"); // Optional: if you use caching elsewhere const cache = new NodeCache({ stdTTL: 3600 }); // Hardcoded OAuth tokens (replace with actual token values) const token = { access_token: "ya29.a0AW4XtxitOJqNQRYaU-dNJVvhlZkyUxtKvwoiQCgKAAtbpgaFqBoA66KUfGVx7nIGIIPvOITXuV_wha1gfEoCb-mUS2w8-n_oL9bF2GK6_u_MvRAqoHAoCePpizyWiCuWqvl34y9yA6c-x1d7DdODRe6s46_Lohx9JfX0qbCpaCgYKAYISARQSFQHGX2MiuFYIV8q_XcOm4oVJ2wtRJQ0175", // <-- your actual token refresh_token: "1//03p-f_j_yN-X3CgYIARAAGAMSNwF-L9IrYAAAyDgBjMbh4H1cOuZMbmmL848MbAKadfF7r21w8MMA9eMxjLpHVUA2AyolKlCumKY", // optional but good to have scope: "https://www.googleapis.com/auth/youtube.readonly", token_type: "Bearer", expiry_date: 1747515139315 // or actual timestamp }; // Initialize OAuth2 client const oauth2Client = new google.auth.OAuth2( "218683238174-vq5g2u7omb13aem373dgev7esqu6lds1.apps.googleusercontent.com", "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", "http://localhost" // not used here unless doing live OAuth flow ); // Set credentials in memory oauth2Client.setCredentials(token); // Define documentary categories/genres that will be shown in the UI const documentaryGenres = [ "History: Ancient", "History: Modern", "History: Hidden", "History: Mythology Myths and Legends", "Science: Space", "Science: Technology", "Science: Environment", "Crime: True Crime", "Crime: Mysteries", "Crime: Conspiracies", "Crime: Political", "Society: Politics", "Society: Social Issues", "Culture: Art & Religion", "Culture: Biography", "Exploration: Nature & Wildlife", "Exploration: Survival", "Specials: The Unexplained", "Specials: Investigative" ]; // Channel-specific genres const channelGenres = [ "Paranormal", "Explainers", "Historical Deep Dives", "True Crime Channels", "Science Channels", "Political Commentary", "Philosophy", "The Unexplained", "Space & Universe", "Engineering & Tech", "Wildlife & Expeditions", "Documentary Filmmakers", "Narrated Storytelling", "Fact-based Channels", "The Smoking Gun" ]; // Playlist-specific genres const playlistGenres = [ "Top Documentaries", "Mini-Series", "Investigation Series", "Crime Series", "Science Explained", "History Timeline", "Compelling Evidence", "Conspiracies and Cover Ups", "Cultural Insights", "YouTube Originals", "Hidden Histories", "The UFO Phenomenon", "Mythology Series", "Conspiracy Deep Dives", "Survival Stories" ]; const manifest = { id: "hy.community.ytdocumentaries", version: "0.5.0", name: "YouTube Documentaries", description: "Discover documentaries from YouTube with channels, playlists, and genres", logo: "https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/1280px-YouTube_full-color_icon_%282017%29.svg.png", resources: ["catalog", "meta", "stream"], types: ["documentary"], // Single coherent type for better organization catalogs: [ { // Main catalog for individual documentaries type: "documentary", id: "ytdocs", name: "YouTube Documentaries", extra: [ { name: "genre", isRequired: false, options: documentaryGenres }, { name: "search", isRequired: false }, { name: "skip", isRequired: false } ], genres: documentaryGenres }, { // Channel catalog type: "documentary", id: "ytdocs-channels", name: "Documentary Channels", extra: [ { name: "genre", isRequired: false, options: channelGenres }, { name: "search", isRequired: false }, { name: "skip", isRequired: false } ], genres: channelGenres }, { // Playlist catalog type: "documentary", id: "ytdocs-playlists", name: "Documentary Playlists", extra: [ { name: "genre", isRequired: false, options: playlistGenres }, { name: "search", isRequired: false }, { name: "skip", isRequired: false } ], genres: playlistGenres }, { // Tag-based search catalog type: "documentary", id: "ytdocs-by-tag", name: "Tagged Documentaries", extra: [ { name: "search", isRequired: true }, { name: "skip", isRequired: false } ] } ], idPrefixes: ["yt:", "ytchannel:", "ytplaylist:"], behaviorHints: { configurable: true, configurationRequired: false } }; const builder = new addonBuilder(manifest); builder.defineCatalogHandler(async ({ type, id, extra }) => { const skip = parseInt(extra.skip || 0); const pageSize = 100; // Only respond to documentary type requests if (type !== "documentary") { return { metas: [] }; } // Handle different catalog types if (id === "ytdocs" || id === "ytdocs-by-tag") { let searchQuery; if (id === "ytdocs-by-tag") { if (!extra.search) return { metas: [] }; searchQuery = extra.search; } else { searchQuery = extra.search ? `${extra.search} documentary` : extra.genre ? `${extra.genre} documentary` : "best documentaries"; } console.log(`[CATALOG] Searching for videos: ${searchQuery}`); const cacheKey = `catalog_${id}_${searchQuery.toLowerCase()}_${skip}`; const cached = cache.get(cacheKey); if (cached) return { metas: cached }; const videos = await searchYouTube({ query: searchQuery, maxResults: pageSize, skip, type: 'video' }); const metas = videos.map(video => ({ id: `yt:${video.id}`, type: "documentary", name: `[${extra.genre || 'Documentary'}] ${video.title}`, poster: video.thumbnail, description: video.description, genres: (video.tags || []).slice(0, 5), releaseInfo: `${new Date(video.publishedAt).getFullYear()} • ${formatViewCount(video.viewCount)}` })); cache.set(cacheKey, metas); return { metas }; } // Handle channel search - explicitly using channel search type else if (id === "ytdocs-channels") { // Use genre if provided, otherwise use default or search const searchTerm = extra.genre ? extra.genre : "documentary"; const searchQuery = extra.search ? `${extra.search} ${searchTerm}` : searchTerm; console.log(`[CATALOG] Searching for channels: ${searchQuery}`); const cacheKey = `catalog_channels_${searchQuery.toLowerCase()}_${skip}`; const cached = cache.get(cacheKey); if (cached) return { metas: cached }; const channels = await searchYouTube({ query: searchQuery, maxResults: pageSize, skip, type: 'channel' }); const metas = channels.map(channel => ({ id: `ytchannel:${channel.id}`, type: "documentary", name: channel.title, poster: channel.thumbnail, posterShape: "square", description: channel.description, genres: ["Documentary Channel", extra.genre || "Educational"], videoCount: "Channel", // Use this field to identify as a channel in UI behaviorHints: { defaultVideoId: null, // Signal this is not a single video hasCollections: true // Signal this item has collections (videos) } })); cache.set(cacheKey, metas); return { metas }; } // Handle playlist search - explicitly using playlist search type else if (id === "ytdocs-playlists") { // Use genre if provided, otherwise use default or search const searchTerm = extra.genre ? extra.genre : "documentary"; const searchQuery = extra.search ? `${extra.search} ${searchTerm}` : searchTerm; console.log(`[CATALOG] Searching for playlists: ${searchQuery}`); const cacheKey = `catalog_playlists_${searchQuery.toLowerCase()}_${skip}`; const cached = cache.get(cacheKey); if (cached) return { metas: cached }; const playlists = await searchYouTube({ query: searchQuery, maxResults: pageSize, skip, type: 'playlist' }); const metas = playlists.map(playlist => ({ id: `ytplaylist:${playlist.id}`, type: "documentary", name: playlist.title, poster: playlist.thumbnail, posterShape: "landscape", description: playlist.description, genres: ["Documentary Playlist", extra.genre || "Collection"], videoCount: "Playlist", // Use this field to identify as a playlist in UI behaviorHints: { defaultVideoId: null, // Signal this is not a single video hasCollections: true // Signal this item has collections (videos) } })); cache.set(cacheKey, metas); return { metas }; } return { metas: [] }; }); builder.defineMetaHandler(async ({ type, id }) => { console.log(`[META] Request for ${type} with id ${id}`); // Only respond to documentary type requests if (type !== "documentary") { return { meta: null }; } // Handle single video meta if (id.startsWith("yt:")) { const videoId = id.split(":")[1]; const meta = await fetchVideoMeta(videoId); return { meta }; } // Handle channel meta with videos as episodes else if (id.startsWith("ytchannel:")) { const channelId = id.split(":")[1]; const cacheKey = `meta_channel_${channelId}`; const cached = cache.get(cacheKey); if (cached) return { meta: cached }; const channelInfo = await fetchChannelInfo(channelId); if (!channelInfo) return { meta: null }; const channelVideos = await fetchChannelVideos(channelId); // Format videos as episodes const videos = await Promise.all( channelVideos.map(async (video, index) => { const tags = await fetchTags(video.id); return { id: `yt:${video.id}`, title: video.title, released: video.publishedAt, thumbnail: video.thumbnail, overview: video.description, season: 1, episode: index + 1, genres: tags.slice(0, 5) }; }) ); const meta = { id: `ytchannel:${channelId}`, type: "documentary", name: channelInfo.title, poster: channelInfo.thumbnail, posterShape: "square", background: channelInfo.banner || channelInfo.thumbnail, description: channelInfo.description, genres: ["Documentary Channel", "Educational"], videos: videos, videoCount: channelInfo.videoCount || "Unknown", releaseInfo: `${videos.length} documentaries` }; cache.set(cacheKey, meta); return { meta }; } // Handle playlist meta with videos as episodes else if (id.startsWith("ytplaylist:")) { const playlistId = id.split(":")[1]; const cacheKey = `meta_playlist_${playlistId}`; const cached = cache.get(cacheKey); if (cached) return { meta: cached }; const playlistInfo = await fetchPlaylistInfo(playlistId); if (!playlistInfo) return { meta: null }; const playlistVideos = await fetchPlaylistVideos(playlistId); // Format videos as episodes - use position to maintain playlist order const videos = await Promise.all( playlistVideos.map(async (video) => { const tags = await fetchTags(video.id); return { id: `yt:${video.id}`, title: video.title, released: video.publishedAt, thumbnail: video.thumbnail, overview: video.description, season: 1, episode: (video.position || 0) + 1, // Use position instead of array index genres: tags.slice(0, 5) }; }) ); // Sort by episode number to maintain playlist order videos.sort((a, b) => a.episode - b.episode); const meta = { id: `ytplaylist:${playlistId}`, type: "documentary", name: playlistInfo.title, poster: playlistInfo.thumbnail, posterShape: "landscape", background: playlistInfo.thumbnail, description: playlistInfo.description, genres: ["Documentary Playlist", "Collection"], videos: videos, videoCount: playlistInfo.videoCount || "Unknown", releaseInfo: `${videos.length} documentaries` }; cache.set(cacheKey, meta); return { meta }; } return { meta: null }; }); // STREAM HANDLER - DIRECT YOUTUBE INTEGRATION builder.defineStreamHandler(({ type, id }) => { console.log(`[STREAM] Request for ${id}`); // Only respond to documentary type requests or handle YouTube IDs if (type !== "documentary" && !id.startsWith("yt:")) { return Promise.resolve({ streams: [] }); } if (!id.startsWith("yt:")) { return Promise.resolve({ streams: [] }); } const videoId = id.split(":")[1]; console.log(`[STREAM] Found YouTube video ID: ${videoId}`); // Return streams directly with YouTube ID return Promise.resolve({ streams: [ { name: "YouTube", ytId: videoId } ] }); }); // Enhanced search function that can handle videos, channels and playlists async function searchYouTube({ query, maxResults = 100, skip = 0, type = 'video' }) { try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); // The key is to use the specific search filters YouTube uses to filter by type const searchParams = { part: "snippet", q: query, maxResults: maxResults + skip, // Request enough to handle skip order: "relevance", relevanceLanguage: "en", type: type // This is the key parameter - must be "video", "channel", or "playlist" }; // Additional parameters based on search type if (type === 'video') { searchParams.videoDuration = "long"; // Prefer longer videos for documentaries searchParams.videoDefinition = "high"; // Prefer HD content } console.log(`[SEARCH] Searching for ${type}s with query: ${query}`); const res = await youtube.search.list(searchParams); const items = res.data.items || []; const paginated = items.slice(skip, skip + maxResults); // Get the appropriate resource IDs based on the type if (type === 'video') { return Promise.all(paginated.map(async item => { const id = item.id.videoId; const tags = await fetchTags(id); return { id, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt, tags: tags }; })); } else if (type === 'channel') { return paginated.map(item => ({ id: item.id.channelId, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt })); } else if (type === 'playlist') { return paginated.map(item => ({ id: item.id.playlistId, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt })); } return []; } catch (error) { console.error(`Error searching YouTube for ${type}:`, error); return []; } } async function fetchTags(videoId) { const cacheKey = `tags_${videoId}`; const cached = cache.get(cacheKey); if (cached) return cached; try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); const res = await youtube.videos.list({ part: "snippet", id: videoId }); const tags = res.data.items?.[0]?.snippet?.tags || []; cache.set(cacheKey, tags); return tags; } catch (error) { console.error("Error fetching tags:", error); return []; } } async function fetchVideoMeta(videoId) { const cacheKey = `video_meta_${videoId}`; const cached = cache.get(cacheKey); if (cached) return cached; try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); const res = await youtube.videos.list({ part: "snippet,contentDetails,statistics", id: videoId }); const item = res.data.items?.[0]; if (!item) return null; const genres = (item.snippet.tags || []).slice(0, 5).map(tag => tag.trim()); const meta = { id: `yt:${videoId}`, type: "documentary", name: item.snippet.title, description: item.snippet.description, poster: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, posterShape: "landscape", background: item.snippet.thumbnails.maxres?.url || item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, released: item.snippet.publishedAt, genres: genres.length > 0 ? genres : ["Documentary"], releaseInfo: item.snippet.publishedAt ? new Date(item.snippet.publishedAt).getFullYear().toString() : "", runtime: item.contentDetails?.duration ? convertDuration(item.contentDetails.duration) : null, // Add watch count trailerStreams: [ { source: `YouTube - ${formatViewCount(item.statistics?.viewCount)}`, ytId: videoId } ] }; cache.set(cacheKey, meta); return meta; } catch (error) { console.error("Error fetching video meta:", error); return null; } } // Format view count nicely function formatViewCount(viewCount) { if (!viewCount) return "Unknown views"; const count = parseInt(viewCount); if (count > 1000000) { return `${(count / 1000000).toFixed(1)}M views`; } else if (count > 1000) { return `${(count / 1000).toFixed(1)}K views`; } return `${count} views`; } // Specifically search for YouTube channels containing documentaries async function fetchChannelInfo(channelId) { try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); const res = await youtube.channels.list({ part: "snippet,statistics,brandingSettings", id: channelId }); const item = res.data.items?.[0]; if (!item) return null; // Get a better banner image if available const bannerUrl = item.brandingSettings?.image?.bannerExternalUrl || item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url; return { id: channelId, title: item.snippet.title, description: `${item.snippet.description}\n\nSubscribers: ${formatSubscriberCount(item.statistics?.subscriberCount)}`, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, banner: bannerUrl, videoCount: formatVideoCount(item.statistics?.videoCount) }; } catch (error) { console.error("Error fetching channel info:", error); return null; } } function formatSubscriberCount(count) { if (!count) return "Unknown"; const subscribers = parseInt(count); if (subscribers > 1000000) { return `${(subscribers / 1000000).toFixed(1)}M`; } else if (subscribers > 1000) { return `${(subscribers / 1000).toFixed(1)}K`; } return subscribers.toString(); } function formatVideoCount(count) { if (!count) return "Unknown"; const videos = parseInt(count); if (videos > 1000) { return `${(videos / 1000).toFixed(1)}K videos`; } return `${videos} videos`; } async function fetchChannelVideos(channelId, maxResults = 50) { try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); // First get uploads playlist ID for the channel const channelRes = await youtube.channels.list({ part: "contentDetails", id: channelId }); const uploadsPlaylistId = channelRes.data.items?.[0]?.contentDetails?.relatedPlaylists?.uploads; if (!uploadsPlaylistId) return []; // Then get videos from that playlist const playlistRes = await youtube.playlistItems.list({ part: "snippet", playlistId: uploadsPlaylistId, maxResults: maxResults }); return (playlistRes.data.items || []).map(item => ({ id: item.snippet.resourceId.videoId, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt })); } catch (error) { console.error("Error fetching channel videos:", error); return []; } } async function fetchPlaylistInfo(playlistId) { try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); const res = await youtube.playlists.list({ part: "snippet,contentDetails,status", id: playlistId }); const item = res.data.items?.[0]; if (!item) return null; // Include privacy status and video count const privacy = item.status?.privacyStatus === 'public' ? 'Public' : (item.status?.privacyStatus === 'unlisted' ? 'Unlisted' : 'Private'); return { id: playlistId, title: item.snippet.title, description: `${item.snippet.description}\n\nVideos: ${item.contentDetails.itemCount || 'Unknown'} (${privacy})`, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.medium?.url || item.snippet.thumbnails.default?.url, videoCount: `${item.contentDetails.itemCount || 'Unknown'} videos` }; } catch (error) { console.error("Error fetching playlist info:", error); return null; } } async function fetchPlaylistVideos(playlistId, maxResults = 50) { try { const youtube = google.youtube({ version: "v3", auth: oauth2Client }); // We need to request more videos for playlists since some might be unavailable const res = await youtube.playlistItems.list({ part: "snippet,contentDetails,status", playlistId: playlistId, maxResults: Math.min(maxResults * 2, 50) // Request more items but respect API limits }); return (res.data.items || []) // Filter out private/deleted videos .filter(item => item.status?.privacyStatus === 'public') .slice(0, maxResults) // Limit to requested amount .map(item => ({ id: item.snippet.resourceId.videoId, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.medium?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt, position: item.snippet.position })); } catch (error) { console.error("Error fetching playlist videos:", error); return []; } } // Utility function to convert YouTube duration format (ISO 8601) to minutes function convertDuration(duration) { const match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); const hours = (match[1] && match[1].slice(0, -1)) || 0; const minutes = (match[2] && match[2].slice(0, -1)) || 0; const seconds = (match[3] && match[3].slice(0, -1)) || 0; return (parseInt(hours) * 60) + parseInt(minutes) + Math.round(parseInt(seconds) / 60); } module.exports = builder.getInterface();