From bd1944aec5d4f98c280f7c19bb2018234455aae4 Mon Sep 17 00:00:00 2001 From: macdja38 Date: Mon, 10 Jun 2019 20:11:22 -0400 Subject: [PATCH] Follow http/https redirects when playing song --- lib/voice/Piper.js | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/voice/Piper.js b/lib/voice/Piper.js index e8111b2d6..620e5ad2f 100644 --- a/lib/voice/Piper.js +++ b/lib/voice/Piper.js @@ -20,6 +20,28 @@ try { EventEmitter = require("events").EventEmitter; } +function resolveHTTPType(link) { + return link.startsWith("http://") ? HTTP : HTTPS; +} + +function webGetter(link, depth = 8) { + return new Promise((resolve, reject) => { + resolveHTTPType(link).get(link, (res) => { + const { statusCode, headers } = res.hasOwnProperty("statusCode") ? res : res.res; + + if(statusCode === 301 || statusCode === 302 || statusCode === 307 || statusCode === 308) { + if(depth <= 0) { + reject(new Error("too many redirects")); + } else { + resolve(webGetter(headers.location, depth - 1)); + } + } else { + resolve(res); + } + }).once('error', reject); + }); +} + class Piper extends EventEmitter { constructor(converterCommand, opus) { super(); @@ -48,11 +70,7 @@ class Piper extends EventEmitter { if(options.format === "dca" || options.format === "ogg" || options.format === "webm" || options.format === "pcm") { if(source.startsWith("http://") || source.startsWith("https://")) { const passThrough = new PassThroughStream(); - if(source.startsWith("http://")) { - HTTP.get(source, (res) => res.pipe(passThrough)).once("error", (e) => this.stop(e)); - } else { - HTTPS.get(source, (res) => res.pipe(passThrough)).once("error", (e) => this.stop(e)); - } + webGetter(source).then(res => res.pipe(passThrough)).catch(e => this.stop(e)); source = passThrough; } else { try {