diff --git a/package.json b/package.json index b9c5212..dac8475 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cobalt", "description": "probably the friendliest social media downloader yet", - "version": "2.2", + "version": "2.2.5", "author": "wukko", "exports": "./cobalt.js", "type": "module", diff --git a/src/cobalt.js b/src/cobalt.js index ae10d38..2fc2c0b 100644 --- a/src/cobalt.js +++ b/src/cobalt.js @@ -9,10 +9,10 @@ import { shortCommit } from "./modules/sub/currentCommit.js"; import { appName, genericUserAgent, version, internetExplorerRedirect } from "./modules/config.js"; import { getJSON } from "./modules/api.js"; import renderPage from "./modules/pageRender.js"; -import { apiJSON } from "./modules/sub/utils.js"; -import loc from "./modules/sub/i18n.js"; +import { apiJSON, languageCode } from "./modules/sub/utils.js"; import { Bright, Cyan } from "./modules/sub/consoleText.js"; import stream from "./modules/stream/stream.js"; +import loc from "./localization/manager.js"; const commitHash = shortCommit(); const app = express(); @@ -26,7 +26,7 @@ if (fs.existsSync('./.env')) { standardHeaders: true, legacyHeaders: false, 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({ @@ -35,7 +35,7 @@ if (fs.existsSync('./.env')) { standardHeaders: true, legacyHeaders: false, 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( req.query.url.trim(), 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.quality ? req.query.quality.slice(0, 3) : "max" ) res.status(j.status).json(j.body); } 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); } break; @@ -78,12 +78,12 @@ if (fs.existsSync('./.env')) { 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); } 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); } break; 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); break; } @@ -108,7 +108,7 @@ if (fs.existsSync('./.env')) { res.send(renderPage({ "hash": commitHash, "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 })) } diff --git a/src/config.json b/src/config.json index 528d321..75120ce 100644 --- a/src/config.json +++ b/src/config.json @@ -1,11 +1,10 @@ { "appName": "cobalt", - "version": "2.2", + "version": "2.2.5", "streamLifespan": 1800000, "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", "repo": "https://github.com/wukko/cobalt", - "supportedLanguages": ["en", "ru"], "authorInfo": { "name": "wukko", "link": "https://wukko.me/", diff --git a/src/i18n/en/accessibility.json b/src/i18n/en/accessibility.json deleted file mode 100644 index 6cefa13..0000000 --- a/src/i18n/en/accessibility.json +++ /dev/null @@ -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" -} \ No newline at end of file diff --git a/src/i18n/en/apiError.json b/src/i18n/en/apiError.json deleted file mode 100644 index 99b0f7c..0000000 --- a/src/i18n/en/apiError.json +++ /dev/null @@ -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 let me know.", - "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 contact me. 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." -} \ No newline at end of file diff --git a/src/i18n/en/settings.json b/src/i18n/en/settings.json deleted file mode 100644 index b40df8f..0000000 --- a/src/i18n/en/settings.json +++ /dev/null @@ -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" -} \ No newline at end of file diff --git a/src/i18n/en/strings.json b/src/i18n/en/strings.json deleted file mode 100644 index f487b87..0000000 --- a/src/i18n/en/strings.json +++ /dev/null @@ -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": ">> 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": ">> 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": ">> see previous changes and contribute on github" -} \ No newline at end of file diff --git a/src/i18n/en/title.json b/src/i18n/en/title.json deleted file mode 100644 index 6fb6cc4..0000000 --- a/src/i18n/en/title.json +++ /dev/null @@ -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" -} \ No newline at end of file diff --git a/src/i18n/ru/accessibility.json b/src/i18n/ru/accessibility.json deleted file mode 100644 index c5e913b..0000000 --- a/src/i18n/ru/accessibility.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "about": "Что за {appName}?", - "settings": "Открыть настройки", - "input": "Вставь ссылку сюда", - "download": "Кнопка скачивания", - "changelog": "Просмотреть последние изменения (на английском)", - "close": "Закрыть окно", - "alwaysVisibleButton": "Всегда оставлять кнопку скачивания на экране", - "downloadPopup": "Спрашивать, что делать с загрузками", - "donate": "Пожертвования" -} \ No newline at end of file diff --git a/src/i18n/ru/apiError.json b/src/i18n/ru/apiError.json deleted file mode 100644 index 7494801..0000000 --- a/src/i18n/ru/apiError.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "generic": "что-то пошло совсем не так, поэтому у меня не получилось ничего для тебя достать. ты можешь попробовать ещё раз, но если так и не получится, напиши об этом.", - "notSupported": "этот сервис ещё не поддерживается, или с твоей ссылкой что-то не так.", - "brokenLink": "{s} поддерживается, но с твоей ссылкой что-то не так. может быть, ты её не полностью скопировал?", - "noLink": "я не могу угадать, что ты хочешь скачать. попробуй в следующий раз вставить ссылку.", - "noRender": "что-то пошло не так, поэтому у меня не получилось срендерить страницу. если это что-то критичное, пожалуйста, напиши мне об этом. приложи хэш текущего коммита ({s}) с действиями для получения ошибки. можно на русском языке. спасибо :)", - "rateLimit": "ты делаешь слишком много запросов. успокойся и попробуй ещё раз через несколько минут.", - "noFetch": "мне не удалось получить информацию о твоей ссылке. проверь её и попробуй ещё раз.", - "lengthLimit": "твоё видео длиннее чем {s} минут(ы). это превышает текущий лимит. скачай что-нибудь покороче, а не войну и мир.", - "errorFetch": "что-то пошло не так с получением данных о твоей ссылке. попробуй другой формат и разрешение. если не получится, то попробуй ещё раз чуть позже.", - "corruptedStream": "эта загрузка повреждена. попробуй ещё раз. если не получится, то попробуй другой формат и разрешение.", - "noInternet": "кажется, нет подключения к интернету. а возможно лежу я, а не твой интернет. в любом случае, проверь подключение к интернету и попробуй ещё раз.", - "cantConnectToAPI": "не получилось подключится к серверу {s}. {s} либо лежит, либо меня добавили в чёрный список. попробуй ещё раз чуть позже.", - "nothingToDownload": "мне нечего скачать. попробуй другую ссылку!", - "liveVideo": "я не могу скачать прямой эфир. дождись окончания трансляции и попробуй ещё раз.", - "noStreamID": "нет такого streamId.", - "noType": "нет такого формата ответа от сервера." -} \ No newline at end of file diff --git a/src/i18n/ru/settings.json b/src/i18n/ru/settings.json deleted file mode 100644 index ca30103..0000000 --- a/src/i18n/ru/settings.json +++ /dev/null @@ -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": "только аудио" -} \ No newline at end of file diff --git a/src/i18n/ru/strings.json b/src/i18n/ru/strings.json deleted file mode 100644 index 2d67629..0000000 --- a/src/i18n/ru/strings.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "input": "вставь ссылку сюда", - "aboutSummary": "{appName} — твой друг при скачивании видео из соц. сетей. никакой рекламы или трекеров. просто вставь ссылку, и ты прекрасен.", - "embed": "сохраняй что хочешь, без мороки и вторжения в личное пространство", - "supportedServices": "что поддерживается:", - "sourceCode": ">> сообщай о проблемах на github", - "popupBottom": "сделано с <3 ~ wukko", - "noScript": "{appName} использует javascript для обработки ссылок и интерактивного интерфейса. ты должен разрешить использование javascript, чтобы пользоваться сайтом. тут нет никаких трекеров или рекламы, обещаю.", - "donationsSub": "сейчас намного сложнее платить за хостинг", - "donations": "я ненавижу крипто, но у меня нет возможности платить любым другим способом.", - "donateDm": ">> если нет подходящей валюты, или же ты из россии, то напиши мне", - "clickToCopy": "нажми, чтобы скопировать", - "iosDownload": "так как у тебя устройство на ios, тебе нужно зажать кнопку \"скачать\" и выбрать что-то похожее на \"сохранить в галерею\" в появившемся окне.", - "normalDownload": "кнопка скачивания открывает новое окно с файлом. ты можешь отключить выбор метода сохранения файла в настройках.", - "download": "скачать", - "copy": "скопировать ссылку", - "github": ">> посмотреть предыдущие изменения на github" -} \ No newline at end of file diff --git a/src/i18n/ru/title.json b/src/i18n/ru/title.json deleted file mode 100644 index 9ced5ff..0000000 --- a/src/i18n/ru/title.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "about": "что за {appName}?", - "settings": "настройки", - "error": "о нет", - "changelog": "что нового?", - "donate": "поддержи {appName}", - "download": "скачивание", - "pickDownload": "как сохранить?" -} \ No newline at end of file diff --git a/src/localization/languages/en.json b/src/localization/languages/en.json new file mode 100644 index 0000000..10958ac --- /dev/null +++ b/src/localization/languages/en.json @@ -0,0 +1,76 @@ +{ + "name": "english", + "code": "en", + "substrings": { + "ContactLink": "let me know" + }, + "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 >> 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": ">> report issues and check out the source code on github", + "LinkGitHubChanges": ">> see previous changes and contribute on github", + "LinkDonateContact": ">> 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" + } +} \ No newline at end of file diff --git a/src/localization/languages/ru.json b/src/localization/languages/ru.json new file mode 100644 index 0000000..27e37f4 --- /dev/null +++ b/src/localization/languages/ru.json @@ -0,0 +1,76 @@ +{ + "name": "русский", + "code": "ru", + "substrings": { + "ContactLink": "напиши об этом" + }, + "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": "оставлять >> на экране", + "AccessibilityKeepDownloadButton": "оставлять кнопку скачивания на экране", + "SettingsEnableDownloadPopup": "спрашивать, как сохранять", + "AccessibilityEnableDownloadPopup": "спрашивать, что делать с загрузками", + "SettingsFormatDescription": "выбирай webm, если хочешь максимальное качество. webm обычно лучше по качеству, но устройства на ios не могут проигрывать их без сторонних приложений. все загрузки \"только аудио\" всегда максимального качества.", + "SettingsQualityDescription": "если выбранное разрешение недоступно, то выбирается ближайшее к нему. если ты хочешь твитнуть загруженное видео, то выбирай 720p. такие видео твиттер обычно воспринимает намного лучше.", + "DonateSubtitle": "сейчас намного сложнее оплачивать хостинг", + "DonateDescription": "я ненавижу крипто, но у меня нет возможности платить любым другим способом.", + "LinkGitHubIssues": ">> сообщай о проблемах и смотри исходный код на github", + "LinkGitHubChanges": ">> посмотреть предыдущие изменения на github", + "LinkDonateContact": ">> напиши мне, если в этом списке нет подходящей валюты", + "NoScriptMessage": "{appName} использует javascript для обработки ссылок и интерактивного интерфейса. ты должен разрешить использование javascript, чтобы пользоваться сайтом. тут нет никаких трекеров или рекламы, обещаю.", + "DownloadPopupDescriptionIOS": "так как у тебя устройство на ios, тебе нужно зажать кнопку \"скачать\" и выбрать что-то похожее на \"сохранить в галерею\" в появившемся окне.", + "DownloadPopupDescription": "кнопка скачивания открывает новое окно с файлом. ты можешь отключить выбор метода сохранения файла в настройках.", + "DownloadPopupWayToSave": "выбери, как сохранить", + "ClickToCopy": "нажми, чтобы скопировать", + "Download": "скачать", + "CopyURL": "скопировать ссылку" + } +} \ No newline at end of file diff --git a/src/localization/manager.js b/src/localization/manager.js new file mode 100644 index 0000000..95b502d --- /dev/null +++ b/src/localization/manager.js @@ -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, '
').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}!!` + } +} diff --git a/src/modules/api.js b/src/modules/api.js index 5584beb..056d7f7 100644 --- a/src/modules/api.js +++ b/src/modules/api.js @@ -4,7 +4,7 @@ import { services as patterns } from "./config.js"; import { cleanURL, apiJSON } from "./sub/utils.js"; import { errorUnsupported } from "./sub/errors.js"; -import loc from "./sub/i18n.js"; +import loc from "../localization/manager.js"; import match from "./match.js"; 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) } ) } } catch (e) { - return apiJSON(0, { t: loc(lang, 'apiError', 'generic') }); + return apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') }); } } \ No newline at end of file diff --git a/src/modules/config.js b/src/modules/config.js index cfc20c9..0cf9b81 100644 --- a/src/modules/config.js +++ b/src/modules/config.js @@ -2,7 +2,7 @@ import loadJson from "./sub/loadJSON.js"; const config = loadJson("./src/config.json"); export const -services = loadJson("./src/modules/services/all.json"), +services = loadJson("./src/modules/services/_config.json"), appName = config.appName, version = config.version, streamLifespan = config.streamLifespan, diff --git a/src/modules/match.js b/src/modules/match.js index 945fdf1..3df9149 100644 --- a/src/modules/match.js +++ b/src/modules/match.js @@ -25,7 +25,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit videoId: patternMatch["videoId"], 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() case "bilibili": 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); 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, isAudioOnly: fetchInfo["isAudioOnly"] ? fetchInfo["isAudioOnly"] : false, time: r.time, @@ -76,7 +76,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit title: patternMatch["title"], lang: lang, }); return (!r.error) ? apiJSON(r.typeId, { - type: r.type, u: r.urls, + type: r.type, u: r.urls, lang: lang, service: host, ip: ip, filename: r.filename, salt: process.env.streamSalt }) : apiJSON(0, { t: r.error }); diff --git a/src/modules/pageRender.js b/src/modules/pageRender.js index a8d09f3..342affe 100644 --- a/src/modules/pageRender.js +++ b/src/modules/pageRender.js @@ -1,6 +1,6 @@ import { services, appName, authorInfo, version, quality, repo, donations } from "./config.js"; import { getCommitInfo } from "./sub/currentCommit.js"; -import loc from "./sub/i18n.js"; +import loc from "../localization/manager.js"; let s = services let enabledServices = Object.keys(s).filter((p) => { @@ -34,10 +34,10 @@ export default function(obj) { - + - + @@ -50,127 +50,130 @@ export default function(obj) { - + - - + +