From 2f3772816c064f18001075a88f35378dd5a23d67 Mon Sep 17 00:00:00 2001 From: Ovyerus Date: Thu, 11 Jan 2018 16:36:26 +1100 Subject: [PATCH] Alter YouTube music handler to get an audio-only Opus format, to increase speed of caching --- src/cmd/main/music/handlers/YouTubeHandler.js | 48 ++++++++----------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/src/cmd/main/music/handlers/YouTubeHandler.js b/src/cmd/main/music/handlers/YouTubeHandler.js index 3613b233..77066247 100644 --- a/src/cmd/main/music/handlers/YouTubeHandler.js +++ b/src/cmd/main/music/handlers/YouTubeHandler.js @@ -6,40 +6,32 @@ const ytdl = require('ytdl-core'); const got = require('got'); +const ITAG = '251'; // Preferred iTag quality to get. Default: 251. + class YouTubeHandler { constructor() {} - getInfo(url) { - return new Promise((resolve, reject) => { - if (typeof url !== 'string') throw new TypeError('url is not a string.'); - - ytdl.getInfo(url, {filter: 'audioonly'}).then(info => { - let res = { - url, - title: info.title, - uploader: info.author.name, - thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'), - length: Number(info.length_seconds), - type: 'YouTubeVideo' - }; - - return res; - }).then(resolve).catch(reject); - }); + async getInfo(url) { + if (typeof url !== 'string') throw new TypeError('url is not a string.'); + + let info = await ytdl.getInfo(url); + let res = { + url, + title: info.title, + uploader: info.author.name, + thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'), + length: Number(info.length_seconds), + type: 'YouTubeVideo' + }; + + return res; } - getStream(url) { - return new Promise((resolve, reject) => { - if (typeof url !== 'string') throw new TypeError('url is not a string.'); + async getStream(url) { + if (typeof url !== 'string') throw new TypeError('url is not a string.'); - ytdl.getInfo(url, {filter: 'audioonly'}).then(info => { - // Sort the various bitrates and pick the highest quality (that is 96kbps or less) - let bitrates = info.formats.filter(f => f.audioBitrate <= 96 && typeof f.audioBitrate === 'number'); - bitrates = bitrates.map(f => {return {bitrate: f.bitrate, url: f.url};}).sort((a, b) => b.bitrate - a.bitrate); - - return got.stream(bitrates[0].url); - }).then(resolve).catch(reject); - }); + let info = await ytdl.getInfo(url) + return got.stream(info.formats.find(f => f.itag === ITAG).url); } }