From d08af58b11f1e201c189a981a36a1a34de8701ea Mon Sep 17 00:00:00 2001 From: wukko Date: Sun, 17 Jul 2022 18:58:51 +0600 Subject: [PATCH] it's all about you and your native language! MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - finally cleaned up localisation (now i18n) - made localisation strings easier to read and understand - removed static selected language in service modules - added support for russian language (привет-привет) - it's now extremely easy to add support for more languages. just copy en folder in i18n and start translating strings. pull requests for adding languages are more than welcome. --- README.md | 9 +++--- src/config.json | 2 +- src/i18n/en/apiError.json | 25 +++++++--------- src/i18n/en/settings.json | 5 ++-- src/i18n/en/{desc.json => strings.json} | 2 +- src/i18n/ru/accessibility.json | 11 +++++++ src/i18n/ru/apiError.json | 18 ++++++++++++ src/i18n/ru/settings.json | 22 ++++++++++++++ src/i18n/ru/strings.json | 18 ++++++++++++ src/i18n/ru/title.json | 9 ++++++ src/modules/api.js | 2 +- src/modules/match.js | 4 +-- src/modules/pageRender.js | 38 ++++++++++++------------- src/modules/services/bilibili.js | 8 +++--- src/modules/services/reddit.js | 4 +-- src/modules/services/twitter.js | 2 +- src/modules/services/vk.js | 10 +++---- src/modules/services/youtube.js | 6 ++-- src/modules/stream/types.js | 2 +- src/modules/sub/errors.js | 4 +-- 20 files changed, 139 insertions(+), 62 deletions(-) rename src/i18n/en/{desc.json => strings.json} (96%) create mode 100644 src/i18n/ru/accessibility.json create mode 100644 src/i18n/ru/apiError.json create mode 100644 src/i18n/ru/settings.json create mode 100644 src/i18n/ru/strings.json create mode 100644 src/i18n/ru/title.json diff --git a/README.md b/README.md index 51b38d3..7cb6fcc 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,11 @@ cobalt doesn't remux any videos, so you get videos of max quality available (unl ## What still has to be done - [ ] Quality switching for bilibili and Twitter -- [ ] Clean up the mess that localisation is right now - - [ ] Sort contents of .json files - - [ ] Rename each entry key to be less linked to specific service (entries like youtubeBroke are awful, I'm sorry) -- [ ] Add support for more languages when localisation clean up is done +- [ ] Language picker in settings +- [x] Clean up the mess that localisation is right now + - [x] Sort contents of .json files + - [x] Rename each entry key to be less linked to specific service (entries like youtubeBroke are awful, I'm sorry) +- [x] Add support for more languages when localisation clean up is done - [ ] Use esmbuild to minify frontend css and js - [ ] Make switch buttons in settings selectable with keyboard - [ ] Do something about changelog because the way it is right now is not really great diff --git a/src/config.json b/src/config.json index 9127278..528d321 100644 --- a/src/config.json +++ b/src/config.json @@ -5,7 +5,7 @@ "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"], + "supportedLanguages": ["en", "ru"], "authorInfo": { "name": "wukko", "link": "https://wukko.me/", diff --git a/src/i18n/en/apiError.json b/src/i18n/en/apiError.json index 9a1969d..99b0f7c 100644 --- a/src/i18n/en/apiError.json +++ b/src/i18n/en/apiError.json @@ -1,21 +1,18 @@ { - "generic": "something went wrong and i couldn't get the video. you can try again,", + "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.", - "noURL": "i can't guess what you want to download! please give me a link.", - "tryAgain": "\ncheck the link and try again.", - "letMeKnow": "but if issue persists, please let me know.", - "fatal": "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", + "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.", - "youtubeFetch": "couldn't fetch metadata. check if your link is correct and try again.", - "youtubeLimit": "current length limit is {s} minutes. what you tried to download was longer than that. pick something else to download!", - "youtubeBroke": "something went wrong with info fetching. you can try a different format and resoltuion or just try again later.", - "corruptedVideo": "oddly enough the requested video is corrupted on its origin server. youtube does this sometimes because it's a hot pile of mess.", - "corruptedAudio": "oddly enough the requested audio is corrupted on its origin server. youtube does this sometimes because it's a hot pile of mess.", + "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.", - "liveVideo": "i can't download a live video. wait for stream to finish and try again.", - "nothingToDownload": "it seems like there's nothing to download. try another link!", "cantConnectToAPI": "i couldn't connect to {s} api. seems like either {s} is down or {appName} server ip got blocked. try again later.", - "noStreamID": "there's no such stream id.", + "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 index 2b2e8da..b40df8f 100644 --- a/src/i18n/en/settings.json +++ b/src/i18n/en/settings.json @@ -16,6 +16,7 @@ "qmid": "medium\n", "qlow": "low\n", "qlos": "lowest", - "qualityDesc": "all resolutions listed here are max values. if there's no video of preferred quality, closest one gets picked instead.", - "extra": "extra" + "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/desc.json b/src/i18n/en/strings.json similarity index 96% rename from src/i18n/en/desc.json rename to src/i18n/en/strings.json index ea05092..f487b87 100644 --- a/src/i18n/en/desc.json +++ b/src/i18n/en/strings.json @@ -11,7 +11,7 @@ "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 video. you can disable this popup in settings.", + "normalDownload": "download button opens a new tab with requested file. you can disable this popup in settings.", "download": "download", "copy": "copy url", "open": "open", diff --git a/src/i18n/ru/accessibility.json b/src/i18n/ru/accessibility.json new file mode 100644 index 0000000..5534e13 --- /dev/null +++ b/src/i18n/ru/accessibility.json @@ -0,0 +1,11 @@ +{ + "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 new file mode 100644 index 0000000..de0f171 --- /dev/null +++ b/src/i18n/ru/apiError.json @@ -0,0 +1,18 @@ +{ + "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 new file mode 100644 index 0000000..55a30cf --- /dev/null +++ b/src/i18n/ru/settings.json @@ -0,0 +1,22 @@ +{ + "appearance": "внешний вид", + "alwaysVisibleButton": "оставлять >> на экране", + "downloadPopupButton": "спрашивать что делать с загрузками", + "format": "формат загрузок", + "formatInfo": "выбирай webm если хочешь максимальное качество. webm обычно лучше чем mp4 в плане качества, но устройства на 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 new file mode 100644 index 0000000..a75500b --- /dev/null +++ b/src/i18n/ru/strings.json @@ -0,0 +1,18 @@ +{ + "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 new file mode 100644 index 0000000..9ced5ff --- /dev/null +++ b/src/i18n/ru/title.json @@ -0,0 +1,9 @@ +{ + "about": "что за {appName}?", + "settings": "настройки", + "error": "о нет", + "changelog": "что нового?", + "donate": "поддержи {appName}", + "download": "скачивание", + "pickDownload": "как сохранить?" +} \ No newline at end of file diff --git a/src/modules/api.js b/src/modules/api.js index 7de3f61..5584beb 100644 --- a/src/modules/api.js +++ b/src/modules/api.js @@ -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') + loc(lang, 'apiError', 'letMeKnow') }); + return apiJSON(0, { t: loc(lang, 'apiError', 'generic') }); } } \ No newline at end of file diff --git a/src/modules/match.js b/src/modules/match.js index 2abcca3..0eb4ebc 100644 --- a/src/modules/match.js +++ b/src/modules/match.js @@ -34,7 +34,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit lang: lang }); return (!r.error) ? apiJSON(2, { - type: "render", urls: r.urls, + type: "render", urls: r.urls, lang: lang, service: host, ip: ip, filename: r.filename, salt: process.env.streamSalt, time: r.time @@ -73,7 +73,7 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit let r = await reddit({ sub: patternMatch["sub"], id: patternMatch["id"], - title: patternMatch["title"] + title: patternMatch["title"], lang: lang, }); return (!r.error) ? apiJSON(2, { type: "render", urls: r.urls, diff --git a/src/modules/pageRender.js b/src/modules/pageRender.js index 1ec3fc1..158f785 100644 --- a/src/modules/pageRender.js +++ b/src/modules/pageRender.js @@ -17,7 +17,7 @@ let enabledServices = Object.keys(s).filter((p) => { let donate = `` for (let i in donations) { - donate += `
${i} (${loc("en", 'desc', 'clickToCopy').trim()})
${donations[i]}
` + donate += `
${i} (REPLACEME)
${donations[i]}
` } let com = getCommitInfo(); @@ -34,10 +34,10 @@ export default function(obj) { - + - + @@ -50,7 +50,7 @@ export default function(obj) { - + @@ -180,7 +180,7 @@ export default function(obj) { @@ -197,6 +197,6 @@ export default function(obj) { `; } catch (err) { - return `${loc('en', 'apiError', 'fatal', obj.hash)}`; + return `${loc('en', 'apiError', 'noRender', obj.hash)}`; } } \ No newline at end of file diff --git a/src/modules/services/bilibili.js b/src/modules/services/bilibili.js index 65717d2..99ff35e 100644 --- a/src/modules/services/bilibili.js +++ b/src/modules/services/bilibili.js @@ -8,7 +8,7 @@ export default async function(obj) { headers: { "user-agent": genericUserAgent } }); html.on('error', (err) => { - return { error: loc('en', 'apiError', 'youtubeFetch') }; + return { error: loc(obj.lang, 'apiError', 'cantConnectToAPI', 'bilibili') }; }); html = html.body; if (html.includes('