minor formatting overhaul (semicolons, removal of curly brackets, etc)

This commit is contained in:
Spax 2024-02-14 23:21:46 -07:00
parent 149e4dcf10
commit 5530ef6661
24 changed files with 248 additions and 277 deletions

View File

@ -21,7 +21,7 @@ jobs:
uses: docker/setup-qemu-action@v2 uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2 uses: docker/setup-buildx-action@v2
- name: Log in to the Container registry - name: Log in to the Container registry
uses: docker/login-action@v2 uses: docker/login-action@v2
with: with:

View File

@ -26,14 +26,14 @@ const webMode = process.env.webURL && process.env.apiURL;
if (apiMode) { if (apiMode) {
const { runAPI } = await import('./core/api.js'); const { runAPI } = await import('./core/api.js');
runAPI(express, app, gitCommit, gitBranch, __dirname) runAPI(express, app, gitCommit, gitBranch, __dirname);
} else if (webMode) { } else if (webMode) {
const { runWeb } = await import('./core/web.js'); const { runWeb } = await import('./core/web.js');
await runWeb(express, app, gitCommit, gitBranch, __dirname) await runWeb(express, app, gitCommit, gitBranch, __dirname);
} else { } else {
console.log( console.log(
Red(`cobalt wasn't configured yet or configuration is invalid.\n`) Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
+ Bright(`please run the setup script to fix this: `) + Bright(`please run the setup script to fix this: `)
+ Green(`npm run setup`) + Green(`npm run setup`)
) );
} }

View File

@ -45,7 +45,7 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
}); });
} }
}); });
const startTime = new Date(); const startTime = new Date();
const startTimestamp = Math.floor(startTime.getTime()); const startTimestamp = Math.floor(startTime.getTime());
@ -95,10 +95,10 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
let request = req.body; let request = req.body;
if (contentCon && request.url) { if (contentCon && request.url) {
request.dubLang = request.dubLang ? lang : false; request.dubLang = request.dubLang ? lang : false;
let chck = checkJSONPost(request); let chck = checkJSONPost(request);
if (!chck) throw new Error(); if (!chck) throw new Error();
j = await getJSON(chck.url, lang, chck); j = await getJSON(chck.url, lang, chck);
} else { } else {
j = apiJSON(0, { j = apiJSON(0, {
@ -119,7 +119,7 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
switch (req.params.type) { switch (req.params.type) {
case 'stream': case 'stream':
if (req.query.t && req.query.h && req.query.e && req.query.t.toString().length === 21 if (req.query.t && req.query.h && req.query.e && req.query.t.toString().length === 21
&& req.query.h.toString().length === 64 && req.query.e.toString().length === 13) { && req.query.h.toString().length === 64 && req.query.e.toString().length === 13) {
let streamInfo = verifyStream(req.query.t, req.query.h, req.query.e); let streamInfo = verifyStream(req.query.t, req.query.h, req.query.e);
if (streamInfo.error) { if (streamInfo.error) {
return res.status(streamInfo.status).json(apiJSON(0, { t: streamInfo.error }).body); return res.status(streamInfo.status).json(apiJSON(0, { t: streamInfo.error }).body);
@ -132,8 +132,8 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
return stream(res, streamInfo); return stream(res, streamInfo);
} else { } else {
let j = apiJSON(0, { let j = apiJSON(0, {
t: "stream token, hmac, or expiry timestamp is missing" t: "stream token, hmac, or expiry timestamp is missing",
}) });
return res.status(j.status).json(j.body); return res.status(j.status).json(j.body);
} }
case 'serverInfo': case 'serverInfo':
@ -149,7 +149,7 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
default: default:
let j = apiJSON(0, { let j = apiJSON(0, {
t: "unknown response type" t: "unknown response type"
}) });
return res.status(j.status).json(j.body); return res.status(j.status).json(j.body);
} }
} catch (e) { } catch (e) {
@ -160,13 +160,13 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
} }
}); });
app.get('/api/status', (req, res) => { app.get('/api/status', (req, res) => {
res.status(200).end() res.status(200).end();
}); });
app.get('/favicon.ico', (req, res) => { app.get('/favicon.ico', (req, res) => {
res.sendFile(`${__dirname}/src/front/icons/favicon.ico`) res.sendFile(`${__dirname}/src/front/icons/favicon.ico`);
}); });
app.get('/*', (req, res) => { app.get('/*', (req, res) => {
res.redirect('/api/json') res.redirect('/api/json');
}); });
app.listen(process.env.apiPort || 9000, () => { app.listen(process.env.apiPort || 9000, () => {
@ -175,6 +175,6 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` + `Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${process.env.apiURL}`)}\n` + `URL: ${Cyan(`${process.env.apiURL}`)}\n` +
`Port: ${process.env.apiPort || 9000}\n` `Port: ${process.env.apiPort || 9000}\n`
) );
}); });
} }

View File

@ -31,49 +31,48 @@ export async function runWeb(express, app, gitCommit, gitBranch, __dirname) {
case "0": case "0":
r = changelogHistory(); r = changelogHistory();
j = r ? apiJSON(3, { t: r }) : apiJSON(0, { j = r ? apiJSON(3, { t: r }) : apiJSON(0, {
t: "couldn't render this block, please try again!" t: "couldn't render this block, please try again!",
}) });
break; break;
// celebrations emoji // celebrations emoji
case "1": case "1":
r = celebrationsEmoji(); r = celebrationsEmoji();
j = r ? apiJSON(3, { t: r }) : false j = r ? apiJSON(3, { t: r }) : false;
break; break;
default: default:
j = apiJSON(0, { j = apiJSON(0, {
t: "couldn't find a block with this id" t: "couldn't find a block with this id"
}) });
break; break;
} }
if (j.body) { if (j.body)
return res.status(j.status).json(j.body); return res.status(j.status).json(j.body);
} else { else
return res.status(204).end(); return res.status(204).end();
}
} else { } else {
return res.status(400).json({ return res.status(400).json({
status: "error", status: "error",
text: "couldn't render this block, please try again!" text: "couldn't render this block, please try again!",
}); });
} }
} catch (e) { } catch (e) {
return res.status(400).json({ return res.status(400).json({
status: "error", status: "error",
text: "couldn't render this block, please try again!" text: "couldn't render this block, please try again!",
}) });
} }
}); });
app.get("/status", (req, res) => { app.get("/status", (req, res) => {
return res.status(200).end() return res.status(200).end();
}); });
app.get("/", (req, res) => { app.get("/", (req, res) => {
return res.sendFile(`${__dirname}/${findRendered(languageCode(req), req.header('user-agent') ? req.header('user-agent') : genericUserAgent)}`) return res.sendFile(`${__dirname}/${findRendered(languageCode(req), req.header('user-agent') ? req.header('user-agent') : genericUserAgent)}`);
}); });
app.get("/favicon.ico", (req, res) => { app.get("/favicon.ico", (req, res) => {
return res.sendFile(`${__dirname}/src/front/icons/favicon.ico`) return res.sendFile(`${__dirname}/src/front/icons/favicon.ico`);
}); });
app.get("/*", (req, res) => { app.get("/*", (req, res) => {
return res.redirect('/') return res.redirect('/');
}); });
app.listen(process.env.webPort || 9001, () => { app.listen(process.env.webPort || 9001, () => {
@ -82,6 +81,6 @@ export async function runWeb(express, app, gitCommit, gitBranch, __dirname) {
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` + `Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${process.env.webURL}`)}\n` + `URL: ${Cyan(`${process.env.webURL}`)}\n` +
`Port: ${process.env.webPort || 9001}\n` `Port: ${process.env.webPort || 9001}\n`
) );
}) });
} }

View File

@ -1018,7 +1018,7 @@ button:active,
/* adapt the page according to screen size */ /* adapt the page according to screen size */
@media screen and (max-width: 1550px) { @media screen and (max-width: 1550px) {
.popup.small { .popup.small {
width: 25% width: 25%;
} }
.popup { .popup {
width: 40%; width: 40%;
@ -1026,7 +1026,7 @@ button:active,
} }
@media screen and (max-width: 1440px) { @media screen and (max-width: 1440px) {
.popup.small { .popup.small {
width: 30% width: 30%;
} }
.popup { .popup {
width: 45%; width: 45%;
@ -1039,7 +1039,7 @@ button:active,
} }
@media screen and (max-width: 1200px) { @media screen and (max-width: 1200px) {
.popup.small { .popup.small {
width: 35% width: 35%;
} }
.popup { .popup {
width: 55%; width: 55%;
@ -1047,7 +1047,7 @@ button:active,
} }
@media screen and (max-width: 1025px) { @media screen and (max-width: 1025px) {
.popup.small { .popup.small {
width: 40% width: 40%;
} }
.popup { .popup {
width: 60%; width: 60%;

View File

@ -42,23 +42,23 @@ const pageQuery = new URLSearchParams(window.location.search);
let store = {}; let store = {};
function fixApiUrl(url) { function fixApiUrl(url) {
return url.endsWith('/') ? url.slice(0, -1) : url return url.endsWith('/') ? url.slice(0, -1) : url;
} }
let apiURL = fixApiUrl(defaultApiUrl); let apiURL = fixApiUrl(defaultApiUrl);
function changeApi(url) { function changeApi(url) {
apiURL = fixApiUrl(url); apiURL = fixApiUrl(url);
return true return true;
} }
function eid(id) { function eid(id) {
return document.getElementById(id) return document.getElementById(id);
} }
function sGet(id) { function sGet(id) {
return localStorage.getItem(id) return localStorage.getItem(id);
} }
function sSet(id, value) { function sSet(id, value) {
localStorage.setItem(id, value) localStorage.setItem(id, value);
} }
function enable(id) { function enable(id) {
eid(id).dataset.enabled = "true"; eid(id).dataset.enabled = "true";
@ -75,40 +75,39 @@ function opposite(state) {
function changeDownloadButton(action, text) { function changeDownloadButton(action, text) {
switch (action) { switch (action) {
case 0: case 0:
eid("download-button").disabled = true eid("download-button").disabled = true;
if (sGet("alwaysVisibleButton") === "true") { if (sGet("alwaysVisibleButton") === "true") {
eid("download-button").value = text eid("download-button").value = text;
eid("download-button").style.padding = '0 1rem' eid("download-button").style.padding = '0 1rem';
} else { } else {
eid("download-button").value = '' eid("download-button").value = '';
eid("download-button").style.padding = '0' eid("download-button").style.padding = '0';
} }
break; break;
case 1: case 1:
eid("download-button").disabled = false eid("download-button").disabled = false;
eid("download-button").value = text eid("download-button").value = text;
eid("download-button").style.padding = '0 1rem' eid("download-button").style.padding = '0 1rem';
break; break;
case 2: case 2:
eid("download-button").disabled = true eid("download-button").disabled = true;
eid("download-button").value = text eid("download-button").value = text;
eid("download-button").style.padding = '0 1rem' eid("download-button").style.padding = '0 1rem';
break; break;
} }
} }
document.addEventListener("keydown", (event) => { document.addEventListener("keydown", (event) => {
if (event.key === "Tab") { if (event.key === "Tab") {
eid("download-button").value = '>>' eid("download-button").value = '>>';
eid("download-button").style.padding = '0 1rem' eid("download-button").style.padding = '0 1rem';
} }
}) });
function button() { function button() {
let regexTest = regex.test(eid("url-input-area").value); let regexTest = regex.test(eid("url-input-area").value);
if ((eid("url-input-area").value).length > 0) { if ((eid("url-input-area").value).length > 0)
eid("url-clear").style.display = "block"; eid("url-clear").style.display = "block";
} else { else
eid("url-clear").style.display = "none"; eid("url-clear").style.display = "none";
}
regexTest ? changeDownloadButton(1, '>>') : changeDownloadButton(0, '>>'); regexTest ? changeDownloadButton(1, '>>') : changeDownloadButton(0, '>>');
} }
function clearInput() { function clearInput() {
@ -127,35 +126,32 @@ async function share(url) {
function detectColorScheme() { function detectColorScheme() {
let theme = "auto"; let theme = "auto";
let localTheme = sGet("theme"); let localTheme = sGet("theme");
if (localTheme) { if (localTheme)
theme = localTheme; theme = localTheme;
} else if (!window.matchMedia) { else if (!window.matchMedia)
theme = "dark" theme = "dark";
}
document.documentElement.setAttribute("data-theme", theme); document.documentElement.setAttribute("data-theme", theme);
} }
function changeTab(evnt, tabId, tabClass) { function changeTab(event, tabId, tabClass) {
if (tabId === "tab-settings-other") updateFilenamePreview(); if (tabId === "tab-settings-other") updateFilenamePreview();
let tabcontent = document.getElementsByClassName(`tab-content-${tabClass}`); let tabcontent = document.getElementsByClassName(`tab-content-${tabClass}`);
let tablinks = document.getElementsByClassName(`tab-${tabClass}`); let tablinks = document.getElementsByClassName(`tab-${tabClass}`);
for (let i = 0; i < tabcontent.length; i++) { for (let i = 0; i < tabcontent.length; i++)
tabcontent[i].dataset.enabled = "false"; tabcontent[i].dataset.enabled = "false";
} for (let i = 0; i < tablinks.length; i++)
for (let i = 0; i < tablinks.length; i++) {
tablinks[i].dataset.enabled = "false"; tablinks[i].dataset.enabled = "false";
}
event.currentTarget.dataset.enabled = "true";
evnt.currentTarget.dataset.enabled = "true";
eid(tabId).dataset.enabled = "true"; eid(tabId).dataset.enabled = "true";
eid(tabId).parentElement.scrollTop = 0; eid(tabId).parentElement.scrollTop = 0;
if (tabId === "tab-about-changelog" && sGet("changelogStatus") !== `${version}`) notificationCheck("changelog"); if (tabId === "tab-about-changelog" && sGet("changelogStatus") !== `${version}`) notificationCheck("changelog");
if (tabId === "tab-about-about" && !sGet("seenAbout")) notificationCheck("about"); if (tabId === "tab-about-about" && !sGet("seenAbout")) notificationCheck("about");
} }
function expandCollapsible(evnt) { function expandCollapsible(event) {
let classlist = evnt.currentTarget.parentNode.classList; let classlist = event.currentTarget.parentNode.classList;
let c = "expanded"; let c = "expanded";
!classlist.contains(c) ? classlist.add(c) : classlist.remove(c); !classlist.contains(c) ? classlist.add(c) : classlist.remove(c);
} }
@ -166,7 +162,7 @@ function notificationCheck(type) {
sSet("seenAbout", "true"); sSet("seenAbout", "true");
break; break;
case "changelog": case "changelog":
sSet("changelogStatus", version) sSet("changelogStatus", version);
break; break;
default: default:
changed = false; changed = false;
@ -174,8 +170,8 @@ function notificationCheck(type) {
if (changed && sGet("changelogStatus") === `${version}` || type === "disable") { if (changed && sGet("changelogStatus") === `${version}` || type === "disable") {
setTimeout(() => { setTimeout(() => {
eid("about-footer").innerHTML = eid("about-footer").innerHTML.replace(notification, ''); eid("about-footer").innerHTML = eid("about-footer").innerHTML.replace(notification, '');
eid("tab-button-about-changelog").innerHTML = eid("tab-button-about-changelog").innerHTML.replace(notification, '') eid("tab-button-about-changelog").innerHTML = eid("tab-button-about-changelog").innerHTML.replace(notification, '');
}, 900) }, 900);
} }
if (sGet("disableChangelog") !== "true") { if (sGet("disableChangelog") !== "true") {
if (!sGet("seenAbout") && !eid("about-footer").innerHTML.includes(notification)) eid("about-footer").innerHTML = `${notification}${eid("about-footer").innerHTML}`; if (!sGet("seenAbout") && !eid("about-footer").innerHTML.includes(notification)) eid("about-footer").innerHTML = `${notification}${eid("about-footer").innerHTML}`;
@ -187,9 +183,8 @@ function notificationCheck(type) {
} }
function hideAllPopups() { function hideAllPopups() {
let filter = document.getElementsByClassName('popup'); let filter = document.getElementsByClassName('popup');
for (let i = 0; i < filter.length; i++) { for (let i = 0; i < filter.length; i++)
filter[i].classList.remove("visible"); filter[i].classList.remove("visible");
}
eid("popup-backdrop").classList.remove("visible"); eid("popup-backdrop").classList.remove("visible");
store.isPopupOpen = false; store.isPopupOpen = false;
@ -237,7 +232,7 @@ function popup(type, action, text) {
isIOS ? `onClick="share('${text.arr[i]["url"]}')"` : `href="${text.arr[i]["url"]}" target="_blank"` isIOS ? `onClick="share('${text.arr[i]["url"]}')"` : `href="${text.arr[i]["url"]}" target="_blank"`
}>` + }>` +
`<img class="picker-image" src="${text.arr[i]["url"]}" onerror="this.parentNode.style.display='none'">` + `<img class="picker-image" src="${text.arr[i]["url"]}" onerror="this.parentNode.style.display='none'">` +
`</a>` `</a>`;
} }
break; break;
default: default:
@ -247,11 +242,11 @@ function popup(type, action, text) {
eid("picker-holder").innerHTML += eid("picker-holder").innerHTML +=
`<a class="picker-image-container" ${ `<a class="picker-image-container" ${
isIOS ? `onClick="share('${text.arr[i]["url"]}')"` : `href="${text.arr[i]["url"]}" target="_blank"` isIOS ? `onClick="share('${text.arr[i]["url"]}')"` : `href="${text.arr[i]["url"]}" target="_blank"`
}>` + }>` +
`<div class="picker-element-name">${text.arr[i].type}</div>` + `<div class="picker-element-name">${text.arr[i].type}</div>` +
(text.arr[i].type === 'photo' ? '' : '<div class="imageBlock"></div>') + (text.arr[i].type === 'photo' ? '' : '<div class="imageBlock"></div>') +
`<img class="picker-image" src="${text.arr[i]["thumb"]}" onerror="this.style.display='none'">` + `<img class="picker-image" src="${text.arr[i]["thumb"]}" onerror="this.style.display='none'">` +
`</a>` `</a>`;
} }
eid("picker-download").classList.remove("visible"); eid("picker-download").classList.remove("visible");
break; break;
@ -265,7 +260,7 @@ function popup(type, action, text) {
if (type === "picker") { if (type === "picker") {
eid("picker-download").href = '/'; eid("picker-download").href = '/';
eid("picker-download").classList.remove("visible"); eid("picker-download").classList.remove("visible");
eid("picker-holder").innerHTML = '' eid("picker-holder").innerHTML = '';
} }
} }
if (bottomPopups.includes(type)) eid(`popup-${type}-container`).classList.toggle("visible"); if (bottomPopups.includes(type)) eid(`popup-${type}-container`).classList.toggle("visible");
@ -277,18 +272,16 @@ function changeSwitcher(li, b) {
if (b) { if (b) {
if (!switchers[li].includes(b)) b = switchers[li][0]; if (!switchers[li].includes(b)) b = switchers[li][0];
sSet(li, b); sSet(li, b);
for (let i in switchers[li]) { for (let i in switchers[li])
(switchers[li][i] === b) ? enable(`${li}-${b}`) : disable(`${li}-${switchers[li][i]}`) (switchers[li][i] === b) ? enable(`${li}-${b}`) : disable(`${li}-${switchers[li][i]}`);
}
if (li === "theme") detectColorScheme(); if (li === "theme") detectColorScheme();
if (li === "filenamePattern") updateFilenamePreview(); if (li === "filenamePattern") updateFilenamePreview();
} else { } else {
let pref = switchers[li][0]; let pref = switchers[li][0];
if (isMobile && exceptions[li]) pref = exceptions[li]; if (isMobile && exceptions[li]) pref = exceptions[li];
sSet(li, pref); sSet(li, pref);
for (let i in switchers[li]) { for (let i in switchers[li])
(switchers[li][i] === pref) ? enable(`${li}-${pref}`) : disable(`${li}-${switchers[li][i]}`) (switchers[li][i] === pref) ? enable(`${li}-${pref}`) : disable(`${li}-${switchers[li][i]}`);
}
} }
} }
function checkbox(action) { function checkbox(action) {
@ -303,7 +296,7 @@ function checkbox(action) {
function changeButton(type, text) { function changeButton(type, text) {
switch (type) { switch (type) {
case 0: //error case 0: //error
eid("url-input-area").disabled = false eid("url-input-area").disabled = false;
eid("url-clear").style.display = "block"; eid("url-clear").style.display = "block";
changeDownloadButton(2, '!!'); changeDownloadButton(2, '!!');
popup("error", 1, text); popup("error", 1, text);
@ -312,18 +305,18 @@ function changeButton(type, text) {
case 1: //enable back case 1: //enable back
changeDownloadButton(1, '>>'); changeDownloadButton(1, '>>');
eid("url-clear").style.display = "block"; eid("url-clear").style.display = "block";
eid("url-input-area").disabled = false eid("url-input-area").disabled = false;
break; break;
case 2: //enable back + information popup case 2: //enable back + information popup
popup("error", 1, text); popup("error", 1, text);
changeDownloadButton(1, '>>'); changeDownloadButton(1, '>>');
eid("url-clear").style.display = "block"; eid("url-clear").style.display = "block";
eid("url-input-area").disabled = false eid("url-input-area").disabled = false;
break; break;
} }
} }
function internetError() { function internetError() {
eid("url-input-area").disabled = false eid("url-input-area").disabled = false;
changeDownloadButton(2, '!!'); changeDownloadButton(2, '!!');
setTimeout(() => { changeButton(1); }, 2500); setTimeout(() => { changeButton(1); }, 2500);
popup("error", 1, loc.ErrorNoInternet); popup("error", 1, loc.ErrorNoInternet);
@ -361,11 +354,10 @@ async function download(url) {
filenamePattern: sGet("filenamePattern"), filenamePattern: sGet("filenamePattern"),
dubLang: false dubLang: false
} }
if (sGet("dubLang") === "auto") { if (sGet("dubLang") === "auto")
req.dubLang = true req.dubLang = true;
} else if (sGet("dubLang") === "custom") { else if (sGet("dubLang") === "custom")
req.dubLang = true req.dubLang = true;
}
if (sGet("vimeoDash") === "true") req.vimeoDash = true; if (sGet("vimeoDash") === "true") req.vimeoDash = true;
if (sGet("audioMode") === "true") { if (sGet("audioMode") === "true") {
req.isAudioOnly = true; req.isAudioOnly = true;
@ -388,14 +380,14 @@ async function download(url) {
}).then((r) => { return r.json() }).catch((e) => { return false }); }).then((r) => { return r.json() }).catch((e) => { return false });
if (!j) { if (!j) {
internetError(); internetError();
return return;
} }
if (j && j.status !== "error" && j.status !== "rate-limit") { if (j && j.status !== "error" && j.status !== "rate-limit") {
if (j.text && (!j.url || !j.picker)) { if (j.text && (!j.url || !j.picker)) {
if (j.status === "success") { if (j.status === "success")
changeButton(2, j.text) changeButton(2, j.text);
} else changeButton(0, loc.ErrorNoUrlReturned); else changeButton(0, loc.ErrorNoUrlReturned);
} }
switch (j.status) { switch (j.status) {
case "redirect": case "redirect":
@ -412,27 +404,23 @@ async function download(url) {
changeDownloadButton(2, '>>>'); changeDownloadButton(2, '>>>');
popup('picker', 1, { arr: j.picker, type: j.pickerType }); popup('picker', 1, { arr: j.picker, type: j.pickerType });
setTimeout(() => { changeButton(1) }, 2500); setTimeout(() => { changeButton(1) }, 2500);
} else { } else changeButton(0, loc.ErrorNoUrlReturned);
changeButton(0, loc.ErrorNoUrlReturned);
}
break; break;
case "stream": case "stream":
changeDownloadButton(2, '?..') changeDownloadButton(2, '?..');
fetch(`${j.url}&p=1`).then(async (res) => { fetch(`${j.url}&p=1`).then(async (res) => {
let jp = await res.json(); let jp = await res.json();
if (jp.status === "continue") { if (jp.status === "continue") {
changeDownloadButton(2, '>>>'); changeDownloadButton(2, '>>>');
if (sGet("downloadPopup") === "true") { if (sGet("downloadPopup") === "true")
popup('download', 1, j.url) popup('download', 1, j.url);
} else { else {
if (isMobile || isSafari) { if (isMobile || isSafari)
window.location.href = j.url; window.location.href = j.url;
} else window.open(j.url, '_blank'); else window.open(j.url, '_blank');
} }
setTimeout(() => { changeButton(1) }, 2500); setTimeout(() => { changeButton(1) }, 2500);
} else { } else changeButton(0, jp.text);
changeButton(0, jp.text);
}
}).catch((error) => internetError()); }).catch((error) => internetError());
break; break;
case "success": case "success":
@ -442,17 +430,14 @@ async function download(url) {
changeButton(0, loc.ErrorUnknownStatus); changeButton(0, loc.ErrorUnknownStatus);
break; break;
} }
} else if (j && j.text) { } else if (j && j.text) changeButton(0, j.text);
changeButton(0, j.text);
}
} }
async function loadCelebrationsEmoji() { async function loadCelebrationsEmoji() {
let bac = eid("about-footer").innerHTML; let bac = eid("about-footer").innerHTML;
try { try {
let j = await fetch(`/onDemand?blockId=1`).then((r) => { if (r.status === 200) { return r.json() } else { return false } }).catch(() => { return false }); let j = await fetch(`/onDemand?blockId=1`).then((r) => { if (r.status === 200) { return r.json() } else { return false } }).catch(() => { return false });
if (j && j.status === "success" && j.text) { if (j && j.status === "success" && j.text)
eid("about-footer").innerHTML = eid("about-footer").innerHTML.replace('<img class="emoji" draggable="false" height="22" width="22" alt="🐲" src="emoji/dragon_face.svg" loading="lazy">', j.text); eid("about-footer").innerHTML = eid("about-footer").innerHTML.replace('<img class="emoji" draggable="false" height="22" width="22" alt="🐲" src="emoji/dragon_face.svg" loading="lazy">', j.text);
}
} catch (e) { } catch (e) {
eid("about-footer").innerHTML = bac; eid("about-footer").innerHTML = bac;
} }
@ -463,9 +448,9 @@ async function loadOnDemand(elementId, blockId) {
eid(elementId).innerHTML = `<div class="loader">...</div>`; eid(elementId).innerHTML = `<div class="loader">...</div>`;
try { try {
if (store.historyContent) { if (store.historyContent)
j = store.historyContent; j = store.historyContent;
} else { else {
await fetch(`/onDemand?blockId=${blockId}`).then(async(r) => { await fetch(`/onDemand?blockId=${blockId}`).then(async(r) => {
j = await r.json(); j = await r.json();
if (j && j.status === "success") { if (j && j.status === "success") {
@ -473,12 +458,12 @@ async function loadOnDemand(elementId, blockId) {
} else throw new Error(); } else throw new Error();
}).catch(() => { throw new Error() }); }).catch(() => { throw new Error() });
} }
if (j.text) { if (j.text)
eid(elementId).innerHTML = `<button class="switch bottom-margin" onclick="restoreUpdateHistory()">${loc.ChangelogPressToHide}</button>${j.text}`; eid(elementId).innerHTML = `<button class="switch bottom-margin" onclick="restoreUpdateHistory()">${loc.ChangelogPressToHide}</button>${j.text}`;
} else throw new Error() else throw new Error();
} catch (e) { } catch (e) {
eid(elementId).innerHTML = store.historyButton; eid(elementId).innerHTML = store.historyButton;
internetError() internetError();
} }
} }
function restoreUpdateHistory() { function restoreUpdateHistory() {
@ -491,20 +476,20 @@ function unpackSettings(b64) {
let currentSettings = JSON.parse(JSON.stringify(localStorage)); let currentSettings = JSON.parse(JSON.stringify(localStorage));
for (let s in settingsToImport) { for (let s in settingsToImport) {
if (checkboxes.includes(s) && (settingsToImport[s] === "true" || settingsToImport[s] === "false") if (checkboxes.includes(s) && (settingsToImport[s] === "true" || settingsToImport[s] === "false")
&& currentSettings[s] !== settingsToImport[s]) { && currentSettings[s] !== settingsToImport[s]) {
sSet(s, settingsToImport[s]); sSet(s, settingsToImport[s]);
changed = true changed = true;
} }
if (switchers[s] && switchers[s].includes(settingsToImport[s]) if (switchers[s] && switchers[s].includes(settingsToImport[s])
&& currentSettings[s] !== settingsToImport[s]) { && currentSettings[s] !== settingsToImport[s]) {
sSet(s, settingsToImport[s]); sSet(s, settingsToImport[s]);
changed = true changed = true;
} }
} }
} catch (e) { } catch (e) {
changed = false; changed = false;
} }
return changed return changed;
} }
function updateFilenamePreview() { function updateFilenamePreview() {
let videoFilePreview = ``; let videoFilePreview = ``;
@ -523,55 +508,50 @@ function updateFilenamePreview() {
switch(sGet("filenamePattern")) { switch(sGet("filenamePattern")) {
case "classic": case "classic":
videoFilePreview = `youtube_yPYZpwSpKmA_${resMatch[sGet('vQuality')]}_${sGet('vCodec')}` videoFilePreview = `youtube_yPYZpwSpKmA_${resMatch[sGet('vQuality')]}_${sGet('vCodec')}`
+ `${sGet("muteAudio") === "true" ? "_mute" : ""}.${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`; + `${sGet("muteAudio") === "true" ? "_mute" : ""}.${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`;
audioFilePreview = `youtube_yPYZpwSpKmA_audio.${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`; audioFilePreview = `youtube_yPYZpwSpKmA_audio.${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`;
break; break;
case "pretty": case "pretty":
videoFilePreview = videoFilePreview =
`${loc.FilenamePreviewVideoTitle} ` `${loc.FilenamePreviewVideoTitle} `
+ `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}, ` + `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}, `
+ `${sGet("muteAudio") === "true" ? "mute, " : ""}youtube).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`; + `${sGet("muteAudio") === "true" ? "mute, " : ""}youtube).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`;
audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor} (soundcloud).${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`; audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor} (soundcloud).${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`;
break; break;
case "basic": case "basic":
videoFilePreview = videoFilePreview =
`${loc.FilenamePreviewVideoTitle} ` `${loc.FilenamePreviewVideoTitle} `
+ `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}${sGet("muteAudio") === "true" ? " mute" : ""}).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`; + `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}${sGet("muteAudio") === "true" ? " mute" : ""}).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`;
audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor}.${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`; audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor}.${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`;
break; break;
case "nerdy": case "nerdy":
videoFilePreview = videoFilePreview =
`${loc.FilenamePreviewVideoTitle} ` `${loc.FilenamePreviewVideoTitle} `
+ `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}, ` + `(${sGet('vQuality') === "max" ? "2160p" : `${sGet('vQuality')}p`}, ${sGet('vCodec')}, `
+ `${sGet("muteAudio") === "true" ? "mute, " : ""}youtube, yPYZpwSpKmA).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`; + `${sGet("muteAudio") === "true" ? "mute, " : ""}youtube, yPYZpwSpKmA).${sGet('vCodec') === "vp9" ? 'webm' : 'mp4'}`;
audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor} (soundcloud, 1242868615).${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`; audioFilePreview = `${loc.FilenamePreviewAudioTitle} - ${loc.FilenamePreviewAudioAuthor} (soundcloud, 1242868615).${sGet('aFormat') !== "best" ? sGet('aFormat') : 'opus'}`;
break; break;
} }
eid("video-filename-text").innerHTML = videoFilePreview eid("video-filename-text").innerHTML = videoFilePreview;
eid("audio-filename-text").innerHTML = audioFilePreview eid("audio-filename-text").innerHTML = audioFilePreview;
} }
function loadSettings() { function loadSettings() {
if (sGet("alwaysVisibleButton") === "true") { if (sGet("alwaysVisibleButton") === "true") {
eid("alwaysVisibleButton").checked = true; eid("alwaysVisibleButton").checked = true;
eid("download-button").value = '>>' eid("download-button").value = '>>';
eid("download-button").style.padding = '0 1rem'; eid("download-button").style.padding = '0 1rem';
} }
if (sGet("downloadPopup") === "true" && !isIOS) { if (sGet("downloadPopup") === "true" && !isIOS)
eid("downloadPopup").checked = true; eid("downloadPopup").checked = true;
} if (sGet("reduceTransparency") === "true" || isOldFirefox)
if (sGet("reduceTransparency") === "true" || isOldFirefox) {
eid("cobalt-body").classList.add('no-transparency'); eid("cobalt-body").classList.add('no-transparency');
} if (sGet("disableAnimations") === "true")
if (sGet("disableAnimations") === "true") {
eid("cobalt-body").classList.add('no-animation'); eid("cobalt-body").classList.add('no-animation');
} for (let i = 0; i < checkboxes.length; i++)
for (let i = 0; i < checkboxes.length; i++) {
if (sGet(checkboxes[i]) === "true") eid(checkboxes[i]).checked = true; if (sGet(checkboxes[i]) === "true") eid(checkboxes[i]).checked = true;
} for (let i in switchers)
for (let i in switchers) { changeSwitcher(i, sGet(i));
changeSwitcher(i, sGet(i)) updateFilenamePreview();
}
updateFilenamePreview()
} }
window.onload = () => { window.onload = () => {
loadCelebrationsEmoji(); loadCelebrationsEmoji();
@ -587,22 +567,22 @@ window.onload = () => {
eid("downloadPopup-chkbx").style.display = "none"; eid("downloadPopup-chkbx").style.display = "none";
} }
eid("home").style.visibility = 'visible'; eid("home").style.visibility = "visible";
eid("home").classList.toggle("visible"); eid("home").classList.toggle("visible");
if (pageQuery.has("u") && regex.test(pageQuery.get("u"))) { if (pageQuery.has("u") && regex.test(pageQuery.get("u"))) {
eid("url-input-area").value = pageQuery.get("u"); eid("url-input-area").value = pageQuery.get("u");
button() button();
} }
if (pageQuery.has("migration")) { if (pageQuery.has("migration")) {
if (pageQuery.has("settingsData") && !sGet("migrated")) { if (pageQuery.has("settingsData") && !sGet("migrated")) {
let setUn = unpackSettings(pageQuery.get("settingsData")); let setUn = unpackSettings(pageQuery.get("settingsData"));
if (setUn !== null) { if (setUn !== null) {
if (setUn) { if (setUn) {
sSet("migrated", "true") sSet("migrated", "true");
eid("desc-migration").innerHTML += `<br><br>${loc.DataTransferSuccess}` eid("desc-migration").innerHTML += `<br><br>${loc.DataTransferSuccess}`;
} else { } else {
eid("desc-migration").innerHTML += `<br><br>${loc.DataTransferError}` eid("desc-migration").innerHTML += `<br><br>${loc.DataTransferError}`;
} }
} }
} }
@ -615,16 +595,15 @@ window.onload = () => {
notificationCheck(); notificationCheck();
// fix for animations not working in Safari // fix for animations not working in Safari
if (isIOS) { if (isIOS)
document.addEventListener('touchstart', () => {}, true); document.addEventListener('touchstart', () => {}, true);
}
} }
eid("url-input-area").addEventListener("keydown", (e) => { eid("url-input-area").addEventListener("keydown", (e) => {
button(); button();
}) });
eid("url-input-area").addEventListener("keyup", (e) => { eid("url-input-area").addEventListener("keyup", (e) => {
if (e.key === 'Enter') eid("download-button").click(); if (e.key === 'Enter') eid("download-button").click();
}) });
document.onkeydown = (e) => { document.onkeydown = (e) => {
if (!store.isPopupOpen) { if (!store.isPopupOpen) {
if (e.metaKey || e.ctrlKey || e.key === "/") eid("url-input-area").focus(); if (e.metaKey || e.ctrlKey || e.key === "/") eid("url-input-area").focus();
@ -636,13 +615,11 @@ document.onkeydown = (e) => {
if (e.key === "D") pasteClipboard(); if (e.key === "D") pasteClipboard();
if (e.key === "K") changeSwitcher('audioMode', 'false'); if (e.key === "K") changeSwitcher('audioMode', 'false');
if (e.key === "L") changeSwitcher('audioMode', 'true'); if (e.key === "L") changeSwitcher('audioMode', 'true');
// popups // popups
if (e.key === "B") popup('about', 1, 'about'); // open about if (e.key === "B") popup('about', 1, 'about'); // open about
if (e.key === "N") popup('about', 1, 'changelog'); // open changelog if (e.key === "N") popup('about', 1, 'changelog'); // open changelog
if (e.key === "M") popup('settings', 1); if (e.key === "M") popup('settings', 1);
} else { } else if (e.key === "Escape") hideAllPopups();
if (e.key === "Escape") hideAllPopups();
}
} }

View File

@ -11,7 +11,7 @@ export async function loadLoc() {
const files = await fs.promises.readdir(locPath).catch((e) => { return [] }); const files = await fs.promises.readdir(locPath).catch((e) => { return [] });
files.forEach(file => { files.forEach(file => {
loc[file.split('.')[0]] = loadJSON(`${locPath}/${file}`); loc[file.split('.')[0]] = loadJSON(`${locPath}/${file}`);
languages.push(file.split('.')[0]) languages.push(file.split('.')[0]);
}); });
} }
@ -24,27 +24,27 @@ export function replaceBase(s) {
.replace(/\*;/g, "&bull;"); .replace(/\*;/g, "&bull;");
} }
export function replaceAll(lang, str, string, replacement) { export function replaceAll(lang, str, string, replacement) {
let s = replaceBase(str[string]) let s = replaceBase(str[string]);
if (replacement) s = s.replace(/{s}/g, replacement); if (replacement) s = s.replace(/{s}/g, replacement);
if (s.match('{')) { if (s.match('{')) {
Object.keys(loc[lang]["substrings"]).forEach(sub => { Object.keys(loc[lang]["substrings"]).forEach(sub => {
s = replaceBase(s.replace(`{${sub}}`, loc[lang]["substrings"][sub])) s = replaceBase(s.replace(`{${sub}}`, loc[lang]["substrings"][sub]));
}); });
} }
return s return s;
} }
export default function(lang, string, replacement) { export default function(lang, string, replacement) {
try { try {
if (!Object.keys(loc).includes(lang)) lang = 'en'; if (!Object.keys(loc).includes(lang)) lang = 'en';
let str = loc[lang]["strings"]; let str = loc[lang]["strings"];
if (str && str[string]) { if (str && str[string]) {
return replaceAll(lang, str, string, replacement) return replaceAll(lang, str, string, replacement);
} else { } else {
str = loc["en"]["strings"]; str = loc["en"]["strings"];
return replaceAll(lang, str, string, replacement) return replaceAll(lang, str, string, replacement);
} }
} catch (e) { } catch (e) {
return `!!${string}!!` return `!!${string}!!`;
} }
} }
export const languageList = languages; export const languageList = languages;

View File

@ -26,8 +26,8 @@ export async function getJSON(url, lang, obj) {
return apiJSON(0, { t: errorUnsupported(lang) }); return apiJSON(0, { t: errorUnsupported(lang) });
} }
return await match(host, patternMatch, url, lang, obj) return await match(host, patternMatch, url, lang, obj);
} catch (e) { } catch (e) {
return apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') }) return apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') });
} }
} }

View File

@ -44,7 +44,7 @@ export async function buildFront(commitHash, branch) {
minify: true, minify: true,
loader: { '.js': 'js', '.css': 'css', }, loader: { '.js': 'js', '.css': 'css', },
charset: 'utf8' charset: 'utf8'
}) });
} catch (e) { } catch (e) {
return; return;
} }

View File

@ -7,10 +7,10 @@ const servicesConfigJson = loadJSON("./src/modules/processing/servicesConfig.jso
Object.values(servicesConfigJson.config).forEach(service => { Object.values(servicesConfigJson.config).forEach(service => {
service.patterns = service.patterns.map( service.patterns = service.patterns.map(
pattern => new UrlPattern(pattern, { pattern => new UrlPattern(pattern, {
segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.' segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.',
}) })
) )
}) });
export const export const
services = servicesConfigJson.config, services = servicesConfigJson.config,
@ -26,4 +26,4 @@ export const
supportedAudio = config.supportedAudio, supportedAudio = config.supportedAudio,
celebrations = config.celebrations, celebrations = config.celebrations,
links = config.links, links = config.links,
sponsors = config.sponsors sponsors = config.sponsors;

View File

@ -62,5 +62,5 @@ export default function(emoji, size, disablePadding, fluent) {
let filePath = `emoji/${names[emoji]}.svg`; let filePath = `emoji/${names[emoji]}.svg`;
if (fluent) filePath = `emoji/3d/${names[emoji]}.svg`; if (fluent) filePath = `emoji/3d/${names[emoji]}.svg`;
return `<img class="emoji" draggable=false height="${size}" width="${size}" ${padding ? `style="${padding}" ` : ''}alt="${emoji}" src="${filePath}" loading="lazy">` return `<img class="emoji" draggable=false height="${size}" width="${size}" ${padding ? `style="${padding}" ` : ''}alt="${emoji}" src="${filePath}" loading="lazy">`;
} }

View File

@ -8,18 +8,20 @@ export const backButtonSVG = `<svg width="22" height="22" viewBox="0 0 32 32" fi
export const dropdownSVG = `<svg width="18" height="18" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> export const dropdownSVG = `<svg width="18" height="18" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M28 12.0533L16 24L4 12.0533L6.03571 10L14.7188 18.4104L16.25 19.9348L17.7813 18.4104L25.9375 10L28 12.0533Z" fill="#E1E1E1"/> <path d="M28 12.0533L16 24L4 12.0533L6.03571 10L14.7188 18.4104L16.25 19.9348L17.7813 18.4104L25.9375 10L28 12.0533Z" fill="#E1E1E1"/>
</svg>` </svg>`;
export const linkSVG = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 256 256"><path fill="currentColor" d="M137.54 186.36a8 8 0 0 1 0 11.31l-9.94 10a56 56 0 0 1-79.22-79.27l24.12-24.12a56 56 0 0 1 76.81-2.28a8 8 0 1 1-10.64 12a40 40 0 0 0-54.85 1.63L59.7 139.72a40 40 0 0 0 56.58 56.58l9.94-9.94a8 8 0 0 1 11.32 0Zm70.08-138a56.08 56.08 0 0 0-79.22 0l-9.94 9.95a8 8 0 0 0 11.32 11.31l9.94-9.94a40 40 0 0 1 56.58 56.58l-24.12 24.14a40 40 0 0 1-54.85 1.6a8 8 0 1 0-10.64 12a56 56 0 0 0 76.81-2.26l24.12-24.12a56.08 56.08 0 0 0 0-79.24Z"/></svg>' export const linkSVG = `<svg width="32" height="32" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" d="M137.54 186.36a8 8 0 0 1 0 11.31l-9.94 10a56 56 0 0 1-79.22-79.27l24.12-24.12a56 56 0 0 1 76.81-2.28a8 8 0 1 1-10.64 12a40 40 0 0 0-54.85 1.63L59.7 139.72a40 40 0 0 0 56.58 56.58l9.94-9.94a8 8 0 0 1 11.32 0Zm70.08-138a56.08 56.08 0 0 0-79.22 0l-9.94 9.95a8 8 0 0 0 11.32 11.31l9.94-9.94a40 40 0 0 1 56.58 56.58l-24.12 24.14a40 40 0 0 1-54.85 1.6a8 8 0 1 0-10.64 12a56 56 0 0 0 76.81-2.26l24.12-24.12a56.08 56.08 0 0 0 0-79.24Z"/>
</svg>`;
export function switcher(obj) { export function switcher(obj) {
let items = ``; let items = ``;
if (obj.name === "download") { if (obj.name === "download")
items = obj.items; items = obj.items;
} else { else {
for (let i = 0; i < obj.items.length; i++) { for (let i = 0; i < obj.items.length; i++) {
let classes = obj.items[i]["classes"] ? obj.items[i]["classes"] : []; let classes = obj.items[i]["classes"] ? obj.items[i]["classes"] : [];
items += `<button id="${obj.name}-${obj.items[i]["action"]}" class="switch${classes.length > 0 ? ' ' + classes.join(' ') : ''}" onclick="changeSwitcher('${obj.name}', '${obj.items[i]["action"]}')">${obj.items[i]["text"] ? obj.items[i]["text"] : obj.items[i]["action"]}</button>` items += `<button id="${obj.name}-${obj.items[i]["action"]}" class="switch${classes.length > 0 ? ' ' + classes.join(' ') : ''}" onclick="changeSwitcher('${obj.name}', '${obj.items[i]["action"]}')">${obj.items[i]["text"] ? obj.items[i]["text"] : obj.items[i]["action"]}</button>`;
} }
} }
@ -28,7 +30,7 @@ export function switcher(obj) {
${obj.subtitle ? `<div class="subtitle">${obj.subtitle}</div>` : ``} ${obj.subtitle ? `<div class="subtitle">${obj.subtitle}</div>` : ``}
<div class="switches">${items}</div> <div class="switches">${items}</div>
${obj.explanation ? `<div class="explanation">${obj.explanation}</div>` : ``} ${obj.explanation ? `<div class="explanation">${obj.explanation}</div>` : ``}
</div>` </div>`;
} }
export function checkbox(obj) { export function checkbox(obj) {
let paddings = ["bottom-margin", "top-margin", "no-margin", "top-margin-only"]; let paddings = ["bottom-margin", "top-margin", "no-margin", "top-margin-only"];
@ -39,14 +41,14 @@ export function checkbox(obj) {
checkboxes += `<label id="${obj[i].action}-chkbx" class="checkbox${paddingClass}"> checkboxes += `<label id="${obj[i].action}-chkbx" class="checkbox${paddingClass}">
<input id="${obj[i].action}" type="checkbox" aria-label="${obj[i].aria ? obj[i].aria : obj[i].name}" onclick="checkbox('${obj[i].action}')"> <input id="${obj[i].action}" type="checkbox" aria-label="${obj[i].aria ? obj[i].aria : obj[i].name}" onclick="checkbox('${obj[i].action}')">
<span>${obj[i].name}</span> <span>${obj[i].name}</span>
</label>` </label>`;
} }
return checkboxes return checkboxes;
} }
export function sep(paddingType) { export function sep(paddingType) {
let paddingClass = `` let paddingClass = ``;
switch(paddingType) { switch(paddingType) {
case 0: case 0:
paddingClass += ` top-margin`; paddingClass += ` top-margin`;
break; break;
} }
@ -56,14 +58,13 @@ export function popup(obj) {
let classes = obj.classes ? obj.classes : []; let classes = obj.classes ? obj.classes : [];
let body = obj.body; let body = obj.body;
if (Array.isArray(obj.body)) { if (Array.isArray(obj.body)) {
body = `` body = ``;
for (let i = 0; i < obj.body.length; i++) { for (let i = 0; i < obj.body.length; i++) {
if (obj.body[i]["text"].length > 0) { if (obj.body[i]["text"].length > 0) {
classes = obj.body[i]["classes"] ?? [] classes = obj.body[i]["classes"] ?? [];
if (i !== obj.body.length - 1 && !obj.body[i]["nopadding"]) { if (i !== obj.body.length - 1 && !obj.body[i]["nopadding"])
classes.push("desc-padding") classes.push("desc-padding");
} body += obj.body[i]["raw"] ? obj.body[i]["text"] : `<div class="${['popup-desc', ...classes].join(' ')}">${obj.body[i]["text"]}</div>`;
body += obj.body[i]["raw"] ? obj.body[i]["text"] : `<div class="${['popup-desc', ...classes].join(' ')}">${obj.body[i]["text"]}</div>`
} }
} }
} }
@ -82,7 +83,7 @@ export function popup(obj) {
${body}${obj.buttonOnly ? `<button class="close-error switch" onclick="popup('${obj.name}', 0)">${obj.buttonText}</button>` : ''} ${body}${obj.buttonOnly ? `<button class="close-error switch" onclick="popup('${obj.name}', 0)">${obj.buttonText}</button>` : ''}
</div> </div>
${classes.includes("small") ? `<div class="glass-bkg small"></div>` : ''} ${classes.includes("small") ? `<div class="glass-bkg small"></div>` : ''}
${obj.standalone ? `</div>` : ''}` ${obj.standalone ? `</div>` : ''}`;
} }
export function multiPagePopup(obj) { export function multiPagePopup(obj) {
@ -93,8 +94,8 @@ export function multiPagePopup(obj) {
let tabContent = ``; let tabContent = ``;
for (let i = 0; i < obj.tabs.length; i++) { for (let i = 0; i < obj.tabs.length; i++) {
tabs += `<button id="tab-button-${obj.name}-${obj.tabs[i]["name"]}" class="switch tab tab-${obj.name}" onclick="changeTab(event, 'tab-${obj.name}-${obj.tabs[i]["name"]}', '${obj.name}')">${obj.tabs[i]["title"]}</button>` tabs += `<button id="tab-button-${obj.name}-${obj.tabs[i]["name"]}" class="switch tab tab-${obj.name}" onclick="changeTab(event, 'tab-${obj.name}-${obj.tabs[i]["name"]}', '${obj.name}')">${obj.tabs[i]["title"]}</button>`;
tabContent += `<div id="tab-${obj.name}-${obj.tabs[i]["name"]}" class="popup-tab-content tab-content-${obj.name}">${obj.tabs[i]["content"]}</div>` tabContent += `<div id="tab-${obj.name}-${obj.tabs[i]["name"]}" class="popup-tab-content tab-content-${obj.name}">${obj.tabs[i]["content"]}</div>`;
} }
return ` return `
@ -112,7 +113,7 @@ export function multiPagePopup(obj) {
<div class="switches popup-tabs-child">${tabs}</div> <div class="switches popup-tabs-child">${tabs}</div>
<div class="glass-bkg alone"></div> <div class="glass-bkg alone"></div>
</div> </div>
</div>` </div>`;
} }
export function collapsibleList(arr) { export function collapsibleList(arr) {
let items = ``; let items = ``;
@ -125,7 +126,7 @@ export function collapsibleList(arr) {
<div class="collapse-indicator">${dropdownSVG}</div> <div class="collapse-indicator">${dropdownSVG}</div>
</div> </div>
<div id="${arr[i]["name"]}-body" class="collapse-body">${arr[i]["body"]}</div> <div id="${arr[i]["name"]}-body" class="collapse-body">${arr[i]["body"]}</div>
</div>` </div>`;
} }
return items; return items;
} }
@ -133,11 +134,10 @@ export function popupWithBottomButtons(obj) {
let tabs = ` let tabs = `
<button class="back-button switch tab-${obj.name}" onclick="popup('${obj.name}', 0)" ${obj.closeAria ? `aria-label="${obj.closeAria}"` : ''}> <button class="back-button switch tab-${obj.name}" onclick="popup('${obj.name}', 0)" ${obj.closeAria ? `aria-label="${obj.closeAria}"` : ''}>
${backButtonSVG} ${backButtonSVG}
</button>` </button>`;
for (let i = 0; i < obj.buttons.length; i++) { for (let i = 0; i < obj.buttons.length; i++)
tabs += obj.buttons[i] tabs += obj.buttons[i];
}
return ` return `
<div id="popup-${obj.name}" class="popup center box scrollable"> <div id="popup-${obj.name}" class="popup center box scrollable">
<div class="popup-content"> <div class="popup-content">
@ -154,30 +154,29 @@ export function popupWithBottomButtons(obj) {
<div id="picker-buttons" class="switches popup-tabs-child">${tabs}</div> <div id="picker-buttons" class="switches popup-tabs-child">${tabs}</div>
<div class="glass-bkg alone"></div> <div class="glass-bkg alone"></div>
</div> </div>
</div>` </div>`;
} }
export function socialLink(emji, name, url) { export function socialLink(emji, name, url) {
return `<div class="cobalt-support-link">${emji} <a class="text-backdrop link" href="${url}" target="_blank">${name}</a></div>` return `<div class="cobalt-support-link">${emji} <a class="text-backdrop link" href="${url}" target="_blank">${name}</a></div>`;
} }
export function socialLinks(lang) { export function socialLinks(lang) {
let links = authorInfo.support[lang] ? authorInfo.support[lang] : authorInfo.support.default; let links = authorInfo.support[lang] ? authorInfo.support[lang] : authorInfo.support.default;
let r = ``; let r = ``;
for (let i in links) { for (let i in links)
r += socialLink( r += socialLink(
emoji(links[i].emoji), links[i].name, links[i].url emoji(links[i].emoji), links[i].name, links[i].url
) );
} return r;
return r
} }
export function settingsCategory(obj) { export function settingsCategory(obj) {
return `<div id="settings-${obj.name}" class="settings-category"> return `<div id="settings-${obj.name}" class="settings-category">
<div class="category-title">${obj.title ?? obj.name}</div> <div class="category-title">${obj.title ?? obj.name}</div>
<div class="category-content">${obj.body}</div> <div class="category-content">${obj.body}</div>
</div>` </div>`;
} }
export function footerButtons(obj) { export function footerButtons(obj) {
let items = `` let items = ``;
for (let i = 0; i < obj.length; i++) { for (let i = 0; i < obj.length; i++) {
let buttonName = obj[i]["context"] ? `${obj[i]["name"]}-${obj[i]["context"]}` : obj[i]["name"], let buttonName = obj[i]["context"] ? `${obj[i]["name"]}-${obj[i]["context"]}` : obj[i]["name"],
context = obj[i]["context"] ? `, '${obj[i]["context"]}'` : '', context = obj[i]["context"] ? `, '${obj[i]["context"]}'` : '',
@ -196,11 +195,10 @@ export function footerButtons(obj) {
</div>`; </div>`;
i++; i++;
} }
return ` return `<div id="footer-buttons">${items}</div>`;
<div id="footer-buttons">${items}</div>`
} }
export function explanation(text) { export function explanation(text) {
return `<div class="explanation">${text}</div>` return `<div class="explanation">${text}</div>`;
} }
export function celebrationsEmoji() { export function celebrationsEmoji() {
try { try {
@ -209,16 +207,16 @@ export function celebrationsEmoji() {
let f = Object.keys(celebrations).includes(dm) ? celebrations[dm] : "🐲"; let f = Object.keys(celebrations).includes(dm) ? celebrations[dm] : "🐲";
return f != "🐲" ? emoji(f, 22) : false; return f != "🐲" ? emoji(f, 22) : false;
} catch (e) { } catch (e) {
return false return false;
} }
} }
export function urgentNotice(obj) { export function urgentNotice(obj) {
if (obj.visible) { if (obj.visible) {
return `<div id="urgent-notice" class="urgent-notice explanation">` + return `<div id="urgent-notice" class="urgent-notice explanation">` +
`<span class="urgent-text" onclick="${obj.action}">${emoji(obj.emoji, 18)} ${obj.text}</span>` + `<span class="urgent-text" onclick="${obj.action}">${emoji(obj.emoji, 18)} ${obj.text}</span>` +
`</div>` `</div>`;
} }
return `` return ``;
} }
export function keyboardShortcuts(arr) { export function keyboardShortcuts(arr) {
let base = `<div id="keyboard-shortcuts" class="explanation">`; let base = `<div id="keyboard-shortcuts" class="explanation">`;
@ -228,10 +226,10 @@ export function keyboardShortcuts(arr) {
for (let c = 0; c < arr[i].items.length; c++) { for (let c = 0; c < arr[i].items.length; c++) {
let combo = arr[i].items[c].combo.split('+').map( let combo = arr[i].items[c].combo.split('+').map(
key => `<span class="text-backdrop key">${key}</span>` key => `<span class="text-backdrop key">${key}</span>`
).join("+") ).join("+");
base += `<div class="shortcut">${combo}: ${arr[i].items[c].name}</div>` base += `<div class="shortcut">${combo}: ${arr[i].items[c].name}</div>`;
} }
base += `</div>` base += `</div>`;
} }
base += `</div>`; base += `</div>`;
@ -239,30 +237,29 @@ export function keyboardShortcuts(arr) {
} }
export function webLoc(t, arr) { export function webLoc(t, arr) {
let base = ``; let base = ``;
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++)
base += `${arr[i]}:` + "`" + t(arr[i]) + "`" + `,` base += `${arr[i]}:` + "`" + t(arr[i]) + "`" + `,`;
}
return `{${base}};` return `{${base}};`
} }
export function sponsoredList() { export function sponsoredList() {
let base = ``; let base = ``;
let altText = `` let altText = ``;
for (let i = 0; i < sponsors.length; i++) { for (let i = 0; i < sponsors.length; i++) {
let s = sponsors[i]; let s = sponsors[i];
let loadedLogo = loadFile(`./src/front/sponsors/${s.name}.svg`); let loadedLogo = loadFile(`./src/front/sponsors/${s.name}.svg`);
altText += `${s.fullName ? s.fullName : s.name}, `; altText += `${s.fullName ? s.fullName : s.name}, `;
base += base +=
`<a class="sponsored-logo ${s.name}" `<a class="sponsored-logo ${s.name}"
href="${s.url}" target="_blank" href="${s.url}" target="_blank"
style="width: calc(${s.logo.width}px / ${s.logo.scale}); height: calc(${s.logo.height}px / ${s.logo.scale});"> style="width: calc(${s.logo.width}px / ${s.logo.scale}); height: calc(${s.logo.height}px / ${s.logo.scale});">
${loadedLogo} ${loadedLogo}
</a>` </a>`;
} }
return `<div id="sponsored-logos" aria-label="${altText.slice(0, -2)}">${base}</div>` return `<div id="sponsored-logos" aria-label="${altText.slice(0, -2)}">${base}</div>`;
} }
export function betaTag() { export function betaTag() {
return process.env.isBeta ? '<span class="logo-sub">β</span>' : '' return process.env.isBeta ? '<span class="logo-sub">β</span>' : '';
} }

View File

@ -1,13 +1,13 @@
import changelogManager from "../changelog/changelogManager.js" import changelogManager from "../changelog/changelogManager.js"
import { cleanHTML } from "../sub/utils.js"; import { cleanHTML } from "../sub/utils.js";
let cache = {} let cache = {};
export function changelogHistory() { // blockId 0 export function changelogHistory() { // blockId 0
if (cache['0']) return cache['0']; if (cache['0']) return cache['0'];
let history = changelogManager("history"); let history = changelogManager("history");
let render = ``; let render = ``;
let historyLen = history.length; let historyLen = history.length;
for (let i in history) { for (let i in history) {
let separator = (i !== 0 && i !== historyLen) ? '<div class="separator"></div>' : ''; let separator = (i !== 0 && i !== historyLen) ? '<div class="separator"></div>' : '';
@ -25,7 +25,7 @@ export function changelogHistory() { // blockId 0
</div>` : ''} </div>` : ''}
<div class="popup-desc changelog-tags">${history[i]["version"]}</div> <div class="popup-desc changelog-tags">${history[i]["version"]}</div>
<div class="popup-desc changelog-subtitle">${history[i]["title"]}</div> <div class="popup-desc changelog-subtitle">${history[i]["title"]}</div>
<div class="popup-desc desc-padding">${history[i]["content"]}</div>` <div class="popup-desc desc-padding">${history[i]["content"]}</div>`;
} }
render = cleanHTML(render); render = cleanHTML(render);
cache['0'] = render; cache['0'] = render;

View File

@ -8,22 +8,21 @@ import changelogManager from "../changelog/changelogManager.js";
let com = getCommitInfo(); let com = getCommitInfo();
let enabledServices = Object.keys(s).filter(p => s[p].enabled).sort().map((p) => { let enabledServices = Object.keys(s).filter(p => s[p].enabled).sort().map((p) => {
return `<br>&bull; ${s[p].alias ? s[p].alias : p}` return `<br>&bull; ${s[p].alias ? s[p].alias : p}`;
}).join('').substring(4) }).join('').substring(4);
let donate = `` let donate = ``;
let donateLinks = `` let donateLinks = ``;
let audioFormats = supportedAudio.map((p) => { let audioFormats = supportedAudio.map((p) => {
return { "action": p } return { "action": p };
}) })
audioFormats.unshift({ "action": "best" }) audioFormats.unshift({ "action": "best" });
for (let i in donations["links"]) { for (let i in donations["links"])
donateLinks += `<a id="don-${i}" class="switch autowidth" href="${donations["links"][i]}" target="_blank">REPLACEME ${i}</a>` donateLinks += `<a id="don-${i}" class="switch autowidth" href="${donations["links"][i]}" target="_blank">REPLACEME ${i}</a>`;
} let extr = '';
let extr = ''
for (let i in donations["crypto"]) { for (let i in donations["crypto"]) {
donate += `<div class="subtitle${extr}">${i} (REPLACEME)</div><div id="don-${i}" class="text-to-copy" onClick="copy('don-${i}')">${donations["crypto"][i]}</div>` donate += `<div class="subtitle${extr}">${i} (REPLACEME)</div><div id="don-${i}" class="text-to-copy" onClick="copy('don-${i}')">${donations["crypto"][i]}</div>`;
extr = ' top-margin' extr = ' top-margin';
} }
export default function(obj) { export default function(obj) {
@ -56,7 +55,7 @@ export default function(obj) {
<meta name="description" content="${t('AboutSummary')}"> <meta name="description" content="${t('AboutSummary')}">
<meta name="theme-color" content="#000000"> <meta name="theme-color" content="#000000">
<meta name="twitter:card" content="summary"> <meta name="twitter:card" content="summary">
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="${t("AppTitleCobalt")}"> <meta name="apple-mobile-web-app-title" content="${t("AppTitleCobalt")}">
@ -107,7 +106,7 @@ export default function(obj) {
}, { }, {
name: "keyboard", name: "keyboard",
title: `${emoji("⌨")} ${t("CollapseKeyboard")}`, title: `${emoji("⌨")} ${t("CollapseKeyboard")}`,
body: body:
`${t("KeyboardShortcutsIntro")} `${t("KeyboardShortcutsIntro")}
${keyboardShortcuts([{ ${keyboardShortcuts([{
items: [{ items: [{
@ -650,7 +649,7 @@ export default function(obj) {
<script src="cobalt.js"></script> <script src="cobalt.js"></script>
</body> </body>
</html> </html>
` `;
} catch (err) { } catch (err) {
return `${t('ErrorPageRenderFail', obj.hash)}`; return `${t('ErrorPageRenderFail', obj.hash)}`;
} }

View File

@ -40,7 +40,7 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "photo": case "photo":
responseType = 1; responseType = 1;
break; break;
case "gif": case "gif":
params = { type: "gif" } params = { type: "gif" }
break; break;
@ -100,7 +100,7 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
responseType = 1; responseType = 1;
} }
break; break;
case "twitter": case "twitter":
if (r.type === "remux") { if (r.type === "remux") {
params = { type: r.type }; params = { type: r.type };
@ -125,14 +125,14 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
} }
break; break;
case "audio": case "audio":
if ((host === "reddit" && r.typeId === 1) || audioIgnore.includes(host)) { if ((host === "reddit" && r.typeId === 1) || audioIgnore.includes(host)) {
return apiJSON(0, { t: loc(lang, 'ErrorEmptyDownload') }) return apiJSON(0, { t: loc(lang, 'ErrorEmptyDownload') })
} }
let processType = "render", let processType = "render",
copy = false; copy = false;
if (!supportedAudio.includes(audioFormat)) { if (!supportedAudio.includes(audioFormat)) {
audioFormat = "best" audioFormat = "best"
} }

View File

@ -11,11 +11,11 @@ export default async function(obj) {
let streamData = JSON.parse(html.split('<script>window.__playinfo__=')[1].split('</script>')[0]); let streamData = JSON.parse(html.split('<script>window.__playinfo__=')[1].split('</script>')[0]);
if (streamData.data.timelength > maxVideoDuration) return { error: ['ErrorLengthLimit', maxVideoDuration / 60000] }; if (streamData.data.timelength > maxVideoDuration) return { error: ['ErrorLengthLimit', maxVideoDuration / 60000] };
let video = streamData["data"]["dash"]["video"].filter(v => let video = streamData["data"]["dash"]["video"].filter(v =>
!v["baseUrl"].includes("https://upos-sz-mirrorcosov.bilivideo.com/") !v["baseUrl"].includes("https://upos-sz-mirrorcosov.bilivideo.com/")
).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth)); ).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth));
let audio = streamData["data"]["dash"]["audio"].filter(a => let audio = streamData["data"]["dash"]["audio"].filter(a =>
!a["baseUrl"].includes("https://upos-sz-mirrorcosov.bilivideo.com/") !a["baseUrl"].includes("https://upos-sz-mirrorcosov.bilivideo.com/")
).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth)); ).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth));

View File

@ -120,7 +120,7 @@ async function getStory(username, id) {
const item = media.items[media.media_ids.indexOf(id)]; const item = media.items[media.media_ids.indexOf(id)];
if (!item) return { error: 'ErrorEmptyDownload' }; if (!item) return { error: 'ErrorEmptyDownload' };
if (item.video_versions) { if (item.video_versions) {
const video = item.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a) const video = item.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a)
return { return {

View File

@ -9,7 +9,7 @@ async function getAccessToken() {
* you can get these by making a reddit app and * you can get these by making a reddit app and
* authenticating an account against reddit's oauth2 api * authenticating an account against reddit's oauth2 api
* see: https://github.com/reddit-archive/reddit/wiki/OAuth2 * see: https://github.com/reddit-archive/reddit/wiki/OAuth2
* *
* any additional cookie fields are managed by this code and you * any additional cookie fields are managed by this code and you
* should not touch them unless you know what you're doing. **/ * should not touch them unless you know what you're doing. **/
const cookie = await getCookie('reddit'); const cookie = await getCookie('reddit');

View File

@ -11,7 +11,7 @@ export default async function(obj) {
if (!play.video_balancer || play.detail) return { error: 'ErrorEmptyDownload' }; if (!play.video_balancer || play.detail) return { error: 'ErrorEmptyDownload' };
if (play.duration > maxVideoDuration) return { error: ['ErrorLengthLimit', maxVideoDuration / 60000] }; if (play.duration > maxVideoDuration) return { error: ['ErrorLengthLimit', maxVideoDuration / 60000] };
let m3u8 = await fetch(play.video_balancer.m3u8).then((r) => { return r.text() }).catch(() => { return false }); let m3u8 = await fetch(play.video_balancer.m3u8).then((r) => { return r.text() }).catch(() => { return false });
if (!m3u8) return { error: 'ErrorCouldntFetch' }; if (!m3u8) return { error: 'ErrorCouldntFetch' };

View File

@ -9,17 +9,17 @@ async function findClientID() {
let scVersion = String(sc.match(/<script>window\.__sc_version="[0-9]{10}"<\/script>/)[0].match(/[0-9]{10}/)); let scVersion = String(sc.match(/<script>window\.__sc_version="[0-9]{10}"<\/script>/)[0].match(/[0-9]{10}/));
if (cachedID.version === scVersion) return cachedID.id; if (cachedID.version === scVersion) return cachedID.id;
let scripts = sc.matchAll(/<script.+src="(.+)">/g); let scripts = sc.matchAll(/<script.+src="(.+)">/g);
let clientid; let clientid;
for (let script of scripts) { for (let script of scripts) {
let url = script[1]; let url = script[1];
if (url && !url.startsWith('https://a-v2.sndcdn.com')) return; if (url && !url.startsWith('https://a-v2.sndcdn.com')) return;
let scrf = await fetch(url).then((r) => {return r.text()}).catch(() => { return false }); let scrf = await fetch(url).then((r) => {return r.text()}).catch(() => { return false });
let id = scrf.match(/\("client_id=[A-Za-z0-9]{32}"\)/); let id = scrf.match(/\("client_id=[A-Za-z0-9]{32}"\)/);
if (id && typeof id[0] === 'string') { if (id && typeof id[0] === 'string') {
clientid = id[0].match(/[A-Za-z0-9]{32}/)[0]; clientid = id[0].match(/[A-Za-z0-9]{32}/)[0];
break; break;

View File

@ -43,7 +43,7 @@ export default async function(o) {
if (info.playability_status.status !== 'OK') return { error: 'ErrorYTUnavailable' }; if (info.playability_status.status !== 'OK') return { error: 'ErrorYTUnavailable' };
if (info.basic_info.is_live) return { error: 'ErrorLiveVideo' }; if (info.basic_info.is_live) return { error: 'ErrorLiveVideo' };
let bestQuality, hasAudio, adaptive_formats = info.streaming_data.adaptive_formats.filter(e => let bestQuality, hasAudio, adaptive_formats = info.streaming_data.adaptive_formats.filter(e =>
e.mime_type.includes(c[o.format].codec) || e.mime_type.includes(c[o.format].aCodec) e.mime_type.includes(c[o.format].codec) || e.mime_type.includes(c[o.format].aCodec)
).sort((a, b) => Number(b.bitrate) - Number(a.bitrate)); ).sort((a, b) => Number(b.bitrate) - Number(a.bitrate));
@ -126,10 +126,10 @@ export default async function(o) {
return { return {
type, type,
urls, urls,
filenameAttributes, filenameAttributes,
fileMetadata fileMetadata
} }
} }
return { error: 'ErrorYTTryOtherCodec' } return { error: 'ErrorYTTryOtherCodec' };
} }

View File

@ -5,7 +5,7 @@ export const testers = {
"instagram": (patternMatch) => "instagram": (patternMatch) =>
patternMatch.postId?.length <= 12 patternMatch.postId?.length <= 12
|| (patternMatch.username?.length <= 30 && patternMatch.storyId?.length <= 24), || (patternMatch.username?.length <= 30 && patternMatch.storyId?.length <= 24),
"ok": (patternMatch) => "ok": (patternMatch) =>
patternMatch.id?.length <= 16, patternMatch.id?.length <= 16,
@ -19,12 +19,12 @@ export const testers = {
patternMatch.id?.length === 32, patternMatch.id?.length === 32,
"soundcloud": (patternMatch) => "soundcloud": (patternMatch) =>
(patternMatch.author?.length <= 255 && patternMatch.song?.length <= 255) (patternMatch.author?.length <= 255 && patternMatch.song?.length <= 255)
|| patternMatch.shortLink?.length <= 32, || patternMatch.shortLink?.length <= 32,
"streamable": (patternMatch) => "streamable": (patternMatch) =>
patternMatch.id?.length === 6, patternMatch.id?.length === 6,
"tiktok": (patternMatch) => "tiktok": (patternMatch) =>
patternMatch.postId?.length <= 21 || patternMatch.id?.length <= 13, patternMatch.postId?.length <= 21 || patternMatch.id?.length <= 13,

View File

@ -14,9 +14,8 @@ let rl = createInterface({ input: process.stdin, output: process.stdout });
let final = () => { let final = () => {
if (existsSync(envPath)) unlinkSync(envPath); if (existsSync(envPath)) unlinkSync(envPath);
for (let i in ob) { for (let i in ob)
appendFileSync(envPath, `${i}=${ob[i]}\n`) appendFileSync(envPath, `${i}=${ob[i]}\n`);
}
console.log(Bright("\nAwesome! I've created a fresh .env file for you.")); console.log(Bright("\nAwesome! I've created a fresh .env file for you."));
console.log(`${Bright("Now I'll run")} ${Cyan("npm install")} ${Bright("to install all dependencies. It shouldn't take long.\n\n")}`); 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] });
@ -28,7 +27,7 @@ let final = () => {
console.log( console.log(
`${Cyan(`Hey, this is cobalt v.${version}!`)}\n${Bright("Let's start by creating a new ")}${Cyan(".env")}${Bright(" file. You can always change it later.")}` `${Cyan(`Hey, this is cobalt v.${version}!`)}\n${Bright("Let's start by creating a new ")}${Cyan(".env")}${Bright(" file. You can always change it later.")}`
) );
function setup() { function setup() {
console.log(Bright("\nWhat kind of server will this instance be?\nOptions: api, web.")); console.log(Bright("\nWhat kind of server will this instance be?\nOptions: api, web."));
@ -59,22 +58,22 @@ function setup() {
rl.question(q, apiCors => { rl.question(q, apiCors => {
let answCors = apiCors.toLowerCase().trim(); let answCors = apiCors.toLowerCase().trim();
if (answCors !== "y" && answCors !== "yes") ob['cors'] = '0' if (answCors !== "y" && answCors !== "yes") ob['cors'] = '0';
final() final();
}) })
}) })
}); });
}) })
break; break;
case 'web': case 'web':
console.log(Bright("\nAwesome! What's the domain this web app instance will be running on? (localhost)\nExample: cobalt.tools")); console.log(Bright("\nAwesome! What's the domain this web app instance will be running on? (localhost)\nExample: cobalt.tools"));
rl.question(q, webURL => { rl.question(q, webURL => {
ob['webURL'] = `http://localhost:9001/`; ob['webURL'] = `http://localhost:9001/`;
ob['webPort'] = 9001; ob['webPort'] = 9001;
if (webURL && webURL !== "localhost") ob['webURL'] = `https://${webURL.toLowerCase()}/`; if (webURL && webURL !== "localhost") ob['webURL'] = `https://${webURL.toLowerCase()}/`;
console.log( console.log(
Bright("\nGreat! Now, what port will it be running on? (9001)") Bright("\nGreat! Now, what port will it be running on? (9001)")
) )
@ -90,16 +89,16 @@ function setup() {
ob['apiURL'] = `https://${apiURL.toLowerCase()}/`; ob['apiURL'] = `https://${apiURL.toLowerCase()}/`;
if (apiURL.includes(':')) ob['apiURL'] = `http://${apiURL.toLowerCase()}/`; if (apiURL.includes(':')) ob['apiURL'] = `http://${apiURL.toLowerCase()}/`;
if (!apiURL) ob['apiURL'] = "https://co.wuk.sh/"; if (!apiURL) ob['apiURL'] = "https://co.wuk.sh/";
final() final();
}) })
}); });
}); });
break; break;
default: default:
console.log(Bright("\nThis is not an option. Try again.")); console.log(Bright("\nThis is not an option. Try again."));
setup() setup();
} }
}) });
} }
setup() setup();

View File

@ -25,7 +25,7 @@ for (let i in services) {
console.log(`\nRunning tests for ${i}...\n`) console.log(`\nRunning tests for ${i}...\n`)
for (let k = 0; k < tests[i].length; k++) { for (let k = 0; k < tests[i].length; k++) {
let test = tests[i][k]; let test = tests[i][k];
console.log(`Running test ${k+1}: ${test.name}`); console.log(`Running test ${k+1}: ${test.name}`);
console.log('params:'); console.log('params:');
let params = {...{url: test.url}, ...test.params}; let params = {...{url: test.url}, ...test.params};