From d19407156eec330d77d9f51f17b83f65dbfdf1f3 Mon Sep 17 00:00:00 2001 From: Ashley Date: Sat, 25 Feb 2023 17:48:15 +0000 Subject: [PATCH] Refactor code :3 --- src/libpoketube/libpoketube-video.js | 64 ++++++++++++++-------------- 1 file changed, 31 insertions(+), 33 deletions(-) diff --git a/src/libpoketube/libpoketube-video.js b/src/libpoketube/libpoketube-video.js index 68fd57da..941c15e1 100644 --- a/src/libpoketube/libpoketube-video.js +++ b/src/libpoketube/libpoketube-video.js @@ -10,7 +10,7 @@ please dont remove this comment while sharing this code - */ +*/ const { fetcher, @@ -34,44 +34,42 @@ const { } = require("./ptutils/libpt-coreutils.js"); module.exports = async function (video_id) { - var url; - + // function to convert an array to an object, ignoring undefined values function toObject(arr) { - var rv = {}; - for (var i = 0; i < arr.length; ++i) - if (arr[i] !== undefined) rv[i] = arr[i]; - return rv; + return arr.reduce((acc, cur, i) => { + if (cur !== undefined) { + acc[i] = cur; + } + return acc; + }, {}); } try { - // gets invidious instances - let inv_url = "https://api.invidious.io/instances.json?sort_by=type,health"; + // gets invidious instances + const invUrl = "https://api.invidious.io/instances.json?sort_by=type,health"; + const invInstanceList = await modules + .fetch(invUrl) + .then((res) => res.text()) + .then((json) => JSON.parse(json)); - let inv_instance_list = await modules - .fetch(inv_url) - .then((res) => res.text()) - .then((json) => JSON.parse(json)); + // gets random instances from the list + const instance = invInstanceList[Math.floor(Math.random() * invInstanceList.length)]; - // gets random instances from the list - const instance = await inv_instance_list[ - Math.floor(Math.random() * inv_instance_list.length) - ]; + let url; + if (instance[1].type != "https") { + url = "https://invidious.weblibre.org"; + } else { + url = instance[1].uri + .replace("invidious.tiekoetter.com", "invidious.weblibre.org") + .replace("yewtu.be", "invidious.sethforprivacy.com") + .replace("invidious.slipfox.xyz", "invidious.weblibre.org") + .replace("vid.priv.au", "inv.vern.cc") + .replace("invidious.snopyta.org", "invidious.sethforprivacy.com"); + } - const stringed = toObject(instance); - - if (stringed[1].type != "https") { - url = "https://invidious.weblibre.org"; - } else { - url = stringed[1].uri - .replace("invidious.tiekoetter.com", "invidious.weblibre.org") - .replace("yewtu.be", "invidious.sethforprivacy.com") - .replace("invidious.slipfox.xyz", "invidious.weblibre.org") - .replace("vid.priv.au", "inv.vern.cc") - .replace("invidious.snopyta.org", "invidious.sethforprivacy.com"); - } - - return url; - } catch { - return " " + return url; + } catch (error) { + console.error("Failed to get Invidious instance:", error); + return " "; } };