remade localization system once again

- new localization system: fast, dynamic, way more organized
- localization strings are WAY more descriptive
- it's now easier to add support for other languages (just one loc file instead of five)
- localization now falls back to english if localized string isnt available
- got rid of all static language selectors (probably)
- slightly updated english and russian strings
- miscellaneous settings items have been bundled together and moved to the bottom, cause they're used the least
- bottom links should no longer touch the popup border on overflow
- rearranged popup order in the rendered page
- bumped version up to 2.2.5

if you see strings that are like this: !!EXAMPLE!! or withoutspace please file an issue on github
This commit is contained in:
wukko 2022-07-24 16:54:05 +06:00
parent 8d275b0213
commit a4a9af6120
32 changed files with 339 additions and 299 deletions

View file

@ -1,7 +1,7 @@
{ {
"name": "cobalt", "name": "cobalt",
"description": "probably the friendliest social media downloader yet", "description": "probably the friendliest social media downloader yet",
"version": "2.2", "version": "2.2.5",
"author": "wukko", "author": "wukko",
"exports": "./cobalt.js", "exports": "./cobalt.js",
"type": "module", "type": "module",

View file

@ -9,10 +9,10 @@ import { shortCommit } from "./modules/sub/currentCommit.js";
import { appName, genericUserAgent, version, internetExplorerRedirect } from "./modules/config.js"; import { appName, genericUserAgent, version, internetExplorerRedirect } from "./modules/config.js";
import { getJSON } from "./modules/api.js"; import { getJSON } from "./modules/api.js";
import renderPage from "./modules/pageRender.js"; import renderPage from "./modules/pageRender.js";
import { apiJSON } from "./modules/sub/utils.js"; import { apiJSON, languageCode } from "./modules/sub/utils.js";
import loc from "./modules/sub/i18n.js";
import { Bright, Cyan } from "./modules/sub/consoleText.js"; import { Bright, Cyan } from "./modules/sub/consoleText.js";
import stream from "./modules/stream/stream.js"; import stream from "./modules/stream/stream.js";
import loc from "./localization/manager.js";
const commitHash = shortCommit(); const commitHash = shortCommit();
const app = express(); const app = express();
@ -26,7 +26,7 @@ if (fs.existsSync('./.env')) {
standardHeaders: true, standardHeaders: true,
legacyHeaders: false, legacyHeaders: false,
handler: (req, res, next, opt) => { handler: (req, res, next, opt) => {
res.status(429).json({ "status": "error", "text": loc('en', 'apiError', 'rateLimit') }); res.status(429).json({ "status": "error", "text": loc(languageCode(req), 'ErrorRateLimit') });
} }
}) })
const apiLimiterStream = rateLimit({ const apiLimiterStream = rateLimit({
@ -35,7 +35,7 @@ if (fs.existsSync('./.env')) {
standardHeaders: true, standardHeaders: true,
legacyHeaders: false, legacyHeaders: false,
handler: (req, res, next, opt) => { handler: (req, res, next, opt) => {
res.status(429).json({ "status": "error", "text": loc('en', 'apiError', 'rateLimit') }); res.status(429).json({ "status": "error", "text": loc(languageCode(req), 'ErrorRateLimit') });
} }
}) })
@ -61,13 +61,13 @@ if (fs.existsSync('./.env')) {
let j = await getJSON( let j = await getJSON(
req.query.url.trim(), req.query.url.trim(),
req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip, req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip,
req.header('Accept-Language') ? req.header('Accept-Language').slice(0, 2) : "en", languageCode(req),
req.query.format ? req.query.format.slice(0, 5) : "mp4", req.query.format ? req.query.format.slice(0, 5) : "mp4",
req.query.quality ? req.query.quality.slice(0, 3) : "max" req.query.quality ? req.query.quality.slice(0, 3) : "max"
) )
res.status(j.status).json(j.body); res.status(j.status).json(j.body);
} else { } else {
let j = apiJSON(3, { t: loc('en', 'apiError', 'noURL', process.env.selfURL) }) let j = apiJSON(3, { t: loc(languageCode(req), 'ErrorNoLink', process.env.selfURL) })
res.status(j.status).json(j.body); res.status(j.status).json(j.body);
} }
break; break;
@ -78,12 +78,12 @@ if (fs.existsSync('./.env')) {
let ip = req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip let ip = req.header('x-forwarded-for') ? req.header('x-forwarded-for') : req.ip
stream(res, ip, req.query.t, req.query.h, req.query.e); stream(res, ip, req.query.t, req.query.h, req.query.e);
} else { } else {
let j = apiJSON(0, { t: loc('en', 'apiError', 'noStreamID') }) let j = apiJSON(0, { t: loc(languageCode(req), 'ErrorNoStreamID') })
res.status(j.status).json(j.body); res.status(j.status).json(j.body);
} }
break; break;
default: default:
let j = apiJSON(0, { t: loc('en', 'apiError', 'noType') }) let j = apiJSON(0, { t: loc(languageCode(req), 'ErrorNoType') })
res.status(j.status).json(j.body); res.status(j.status).json(j.body);
break; break;
} }
@ -108,7 +108,7 @@ if (fs.existsSync('./.env')) {
res.send(renderPage({ res.send(renderPage({
"hash": commitHash, "hash": commitHash,
"type": "default", "type": "default",
"lang": req.header('Accept-Language') ? req.header('Accept-Language').slice(0, 2) : "en", "lang": languageCode(req),
"useragent": req.header('user-agent') ? req.header('user-agent') : genericUserAgent "useragent": req.header('user-agent') ? req.header('user-agent') : genericUserAgent
})) }))
} }

View file

@ -1,11 +1,10 @@
{ {
"appName": "cobalt", "appName": "cobalt",
"version": "2.2", "version": "2.2.5",
"streamLifespan": 1800000, "streamLifespan": 1800000,
"maxVideoDuration": 1920000, "maxVideoDuration": 1920000,
"genericUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36", "genericUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
"repo": "https://github.com/wukko/cobalt", "repo": "https://github.com/wukko/cobalt",
"supportedLanguages": ["en", "ru"],
"authorInfo": { "authorInfo": {
"name": "wukko", "name": "wukko",
"link": "https://wukko.me/", "link": "https://wukko.me/",

View file

@ -1,11 +0,0 @@
{
"about": "View about",
"settings": "Open settings",
"input": "Link input area",
"download": "Download button",
"changelog": "View changelog",
"close": "Close the popup",
"alwaysVisibleButton": "Keep the download button always visible",
"downloadPopup": "Ask what to do with downloads",
"donate": "Open donation popup"
}

View file

@ -1,18 +0,0 @@
{
"generic": "something went wrong and i couldn't get anything for you. you can try again, but if issue persists, please <a class=\"text-backdrop nowrap\" href=\"{repo}\">let me know</a>.",
"notSupported": "it seems like this service is not supported yet or your link is invalid.",
"brokenLink": "{s} is supported, but something is wrong with your link. maybe you didn't copy it fully?",
"noLink": "i can't guess what you want to download! please give me a link.",
"noRender": "something went wrong and page couldn't render. if you want me to fix this, please <a href=\"https://wukko.me/contacts\">contact me</a>. it'd be useful if you provided the commit hash ({s}) along with recreation steps. thank you :D",
"rateLimit": "you're making way too many requests. calm down and try again in a few minutes.",
"noFetch": "couldn't fetch metadata. check if your link is correct and try again.",
"lengthLimit": "current length limit is {s} minutes. what you tried to download was longer than that. pick something else to download!",
"errorFetch": "something went wrong with info fetching. you can try a different format and resoltuion or just try again later.",
"corruptedStream": "it seems like this download is corrupted. try again or try a different format and resolution.",
"noInternet": "it seems like there's no internet or {appName} api is down. check your connection and try again.",
"cantConnectToAPI": "i couldn't connect to {s} api. seems like either {s} is down or {appName} server ip got blocked. try again later.",
"nothingToDownload": "it seems like there's nothing to download. try another link!",
"liveVideo": "i can't download a live video. wait for stream to finish and try again.",
"noStreamID": "there's no such streamId.",
"noType": "there's no such expected response type."
}

View file

@ -1,22 +0,0 @@
{
"appearance": "appearance",
"alwaysVisibleButton": "keep >> visible",
"downloadPopupButton": "ask for a way to save",
"format": "download format",
"formatInfo": "select webm if you need max quality available. webm videos are usually higher quality but ios devices can't play them natively. all \"audio only\" downloads are max quality.",
"theme": "theme",
"themeAuto": "auto",
"themeLight": "light",
"themeDark": "dark",
"misc": "miscellaneous",
"general": "downloads",
"quality": "quality",
"qmax": "max",
"qhig": "high\n",
"qmid": "medium\n",
"qlow": "low\n",
"qlos": "lowest",
"qualityDesc": "if selected resolution isn't available, closest one gets picked instead.",
"extra": "extra",
"audioOnly": "audio only"
}

View file

@ -1,19 +0,0 @@
{
"input": "paste the link here",
"aboutSummary": "{appName} is your go-to place for social media downloads. zero ads or other creepy bullshit attached. simply paste a share link and you're ready to rock!",
"embed": "save content from social media without creeps following you around",
"supportedServices": "currently supported services:",
"sourceCode": "&gt;&gt; report issues and check out the source code on github",
"popupBottom": "made with <3 by wukko",
"noScript": "{appName} uses javascript for api requests and interactive interface. you have to allow javascript to use this site. we don't have any ads or trackers, pinky promise.",
"donationsSub": "it's a little complicated to pay for hosting right now",
"donations": "i don't like crypto how it is right now, but it's the only way for me to pay for anything (including hosting) online. services similar paypal are no longer available too.",
"donateDm": "&gt;&gt; let me know if currency you want to donate isn't listed",
"clickToCopy": "click to copy",
"iosDownload": "you have to press and hold the download button and then select \"download video\" in appeared popup to save the video. this is required because you have an ios device.",
"normalDownload": "download button opens a new tab with requested file. you can disable this popup in settings.",
"download": "download",
"copy": "copy url",
"open": "open",
"github": "&gt;&gt; see previous changes and contribute on github"
}

View file

@ -1,9 +0,0 @@
{
"about": "what's {appName}?",
"settings": "settings",
"error": "uh-oh...",
"changelog": "what's new?",
"donate": "support {appName}",
"download": "download",
"pickDownload": "pick a way to save"
}

View file

@ -1,11 +0,0 @@
{
"about": "Что за {appName}?",
"settings": "Открыть настройки",
"input": "Вставь ссылку сюда",
"download": "Кнопка скачивания",
"changelog": "Просмотреть последние изменения (на английском)",
"close": "Закрыть окно",
"alwaysVisibleButton": "Всегда оставлять кнопку скачивания на экране",
"downloadPopup": "Спрашивать, что делать с загрузками",
"donate": "Пожертвования"
}

View file

@ -1,18 +0,0 @@
{
"generic": "что-то пошло совсем не так, поэтому у меня не получилось ничего для тебя достать. ты можешь попробовать ещё раз, но если так и не получится, <a class=\"text-backdrop nowrap\" href=\"{repo}\">напиши об этом</a>.",
"notSupported": "этот сервис ещё не поддерживается, или с твоей ссылкой что-то не так.",
"brokenLink": "{s} поддерживается, но с твоей ссылкой что-то не так. может быть, ты её не полностью скопировал?",
"noLink": "я не могу угадать, что ты хочешь скачать. попробуй в следующий раз вставить ссылку.",
"noRender": "что-то пошло не так, поэтому у меня не получилось срендерить страницу. если это что-то критичное, пожалуйста, <a href=\"https://wukko.me/contacts\">напиши мне об этом</a>. приложи хэш текущего коммита ({s}) с действиями для получения ошибки. можно на русском языке. спасибо :)",
"rateLimit": "ты делаешь слишком много запросов. успокойся и попробуй ещё раз через несколько минут.",
"noFetch": "мне не удалось получить информацию о твоей ссылке. проверь её и попробуй ещё раз.",
"lengthLimit": "твоё видео длиннее чем {s} минут(ы). это превышает текущий лимит. скачай что-нибудь покороче, а не войну и мир.",
"errorFetch": "что-то пошло не так с получением данных о твоей ссылке. попробуй другой формат и разрешение. если не получится, то попробуй ещё раз чуть позже.",
"corruptedStream": "эта загрузка повреждена. попробуй ещё раз. если не получится, то попробуй другой формат и разрешение.",
"noInternet": "кажется, нет подключения к интернету. а возможно лежу я, а не твой интернет. в любом случае, проверь подключение к интернету и попробуй ещё раз.",
"cantConnectToAPI": "не получилось подключится к серверу {s}. {s} либо лежит, либо меня добавили в чёрный список. попробуй ещё раз чуть позже.",
"nothingToDownload": "мне нечего скачать. попробуй другую ссылку!",
"liveVideo": "я не могу скачать прямой эфир. дождись окончания трансляции и попробуй ещё раз.",
"noStreamID": "нет такого streamId.",
"noType": "нет такого формата ответа от сервера."
}

View file

@ -1,22 +0,0 @@
{
"appearance": "внешний вид",
"alwaysVisibleButton": "оставлять >> на экране",
"downloadPopupButton": "спрашивать, что делать с загрузками",
"format": "формат загрузок",
"formatInfo": "выбирай webm, если хочешь максимальное качество. webm обычно лучше по качеству, но устройства на ios не могут проигрывать их без сторонних приложений. все загрузки \"только аудио\" всегда максимального качества.",
"theme": "тема",
"themeAuto": "авто",
"themeLight": "светлая",
"themeDark": "тёмная",
"misc": "ещё",
"general": "загрузки",
"quality": "качество",
"qmax": "макс",
"qhig": "высокое\n",
"qmid": "среднее\n",
"qlow": "низкое\n",
"qlos": "ужасное",
"qualityDesc": "если выбранное разрешение недоступно, то выбирается ближайшее.",
"extra": "ещё",
"audioOnly": "только аудио"
}

View file

@ -1,18 +0,0 @@
{
"input": "вставь ссылку сюда",
"aboutSummary": "{appName} — твой друг при скачивании видео из соц. сетей. никакой рекламы или трекеров. просто вставь ссылку, и ты прекрасен.",
"embed": "сохраняй что хочешь, без мороки и вторжения в личное пространство",
"supportedServices": "что поддерживается:",
"sourceCode": "&gt;&gt; сообщай о проблемах на github",
"popupBottom": "сделано с <3 ~ wukko",
"noScript": "{appName} использует javascript для обработки ссылок и интерактивного интерфейса. ты должен разрешить использование javascript, чтобы пользоваться сайтом. тут нет никаких трекеров или рекламы, обещаю.",
"donationsSub": "сейчас намного сложнее платить за хостинг",
"donations": "я ненавижу крипто, но у меня нет возможности платить любым другим способом.",
"donateDm": "&gt;&gt; если нет подходящей валюты, или же ты из россии, то напиши мне",
"clickToCopy": "нажми, чтобы скопировать",
"iosDownload": "так как у тебя устройство на ios, тебе нужно зажать кнопку \"скачать\" и выбрать что-то похожее на \"сохранить в галерею\" в появившемся окне.",
"normalDownload": "кнопка скачивания открывает новое окно с файлом. ты можешь отключить выбор метода сохранения файла в настройках.",
"download": "скачать",
"copy": "скопировать ссылку",
"github": "&gt;&gt; посмотреть предыдущие изменения на github"
}

View file

@ -1,9 +0,0 @@
{
"about": "что за {appName}?",
"settings": "настройки",
"error": "о нет",
"changelog": "что нового?",
"donate": "поддержи {appName}",
"download": "скачивание",
"pickDownload": "как сохранить?"
}

View file

@ -0,0 +1,76 @@
{
"name": "english",
"code": "en",
"substrings": {
"ContactLink": "<a class=\"text-backdrop\" href=\"{repo}\">let me know</a>"
},
"strings": {
"LinkInput": "paste the link here",
"AboutSummary": "{appName} is your go-to place for social media downloads. zero ads, trackers, or any other creepy bullshit attached. simply paste a share link and you're ready to rock!",
"AboutSupportedServices": "currently supported services:",
"EmbedBriefDescription": "save content from social media without creeps following you around",
"MadeWithLove": "made with <3 by wukko",
"AccessibilityInputArea": "link input area",
"AccessibilityOpenAbout": "open about popup",
"AccessibilityDownloadButton": "download button",
"AccessibilityOpenSettings": "open settings popup",
"AccessibilityOpenChangelog": "view changelog popup",
"AccessibilityClosePopup": "close the popup",
"AccessibilityOpenDonate": "open donation popup",
"TitlePopupAbout": "what's {appName}?",
"TitlePopupSettings": "settings",
"TitlePopupError": "uh-oh...",
"TitlePopupChangelog": "what's new?",
"TitlePopupDonate": "support {appName}",
"TitlePopupDownload": "download",
"ErrorSomethingWentWrong": "something went wrong and i couldn't get anything for you. you can try again, but if issue persists, please {ContactLink}.",
"ErrorUnsupported": "it seems like this service is not supported yet or your link is invalid.",
"ErrorBrokenLink": "{s} is supported, but something is wrong with your link. maybe you didn't copy it fully?",
"ErrorNoLink": "i can't guess what you want to download! please give me a link.",
"ErrorPageRenderFail": "something went wrong and page couldn't render. if it's a recurring or critical issue, please {ContactLink}. it'd be useful if you provided current commit hash ({s}) and error recreation steps. thank you :D",
"ErrorRateLimit": "you're making way too many requests. calm down and try again in a few minutes.",
"ErrorCouldntFetch": "couldn't fetch metadata. check if your link is correct and try again.",
"ErrorLengthLimit": "current length limit is {s} minutes. what you tried to download was longer than {s} minutes. pick something else to download!",
"ErrorBadFetch": "something went wrong with info fetching. you can try a different format and resolution or just try again later.",
"ErrorCorruptedStream": "this download is unfortunately corrupted. try again or try a different format and resolution.",
"ErrorNoInternet": "there's no internet or {appName} api is down. check your connection and try again.",
"ErrorCantConnectToServiceAPI": "i couldn't connect to {s} api. seems like either {s} is down or {appName} server ip got blocked. try again later.",
"ErrorEmptyDownload": "there's no media content to download. try something else!",
"ErrorLiveVideo": "i can't download a live video. wait for stream to finish and try again.",
"ErrorNoStreamID": "there's no such streamId.",
"ErrorNoType": "there's no such expected response type.",
"SettingsAppearanceSubtitle": "appearance",
"SettingsThemeSubtitle": "theme",
"SettingsFormatSubtitle": "download format",
"SettingsMiscSubtitle": "more settings",
"SettingsDownloadsSubtitle": "downloads",
"SettingsQualitySubtitle": "quality",
"SettingsThemeAuto": "auto",
"SettingsThemeLight": "light",
"SettingsThemeDark": "dark",
"SettingsQualitySwitchMax": "max",
"SettingsQualitySwitchHigh": "high\n",
"SettingsQualitySwitchMedium": "medium\n",
"SettingsQualitySwitchLow": "low\n",
"SettingsQualitySwitchLowest": "lowest",
"SettingsFormatSwitchAudio": "audio only",
"SettingsKeepDownloadButton": "keep &gt;&gt; visible",
"AccessibilityKeepDownloadButton": "keep the download button always visible",
"SettingsEnableDownloadPopup": "ask for a way to save",
"AccessibilityEnableDownloadPopup": "ask what to do with downloads",
"SettingsFormatDescription": "select webm if you need max quality available. webm videos are usually higher quality but ios devices can't play them natively. all \"audio only\" downloads are max quality.",
"SettingsQualityDescription": "if selected resolution isn't available, closest one gets picked instead. if you want to post a youtube video on twitter, select 720p. twitter likes videos like that way more.",
"DonateSubtitle": "it's hard to pay for hosting right now",
"DonateDescription": "i don't like crypto how it is right now, but it's currently the only way for me to pay for anything abroad. mastercard/visa cards and services similar to paypal are no longer an option.",
"LinkGitHubIssues": "&gt;&gt; report issues and check out the source code on github",
"LinkGitHubChanges": "&gt;&gt; see previous changes and contribute on github",
"LinkDonateContact": "&gt;&gt; let me know if currency you want to donate isn't listed",
"NoScriptMessage": "{appName} uses javascript for api requests and interactive interface. you have to allow javascript to use this site. we don't have any ads or trackers, pinky promise.",
"DownloadPopupDescriptionIOS": "since you have an ios device, you have to press and hold the download button and then select \"download video\" in appeared popup to save the video. this will be required for as long as apple forces safari webview upon all browser developers on ios.",
"DownloadPopupDescription": "download button opens a new tab with requested file. you can disable this popup in settings.",
"DownloadPopupWayToSave": "pick a way to save",
"ClickToCopy": "click to copy",
"Download": "download",
"CopyURL": "copy url"
}
}

View file

@ -0,0 +1,76 @@
{
"name": "русский",
"code": "ru",
"substrings": {
"ContactLink": "<a class=\"text-backdrop\" href=\"{repo}\">напиши об этом</a>"
},
"strings": {
"LinkInput": "вставь ссылку сюда",
"AboutSummary": "{appName} — твой друг при скачивании контента из соц. сетей. никакой рекламы или трекеров. просто вставь ссылку, и ты прекрасен.",
"AboutSupportedServices": "что поддерживается:",
"EmbedBriefDescription": "сохраняй что хочешь, без мороки и вторжения в личное пространство",
"MadeWithLove": "сделано с <3 ~ wukko",
"AccessibilityInputArea": "зона вставки ссылки",
"AccessibilityOpenAbout": "открыть окно с информацией",
"AccessibilityDownloadButton": "кнопка скачивания",
"AccessibilityOpenSettings": "открыть настройки",
"AccessibilityOpenChangelog": "просмотреть последние изменения (на английском)",
"AccessibilityClosePopup": "закрыть окно",
"AccessibilityOpenDonate": "сделать пожертвование",
"TitlePopupAbout": "что за {appName}?",
"TitlePopupSettings": "настройки",
"TitlePopupError": "о нет...",
"TitlePopupChangelog": "что нового?",
"TitlePopupDonate": "поддержи {appName}",
"TitlePopupDownload": "скачивание",
"ErrorSomethingWentWrong": "что-то пошло совсем не так, поэтому у меня не получилось ничего для тебя достать. ты можешь попробовать ещё раз, но если так и не получится, {ContactLink}.",
"ErrorUnsupported": "этот сервис ещё не поддерживается, или с твоей ссылкой что-то не так.",
"ErrorBrokenLink": "{s} поддерживается, но с твоей ссылкой что-то не так. может быть, ты её не полностью скопировал?",
"ErrorNoLink": "я не могу угадать, что ты хочешь скачать! попробуй в следующий раз вставить ссылку.",
"ErrorPageRenderFail": "что-то пошло не так, поэтому у меня не получилось срендерить страницу. если это что-то критичное, пожалуйста, {ContactLink}. приложи хэш текущего коммита ({s}) с действиями для получения ошибки. можно на русском языке. спасибо :)",
"ErrorRateLimit": "ты делаешь слишком много запросов. успокойся и попробуй ещё раз через несколько минут.",
"ErrorCouldntFetch": "мне не удалось получить информацию о твоей ссылке. проверь её и попробуй ещё раз.",
"ErrorLengthLimit": "твоё видео длиннее чем {s} минут(ы). это превышает текущий лимит. скачай что-нибудь покороче, а не войну и мир.",
"ErrorBadFetch": "что-то пошло не так с получением информации о твоей ссылке. попробуй другой формат и разрешение. если не получится, то попробуй ещё раз чуть позже.",
"ErrorCorruptedStream": "эта загрузка повреждена. попробуй ещё раз. если не получится, то попробуй другой формат и разрешение.",
"ErrorNoInternet": "кажется, нет подключения к интернету. возможно лежит сервер {appName}. в любом случае, проверь подключение к интернету и попробуй ещё раз.",
"ErrorCantConnectToServiceAPI": "у меня не получилось подключится к серверу {s}. возможно {s} лежит, или же меня добавили в чёрный список. попробуй ещё раз чуть позже.",
"ErrorEmptyDownload": "мне нечего скачать. попробуй другую ссылку!",
"ErrorLiveVideo": "я не могу скачать прямой эфир. дождись окончания трансляции и попробуй ещё раз.",
"ErrorNoStreamID": "нет такого streamId.",
"ErrorNoType": "нет такого типа ответа от сервера.",
"SettingsAppearanceSubtitle": "внешний вид",
"SettingsThemeSubtitle": "тема",
"SettingsFormatSubtitle": "формат загрузок",
"SettingsMiscSubtitle": "дополнительные настройки",
"SettingsDownloadsSubtitle": "загрузки",
"SettingsQualitySubtitle": "качество",
"SettingsThemeAuto": "авто",
"SettingsThemeLight": "светлая",
"SettingsThemeDark": "тёмная",
"SettingsQualitySwitchMax": "макс",
"SettingsQualitySwitchHigh": "высокое\n",
"SettingsQualitySwitchMedium": "среднее\n",
"SettingsQualitySwitchLow": "низкое\n",
"SettingsQualitySwitchLowest": "худшее",
"SettingsFormatSwitchAudio": "только аудио",
"SettingsKeepDownloadButton": "оставлять &gt;&gt; на экране",
"AccessibilityKeepDownloadButton": "оставлять кнопку скачивания на экране",
"SettingsEnableDownloadPopup": "спрашивать, как сохранять",
"AccessibilityEnableDownloadPopup": "спрашивать, что делать с загрузками",
"SettingsFormatDescription": "выбирай webm, если хочешь максимальное качество. webm обычно лучше по качеству, но устройства на ios не могут проигрывать их без сторонних приложений. все загрузки \"только аудио\" всегда максимального качества.",
"SettingsQualityDescription": "если выбранное разрешение недоступно, то выбирается ближайшее к нему. если ты хочешь твитнуть загруженное видео, то выбирай 720p. такие видео твиттер обычно воспринимает намного лучше.",
"DonateSubtitle": "сейчас намного сложнее оплачивать хостинг",
"DonateDescription": "я ненавижу крипто, но у меня нет возможности платить любым другим способом.",
"LinkGitHubIssues": "&gt;&gt; сообщай о проблемах и смотри исходный код на github",
"LinkGitHubChanges": "&gt;&gt; посмотреть предыдущие изменения на github",
"LinkDonateContact": "&gt;&gt; напиши мне, если в этом списке нет подходящей валюты",
"NoScriptMessage": "{appName} использует javascript для обработки ссылок и интерактивного интерфейса. ты должен разрешить использование javascript, чтобы пользоваться сайтом. тут нет никаких трекеров или рекламы, обещаю.",
"DownloadPopupDescriptionIOS": "так как у тебя устройство на ios, тебе нужно зажать кнопку \"скачать\" и выбрать что-то похожее на \"сохранить в галерею\" в появившемся окне.",
"DownloadPopupDescription": "кнопка скачивания открывает новое окно с файлом. ты можешь отключить выбор метода сохранения файла в настройках.",
"DownloadPopupWayToSave": "выбери, как сохранить",
"ClickToCopy": "нажми, чтобы скопировать",
"Download": "скачать",
"CopyURL": "скопировать ссылку"
}
}

View file

@ -0,0 +1,42 @@
import * as fs from "fs";
import { appName, repo } from "../modules/config.js";
import loadJson from "../modules/sub/loadJSON.js";
const locPath = './src/localization/languages'
let loc = {}
export async function loadLoc() {
fs.readdir(locPath, (err, files) => {
files.forEach(file => {
loc[file.split('.')[0]] = loadJson(`${locPath}/${file}`)
});
})
}
await loadLoc();
export function replaceBase(s) {
return s.replace(/\n/g, '<br/>').replace(/{appName}/g, appName).replace(/{repo}/g, repo)
}
export function replaceAll(lang, str, string, replacement) {
let s = replaceBase(str[string])
if (replacement) s = s.replace(/{s}/g, replacement);
if (s.match('{')) {
Object.keys(loc[lang]["substrings"]).forEach(sub => {
s = replaceBase(s.replace(`{${sub}}`, loc[lang]["substrings"][sub]))
});
}
return s
}
export default function(lang, string, replacement) {
try {
if (!Object.keys(loc).includes(lang)) lang = 'en';
let str = loc[lang]["strings"];
if (str && str[string]) {
return replaceAll(lang, str, string, replacement)
} else {
str = loc["en"]["strings"];
return replaceAll(lang, str, string, replacement)
}
} catch (e) {
return `!!${string}!!`
}
}

View file

@ -4,7 +4,7 @@ import { services as patterns } from "./config.js";
import { cleanURL, apiJSON } from "./sub/utils.js"; import { cleanURL, apiJSON } from "./sub/utils.js";
import { errorUnsupported } from "./sub/errors.js"; import { errorUnsupported } from "./sub/errors.js";
import loc from "./sub/i18n.js"; import loc from "../localization/manager.js";
import match from "./match.js"; import match from "./match.js";
export async function getJSON(originalURL, ip, lang, format, quality) { export async function getJSON(originalURL, ip, lang, format, quality) {
@ -30,6 +30,6 @@ export async function getJSON(originalURL, ip, lang, format, quality) {
return apiJSON(0, { t: errorUnsupported(lang) } ) return apiJSON(0, { t: errorUnsupported(lang) } )
} }
} catch (e) { } catch (e) {
return apiJSON(0, { t: loc(lang, 'apiError', 'generic') }); return apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') });
} }
} }

View file

@ -2,7 +2,7 @@ import loadJson from "./sub/loadJSON.js";
const config = loadJson("./src/config.json"); const config = loadJson("./src/config.json");
export const export const
services = loadJson("./src/modules/services/all.json"), services = loadJson("./src/modules/services/_config.json"),
appName = config.appName, appName = config.appName,
version = config.version, version = config.version,
streamLifespan = config.streamLifespan, streamLifespan = config.streamLifespan,

View file

@ -25,7 +25,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit
videoId: patternMatch["videoId"], videoId: patternMatch["videoId"],
lang: lang, quality: quality lang: lang, quality: quality
}); });
return (!r.error) ? apiJSON(2, { type: "bridge", u: r.url, filename: r.filename, service: host, ip: ip, salt: process.env.streamSalt }) : apiJSON(0, { t: r.error }); return (!r.error) ? apiJSON(2, { type: "bridge", lang: lang, u: r.url, filename: r.filename, service: host, ip: ip, salt: process.env.streamSalt }) : apiJSON(0, { t: r.error });
} else throw Error() } else throw Error()
case "bilibili": case "bilibili":
if (patternMatch["id"] && patternMatch["id"].length >= 12) { if (patternMatch["id"] && patternMatch["id"].length >= 12) {
@ -62,7 +62,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit
} }
let r = await youtube(fetchInfo); let r = await youtube(fetchInfo);
return (!r.error) ? apiJSON(2, { return (!r.error) ? apiJSON(2, {
type: r.type, u: r.urls, service: host, ip: ip, type: r.type, u: r.urls, lang: lang, service: host, ip: ip,
filename: r.filename, salt: process.env.streamSalt, filename: r.filename, salt: process.env.streamSalt,
isAudioOnly: fetchInfo["isAudioOnly"] ? fetchInfo["isAudioOnly"] : false, isAudioOnly: fetchInfo["isAudioOnly"] ? fetchInfo["isAudioOnly"] : false,
time: r.time, time: r.time,
@ -76,7 +76,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit
title: patternMatch["title"], lang: lang, title: patternMatch["title"], lang: lang,
}); });
return (!r.error) ? apiJSON(r.typeId, { return (!r.error) ? apiJSON(r.typeId, {
type: r.type, u: r.urls, type: r.type, u: r.urls, lang: lang,
service: host, ip: ip, service: host, ip: ip,
filename: r.filename, salt: process.env.streamSalt filename: r.filename, salt: process.env.streamSalt
}) : apiJSON(0, { t: r.error }); }) : apiJSON(0, { t: r.error });

View file

@ -1,6 +1,6 @@
import { services, appName, authorInfo, version, quality, repo, donations } from "./config.js"; import { services, appName, authorInfo, version, quality, repo, donations } from "./config.js";
import { getCommitInfo } from "./sub/currentCommit.js"; import { getCommitInfo } from "./sub/currentCommit.js";
import loc from "./sub/i18n.js"; import loc from "../localization/manager.js";
let s = services let s = services
let enabledServices = Object.keys(s).filter((p) => { let enabledServices = Object.keys(s).filter((p) => {
@ -34,10 +34,10 @@ export default function(obj) {
<meta property="og:url" content="${process.env.selfURL}" /> <meta property="og:url" content="${process.env.selfURL}" />
<meta property="og:title" content="${appName}" /> <meta property="og:title" content="${appName}" />
<meta property="og:description" content="${loc(obj.lang, 'strings', 'embed')}" /> <meta property="og:description" content="${loc(obj.lang, 'EmbedBriefDescription')}" />
<meta property="og:image" content="${process.env.selfURL}icons/generic.png" /> <meta property="og:image" content="${process.env.selfURL}icons/generic.png" />
<meta name="title" content="${appName}" /> <meta name="title" content="${appName}" />
<meta name="description" content="${loc(obj.lang, 'strings', 'embed')}" /> <meta name="description" content="${loc(obj.lang, '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" />
@ -50,127 +50,130 @@ export default function(obj) {
<link rel="stylesheet" href="cobalt.css" /> <link rel="stylesheet" href="cobalt.css" />
<link rel="stylesheet" href="fonts/notosansmono/notosansmono.css" /> <link rel="stylesheet" href="fonts/notosansmono/notosansmono.css" />
<noscript><div style="margin: 2rem;">${loc(obj.lang, 'strings', 'noScript')}</div></noscript> <noscript><div style="margin: 2rem;">${loc(obj.lang, 'NoScriptMessage')}</div></noscript>
</head> </head>
<body id="cobalt-body"> <body id="cobalt-body" data-nosnippet>
<div id="popup-download" class="popup center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('download', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button>
<div id="title" class="popup-subtitle">${loc(obj.lang, 'title', 'download')}</div>
</div>
<div id="content" class="popup-content">
<div id="theme-switcher" class="switch-container small-padding">
<div class="subtitle">${loc(obj.lang, 'title', 'pickDownload')}</div>
<div class="switches">
<a id="pd-download" class="switch full space-right" target="_blank"">${loc(obj.lang, 'strings', 'download')}</a>
<div id="pd-copy" class="switch full">${loc(obj.lang, 'strings', 'copy')}</div>
</div>
</div>
<div id="desc" class="explanation about-padding">${isIOS ? loc(obj.lang, 'strings', 'iosDownload') : loc(obj.lang, 'strings', 'normalDownload')}</div>
</div>
</div>
<div id="popup-about" class="popup center box" style="visibility: hidden;"> <div id="popup-about" class="popup center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header"> <div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('about', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button> <button id="close" class="button mono" onclick="popup('about', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'about')}</div> <div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupAbout')}</div>
</div> </div>
<div id="content" class="popup-content with-footer"> <div id="content" class="popup-content with-footer">
<div id="desc" class="popup-desc about-padding">${loc(obj.lang, 'strings', 'aboutSummary')}</div> <div id="desc" class="popup-desc about-padding">${loc(obj.lang, 'AboutSummary')}</div>
<div id="desc" class="popup-desc about-padding">${loc(obj.lang, 'strings', 'supportedServices')} ${enabledServices}.</div> <div id="desc" class="popup-desc about-padding">${loc(obj.lang, 'AboutSupportedServices')} ${enabledServices}.</div>
<div id="desc" class="popup-desc"><a class="text-backdrop" href="${repo}">${loc(obj.lang, 'strings', 'sourceCode')}</a></div> <div id="desc" class="popup-desc bottom-link"><a class="text-backdrop" href="${repo}">${loc(obj.lang, 'LinkGitHubIssues')}</a></div>
</div> </div>
<div id="popup-footer" class="popup-footer"> <div id="popup-footer" class="popup-footer">
<a id="popup-bottom" class="popup-footer-content" href="${authorInfo.link}">${loc(obj.lang, 'strings', 'popupBottom')}</a> <a id="popup-bottom" class="popup-footer-content" href="${authorInfo.link}">${loc(obj.lang, 'MadeWithLove')}</a>
</div> </div>
</div> </div>
<div id="popup-changelog" class="popup center box" style="visibility: hidden;"> <div id="popup-changelog" class="popup center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header"> <div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('changelog', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button> <button id="close" class="button mono" onclick="popup('changelog', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'changelog')}</div> <div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupChangelog')}</div>
<div id="desc" class="popup-subtitle">${com[0]} (${obj.hash})</div> <div id="desc" class="popup-subtitle">${com[0]} (${obj.hash})</div>
</div> </div>
<div id="content" class="popup-content"> <div id="content" class="popup-content">
<div id="desc" class="popup-desc about-padding">${com[1]}</div> <div id="desc" class="popup-desc about-padding">${com[1]}</div>
<div id="desc" class="popup-desc"><a class="text-backdrop" href="${repo}/commits">${loc(obj.lang, 'strings', 'github')}</a></div> <div id="desc" class="popup-desc bottom-link"><a class="text-backdrop" href="${repo}/commits">${loc(obj.lang, 'LinkGitHubChanges')}</a></div>
</div> </div>
</div> </div>
<div id="popup-donate" class="popup scrollable center box" style="visibility: hidden;"> <div id="popup-donate" class="popup scrollable center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header"> <div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('donate', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button> <button id="close" class="button mono" onclick="popup('donate', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'donate')}</div> <div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupDonate')}</div>
<div id="desc" class="little-subtitle">${loc(obj.lang, 'strings', 'donationsSub')}</div> <div id="desc" class="little-subtitle">${loc(obj.lang, 'DonateSubtitle')}</div>
</div> </div>
<div id="content" class="popup-content"> <div id="content" class="popup-content">
${donate.replace(/REPLACEME/g, loc(obj.lang, 'strings', 'clickToCopy').trim())} ${donate.replace(/REPLACEME/g, loc(obj.lang, 'ClickToCopy').trim())}
<div id="desc" class="explanation about-padding">${loc(obj.lang, 'strings', 'donations')}</div> <div id="desc" class="explanation about-padding">${loc(obj.lang, 'DonateDescription')}</div>
<div id="desc" class="popup-desc"><a class="text-backdrop" href="${authorInfo.contact}">${loc(obj.lang, 'strings', 'donateDm')}</a></div> <div id="desc" class="popup-desc bottom-link"><a class="text-backdrop" href="${authorInfo.contact}">${loc(obj.lang, 'LinkDonateContact')}</a></div>
</div> </div>
</div> </div>
<div id="popup-settings" class="popup scrollable center box" style="visibility: hidden;"> <div id="popup-settings" class="popup scrollable center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header"> <div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('settings', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button> <button id="close" class="button mono" onclick="popup('settings', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="version" class="popup-above-title">v.${version} ~ ${obj.hash}</div> <div id="version" class="popup-above-title">v.${version} ~ ${obj.hash}</div>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'settings')}</div> <div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupSettings')}</div>
</div> </div>
<div id="content" class="popup-content"> <div id="content" class="popup-content">
<div id="settings-appearance" class="settings-category"> <div id="settings-appearance" class="settings-category">
<div class="title">${loc(obj.lang, 'settings', 'appearance')}</div> <div class="title">${loc(obj.lang, 'SettingsAppearanceSubtitle')}</div>
<div class="settings-category-content"> <div class="settings-category-content">
<div id="theme-switcher" class="switch-container"> <div id="theme-switcher" class="switch-container">
<div class="subtitle">${loc(obj.lang, 'settings', 'theme')}</div> <div class="subtitle">${loc(obj.lang, 'SettingsThemeSubtitle')}</div>
<div class="switches"> <div class="switches">
<div id="theme-auto" class="switch full" onclick="changeSwitcher('theme', 'auto', 1)">${loc(obj.lang, 'settings', 'themeAuto')}</div> <div id="theme-auto" class="switch full" onclick="changeSwitcher('theme', 'auto', 1)">${loc(obj.lang, 'SettingsThemeAuto')}</div>
<div id="theme-dark" class="switch" onclick="changeSwitcher('theme', 'dark', 1)">${loc(obj.lang, 'settings', 'themeDark')}</div> <div id="theme-dark" class="switch" onclick="changeSwitcher('theme', 'dark', 1)">${loc(obj.lang, 'SettingsThemeDark')}</div>
<div id="theme-light" class="switch full" onclick="changeSwitcher('theme', 'light', 1)">${loc(obj.lang, 'settings', 'themeLight')}</div> <div id="theme-light" class="switch full" onclick="changeSwitcher('theme', 'light', 1)">${loc(obj.lang, 'SettingsThemeLight')}</div>
</div> </div>
</div> </div>
<div class="subtitle">${loc(obj.lang, 'settings', 'misc')}</div>
<label class="checkbox">
<input id="alwaysVisibleButton" type="checkbox" aria-label="${loc(obj.lang, 'accessibility', 'alwaysVisibleButton')}" onclick="checkbox('alwaysVisibleButton', 'always-visible-button')">
<span>${loc(obj.lang, 'settings', 'alwaysVisibleButton')}</span>
</label>
</div> </div>
</div> </div>
<div id="settings-downloads" class="settings-category"> <div id="settings-downloads" class="settings-category">
<div class="title">${loc(obj.lang, 'settings', 'general')}</div> <div class="title">${loc(obj.lang, 'SettingsDownloadsSubtitle')}</div>
<div class="settings-category-content"> <div class="settings-category-content">
<div id="quality-switcher" class="switch-container"> <div id="quality-switcher" class="switch-container">
<div class="subtitle">${loc(obj.lang, 'settings', 'quality')}</div> <div class="subtitle">${loc(obj.lang, 'SettingsQualitySubtitle')}</div>
<div class="switches"> <div class="switches">
<div id="quality-max" class="switch full" onclick="changeSwitcher('quality', 'max', 1)">${loc(obj.lang, 'settings', 'qmax')}</div> <div id="quality-max" class="switch full" onclick="changeSwitcher('quality', 'max', 1)">${loc(obj.lang, 'SettingsQualitySwitchMax')}</div>
<div id="quality-hig" class="switch" onclick="changeSwitcher('quality', 'hig', 1)">${loc(obj.lang, 'settings', 'qhig')}(${quality.hig}p)</div> <div id="quality-hig" class="switch" onclick="changeSwitcher('quality', 'hig', 1)">${loc(obj.lang, 'SettingsQualitySwitchHigh')}(${quality.hig}p)</div>
<div id="quality-mid" class="switch full" onclick="changeSwitcher('quality', 'mid', 1)">${loc(obj.lang, 'settings', 'qmid')}(${quality.mid}p)</div> <div id="quality-mid" class="switch full" onclick="changeSwitcher('quality', 'mid', 1)">${loc(obj.lang, 'SettingsQualitySwitchMedium')}(${quality.mid}p)</div>
<div id="quality-low" class="switch right" onclick="changeSwitcher('quality', 'low', 1)">${loc(obj.lang, 'settings', 'qlow')}(${quality.low}p)</div> <div id="quality-low" class="switch right" onclick="changeSwitcher('quality', 'low', 1)">${loc(obj.lang, 'SettingsQualitySwitchLow')}(${quality.low}p)</div>
</div> </div>
<div class="explanation">${loc(obj.lang, 'settings', 'qualityDesc')}</div> <div class="explanation">${loc(obj.lang, 'SettingsQualityDescription')}</div>
</div> </div>
${!isIOS ? `<div class="subtitle">${loc(obj.lang, 'settings', 'extra')}</div>
<label class="checkbox">
<input id="downloadPopup" type="checkbox" aria-label="${loc(obj.lang, 'accessibility', 'downloadPopup')}" onclick="checkbox('downloadPopup', 'always-visible-button')">
<span>${loc(obj.lang, 'settings', 'downloadPopupButton')}</span>
</label>` : ``}
</div> </div>
</div> </div>
<div id="settings-youtube" class="settings-category"> <div id="settings-youtube" class="settings-category">
<div class="title">youtube</div> <div class="title">youtube</div>
<div class="settings-category-content"> <div class="settings-category-content">
<div id="youtube-switcher" class="switch-container"> <div id="youtube-switcher" class="switch-container">
<div class="subtitle">${loc(obj.lang, 'settings', 'format')}</div> <div class="subtitle">${loc(obj.lang, 'SettingsFormatSubtitle')}</div>
<div class="switches"> <div class="switches">
<div id="youtubeFormat-mp4" class="switch full" onclick="changeSwitcher('youtubeFormat', 'mp4', 1)">mp4</div> <div id="youtubeFormat-mp4" class="switch full" onclick="changeSwitcher('youtubeFormat', 'mp4', 1)">mp4</div>
<div id="youtubeFormat-webm" class="switch" onclick="changeSwitcher('youtubeFormat', 'webm', 1)">webm</div> <div id="youtubeFormat-webm" class="switch" onclick="changeSwitcher('youtubeFormat', 'webm', 1)">webm</div>
<div id="youtubeFormat-audio" class="switch full" onclick="changeSwitcher('youtubeFormat', 'audio', 1)">${loc(obj.lang, 'settings', 'audioOnly')}</div> <div id="youtubeFormat-audio" class="switch full" onclick="changeSwitcher('youtubeFormat', 'audio', 1)">${loc(obj.lang, 'SettingsFormatSwitchAudio')}</div>
</div> </div>
<div class="explanation">${loc(obj.lang, 'settings', 'formatInfo')}</div> <div class="explanation">${loc(obj.lang, 'SettingsFormatDescription')}</div>
</div> </div>
</div> </div>
</div> </div>
<div id="settings-misc" class="settings-category">
<div class="title bottom-margin">${loc(obj.lang, 'SettingsMiscSubtitle')}</div>
<div class="settings-category-content">
<label class="checkbox">
<input id="alwaysVisibleButton" type="checkbox" aria-label="${loc(obj.lang, 'AccessibilityKeepDownloadButton')}" onclick="checkbox('alwaysVisibleButton', 'always-visible-button')">
<span>${loc(obj.lang, 'SettingsKeepDownloadButton')}</span>
</label>${!isIOS ? `
<label class="checkbox">
<input id="downloadPopup" type="checkbox" aria-label="${loc(obj.lang, 'AccessibilityEnableDownloadPopup')}" onclick="checkbox('downloadPopup', 'always-visible-button')">
<span>${loc(obj.lang, 'SettingsEnableDownloadPopup')}</span>
</label>` : ``}
</div>
</div>
</div>
</div>
<div id="popup-download" class="popup center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('download', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="title" class="popup-subtitle">${loc(obj.lang, 'TitlePopupDownload')}</div>
</div>
<div id="content" class="popup-content">
<div id="theme-switcher" class="switch-container small-padding">
<div class="subtitle">${loc(obj.lang, 'DownloadPopupDescription')}</div>
<div class="switches">
<a id="pd-download" class="switch full space-right" target="_blank"">${loc(obj.lang, 'Download')}</a>
<div id="pd-copy" class="switch full">${loc(obj.lang, 'CopyURL')}</div>
</div>
</div>
<div id="desc" class="explanation about-padding">${isIOS ? loc(obj.lang, 'DownloadPopupDescriptionIOS') : loc(obj.lang, 'DownloadPopupDescription')}</div>
</div> </div>
</div> </div>
<div id="popup-error" class="popup center box" style="visibility: hidden;"> <div id="popup-error" class="popup center box" style="visibility: hidden;">
<div id="popup-header" class="popup-header"> <div id="popup-header" class="popup-header">
<button id="close" class="button mono" onclick="popup('error', 0)" aria-label="${loc(obj.lang, 'accessibility', 'close')}">x</button> <button id="close" class="button mono" onclick="popup('error', 0)" aria-label="${loc(obj.lang, 'AccessibilityClosePopup')}">x</button>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'error')}</div> <div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupError')}</div>
</div> </div>
<div id="content" class="popup-content"> <div id="content" class="popup-content">
<div id="desc-error" class="popup-desc"></div> <div id="desc-error" class="popup-desc"></div>
@ -180,23 +183,23 @@ export default function(obj) {
<div id="cobalt-main-box" class="center box" style="visibility: hidden;"> <div id="cobalt-main-box" class="center box" style="visibility: hidden;">
<div id="logo-area">${appName}</div> <div id="logo-area">${appName}</div>
<div id="download-area" class="mobile-center"> <div id="download-area" class="mobile-center">
<input id="url-input-area" class="mono" type="text" autocorrect="off" maxlength="110" autocapitalize="off" placeholder="${loc(obj.lang, 'strings', 'input')}" aria-label="${loc(obj.lang, 'accessibility', 'input')}" oninput="button()"> <input id="url-input-area" class="mono" type="text" autocorrect="off" maxlength="110" autocapitalize="off" placeholder="${loc(obj.lang, 'LinkInput')}" aria-label="${loc(obj.lang, 'AccessibilityInputArea')}" oninput="button()">
<input id="download-button" class="mono dontRead" onclick="download(document.getElementById('url-input-area').value)" type="submit" value="" disabled=true aria-label="${loc(obj.lang, 'accessibility', 'download')}"> <input id="download-button" class="mono dontRead" onclick="download(document.getElementById('url-input-area').value)" type="submit" value="" disabled=true aria-label="${loc(obj.lang, 'AccessibilityDownloadButton')}">
</div> </div>
</div> </div>
<footer id="footer" style="visibility: hidden;"> <footer id="footer" style="visibility: hidden;">
<div id="footer-buttons"> <div id="footer-buttons">
<button id="about-open" class="button footer-button" onclick="popup('about', 1)" aria-label="${loc(obj.lang, 'accessibility', 'about')}">?</button> <button id="about-open" class="button footer-button" onclick="popup('about', 1)" aria-label="${loc(obj.lang, 'AccessibilityOpenAbout')}">?</button>
<button id="changelog-open" class="button footer-button" onclick="popup('changelog', 1)" aria-label="${loc(obj.lang, 'accessibility', 'changelog')}">!</button> <button id="changelog-open" class="button footer-button" onclick="popup('changelog', 1)" aria-label="${loc(obj.lang, 'AccessibilityOpenChangelog')}">!</button>
<button id="donate-open" class="button footer-button" onclick="popup('donate', 1)" aria-label="${loc(obj.lang, 'accessibility', 'donate')}">$</button> <button id="donate-open" class="button footer-button" onclick="popup('donate', 1)" aria-label="${loc(obj.lang, 'AccessibilityOpenDonate')}">$</button>
<button id="settings-open" class="button footer-button" onclick="popup('settings', 1)" aria-label="${loc(obj.lang, 'accessibility', 'settings')}">+</button> <button id="settings-open" class="button footer-button" onclick="popup('settings', 1)" aria-label="${loc(obj.lang, 'AccessibilityOpenSettings')}">+</button>
</div> </div>
</footer> </footer>
</body> </body>
<script type="text/javascript">const loc = {noInternet:"${loc(obj.lang, 'apiError', 'noInternet')}", noURLReturned: "${loc(obj.lang, 'apiError', 'errorFetch')}"}</script> <script type="text/javascript">const loc = {noInternet:"${loc(obj.lang, 'ErrorNoInternet')}", noURLReturned: "${loc(obj.lang, 'ErrorBadFetch')}"}</script>
<script type="text/javascript" src="cobalt.js"></script> <script type="text/javascript" src="cobalt.js"></script>
</html>`; </html>`;
} catch (err) { } catch (err) {
return `${loc('en', 'apiError', 'noRender', obj.hash)}`; return `${loc(obj.lang, 'ErrorPageRenderFail', obj.hash)}`;
} }
} }

View file

@ -1,5 +1,5 @@
import got from "got"; import got from "got";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration } from "../config.js"; import { genericUserAgent, maxVideoDuration } from "../config.js";
export default async function(obj) { export default async function(obj) {
@ -8,7 +8,7 @@ export default async function(obj) {
headers: { "user-agent": genericUserAgent } headers: { "user-agent": genericUserAgent }
}); });
html.on('error', (err) => { html.on('error', (err) => {
return { error: loc(obj.lang, 'apiError', 'cantConnectToAPI', 'bilibili') }; return { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI', 'bilibili') };
}); });
html = html.body; html = html.body;
if (html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"')) { if (html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"')) {
@ -22,13 +22,13 @@ export default async function(obj) {
}).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth)); }).sort((a, b) => Number(b.bandwidth) - Number(a.bandwidth));
return { urls: [video[0]["baseUrl"], audio[0]["baseUrl"]], time: streamData.data.timelength, filename: `bilibili_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.mp4` }; return { urls: [video[0]["baseUrl"], audio[0]["baseUrl"]], time: streamData.data.timelength, filename: `bilibili_${obj.id}_${video[0]["width"]}x${video[0]["height"]}.mp4` };
} else { } else {
return { error: loc(obj.lang, 'apiError', 'lengthLimit', maxVideoDuration / 60000) }; return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
} }
} else { } else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') }; return { error: loc(obj.lang, 'ErrorEmptyDownload') };
} }
} catch (e) { } catch (e) {
return { error: loc(obj.lang, 'apiError', 'noFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} }

View file

@ -1,5 +1,5 @@
import got from "got"; import got from "got";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration } from "../config.js"; import { genericUserAgent, maxVideoDuration } from "../config.js";
export default async function(obj) { export default async function(obj) {
@ -20,9 +20,9 @@ export default async function(obj) {
return { typeId: 1, urls: video}; return { typeId: 1, urls: video};
} }
} else { } else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') }; return { error: loc(obj.lang, 'ErrorEmptyDownload') };
} }
} catch (err) { } catch (err) {
return { error: loc(obj.lang, 'apiError', 'noFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} }

View file

@ -1,11 +1,11 @@
import got from "got"; import got from "got";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
import { services } from "../config.js"; import { services } from "../config.js";
const configSt = services.twitter; const configSt = services.twitter;
async function fetchTweetInfo(obj) { async function fetchTweetInfo(obj) {
let cantConnect = { error: loc('en', 'apiError', 'cantConnectToAPI', 'twitter') } let cantConnect = { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI', 'twitter') }
try { try {
let _headers = { let _headers = {
"Authorization": `Bearer ${configSt.token}`, "Authorization": `Bearer ${configSt.token}`,
@ -28,11 +28,11 @@ async function fetchTweetInfo(obj) {
}) })
return JSON.parse(req_status.body); return JSON.parse(req_status.body);
} catch (err) { } catch (err) {
return { error: cantConnect }; return cantConnect;
} }
} }
export default async function (obj) { export default async function (obj) {
let nothing = { error: loc('en', 'apiError', 'nothingToDownload') } let nothing = { error: loc(obj.lang, 'ErrorEmptyDownload') }
try { try {
let parsbod = await fetchTweetInfo(obj); let parsbod = await fetchTweetInfo(obj);
if (!parsbod.error) { if (!parsbod.error) {
@ -52,6 +52,6 @@ export default async function (obj) {
} }
} else return parsbod; } else return parsbod;
} catch (err) { } catch (err) {
return { error: loc("en", "apiError", "errorFetch") }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} }

View file

@ -1,6 +1,6 @@
import got from "got"; import got from "got";
import { xml2json } from "xml-js"; import { xml2json } from "xml-js";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration, services } from "../config.js"; import { genericUserAgent, maxVideoDuration, services } from "../config.js";
import selectQuality from "../stream/selectQuality.js"; import selectQuality from "../stream/selectQuality.js";
@ -30,18 +30,18 @@ export default async function(obj) {
if (selectedQuality in js["player"]["params"][0]) { if (selectedQuality in js["player"]["params"][0]) {
return { url: js["player"]["params"][0][selectedQuality].replace(`type=${maxQuality}`, `type=${services.vk.quality_match[userQuality]}`), filename: `vk_${js["player"]["params"][0][selectedQuality].split("id=")[1]}_${attr['width']}x${attr['height']}.mp4` }; return { url: js["player"]["params"][0][selectedQuality].replace(`type=${maxQuality}`, `type=${services.vk.quality_match[userQuality]}`), filename: `vk_${js["player"]["params"][0][selectedQuality].split("id=")[1]}_${attr['width']}x${attr['height']}.mp4` };
} else { } else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') }; return { error: loc(obj.lang, 'ErrorEmptyDownload') };
} }
} else { } else {
return { error: loc(obj.lang, 'apiError', 'lengthLimit', maxVideoDuration / 60000) }; return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
} }
} else { } else {
return { error: loc(obj.lang, 'apiError', 'liveVideo') }; return { error: loc(obj.lang, 'ErrorLiveVideo') };
} }
} else { } else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') }; return { error: loc(obj.lang, 'ErrorEmptyDownload') };
} }
} catch (err) { } catch (err) {
return { error: loc(obj.lang, 'apiError', 'errorFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} }

View file

@ -1,5 +1,5 @@
import ytdl from "ytdl-core"; import ytdl from "ytdl-core";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
import { maxVideoDuration, quality as mq } from "../config.js"; import { maxVideoDuration, quality as mq } from "../config.js";
import selectQuality from "../stream/selectQuality.js"; import selectQuality from "../stream/selectQuality.js";
@ -48,7 +48,7 @@ export default async function (obj) {
filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` }; filename: `youtube_${obj.id}_${videoMatch[0]["width"]}x${videoMatch[0]["height"]}.${obj.format}` };
} }
} else { } else {
return { error: loc('en', 'apiError', 'errorFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} else if (!obj.isAudioOnly) { } else if (!obj.isAudioOnly) {
return { type: "render", urls: [video[0]["url"], audio[0]["url"]], time: video[0]["approxDurationMs"], return { type: "render", urls: [video[0]["url"], audio[0]["url"]], time: video[0]["approxDurationMs"],
@ -56,19 +56,19 @@ export default async function (obj) {
} else if (audio.length > 0) { } else if (audio.length > 0) {
return { type: "render", isAudioOnly: true, urls: [audio[0]["url"]], filename: `youtube_${obj.id}_${audio[0]["audioBitrate"]}kbps.opus` }; return { type: "render", isAudioOnly: true, urls: [audio[0]["url"]], filename: `youtube_${obj.id}_${audio[0]["audioBitrate"]}kbps.opus` };
} else { } else {
return { error: loc('en', 'apiError', 'errorFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} else { } else {
return { error: loc('en', 'apiError', 'lengthLimit', maxVideoDuration / 60000) }; return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
} }
} else { } else {
return { error: loc('en', 'apiError', 'liveVideo') }; return { error: loc(obj.lang, 'ErrorLiveVideo') };
} }
} else { } else {
return { error: loc('en', 'apiError', 'youtubeFetch') }; return { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI') };
} }
} catch (e) { } catch (e) {
return { error: loc('en', 'apiError', 'youtubeFetch') }; return { error: loc(obj.lang, 'ErrorBadFetch') };
} }
} }

View file

@ -21,7 +21,8 @@ export function createStream(obj) {
ip: iphmac, ip: iphmac,
exp: exp, exp: exp,
isAudioOnly: obj.isAudioOnly ? true : false, isAudioOnly: obj.isAudioOnly ? true : false,
time: obj.time time: obj.time,
lang: obj.lang
}); });
return `${process.env.selfURL}api/stream?t=${streamUUID}&e=${exp}&h=${ghmac}`; return `${process.env.selfURL}api/stream?t=${streamUUID}&e=${exp}&h=${ghmac}`;
} }

View file

@ -4,7 +4,7 @@ import got from "got";
import { ffmpegArgs, genericUserAgent } from "../config.js"; import { ffmpegArgs, genericUserAgent } from "../config.js";
import { msToTime } from "../sub/utils.js"; import { msToTime } from "../sub/utils.js";
import { internalError } from "../sub/errors.js"; import { internalError } from "../sub/errors.js";
import loc from "../sub/i18n.js"; import loc from "../../localization/manager.js";
export async function streamDefault(streamInfo, res) { export async function streamDefault(streamInfo, res) {
try { try {
@ -69,7 +69,7 @@ export async function streamLiveRender(streamInfo, res) {
ffmpegProcess.kill(); ffmpegProcess.kill();
}); });
} else { } else {
res.status(400).json({ status: "error", text: loc('en', 'apiError', 'corruptedStream') }); res.status(400).json({ status: "error", text: loc(streamInfo.lang, 'ErrorCorruptedStream') });
} }
} catch (e) { } catch (e) {
internalError(res); internalError(res);

View file

@ -1,11 +1,11 @@
import loc from "./i18n.js"; import loc from "../../localization/manager.js";
export function internalError(res) { export function internalError(res) {
res.status(501).json({ status: "error", text: "Internal Server Error" }); res.status(501).json({ status: "error", text: "Internal Server Error" });
} }
export function errorUnsupported(lang) { export function errorUnsupported(lang) {
return loc(lang, 'apiError', 'notSupported'); return loc(lang, 'ErrorUnsupported');
} }
export function genericError(lang, host) { export function genericError(lang, host) {
return loc(lang, 'apiError', 'brokenLink', host); return loc(lang, 'ErrorBrokenLink', host);
} }

View file

@ -1,18 +0,0 @@
import { supportedLanguages, appName, repo } from "../config.js";
import loadJson from "./loadJSON.js";
export default function(lang, cat, string, replacement) {
try {
if (!supportedLanguages.includes(lang)) lang = 'en';
let str = loadJson(`./src/i18n/${lang}/${cat}.json`);
if (str && str[string]) {
let s = str[string].replace(/\n/g, '<br/>').replace(/{appName}/g, appName).replace(/{repo}/g, repo)
if (replacement) s = s.replace(/{s}/g, replacement);
return s + ' '
} else {
return string
}
} catch (e) {
return string
}
}

View file

@ -48,4 +48,7 @@ export function cleanURL(url, host) {
} }
} }
return url return url
}
export function languageCode(req) {
return req.header('Accept-Language') ? req.header('Accept-Language').slice(0, 2) : "en"
} }

View file

@ -248,6 +248,9 @@ input[type="checkbox"] {
.popup.scrollable { .popup.scrollable {
height: 80%; height: 80%;
} }
.scrollable .bottom-link {
padding-bottom: 2rem;
}
.nowrap { .nowrap {
white-space: nowrap; white-space: nowrap;
} }
@ -321,6 +324,9 @@ input[type="checkbox"] {
border-bottom: 0.05rem solid var(--accent-unhover-2); border-bottom: 0.05rem solid var(--accent-unhover-2);
padding-bottom: 0.25rem; padding-bottom: 0.25rem;
} }
.bottom-margin {
margin-bottom: 1rem;
}
.checkbox { .checkbox {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@ -331,7 +337,7 @@ input[type="checkbox"] {
padding-right: 1rem; padding-right: 1rem;
border: 0.1rem solid; border: 0.1rem solid;
width: auto; width: auto;
margin: 0 1rem 0 0; margin: 0 0.5rem 0.5rem 0;
} }
.checkbox-label { .checkbox-label {
line-height: 1.3rem; line-height: 1.3rem;
@ -435,6 +441,9 @@ input[type="checkbox"] {
.popup { .popup {
height: 80% height: 80%
} }
.bottom-link {
padding-bottom: 2rem;
}
} }
/* mobile page */ /* mobile page */
@media screen and (max-width: 949px) { @media screen and (max-width: 949px) {
@ -459,6 +468,9 @@ input[type="checkbox"] {
height: 90%; height: 90%;
max-height: 100%; max-height: 100%;
} }
.bottom-link {
padding-bottom: 2rem;
}
} }
@media screen and (max-width: 524px) { @media screen and (max-width: 524px) {
#logo-area { #logo-area {
@ -482,4 +494,7 @@ input[type="checkbox"] {
height: 90%; height: 90%;
max-height: 100%; max-height: 100%;
} }
.bottom-link {
padding-bottom: 2rem;
}
} }