@alufi/ytsr
Version:
A ytsr fork. Made for Alufi Bot Utility
71 lines (63 loc) • 3.01 kB
JavaScript
const UTIL = require('./util');
const BASE_VIDEO_URL = 'https://www.youtube.com/watch?v=';
const URL = require('url').URL;
module.exports = item => {
const type = Object.keys(item)[0];
try {
switch (type) {
case 'videoRenderer':
return parseVideo(item[type]);
case 'playlistRenderer':
return parsePlaylist(item[type]);
case 'gridVideoRenderer':
return parseVideo(item[type]);
default:
return null;
}
} catch (Error) {
console.error(Error);
return null;
}
};
const parseVideo = obj => {
if (!obj.videoId || obj.upcomingEventData) return null;
const author = obj.ownerText && obj.ownerText.runs[0];
const authorUrl = author && (author.navigationEndpoint.browseEndpoint.canonicalBaseUrl ||
author.navigationEndpoint.commandMetadata.webCommandMetadata.url);
const isLive = Array.isArray(obj.badges) ? !obj.badges.find(a => a.metadataBadgeRenderer.label === 'LIVE NOW') : false;
const authorThumbnails = !author ? null : obj.channelThumbnailSupportedRenderers.channelThumbnailWithLinkRenderer.thumbnail.thumbnails;
const ownerBadges = obj.ownerBadges && JSON.stringify(obj.ownerBadges);
const isOfficial = ownerBadges && !!ownerBadges.includes('OFFICIAL');
const isVerified = ownerBadges && !!ownerBadges.includes('VERIFIED');
const lengthFallback = obj.thumbnailOverlays.find(x => Object.keys(x)[0] === 'thumbnailOverlayTimeStatusRenderer');
const length = obj.lengthText || (lengthFallback && lengthFallback.thumbnailOverlayTimeStatusRenderer.text);
return {
type: 'video',
name: UTIL.parseText(obj.title),
id: obj.videoId,
url: BASE_VIDEO_URL + obj.videoId,
thumbnail: UTIL.validateThumbUrl(UTIL.sortImg(obj.thumbnail.thumbnails)[0].url),
isLive,
// Author can be null for shows like whBqghP5Oow
author: author ? {
name: author.text,
channelID: author.navigationEndpoint.browseEndpoint.browseId,
url: new URL(authorUrl, BASE_VIDEO_URL).toString(),
bestAvatar: UTIL.sortImg(authorThumbnails)[0],
avatars: UTIL.sortImg(authorThumbnails),
ownerBadges: Array.isArray(obj.ownerBadges) ? obj.ownerBadges.map(a => a.metadataBadgeRenderer.tooltip) : [],
verified: isOfficial || isVerified,
} : null,
description: obj.descriptionSnippet ? UTIL.parseText(obj.descriptionSnippet) : null,
views: obj.viewCountText ? UTIL.parseIntegerFromText(obj.viewCountText) : null,
duration: isLive ? 'Live' : length,
uploadedAt: obj.publishedTimeText ? UTIL.parseText(obj.publishedTimeText) : null,
};
};
const parsePlaylist = obj => ({
type: 'playlist',
id: obj.playlistId,
name: UTIL.parseText(obj.title),
url: `https://www.youtube.com/playlist?list=${obj.playlistId}`,
length: UTIL.parseIntegerFromText(obj.videoCount),
});