Merge branch 'wukko:current' into current

This commit is contained in:
adrigoomy 2022-07-26 19:51:17 -04:00 committed by GitHub
commit 1deee82f74
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
34 changed files with 455 additions and 411 deletions

141
LICENSE
View file

@ -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. <https://fsf.org/>
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 <https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -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",

View file

@ -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
}))
}

View file

@ -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/",

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 обычно лучше, чем mp4 в плане качества, но устройства на 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 { 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') });
}
}

View file

@ -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,

View file

@ -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 });

View file

@ -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) {
<meta property="og:url" content="${process.env.selfURL}" />
<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 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="twitter:card" content="summary" />
@ -50,127 +50,130 @@ export default function(obj) {
<link rel="stylesheet" href="cobalt.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>
<body id="cobalt-body">
<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>
<body id="cobalt-body" data-nosnippet>
<div id="popup-about" class="popup center box" style="visibility: hidden;">
<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>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'about')}</div>
<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, 'TitlePopupAbout')}</div>
</div>
<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, 'strings', 'supportedServices')} ${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 about-padding">${loc(obj.lang, 'AboutSummary')}</div>
<div id="desc" class="popup-desc about-padding">${loc(obj.lang, 'AboutSupportedServices')} ${enabledServices}.</div>
<div id="desc" class="popup-desc bottom-link"><a class="text-backdrop" href="${repo}">${loc(obj.lang, 'LinkGitHubIssues')}</a></div>
</div>
<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 id="popup-changelog" class="popup center box" style="visibility: hidden;">
<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>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'changelog')}</div>
<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, 'TitlePopupChangelog')}</div>
<div id="desc" class="popup-subtitle">${com[0]} (${obj.hash})</div>
</div>
<div id="content" class="popup-content">
<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 id="popup-donate" class="popup scrollable center box" style="visibility: hidden;">
<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>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'donate')}</div>
<div id="desc" class="little-subtitle">${loc(obj.lang, 'strings', 'donationsSub')}</div>
<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, 'TitlePopupDonate')}</div>
<div id="desc" class="little-subtitle">${loc(obj.lang, 'DonateSubtitle')}</div>
</div>
<div id="content" class="popup-content">
${donate.replace(/REPLACEME/g, loc(obj.lang, 'strings', 'clickToCopy').trim())}
<div id="desc" class="explanation about-padding">${loc(obj.lang, 'strings', 'donations')}</div>
<div id="desc" class="popup-desc"><a class="text-backdrop" href="${authorInfo.contact}">${loc(obj.lang, 'strings', 'donateDm')}</a></div>
${donate.replace(/REPLACEME/g, loc(obj.lang, 'ClickToCopy').trim())}
<div id="desc" class="explanation about-padding">${loc(obj.lang, 'DonateDescription')}</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 id="popup-settings" class="popup scrollable center box" style="visibility: hidden;">
<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="title" class="popup-title">${loc(obj.lang, 'title', 'settings')}</div>
<div id="title" class="popup-title">${loc(obj.lang, 'TitlePopupSettings')}</div>
</div>
<div id="content" class="popup-content">
<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 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 id="theme-auto" class="switch full" onclick="changeSwitcher('theme', 'auto', 1)">${loc(obj.lang, 'settings', 'themeAuto')}</div>
<div id="theme-dark" class="switch" onclick="changeSwitcher('theme', 'dark', 1)">${loc(obj.lang, 'settings', 'themeDark')}</div>
<div id="theme-light" class="switch full" onclick="changeSwitcher('theme', 'light', 1)">${loc(obj.lang, 'settings', 'themeLight')}</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, 'SettingsThemeDark')}</div>
<div id="theme-light" class="switch full" onclick="changeSwitcher('theme', 'light', 1)">${loc(obj.lang, 'SettingsThemeLight')}</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 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 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 id="quality-max" class="switch full" onclick="changeSwitcher('quality', 'max', 1)">${loc(obj.lang, 'settings', 'qmax')}</div>
<div id="quality-hig" class="switch" onclick="changeSwitcher('quality', 'hig', 1)">${loc(obj.lang, 'settings', 'qhig')}(${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-low" class="switch right" onclick="changeSwitcher('quality', 'low', 1)">${loc(obj.lang, 'settings', 'qlow')}(${quality.low}p)</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, 'SettingsQualitySwitchHigh')}(${quality.hig}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, 'SettingsQualitySwitchLow')}(${quality.low}p)</div>
</div>
<div class="explanation">${loc(obj.lang, 'settings', 'qualityDesc')}</div>
<div class="explanation">${loc(obj.lang, 'SettingsQualityDescription')}</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 id="settings-youtube" class="settings-category">
<div class="title">youtube</div>
<div class="settings-category-content">
<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 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-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 class="explanation">${loc(obj.lang, 'settings', 'formatInfo')}</div>
<div class="explanation">${loc(obj.lang, 'SettingsFormatDescription')}</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 id="popup-error" class="popup center box" style="visibility: hidden;">
<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>
<div id="title" class="popup-title">${loc(obj.lang, 'title', 'error')}</div>
<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, 'TitlePopupError')}</div>
</div>
<div id="content" class="popup-content">
<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="logo-area">${appName}</div>
<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="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="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, 'AccessibilityDownloadButton')}">
</div>
</div>
<footer id="footer" style="visibility: hidden;">
<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="changelog-open" class="button footer-button" onclick="popup('changelog', 1)" aria-label="${loc(obj.lang, 'accessibility', 'changelog')}">!</button>
<button id="donate-open" class="button footer-button" onclick="popup('donate', 1)" aria-label="${loc(obj.lang, 'accessibility', 'donate')}">$</button>
<button id="settings-open" class="button footer-button" onclick="popup('settings', 1)" aria-label="${loc(obj.lang, 'accessibility', 'settings')}">+</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, 'AccessibilityOpenChangelog')}">!</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, 'AccessibilityOpenSettings')}">+</button>
</div>
</footer>
</body>
<script type="text/javascript">const loc = {noInternet:"${loc(obj.lang, 'apiError', 'noInternet')}"}</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>
</html>`;
} 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 loc from "../sub/i18n.js";
import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration } from "../config.js";
export default async function(obj) {
@ -8,7 +8,7 @@ export default async function(obj) {
headers: { "user-agent": genericUserAgent }
});
html.on('error', (err) => {
return { error: loc(obj.lang, 'apiError', 'cantConnectToAPI', 'bilibili') };
return { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI', 'bilibili') };
});
html = html.body;
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));
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 {
return { error: loc(obj.lang, 'apiError', 'lengthLimit', maxVideoDuration / 60000) };
return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
}
} else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') };
return { error: loc(obj.lang, 'ErrorEmptyDownload') };
}
} 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 loc from "../sub/i18n.js";
import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration } from "../config.js";
export default async function(obj) {
@ -7,11 +7,22 @@ export default async function(obj) {
let req = await got.get(`https://www.reddit.com/r/${obj.sub}/comments/${obj.id}/${obj.name}.json`, { headers: { "user-agent": genericUserAgent } });
let data = (JSON.parse(req.body))[0]["data"]["children"][0]["data"];
if ("reddit_video" in data["secure_media"] && data["secure_media"]["reddit_video"]["duration"] * 1000 < maxVideoDuration) {
return { urls: [data["secure_media"]["reddit_video"]["fallback_url"].split('?')[0], `${data["secure_media"]["reddit_video"]["fallback_url"].split('_')[0]}_audio.mp4`], filename: `reddit_${data["secure_media"]["reddit_video"]["fallback_url"].split('/')[3]}.mp4` };
let video = data["secure_media"]["reddit_video"]["fallback_url"].split('?')[0],
audio = video.match('.mp4') ? `${video.split('_')[0]}_audio.mp4` : `${data["secure_media"]["reddit_video"]["fallback_url"].split('DASH')[0]}audio`;
try {
await got.head(audio, { headers: { "user-agent": genericUserAgent } });
} catch (err) {
audio = ''
}
if (audio.length > 0) {
return { typeId: 2, type: "render", urls: [video, audio], filename: `reddit_${data["secure_media"]["reddit_video"]["fallback_url"].split('/')[3]}.mp4` };
} else {
return { typeId: 1, urls: video};
}
} else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') };
return { error: loc(obj.lang, 'ErrorEmptyDownload') };
}
} 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 loc from "../sub/i18n.js";
import loc from "../../localization/manager.js";
import { services } from "../config.js";
const configSt = services.twitter;
async function fetchTweetInfo(obj) {
let cantConnect = { error: loc('en', 'apiError', 'cantConnectToAPI', 'twitter') }
let cantConnect = { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI', 'twitter') }
try {
let _headers = {
"Authorization": `Bearer ${configSt.token}`,
@ -28,11 +28,11 @@ async function fetchTweetInfo(obj) {
})
return JSON.parse(req_status.body);
} catch (err) {
return { error: cantConnect };
return cantConnect;
}
}
export default async function (obj) {
let nothing = { error: loc('en', 'apiError', 'nothingToDownload') }
let nothing = { error: loc(obj.lang, 'ErrorEmptyDownload') }
try {
let parsbod = await fetchTweetInfo(obj);
if (!parsbod.error) {
@ -52,6 +52,6 @@ export default async function (obj) {
}
} else return parsbod;
} 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 { xml2json } from "xml-js";
import loc from "../sub/i18n.js";
import loc from "../../localization/manager.js";
import { genericUserAgent, maxVideoDuration, services } from "../config.js";
import selectQuality from "../stream/selectQuality.js";
@ -30,18 +30,18 @@ export default async function(obj) {
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` };
} else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') };
return { error: loc(obj.lang, 'ErrorEmptyDownload') };
}
} else {
return { error: loc(obj.lang, 'apiError', 'lengthLimit', maxVideoDuration / 60000) };
return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
}
} else {
return { error: loc(obj.lang, 'apiError', 'liveVideo') };
return { error: loc(obj.lang, 'ErrorLiveVideo') };
}
} else {
return { error: loc(obj.lang, 'apiError', 'nothingToDownload') };
return { error: loc(obj.lang, 'ErrorEmptyDownload') };
}
} 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 loc from "../sub/i18n.js";
import loc from "../../localization/manager.js";
import { maxVideoDuration, quality as mq } from "../config.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}` };
}
} else {
return { error: loc('en', 'apiError', 'errorFetch') };
return { error: loc(obj.lang, 'ErrorBadFetch') };
}
} else if (!obj.isAudioOnly) {
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) {
return { type: "render", isAudioOnly: true, urls: [audio[0]["url"]], filename: `youtube_${obj.id}_${audio[0]["audioBitrate"]}kbps.opus` };
} else {
return { error: loc('en', 'apiError', 'errorFetch') };
return { error: loc(obj.lang, 'ErrorBadFetch') };
}
} else {
return { error: loc('en', 'apiError', 'lengthLimit', maxVideoDuration / 60000) };
return { error: loc(obj.lang, 'ErrorLengthLimit', maxVideoDuration / 60000) };
}
} else {
return { error: loc('en', 'apiError', 'liveVideo') };
return { error: loc(obj.lang, 'ErrorLiveVideo') };
}
} else {
return { error: loc('en', 'apiError', 'youtubeFetch') };
return { error: loc(obj.lang, 'ErrorCantConnectToServiceAPI') };
}
} catch (e) {
return { error: loc('en', 'apiError', 'youtubeFetch') };
return { error: loc(obj.lang, 'ErrorBadFetch') };
}
}

View file

@ -15,13 +15,14 @@ export function createStream(obj) {
id: streamUUID,
service: obj.service,
type: obj.type,
urls: obj.urls,
urls: obj.u,
filename: obj.filename,
hmac: ghmac,
ip: iphmac,
exp: exp,
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}`;
}

View file

@ -4,7 +4,7 @@ import got from "got";
import { ffmpegArgs, genericUserAgent } from "../config.js";
import { msToTime } from "../sub/utils.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) {
try {
@ -42,7 +42,8 @@ export async function streamLiveRender(streamInfo, res) {
'-map', '1:a',
];
args = args.concat(ffmpegArgs[format])
args.push('-t', msToTime(streamInfo.time), '-f', format, 'pipe:5');
if (streamInfo.time) args.push('-t', msToTime(streamInfo.time));
args.push('-f', format, 'pipe:5');
const ffmpegProcess = spawn(ffmpeg, args, {
windowsHide: true,
stdio: [
@ -68,7 +69,7 @@ export async function streamLiveRender(streamInfo, res) {
ffmpegProcess.kill();
});
} 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) {
internalError(res);

View file

@ -1,11 +1,11 @@
import loc from "./i18n.js";
import loc from "../../localization/manager.js";
export function internalError(res) {
res.status(501).json({ status: "error", text: "Internal Server Error" });
}
export function errorUnsupported(lang) {
return loc(lang, 'apiError', 'notSupported');
return loc(lang, 'ErrorUnsupported');
}
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

@ -1,5 +1,4 @@
import { createStream } from "../stream/manage.js";
import { execSync } from "child_process";
export function apiJSON(type, obj) {
try {
@ -49,4 +48,7 @@ export function cleanURL(url, host) {
}
}
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 {
height: 80%;
}
.scrollable .bottom-link {
padding-bottom: 2rem;
}
.nowrap {
white-space: nowrap;
}
@ -321,6 +324,9 @@ input[type="checkbox"] {
border-bottom: 0.05rem solid var(--accent-unhover-2);
padding-bottom: 0.25rem;
}
.bottom-margin {
margin-bottom: 1rem;
}
.checkbox {
display: inline-flex;
align-items: center;
@ -331,7 +337,7 @@ input[type="checkbox"] {
padding-right: 1rem;
border: 0.1rem solid;
width: auto;
margin: 0 1rem 0 0;
margin: 0 0.5rem 0.5rem 0;
}
.checkbox-label {
line-height: 1.3rem;
@ -435,6 +441,9 @@ input[type="checkbox"] {
.popup {
height: 80%
}
.bottom-link {
padding-bottom: 2rem;
}
}
/* mobile page */
@media screen and (max-width: 949px) {
@ -459,6 +468,9 @@ input[type="checkbox"] {
height: 90%;
max-height: 100%;
}
.bottom-link {
padding-bottom: 2rem;
}
}
@media screen and (max-width: 524px) {
#logo-area {
@ -482,4 +494,7 @@ input[type="checkbox"] {
height: 90%;
max-height: 100%;
}
.bottom-link {
padding-bottom: 2rem;
}
}

View file

@ -141,37 +141,43 @@ async function download(url) {
fetch(`/api/json?quality=${localStorage.getItem("quality")}${format}&url=${encodeURIComponent(url)}`).then(async (response) => {
let j = await response.json();
if (j.status != "error" && j.status != "rate-limit") {
switch (j.status) {
case "redirect":
changeDownloadButton(2, '>>>')
setTimeout(() => {
changeDownloadButton(1, '>>')
eid("url-input-area").disabled = false
}, 3000)
if (localStorage.getItem("downloadPopup") == "true") {
popup('download', 1, j.url)
} else {
window.open(j.url, '_blank');
}
break;
case "stream":
changeDownloadButton(2, '?..')
fetch(`${j.url}&p=1&origin=front`).then(async (response) => {
let jp = await response.json();
if (jp.status == "continue") {
changeDownloadButton(2, '>>>')
window.location.href = j.url
setTimeout(() => {
changeDownloadButton(1, '>>')
eid("url-input-area").disabled = false
}, 5000)
} else {
if (j.url) {
switch (j.status) {
case "redirect":
changeDownloadButton(2, '>>>')
setTimeout(() => {
changeDownloadButton(1, '>>')
eid("url-input-area").disabled = false
changeDownloadButton(2, '!!')
popup("error", 1, jp.text);
}, 3000)
if (localStorage.getItem("downloadPopup") == "true") {
popup('download', 1, j.url)
} else {
window.open(j.url, '_blank');
}
}).catch((error) => internetError());
break;
break;
case "stream":
changeDownloadButton(2, '?..')
fetch(`${j.url}&p=1&origin=front`).then(async (response) => {
let jp = await response.json();
if (jp.status == "continue") {
changeDownloadButton(2, '>>>')
window.location.href = j.url
setTimeout(() => {
changeDownloadButton(1, '>>')
eid("url-input-area").disabled = false
}, 5000)
} else {
eid("url-input-area").disabled = false
changeDownloadButton(2, '!!')
popup("error", 1, jp.text);
}
}).catch((error) => internetError());
break;
}
} else {
eid("url-input-area").disabled = false
changeDownloadButton(2, '!!')
popup("error", 1, loc.noURLReturned);
}
} else {
eid("url-input-area").disabled = false