diff --git a/LICENSE b/LICENSE index ab7cd999..f79473af 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies @@ -7,17 +7,15 @@ Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to +our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and modification follow. @@ -72,7 +60,7 @@ modification follow. 0. Definitions. - "This License" refers to version 3 of the GNU General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single +under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General +Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published +GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's +versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. @@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found. Copyright (C) 2022 wukko This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by + it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - cobalt Copyright (C) 2022 wukko - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see +For more information on this, and how to apply and follow the GNU AGPL, see . - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/package.json b/package.json index b9c52126..dac84752 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 ae10d381..2fc2c0b6 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 528d3212..75120ce3 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 6cefa134..00000000 --- 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 99b0f7cf..00000000 --- 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 b40df8f3..00000000 --- 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 f487b87f..00000000 --- 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 6fb6cc46..00000000 --- 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 c5e913ba..00000000 --- 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 5bc82704..00000000 --- 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 f6805e26..00000000 --- a/src/i18n/ru/settings.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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 deleted file mode 100644 index 6e529ff2..00000000 --- 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 9ced5ff4..00000000 --- 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 00000000..10958ac2 --- /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 00000000..27e37f49 --- /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 00000000..95b502dd --- /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 5584beba..056d7f7e 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 cfc20c95..0cf9b811 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 0eb4ebc3..3df91496 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", urls: 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) { @@ -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, lang: lang, + type: "render", u: r.urls, lang: lang, service: host, ip: ip, filename: r.filename, salt: process.env.streamSalt, time: r.time @@ -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, urls: 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, @@ -75,8 +75,8 @@ export default async function (host, patternMatch, url, ip, lang, format, qualit id: patternMatch["id"], title: patternMatch["title"], lang: lang, }); - return (!r.error) ? apiJSON(2, { - type: "render", urls: r.urls, + return (!r.error) ? apiJSON(r.typeId, { + 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 158f785d..342affe7 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) { - + - - + +