const { addonBuilder } = require("stremio-addon-sdk"); const { google } = require("googleapis"); const NodeCache = require("node-cache"); const cache = new NodeCache({ stdTTL: 3600 }); // Define documentary categories/genres that will be shown in the UI const documentaryGenres = [ "History: Ancient", "History: Modern", "Science: Space", "Science: Technology", "Science: Environment", "Crime: True Crime", "Crime: Mysteries", "Society: Politics", "Society: Social Issues", "Culture: Art & Religion", "Culture: Biography", "Exploration: Nature & Wildlife", "Exploration: Survival", "Specials: Conspiracies", "Specials: Investigative" ]; // Channel-specific genres const channelGenres = [ "Education", "History", "Science", "Travel", "Wildlife", "News", "Conspiracy", "Technology", "Archaeology", "Space", "Anthropology", "Culture" ]; // Playlist-specific genres const playlistGenres = [ "Educational", "Series", "Collections", "Lectures", "Top Documentaries", "Mysteries", "Historical Events", "Science Explained", "Nature & Wildlife" ]; // Quality documentary channels to prioritize const QUALITY_CHANNELS = [ 'UCsXVk37bltHxD1rDPwtNM8Q', // Kurzgesagt 'UC6nSFpj9HTCZ5t-N3Rm3-HA', // Vsauce 'UCHnyfMqiRRG1u-2MsSQLbXA', // Veritasium 'UCYO_jab_esuFRV4b17AJtAw', // 3Blue1Brown 'UCJ0-OtVpF0wOKEqT2Z1HEtA', // ElectroBOOM 'UCBa659QWEk1AI4Tg--mrJ2A', // Tom Scott 'UC2C_jShtL725hvbm1arSV9w', // CGP Grey 'UCoxcjq-8xIDTYp3uz647V5A', // Numberphile 'UCP5tjEmvPItGyLhmjdwP7Ww', // Real Engineering 'UCJ24N4O0bP7LGLBDvye7oCA', // Matt Parker 'UC9-y-6csu5WGm29I7JiwpnA', // Computerphile 'UCsXVk37bltHxD1rDPwtNM8Q', // Kurzgesagt 'UCUHW94eEFW7hkUMVaZz4eDg', // minutephysics 'UCimiUgDLbi6P17BdaCZpVbg', // Domain of Science 'UC7_gcs09iThXybpVgjHZ_7g', // PBS Space Time 'UCAL3JXZSzSm8AlZyD3nQdBA', // Primitive Technology 'UCZYTClx2T1of7BRZ86-8fow', // SciShow 'UC6107grRI4m0o2-emgoDnAA', // SmarterEveryDay 'UCp68_FLety0O-n9QU6phsgw', // AsapSCIENCE 'UCEIwxahdLz7bap-VDs9h35A' // Steve1989MREInfo ]; // Keywords that indicate low-quality content const LOW_QUALITY_KEYWORDS = [ 'react', 'reacts', 'reaction', 'responds', 'response', 'shorts', 'tiktok', 'instagram', 'stories', 'unboxing', 'haul', 'vlog', 'daily', 'challenge', 'prank', 'funny', 'fails', 'compilation', 'memes', 'cringe', 'top 10', 'top 5', 'listicle', 'clickbait', 'exposed', 'truth about', 'you won\'t believe', 'shocking', 'influencer', 'lifestyle', 'routine', 'trending', 'viral', 'drama' ]; // Keywords that indicate high-quality documentary content const QUALITY_KEYWORDS = [ 'documentary', 'investigation', 'analysis', 'explained', 'history', 'science', 'research', 'study', 'lecture', 'educational', 'academic', 'deep dive', 'comprehensive', 'thorough', 'evidence', 'facts', 'data', 'statistics', 'expert', 'professor', 'scientist', 'exploration', 'discovery', 'breakthrough', 'understanding', 'knowledge', 'learning' ]; const manifest = { id: "hy.community.ytdocumentaries", version: "0.6.0", name: "YouTube Documentaries (Quality Filtered)", description: "Discover high-quality documentaries from YouTube with advanced filtering", 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"], catalogs: [ { type: "documentary", id: "ytdocs", name: "YouTube Documentaries", extra: [ { name: "genre", isRequired: false, options: documentaryGenres }, { name: "search", isRequired: false }, { name: "skip", isRequired: false } ], genres: documentaryGenres }, { 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 }, { 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 }, { type: "documentary", id: "ytdocs-by-tag", name: "Tagged Documentaries", extra: [ { name: "search", isRequired: true }, { name: "skip", isRequired: false } ] }, { type: "documentary", id: "ytdocs-quality", name: "Premium Quality Documentaries", extra: [ { name: "search", isRequired: false }, { name: "skip", isRequired: false } ] } ], idPrefixes: ["yt:", "ytchannel:", "ytplaylist:"], behaviorHints: { configurable: true, configurationRequired: false } }; const builder = new addonBuilder(manifest); // Quality scoring function function calculateQualityScore(video) { let score = 0; const title = video.title.toLowerCase(); const description = (video.description || '').toLowerCase(); const text = title + ' ' + description; // Duration scoring (prefer longer videos) if (video.duration) { const minutes = parseDuration(video.duration); if (minutes > 60) score += 30; // 1+ hour else if (minutes > 30) score += 20; // 30+ minutes else if (minutes > 15) score += 10; // 15+ minutes else if (minutes < 5) score -= 20; // Very short videos } // View count scoring (prefer established content) if (video.viewCount) { const views = parseInt(video.viewCount); if (views > 1000000) score += 15; // 1M+ views else if (views > 100000) score += 10; // 100K+ views else if (views > 10000) score += 5; // 10K+ views else if (views < 1000) score -= 10; // Very low views } // Channel quality scoring if (QUALITY_CHANNELS.includes(video.channelId)) { score += 50; // Big boost for known quality channels } // Content quality keywords QUALITY_KEYWORDS.forEach(keyword => { if (text.includes(keyword)) score += 5; }); // Penalize low-quality indicators LOW_QUALITY_KEYWORDS.forEach(keyword => { if (text.includes(keyword)) score -= 15; }); // Prefer videos with educational tags if (video.tags && video.tags.length > 0) { const educationalTags = video.tags.filter(tag => ['documentary', 'educational', 'science', 'history', 'learning'].some(edu => tag.toLowerCase().includes(edu) ) ); score += educationalTags.length * 3; } // Title quality indicators if (title.includes('documentary')) score += 10; if (title.includes('full') || title.includes('complete')) score += 8; if (title.includes('hd') || title.includes('4k')) score += 5; // Penalize obvious clickbait patterns if (/\d+\s*(amazing|shocking|incredible|unbelievable)/.test(title)) score -= 20; if (title.includes('!!!') || title.includes('???')) score -= 10; if (title.toUpperCase() === title) score -= 15; // ALL CAPS return score; } // Enhanced duration parser function parseDuration(duration) { if (!duration) return 0; // Handle ISO 8601 format (PT1H30M45S) const iso8601Match = duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/); if (iso8601Match) { const hours = parseInt(iso8601Match[1]) || 0; const minutes = parseInt(iso8601Match[2]) || 0; const seconds = parseInt(iso8601Match[3]) || 0; return (hours * 60) + minutes + (seconds / 60); } // Handle simple formats like "45:30" or "1:30:45" const timeParts = duration.split(':').map(p => parseInt(p)); if (timeParts.length === 2) { return timeParts[0] + (timeParts[1] / 60); } else if (timeParts.length === 3) { return (timeParts[0] * 60) + timeParts[1] + (timeParts[2] / 60); } return 0; } builder.defineCatalogHandler(async ({ type, id, extra }) => { const skip = parseInt(extra.skip || 0); const pageSize = 50; if (type !== "documentary") { return { metas: [] }; } // Handle premium quality catalog if (id === "ytdocs-quality") { console.log(`[CATALOG] Fetching premium quality documentaries`); const cacheKey = `catalog_quality_${extra.search || 'default'}_${skip}`; const cached = cache.get(cacheKey); if (cached) return { metas: cached }; let allVideos = []; // Search from quality channels first const channelPromises = QUALITY_CHANNELS.slice(0, 10).map(async channelId => { try { const videos = await fetchChannelVideos(channelId, 10); return videos.map(v => ({ ...v, channelId, isQualityChannel: true })); } catch (error) { console.error(`Error fetching from quality channel ${channelId}:`, error); return []; } }); const channelResults = await Promise.all(channelPromises); allVideos = channelResults.flat(); // Also search with quality-focused queries const searchQuery = extra.search ? `${extra.search} documentary full length HD` : "documentary full length educational science history"; const searchVideos = await searchYouTube({ query: searchQuery, maxResults: pageSize, skip: 0, type: 'video', qualityFilter: true }); allVideos = allVideos.concat(searchVideos); // Remove duplicates and score const uniqueVideos = allVideos.reduce((acc, video) => { if (!acc.find(v => v.id === video.id)) { acc.push(video); } return acc; }, []); // Score and sort by quality const scoredVideos = uniqueVideos.map(video => ({ ...video, qualityScore: calculateQualityScore(video) })); scoredVideos.sort((a, b) => b.qualityScore - a.qualityScore); const paginatedVideos = scoredVideos.slice(skip, skip + pageSize); const metas = paginatedVideos.map(video => ({ id: `yt:${video.id}`, type: "documentary", name: `[Quality] ${video.title}`, poster: video.thumbnail, description: video.description, genres: (video.tags || []).slice(0, 5), releaseInfo: video.publishedAt ? `${new Date(video.publishedAt).getFullYear()} • ${formatViewCount(video.viewCount)} • Score: ${video.qualityScore}` : `Score: ${video.qualityScore}` })); cache.set(cacheKey, metas); return { metas }; } // Handle other catalog types with enhanced filtering 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 + " -shorts -react -reaction", // Exclude common low-quality content maxResults: pageSize * 2, // Get more to filter skip, type: 'video', qualityFilter: true }); // Filter and score videos const qualityVideos = videos .map(video => ({ ...video, qualityScore: calculateQualityScore(video) })) .filter(video => video.qualityScore > 0) // Only include positive scores .sort((a, b) => b.qualityScore - a.qualityScore) .slice(0, pageSize); const metas = qualityVideos.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: video.publishedAt ? `${new Date(video.publishedAt).getFullYear()} • ${formatViewCount(video.viewCount)}` : "" })); cache.set(cacheKey, metas); return { metas }; } // Handle channel search with quality filtering else if (id === "ytdocs-channels") { 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 + " educational documentary channel", 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", behaviorHints: { defaultVideoId: null, hasCollections: true } })); cache.set(cacheKey, metas); return { metas }; } // Handle playlist search with quality filtering else if (id === "ytdocs-playlists") { 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 + " playlist documentary collection", 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", behaviorHints: { defaultVideoId: null, hasCollections: true } })); cache.set(cacheKey, metas); return { metas }; } return { metas: [] }; }); builder.defineMetaHandler(async ({ type, id }) => { console.log(`[META] Request for ${type} with id ${id}`); if (type !== "documentary") { return { meta: null }; } if (id.startsWith("yt:")) { const videoId = id.split(":")[1]; const meta = await fetchVideoMeta(videoId); return { meta }; } 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); // Filter channel videos for quality const qualityVideos = channelVideos .map(video => ({ ...video, qualityScore: calculateQualityScore(video) })) .filter(video => video.qualityScore > -10) // More lenient for channel content .sort((a, b) => b.qualityScore - a.qualityScore); const videos = await Promise.all( qualityVideos.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 }; } 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); // Filter playlist videos for quality const qualityVideos = playlistVideos .map(video => ({ ...video, qualityScore: calculateQualityScore(video) })) .filter(video => video.qualityScore > -15) // More lenient for playlist content .sort((a, b) => (a.position || 0) - (b.position || 0)); // Maintain playlist order const videos = await Promise.all( qualityVideos.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, genres: (tags || []).slice(0, 5) }; }) ); 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 }; }); builder.defineStreamHandler(({ type, id }) => { console.log(`[STREAM] Request for ${id}`); 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 Promise.resolve({ streams: [ { name: "YouTube", ytId: videoId } ] }); }); // Enhanced search function with quality filtering async function searchYouTube({ query, maxResults = 50, skip = 0, type = 'video', qualityFilter = false }) { try { const youtube = google.youtube({ version: "v3", auth: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); const searchParams = { part: "snippet", q: query, maxResults: maxResults + skip, order: "relevance", relevanceLanguage: "en", type: type }; if (type === 'video') { searchParams.videoDuration = "medium"; // At least 4 minutes, prefer longer searchParams.videoDefinition = "high"; searchParams.videoCaption = "closedCaption"; // Prefer videos with captions if (qualityFilter) { searchParams.videoDuration = "long"; // Prefer longer videos for quality filter searchParams.order = "viewCount"; // Sort by view count for quality } } 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); if (type === 'video') { // Get detailed video information for quality scoring const videoIds = paginated.map(item => item.id.videoId).join(','); const detailsRes = await youtube.videos.list({ part: "snippet,contentDetails,statistics", id: videoIds }); return detailsRes.data.items.map(item => { const tags = item.snippet.tags || []; return { id: item.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, duration: item.contentDetails.duration, viewCount: item.statistics.viewCount, channelId: item.snippet.channelId }; }); } 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: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); 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: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); 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, 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; } } 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`; } async function fetchChannelInfo(channelId) { try { const youtube = google.youtube({ version: "v3", auth: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); const res = await youtube.channels.list({ part: "snippet,statistics,brandingSettings", id: channelId }); const item = res.data.items?.[0]; if (!item) return null; 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: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); // 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 []; // Get videos from uploads playlist const playlistRes = await youtube.playlistItems.list({ part: "snippet", playlistId: uploadsPlaylistId, maxResults: Math.min(maxResults * 2, 50) // Get more to filter out low quality }); const videoIds = (playlistRes.data.items || []) .map(item => item.snippet.resourceId.videoId) .join(','); if (!videoIds) return []; // Get detailed video information for quality filtering const detailsRes = await youtube.videos.list({ part: "snippet,contentDetails,statistics", id: videoIds }); return (detailsRes.data.items || []).map(item => ({ id: item.id, title: item.snippet.title, description: item.snippet.description, thumbnail: item.snippet.thumbnails.high?.url || item.snippet.thumbnails.default?.url, publishedAt: item.snippet.publishedAt, duration: item.contentDetails.duration, viewCount: item.statistics.viewCount, tags: item.snippet.tags || [], channelId: item.snippet.channelId })); } catch (error) { console.error("Error fetching channel videos:", error); return []; } } async function fetchPlaylistInfo(playlistId) { try { const youtube = google.youtube({ version: "v3", auth: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); const res = await youtube.playlists.list({ part: "snippet,contentDetails,status", id: playlistId }); const item = res.data.items?.[0]; if (!item) return null; 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: "AIzaSyAHF0m6WwH4nYU_ebnrJXCjQ4bGYBrvi68" }); const res = await youtube.playlistItems.list({ part: "snippet,contentDetails,status", playlistId: playlistId, maxResults: Math.min(maxResults * 2, 50) }); const videoIds = (res.data.items || []) .filter(item => item.status?.privacyStatus === 'public') .map(item => item.snippet.resourceId.videoId) .join(','); if (!videoIds) return []; // Get detailed video information for quality filtering const detailsRes = await youtube.videos.list({ part: "snippet,contentDetails,statistics", id: videoIds }); // Map back to playlist items to preserve position const playlistItems = (res.data.items || []) .filter(item => item.status?.privacyStatus === 'public') .slice(0, maxResults); return playlistItems.map(playlistItem => { const videoId = playlistItem.snippet.resourceId.videoId; const videoDetails = detailsRes.data.items.find(v => v.id === videoId); return { id: videoId, title: playlistItem.snippet.title, description: playlistItem.snippet.description, thumbnail: playlistItem.snippet.thumbnails.high?.url || playlistItem.snippet.thumbnails.medium?.url || playlistItem.snippet.thumbnails.default?.url, publishedAt: playlistItem.snippet.publishedAt, position: playlistItem.snippet.position, duration: videoDetails?.contentDetails?.duration, viewCount: videoDetails?.statistics?.viewCount, tags: videoDetails?.snippet?.tags || [], channelId: videoDetails?.snippet?.channelId }; }); } 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();