const { addonBuilder } = require("stremio-addon-sdk"); const { google } = require("googleapis"); const axios = require("axios"); // Documentaries-focused manifest const manifest = { id: "hy.community.ytdocumentaries", version: "0.1.0", name: "YouTube Documentaries", description: "Discover documentaries from YouTube with categories and search", 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: ["movie"], // Multiple catalogs for different documentary categories catalogs: [ { type: "movie", id: "ytdocs", name: "YouTube Documentaries", extra: [ { name: "genre", isRequired: false }, { name: "search", isRequired: false }, { name: "skip", isRequired: false } ] } ], idPrefixes: ["yt:"] }; // Documentary categories with search terms const DOCUMENTARY_CATEGORIES = { "history": "history documentary", "nature": "nature documentary", "science": "science documentary", "space": "space documentary", "technology": "technology documentary", "travel": "travel documentary", "war": "war documentary", "crime": "crime documentary", "biography": "biography documentary", "conspiracy": "conspiracy theories documentary" }; // YouTube API key const YT_API_KEY = process.env.YT_API_KEY || "AIzaSyCRFgNu3-oNfGA1IZQ88Qc4k0Pq_jG6IpY"; const builder = new addonBuilder(manifest); // CATALOG HANDLER builder.defineCatalogHandler(({ type, id, extra }) => { console.log(`[CATALOG] Request for ${id} with params:`, extra); if (type !== "movie" || id !== "ytdocs") { return Promise.resolve({ metas: [] }); } let searchQuery; if (extra.search) { searchQuery = extra.search + " documentary"; console.log(`[CATALOG] Searching for: "${searchQuery}"`); } else if (extra.genre && DOCUMENTARY_CATEGORIES[extra.genre]) { searchQuery = DOCUMENTARY_CATEGORIES[extra.genre]; console.log(`[CATALOG] Using category: ${extra.genre} => "${searchQuery}"`); } else { searchQuery = "best documentaries"; console.log(`[CATALOG] Using default catalog: "${searchQuery}"`); } return searchYouTubeVideos(searchQuery) .then(videos => { if (!videos || videos.length === 0) { console.log(`[CATALOG] No results found for: "${searchQuery}"`); return { metas: [] }; } const metas = videos.map(video => ({ id: `yt:${video.videoId}`, type: "movie", name: video.title, poster: video.thumbnail, posterShape: "landscape", description: video.description || "YouTube documentary", releaseInfo: video.publishedAt ? new Date(video.publishedAt).getFullYear().toString() : "" })); console.log(`[CATALOG] Found ${metas.length} results for: "${searchQuery}"`); return { metas, genres: Object.keys(DOCUMENTARY_CATEGORIES) }; }) .catch(error => { console.error(`[CATALOG] Error: ${error.message}`); return { metas: [] }; }); }); // META HANDLER builder.defineMetaHandler(({ type, id }) => { console.log(`[META] Request for ${id}`); if (type !== "movie" || !id.startsWith("yt:")) { return Promise.resolve({ meta: null }); } const videoId = id.split(":")[1]; return getYouTubeVideoDetails(videoId) .then(details => { if (!details) return { meta: null }; const genres = []; if (details.tags && details.tags.length) { const lowercaseTags = details.tags.map(tag => tag.toLowerCase()); Object.keys(DOCUMENTARY_CATEGORIES).forEach(category => { if (lowercaseTags.some(tag => tag.includes(category))) { genres.push(category); } }); } return { meta: { id: id, type: "movie", name: details.title, poster: details.thumbnail, posterShape: "landscape", background: details.thumbnail, logo: details.channelThumbnail || details.thumbnail, description: details.description, runtime: details.duration, releaseInfo: details.publishedAt ? new Date(details.publishedAt).getFullYear().toString() : "", genres: genres.length ? genres : undefined, director: [details.channelTitle] || undefined } }; }) .catch(error => { console.error(`[META] Error: ${error.message}`); return { meta: null }; }); }); // STREAM HANDLER - SIMPLE VERSION THAT WORKS builder.defineStreamHandler(({ type, id }) => { if (!id.startsWith("yt:")) return Promise.resolve({ streams: [] }); const videoId = id.split(":")[1]; return Promise.resolve({ streams: [ { ytId: videoId, // 🔥 Key for inline YouTube playback in Stremio title: "Play Documentary on YouTube" } ] }); }); // HELPER FUNCTIONS // Search YouTube videos with better formatting and filtering for documentaries function searchYouTubeVideos(query, maxResults = 50) { const youtube = google.youtube({ version: "v3", auth: YT_API_KEY }); // Enhanced search params for better documentary results const searchParams = { part: "snippet", q: query, type: "video", maxResults: maxResults, videoDuration: "long", // Prefer longer videos (documentaries) videoDefinition: "high", // Prefer HD content relevanceLanguage: "en" // English content }; console.log(`[YouTube] Searching for: "${query}"`); return youtube.search.list(searchParams) .then(response => { if (!response.data.items || response.data.items.length === 0) { return []; } // Format the results return response.data.items.map(item => ({ videoId: item.id.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, channelTitle: item.snippet.channelTitle })); }) .catch(error => { console.error(`[YouTube] Search error: ${error.message}`); return []; }); } // Get detailed video information function getYouTubeVideoDetails(videoId) { const youtube = google.youtube({ version: "v3", auth: YT_API_KEY }); // Get video details and channel info return youtube.videos.list({ part: "snippet,contentDetails,statistics", id: videoId }) .then(videoResponse => { if (!videoResponse.data.items || videoResponse.data.items.length === 0) { return null; } const video = videoResponse.data.items[0]; const duration = parseDuration(video.contentDetails.duration); const channelId = video.snippet.channelId; // Get channel thumbnail return youtube.channels.list({ part: "snippet", id: channelId }) .then(channelResponse => { let channelThumbnail = null; if (channelResponse.data.items && channelResponse.data.items.length > 0) { channelThumbnail = channelResponse.data.items[0].snippet.thumbnails.default?.url; } return { videoId: video.id, title: video.snippet.title, description: video.snippet.description, thumbnail: video.snippet.thumbnails.high?.url || video.snippet.thumbnails.medium?.url || video.snippet.thumbnails.default?.url, publishedAt: video.snippet.publishedAt, duration: duration, viewCount: video.statistics?.viewCount, channelTitle: video.snippet.channelTitle, channelThumbnail: channelThumbnail, tags: video.snippet.tags || [] }; }) .catch(e => { console.error(`[YouTube] Channel details error: ${e.message}`); // Return video details even without channel thumbnail return { videoId: video.id, title: video.snippet.title, description: video.snippet.description, thumbnail: video.snippet.thumbnails.high?.url || video.snippet.thumbnails.medium?.url || video.snippet.thumbnails.default?.url, publishedAt: video.snippet.publishedAt, duration: duration, viewCount: video.statistics?.viewCount, channelTitle: video.snippet.channelTitle, tags: video.snippet.tags || [] }; }); }) .catch(error => { console.error(`[YouTube] Video details error: ${error.message}`); return null; }); } // Parse ISO 8601 duration format function parseDuration(isoDuration) { const match = isoDuration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); let hours = 0; let minutes = 0; let seconds = 0; if (match[1]) hours = parseInt(match[1].slice(0, -1)); if (match[2]) minutes = parseInt(match[2].slice(0, -1)); if (match[3]) seconds = parseInt(match[3].slice(0, -1)); return `${hours ? hours + "h " : ""}${minutes}min${seconds ? " " + seconds + "s" : ""}`; } module.exports = builder.getInterface();