From e11ee6fb629e4ab1ddc8d5f5c7a4b5fe8c75e51f Mon Sep 17 00:00:00 2001 From: wukko Date: Tue, 16 Aug 2022 13:14:19 +0600 Subject: [PATCH] clean up --- README.md | 6 +-- src/cobalt.js | 4 +- src/front/cobalt.js | 6 +-- src/localization/languages/ru.json | 2 +- src/modules/api.js | 6 +-- src/modules/build.js | 2 +- src/modules/config.js | 28 ++++++------ src/modules/emoji.js | 2 +- src/modules/match.js | 4 +- src/modules/pageRender/elements.js | 8 ++-- src/modules/pageRender/page.js | 62 +++++++++++++-------------- src/modules/services/bilibili.js | 2 +- src/modules/services/douyin.js | 18 ++++---- src/modules/services/reddit.js | 2 +- src/modules/services/twitter.js | 2 +- src/modules/services/vk.js | 2 +- src/modules/services/youtube.js | 20 ++++++--- src/modules/servicesConfig.json | 9 +--- src/modules/servicesPatternTesters.js | 10 ++--- src/modules/setup.js | 4 +- src/modules/stream/selectQuality.js | 11 ++--- src/modules/stream/types.js | 5 --- src/modules/sub/matchActionDecider.js | 4 +- src/modules/sub/utils.js | 2 +- 24 files changed, 106 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index 5bdc8a7a..6b26b9c2 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Take English or Russian localization from [this directory](https://github.com/wu - [ ] Add an option to keep watermark on TikTok videos ### Other -- [ ] Remake video quality picking (do it more like I did in Vimeo module) +- [ ] Remake video quality picking - [ ] Add support for emoji in localization - [ ] Language picker in settings - [ ] Make cobalt fully PWA compatible (add a service worker) @@ -96,8 +96,6 @@ Setup script installs all needed `npm` dependencies, but you have to install `No ## Disclaimer This is my passion project, so update scheduele depends solely on my motivation. Don't expect any consistency in that. -## Third party stuff -[Fluent Emoji](https://github.com/microsoft/fluentui-emoji) by Microsoft. - ## License cobalt is under [AGPL-3.0](https://github.com/wukko/cobalt/blob/current/LICENSE). +[Fluent Emoji](https://github.com/microsoft/fluentui-emoji) by Microsoft is under [MIT](https://github.com/microsoft/fluentui-emoji/blob/main/LICENSE). diff --git a/src/cobalt.js b/src/cobalt.js index 1918e689..cb327708 100644 --- a/src/cobalt.js +++ b/src/cobalt.js @@ -50,8 +50,8 @@ if (fs.existsSync('./.env')) { try { decodeURIComponent(req.path) } - catch(e) { - return res.redirect(process.env.selfURL); + catch (e) { + return res.redirect(process.env.selfURL); } next(); }); diff --git a/src/front/cobalt.js b/src/front/cobalt.js index 1157d927..9424d82d 100644 --- a/src/front/cobalt.js +++ b/src/front/cobalt.js @@ -51,7 +51,7 @@ function changeDownloadButton(action, text) { break; } } -document.addEventListener("keydown", function (event) { +document.addEventListener("keydown", (event) => { if (event.key == "Tab") { eid("download-button").value = '>>' eid("download-button").style.padding = '0 1rem' @@ -257,7 +257,7 @@ async function download(url) { } }).catch((error) => internetError()); } -window.onload = function () { +window.onload = () => { loadSettings(); detectColorScheme(); changeDownloadButton(0, '>>'); @@ -274,6 +274,6 @@ window.onload = function () { eid("url-input-area").addEventListener("keyup", (event) => { if (event.key === 'Enter') eid("download-button").click(); }) -document.onkeydown = function(event) { +document.onkeydown = (event) => { if (event.key === 'Escape') hideAllPopups(); }; \ No newline at end of file diff --git a/src/localization/languages/ru.json b/src/localization/languages/ru.json index 7ee8310f..19a6f161 100644 --- a/src/localization/languages/ru.json +++ b/src/localization/languages/ru.json @@ -59,7 +59,7 @@ "SettingsEnableDownloadPopup": "спрашивать, как сохранять", "AccessibilityEnableDownloadPopup": "спрашивать, что делать с загрузками", "SettingsFormatDescription": "выбирай webm, если хочешь максимальное качество. webm обычно лучше по качеству, но устройства на ios не могут проигрывать их без сторонних приложений.", - "SettingsQualityDescription": "если выбранное разрешение недоступно, то выбирается ближайшее к нему. если ты хочешь твитнуть загруженное видео, то выбирай комбинацию из mp4 и 720p. такие видео твиттер обычно воспринимает намного лучше.", + "SettingsQualityDescription": "если выбранное разрешение недоступно, то выбирается ближайшее к нему. если ты хочешь твитнуть загруженное видео, то выбирай комбинацию из mp4 и 720p. твиттер такие видео обычно воспринимает намного лучше.", "DonateSubtitle": "помоги мне платить за хостинг", "DonateDescription": "я не люблю крипто в его текущем состоянии, но у меня нет другого надёжного способа оплаты хостинга.", "LinkGitHubIssues": ">> сообщай о проблемах и смотри исходный код на github", diff --git a/src/modules/api.js b/src/modules/api.js index 9e956aad..0d53760d 100644 --- a/src/modules/api.js +++ b/src/modules/api.js @@ -29,10 +29,10 @@ export async function getJSON(originalURL, ip, lang, format, quality, audioForma } if (patternMatch) { return await match(host, patternMatch, url, ip, lang, format, quality, audioFormat, isAudioOnly); - } return apiJSON(0, { t: errorUnsupported(lang) } ) - } return apiJSON(0, { t: errorUnsupported(lang) } ) + } return apiJSON(0, { t: errorUnsupported(lang) }) + } return apiJSON(0, { t: errorUnsupported(lang) }) } else { - return apiJSON(0, { t: errorUnsupported(lang) } ) + return apiJSON(0, { t: errorUnsupported(lang) }) } } catch (e) { return apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') }); diff --git a/src/modules/build.js b/src/modules/build.js index a1f9a9cd..fdeebdab 100644 --- a/src/modules/build.js +++ b/src/modules/build.js @@ -6,7 +6,7 @@ export async function buildFront() { entryPoints: ['src/front/cobalt.js', 'src/front/cobalt.css'], outdir: `min/`, minify: true, - loader: {".js": "js", ".css": "css"} + loader: { ".js": "js", ".css": "css" } }) } catch (e) { return; diff --git a/src/modules/config.js b/src/modules/config.js index a0a4521f..a8bb8424 100644 --- a/src/modules/config.js +++ b/src/modules/config.js @@ -3,17 +3,17 @@ const config = loadJson("./src/config.json"); const packageJson = loadJson("./package.json"); export const -services = loadJson("./src/modules/servicesConfig.json"), -appName = packageJson.name, -version = packageJson.version, -streamLifespan = config.streamLifespan, -maxVideoDuration = config.maxVideoDuration, -genericUserAgent = config.genericUserAgent, -repo = packageJson["bugs"]["url"].replace('/issues', ''), -authorInfo = config.authorInfo, -supportedLanguages = config.supportedLanguages, -quality = config.quality, -internetExplorerRedirect = config.internetExplorerRedirect, -donations = config.donations, -ffmpegArgs = config.ffmpegArgs, -supportedAudio = config.supportedAudio + services = loadJson("./src/modules/servicesConfig.json"), + appName = packageJson.name, + version = packageJson.version, + streamLifespan = config.streamLifespan, + maxVideoDuration = config.maxVideoDuration, + genericUserAgent = config.genericUserAgent, + repo = packageJson["bugs"]["url"].replace('/issues', ''), + authorInfo = config.authorInfo, + supportedLanguages = config.supportedLanguages, + quality = config.quality, + internetExplorerRedirect = config.internetExplorerRedirect, + donations = config.donations, + ffmpegArgs = config.ffmpegArgs, + supportedAudio = config.supportedAudio diff --git a/src/modules/emoji.js b/src/modules/emoji.js index 705913a3..98bce6e0 100644 --- a/src/modules/emoji.js +++ b/src/modules/emoji.js @@ -17,7 +17,7 @@ let sizing = { } export default function(emoji, size, disablePadding) { if (!size) size = 22; - let padding = size != 22 ? `margin-right:${sizing[size] ? sizing[size] : "0.4"}rem;`: ``; + let padding = size != 22 ? `margin-right:${sizing[size] ? sizing[size] : "0.4"}rem;` : ``; if (disablePadding) padding = 'margin-right:0!important;'; if (!names[emoji]) emoji = "❓"; return `${emoji}` diff --git a/src/modules/match.js b/src/modules/match.js index 00f6c20e..5d03d63d 100644 --- a/src/modules/match.js +++ b/src/modules/match.js @@ -42,7 +42,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit break; case "youtube": let fetchInfo = { - id: patternMatch["id"].slice(0,11), + id: patternMatch["id"].slice(0, 11), lang: lang, quality: quality, format: "webm" }; @@ -87,7 +87,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit break; case "vimeo": r = await vimeo({ - id: patternMatch["id"], quality: quality, + id: patternMatch["id"].slice(0, 11), quality: quality, lang: lang }); break; diff --git a/src/modules/pageRender/elements.js b/src/modules/pageRender/elements.js index e0901ad7..a9c60878 100644 --- a/src/modules/pageRender/elements.js +++ b/src/modules/pageRender/elements.js @@ -40,9 +40,9 @@ export function popup(obj) { } } return ` - ${!obj.embed ? `` : ''}${tabContent} ` } diff --git a/src/modules/pageRender/page.js b/src/modules/pageRender/page.js index 3fe60e14..ff965e5d 100644 --- a/src/modules/pageRender/page.js +++ b/src/modules/pageRender/page.js @@ -1,7 +1,7 @@ +import { backdropLink, checkbox, footerButtons, multiPagePopup, popup, settingsCategory, switcher } from "./elements.js"; import { services, appName, authorInfo, version, quality, repo, donations, supportedAudio } from "../config.js"; import { getCommitInfo } from "../sub/currentCommit.js"; import loc from "../../localization/manager.js"; -import { backdropLink, checkbox, footerButtons, multiPagePopup, popup, settingsCategory, switcher } from "./elements.js"; import emoji from "../emoji.js"; let s = services; @@ -16,7 +16,7 @@ let enabledServices = Object.keys(s).filter((p) => { let donate = `` let donateLinks = `` let audioFormats = supportedAudio.map((p) => { - return {"action": p} + return { "action": p } }) audioFormats.unshift({ "action": "best" }) for (let i in donations["other"]) { @@ -183,19 +183,19 @@ export default function(obj) { }] }) }) + `${!isIOS ? checkbox("downloadPopup", loc(obj.lang, 'SettingsEnableDownloadPopup'), loc(obj.lang, 'AccessibilityEnableDownloadPopup')) : ''}` - + settingsCategory({ - name: "youtube", - body: switcher({ - name: "ytFormat", - subtitle: loc(obj.lang, 'SettingsFormatSubtitle'), - explanation: loc(obj.lang, 'SettingsFormatDescription'), - items: [{ - "action": "mp4" - }, { - "action": "webm" - }] + + settingsCategory({ + name: "youtube", + body: switcher({ + name: "ytFormat", + subtitle: loc(obj.lang, 'SettingsFormatSubtitle'), + explanation: loc(obj.lang, 'SettingsFormatDescription'), + items: [{ + "action": "mp4" + }, { + "action": "webm" + }] + }) }) - }) }, { name: "audio", title: `${emoji("🎶")} ${loc(obj.lang, 'SettingsAudioTab')}`, @@ -221,10 +221,10 @@ export default function(obj) { items: [{ "action": "auto", "text": loc(obj.lang, 'SettingsThemeAuto') - },{ + }, { "action": "dark", "text": loc(obj.lang, 'SettingsThemeDark') - },{ + }, { "action": "light", "text": loc(obj.lang, 'SettingsThemeLight') }] @@ -264,21 +264,21 @@ export default function(obj) { diff --git a/src/modules/services/bilibili.js b/src/modules/services/bilibili.js index 5f7af908..6546889a 100644 --- a/src/modules/services/bilibili.js +++ b/src/modules/services/bilibili.js @@ -20,7 +20,7 @@ export default async function(obj) { let audio = streamData["data"]["dash"]["audio"].filter((a) => { if (!a["baseUrl"].includes("https://upos-sz-mirrorcosov.bilivideo.com/")) return true; }).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth)); - return { urls: [video[0]["baseUrl"], audio[0]["baseUrl"]], time: streamData.data.timelength, audioFilename: `bilibili_${obj.id}_audio`, filename: `bilibili_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.mp4` }; + return { urls: [video[0]["baseUrl"], audio[0]["baseUrl"]], time: streamData.data.timelength, audioFilename: `bilibili_${obj.id}_audio`, filename: `bilibili_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.mp4` }; } else { return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) }; } diff --git a/src/modules/services/douyin.js b/src/modules/services/douyin.js index 5dcd954d..81978077 100644 --- a/src/modules/services/douyin.js +++ b/src/modules/services/douyin.js @@ -15,14 +15,16 @@ export default async function(obj) { obj.postId = html.body.split('video/')[1].split('/?')[0] } } - let iteminfo = await got.get(`https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${obj.postId}`, {headers: { - 'authority': 'www.iesdouyin.com', - 'user-agent': genericUserAgent, - 'content-type': 'application/x-www-form-urlencoded', - 'accept': '*/*', - 'referer': `https://www.iesdouyin.com/share/video/${obj.postId}/?region=CN&u_code=15b9142gf&titleType=title&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme`, - 'accept-language': 'zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7' - }}); + let iteminfo = await got.get(`https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${obj.postId}`, { + headers: { + 'authority': 'www.iesdouyin.com', + 'user-agent': genericUserAgent, + 'content-type': 'application/x-www-form-urlencoded', + 'accept': '*/*', + 'referer': `https://www.iesdouyin.com/share/video/${obj.postId}/?region=CN&u_code=15b9142gf&titleType=title&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme`, + 'accept-language': 'zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7' + } + }); iteminfo.on('error', (err) => { return { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI', 'douyin') }; }); diff --git a/src/modules/services/reddit.js b/src/modules/services/reddit.js index 5673bce4..28e068e8 100644 --- a/src/modules/services/reddit.js +++ b/src/modules/services/reddit.js @@ -18,7 +18,7 @@ export default async function(obj) { if (audio.length > 0) { return { typeId: 2, type: "render", urls: [video, audio], audioFilename: `reddit_${id}_audio`, filename: `reddit_${id}.mp4` }; } else { - return { typeId: 1, urls: video, audioFilename: loc(obj.lang, 'ErrorEmptyDownload')}; + return { typeId: 1, urls: video, audioFilename: loc(obj.lang, 'ErrorEmptyDownload') }; } } else { return { error: loc(obj.lang, 'ErrorEmptyDownload') }; diff --git a/src/modules/services/twitter.js b/src/modules/services/twitter.js index 32c99bc4..0bfeba24 100644 --- a/src/modules/services/twitter.js +++ b/src/modules/services/twitter.js @@ -31,7 +31,7 @@ async function fetchTweetInfo(obj) { return cantConnect; } } -export default async function (obj) { +export default async function(obj) { let nothing = { error: loc(obj.lang, 'ErrorEmptyDownload') } try { let parsbod = await fetchTweetInfo(obj); diff --git a/src/modules/services/vk.js b/src/modules/services/vk.js index c1820b88..66e65887 100644 --- a/src/modules/services/vk.js +++ b/src/modules/services/vk.js @@ -25,7 +25,7 @@ export default async function(obj) { let selectedQuality = `url${attr["height"]}`; let maxQuality = js["player"]["params"][0][selectedQuality].split('type=')[1].slice(0, 1) - let userQuality = selectQuality('vk', obj.quality, Object.entries(services.vk.quality_match).reduce((r, [k, v]) => { r[v] = k; return r;})[maxQuality]) + let userQuality = selectQuality('vk', obj.quality, Object.entries(services.vk.quality_match).reduce((r, [k, v]) => { r[v] = k; return r; })[maxQuality]) let id = js["player"]["params"][0][selectedQuality].split("id=")[1] if (selectedQuality in js["player"]["params"][0]) { return { urls: js["player"]["params"][0][selectedQuality].replace(`type=${maxQuality}`, `type=${services.vk.quality_match[userQuality]}`), filename: `vk_${id}_${attr['width']}x${attr['height']}.mp4`, audioFilename: loc(obj.lang, 'ErrorEmptyDownload') }; diff --git a/src/modules/services/youtube.js b/src/modules/services/youtube.js index fd362c64..5211854d 100644 --- a/src/modules/services/youtube.js +++ b/src/modules/services/youtube.js @@ -3,7 +3,7 @@ import loc from "../../localization/manager.js"; import { maxVideoDuration, quality as mq } from "../config.js"; import selectQuality from "../stream/selectQuality.js"; -export default async function (obj) { +export default async function(obj) { try { let info = await ytdl.getInfo(obj.id); if (info) { @@ -41,18 +41,24 @@ export default async function (obj) { if (!obj.isAudioOnly && videoMatch.length > 0) { if (video.length > 0 && audio.length > 0) { if (videoMatch[0]["hasVideo"] && videoMatch[0]["hasAudio"]) { - return { type: "bridge", urls: videoMatch[0]["url"], time: videoMatch[0]["approxDurationMs"], - filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` }; + return { + type: "bridge", urls: videoMatch[0]["url"], time: videoMatch[0]["approxDurationMs"], + filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` + }; } else { - return { type: "render", urls: [videoMatch[0]["url"], audio[0]["url"]], time: videoMatch[0]["approxDurationMs"], - filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` }; + return { + type: "render", urls: [videoMatch[0]["url"], audio[0]["url"]], time: videoMatch[0]["approxDurationMs"], + filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` + }; } } else { return { error: loc(obj.lang, 'ErrorBadFetch') }; } } else if (!obj.isAudioOnly) { - return { type: "render", urls: [video[0]["url"], audio[0]["url"]], time: video[0]["approxDurationMs"], - filename: `youtube_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.${video[0]["container"]}` }; + return { + type: "render", urls: [video[0]["url"], audio[0]["url"]], time: video[0]["approxDurationMs"], + filename: `youtube_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.${video[0]["container"]}` + }; } else if (audio.length > 0) { return { type: "bridge", isAudioOnly: true, urls: audio[0]["url"], audioFilename: `youtube_${obj.id}_audio` }; } else { diff --git a/src/modules/servicesConfig.json b/src/modules/servicesConfig.json index 1e9be319..90d9d0bf 100644 --- a/src/modules/servicesConfig.json +++ b/src/modules/servicesConfig.json @@ -40,6 +40,7 @@ "enabled": true }, "youtube": { + "alias": "youtube, youtube music", "patterns": ["watch?v=:id"], "quality_match": ["2160", "1440", "1080", "720", "480", "360", "240", "144"], "quality": { @@ -49,18 +50,10 @@ }, "enabled": true }, - "youtube music": { - "patterns": ["watch?v=:id"], - "enabled": true - }, "tumblr": { "patterns": ["post/:id", "blog/view/:user/:id"], "enabled": true }, - "instagram": { - "patterns": [":type/:id"], - "enabled": false - }, "tiktok": { "patterns": [":user/video/:postId", ":id", "t/:id"], "enabled": true diff --git a/src/modules/servicesPatternTesters.js b/src/modules/servicesPatternTesters.js index 8b888226..9634ad30 100644 --- a/src/modules/servicesPatternTesters.js +++ b/src/modules/servicesPatternTesters.js @@ -2,23 +2,23 @@ export let testers = { "twitter": (patternMatch) => (patternMatch["id"] && patternMatch["id"].length < 20), "vk": (patternMatch) => (patternMatch["userId"] && patternMatch["videoId"] && - patternMatch["userId"].length <= 10 && patternMatch["videoId"].length == 9), + patternMatch["userId"].length <= 10 && patternMatch["videoId"].length == 9), "bilibili": (patternMatch) => (patternMatch["id"] && patternMatch["id"].length >= 12), "youtube": (patternMatch) => (patternMatch["id"] && patternMatch["id"].length >= 11), "reddit": (patternMatch) => (patternMatch["sub"] && patternMatch["id"] && patternMatch["title"] && - patternMatch["sub"].length <= 22 && patternMatch["id"].length <= 10 && patternMatch["title"].length <= 96), + patternMatch["sub"].length <= 22 && patternMatch["id"].length <= 10 && patternMatch["title"].length <= 96), "tiktok": (patternMatch) => ((patternMatch["user"] && patternMatch["postId"] && patternMatch["postId"].length <= 21) || - (patternMatch["id"] && patternMatch["id"].length <= 13)), + (patternMatch["id"] && patternMatch["id"].length <= 13)), "douyin": (patternMatch) => ((patternMatch["postId"] && patternMatch["postId"].length <= 21) || - (patternMatch["id"] && patternMatch["id"].length <= 13)), + (patternMatch["id"] && patternMatch["id"].length <= 13)), "tumblr": (patternMatch) => ((patternMatch["id"] && patternMatch["id"].length < 21) || - (patternMatch["id"] && patternMatch["id"].length < 21 && patternMatch["user"] && patternMatch["user"].length <= 32)), + (patternMatch["id"] && patternMatch["id"].length < 21 && patternMatch["user"] && patternMatch["user"].length <= 32)), "vimeo": (patternMatch) => ((patternMatch["id"] && patternMatch["id"].length <= 11)), }; \ No newline at end of file diff --git a/src/modules/setup.js b/src/modules/setup.js index 514706c7..401eb0f8 100644 --- a/src/modules/setup.js +++ b/src/modules/setup.js @@ -7,7 +7,7 @@ import { execSync } from "child_process"; let envPath = './.env'; let q = `${Cyan('?')} \x1b[1m`; let ob = { streamSalt: randomBytes(64).toString('hex') } -let rl = createInterface({ input: process.stdin,output: process.stdout }); +let rl = createInterface({ input: process.stdin, output: process.stdout }); console.log( `${Cyan("Welcome to cobalt!")}\n${Bright("We'll get you up and running in no time.\nLet's start by creating a ")}${Cyan(".env")}${Bright(" file. You can always change it later.")}` @@ -46,7 +46,7 @@ let final = () => { } console.log(Bright("\nI've created a .env file with selfURL, port, and stream salt.")) console.log(`${Bright("Now I'll run")} ${Cyan("npm install")} ${Bright("to install all dependencies. It shouldn't take long.\n\n")}`) - execSync('npm install',{stdio:[0,1,2]}); + execSync('npm install', { stdio: [0, 1, 2] }); console.log(`\n\n${Green("All done!\n")}`) console.log("You can re-run this script any time to update the configuration.") console.log("\nYou're now ready to start the main project.\nHave fun!") diff --git a/src/modules/stream/selectQuality.js b/src/modules/stream/selectQuality.js index e2b99417..bfe2001e 100644 --- a/src/modules/stream/selectQuality.js +++ b/src/modules/stream/selectQuality.js @@ -1,22 +1,19 @@ import { services, quality as mq } from "../config.js"; function closest(goal, array) { - return array.sort().reduce(function(prev, curr) { + return array.sort().reduce(function (prev, curr) { return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev); }); } export default function(service, quality, maxQuality) { - if (quality == "max") { - return maxQuality - } + if (quality == "max") return maxQuality; quality = parseInt(mq[quality]) maxQuality = parseInt(maxQuality) - if (quality >= maxQuality || quality == maxQuality) { - return maxQuality - } + if (quality >= maxQuality || quality == maxQuality) return maxQuality; + if (quality < maxQuality) { if (services[service]["quality"][quality]) { return quality diff --git a/src/modules/stream/types.js b/src/modules/stream/types.js index 72d5a779..e2ca5322 100644 --- a/src/modules/stream/types.js +++ b/src/modules/stream/types.js @@ -55,27 +55,22 @@ export async function streamLiveRender(streamInfo, res) { ffmpegProcess.on('error', (err) => { ffmpegProcess.kill(); res.end(); - return; }); video.pipe(ffmpegProcess.stdio[3]).on('error', (err) => { ffmpegProcess.kill(); res.end(); - return; }); audio.pipe(ffmpegProcess.stdio[4]).on('error', (err) => { ffmpegProcess.kill(); res.end(); - return; }); audio.on('error', (err) => { ffmpegProcess.kill(); res.end(); - return; }); video.on('error', (err) => { ffmpegProcess.kill(); res.end(); - return; }); } else { res.end(); diff --git a/src/modules/sub/matchActionDecider.js b/src/modules/sub/matchActionDecider.js index a450f3ea..a60dd30b 100644 --- a/src/modules/sub/matchActionDecider.js +++ b/src/modules/sub/matchActionDecider.js @@ -40,9 +40,9 @@ export default function(r, host, ip, audioFormat, isAudioOnly) { filename: r.filename, salt: process.env.streamSalt }) case "tumblr": - return apiJSON(1, { u: r.urls }) + return apiJSON(1, { u: r.urls }) case "vimeo": - return apiJSON(1, { u: r.urls }) + return apiJSON(1, { u: r.urls }) } } else { let type = "render" diff --git a/src/modules/sub/utils.js b/src/modules/sub/utils.js index ca2cef6b..2981c739 100644 --- a/src/modules/sub/utils.js +++ b/src/modules/sub/utils.js @@ -7,7 +7,7 @@ export function apiJSON(type, obj) { return { status: 400, body: { status: "error", text: obj.t } }; case 1: return { status: 200, body: { status: "redirect", url: obj.u } }; - case 2: + case 2: return { status: 200, body: { status: "stream", url: createStream(obj) } }; case 3: return { status: 200, body: { status: "success", text: obj.t } };