Merge remote-tracking branch 'upstream/main' into feat/threads

This commit is contained in:
Snazzah 2024-10-08 14:33:24 -05:00
commit acd04d18ae
No known key found for this signature in database
GPG Key ID: EA479766A94CEB61
438 changed files with 22086 additions and 8723 deletions

21
.dockerignore Normal file
View File

@ -0,0 +1,21 @@
# OS directory info files
.DS_Store
desktop.ini
# node
node_modules
# static build
build
# secrets
.env
.env.*
!.env.example
cookies.json
# docker
docker-compose.yml
# ide
.vscode

View File

@ -1,36 +0,0 @@
---
name: main instance bug report
about: report an issue with cobalt.tools or api.cobalt.tools
title: '[short description of the bug]'
labels: main instance issue
assignees: ''
---
### bug description
clear and concise description of what the issue is.
### reproduction steps
steps to reproduce the described behavior.
here's an example of what it could look like:
1. go to '...'
2. click on '....'
3. download [media type] from [service]
4. see error
### screenshots
if applicable, add screenshots or screen recordings to support your explanation.
if not, remove this section.
### links
if applicable, add links that cause the issue. more = better.
if not, remove this section.
### platform information
- OS [e.g. iOS, windows]
- browser [e.g. chrome, safari, firefox]
- version [e.g. 115]
### additional context
add any other context about the problem here if applicable.
if not, remove this section.

View File

@ -0,0 +1,47 @@
name: main instance bug report
description: "report an issue with cobalt.tools or api.cobalt.tools"
labels: ["main instance issue"]
body:
- type: textarea
id: bug-description
attributes:
label: bug description
description: "clear and concise description of what the issue is."
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: reproduction steps
description: steps to reproduce the described behavior.
placeholder: |
1. go to '...'
2. click on '....'
3. download [media type] from [service]
4. see error
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: screenshots
description: if applicable, add screenshots or screen recordings to support your explanation.
- type: textarea
id: links
attributes:
label: links
description: if applicable, add links that cause the issue. more = better.
render: shell
- type: input
id: platform
attributes:
label: platform information
description: "the operating system, browser and their versions where you encounter the issue"
placeholder: safari 7 on mac os x 10.8
validations:
required: true
- type: textarea
id: more-context
attributes:
label: additional context
description: add any other context about the problem here if applicable.

View File

@ -1,36 +0,0 @@
---
name: bug report
about: report a global issue with the cobalt codebase
title: '[short description of the bug]'
labels: bug
assignees: ''
---
### bug description
clear and concise description of what the issue is.
### reproduction steps
steps to reproduce the described behavior.
here's an example of what it could look like:
1. go to '...'
2. click on '....'
3. download [media type] from [service]
4. see error
### screenshots
if applicable, add screenshots or screen recordings to support your explanation.
if not, remove this section.
### links
if applicable, add links that cause the issue. more = better.
if not, remove this section.
### platform information
- OS [e.g. iOS, windows]
- browser [e.g. chrome, safari, firefox]
- version [e.g. 115]
### additional context
add any other context about the problem here if applicable.
if not, remove this section.

47
.github/ISSUE_TEMPLATE/bug-report.yml vendored Normal file
View File

@ -0,0 +1,47 @@
name: bug report
description: report a global issue with the cobalt codebase
labels: ["bug"]
body:
- type: textarea
id: bug-description
attributes:
label: bug description
description: "clear and concise description of what the issue is."
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: reproduction steps
description: steps to reproduce the described behavior.
placeholder: |
1. go to '...'
2. click on '....'
3. download [media type] from [service]
4. see error
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: screenshots
description: if applicable, add screenshots or screen recordings to support your explanation.
- type: textarea
id: links
attributes:
label: links
description: if applicable, add links that cause the issue. more = better.
render: shell
- type: input
id: platform
attributes:
label: platform information
description: "the operating system, browser and their versions where you encounter the issue"
placeholder: safari 7 on mac os x 10.8
validations:
required: true
- type: textarea
id: more-context
attributes:
label: additional context
description: add any other context about the problem here if applicable.

7
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,7 @@
blank_issues_enabled: false
contact_links:
- name: discord community
url: https://discord.gg/pQPt8HBUPu
about: |
ask questions and discuss cobalt with others at any time.
usually faster responses as more people are there to help.

View File

@ -1,15 +0,0 @@
---
name: feature request
about: suggest a feature for cobalt
title: '[short feature request description]'
labels: feature request
assignees: ''
---
### describe the feature you'd like to see
clear and concise description of the feature you want to see in cobalt.
### additional context
if applicable, add any other context or screenshots related to the feature request here.
if not, remove this section.

View File

@ -0,0 +1,22 @@
name: feature request
description: suggest a feature for cobalt
labels: ["feature request"]
body:
- type: markdown
attributes:
value: |
thanks for taking the time to make a feature request!
before you start, please make to read the "adding features or support for services" section of
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
- type: textarea
id: feat-description
attributes:
label: describe the feature you'd like to see
description: "clear and concise description of the feature you want to see in cobalt."
validations:
required: true
- type: textarea
id: more-context
attributes:
label: additional context
description: add any other context about the problem here if applicable.

View File

@ -1,12 +0,0 @@
---
name: instance hosting help
about: ask any question regarding cobalt instance hosting
title: '[short description of the problem]'
labels: instance hosting help
assignees: ''
---
### problem description
describe what issue you're having, clearly and concisely.
support your description with screenshots/links/etc when needed.

21
.github/ISSUE_TEMPLATE/hosting-help.yml vendored Normal file
View File

@ -0,0 +1,21 @@
name: instance hosting help
description: ask any question regarding cobalt instance hosting
labels: ["instance hosting help"]
body:
- type: textarea
id: problem-description
attributes:
label: problem description
description: |
describe what issue you're having, clearly and concisely.
support your description with screenshots/links/etc when needed.
validations:
required: true
- type: textarea
id: configuration
attributes:
label: your instance configuration
description: |
if applicable, add or describe your instance configuration (e.g. compose file) or any changes you made to it.
please **do not share senstive information** such as secret keys or the contents of your cookies file!
render: shell

View File

@ -1,18 +0,0 @@
---
name: service request
about: request service support in cobalt
title: 'add support for [service name]'
labels: service request
assignees: ''
---
### service name & description
provide the service name and brief description of what it is.
### link samples for the service you'd like cobalt to support
list of links that cobalt should recognize.
could be regular video link, shared video link, mobile video link, shortened link, etc.
### additional context
any additional context or screenshots should go here. if there aren't any, just remove this part.

View File

@ -0,0 +1,39 @@
name: service request
description: "request service support in cobalt"
title: "add support for [service name]"
labels: ["service request"]
body:
- type: markdown
attributes:
value: |
thanks for taking the time to make a service request!
before you start, please make to read the "adding features or support for services" section of
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
- type: input
id: service-name
attributes:
label: service name
validations:
required: true
- type: textarea
id: service-description
attributes:
label: service description
description: a brief description of what the service is and/or what it provides
validations:
required: true
- type: textarea
id: link-samples
attributes:
label: link samples
description: |
list of links that cobalt should recognize.
could be regular video link, shared video link, mobile video link, shortened link, etc.
render: shell
validations:
required: true
- type: textarea
id: more-context
attributes:
label: additional context
description: any additional context or screenshots should go here.

38
.github/test.sh vendored
View File

@ -13,19 +13,20 @@ waitport() {
test_api() {
waitport 3000
curl -m 3 http://localhost:3000/api/serverInfo
API_RESPONSE=$(curl -m 3 http://localhost:3000/api/json \
curl -m 3 http://localhost:3000/
API_RESPONSE=$(curl -m 10 http://localhost:3000/ \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{"url":"https://vine.co/v/huwVJIEJW50", "isAudioOnly": true}')
-d '{"url":"https://www.tiktok.com/@fatfatmillycat/video/7195741644585454894"}')
echo "$API_RESPONSE"
echo "API_RESPONSE=$API_RESPONSE"
STATUS=$(echo "$API_RESPONSE" | jq -r .status)
STREAM_URL=$(echo "$API_RESPONSE" | jq -r .url)
[ "$STATUS" = stream ] || exit 1;
[ "$STATUS" = tunnel ] || exit 1;
S=$(curl -I -m 10 "$STREAM_URL")
CONTENT_LENGTH=$(curl -I -m 3 "$STREAM_URL" \
CONTENT_LENGTH=$(echo "$S" \
| grep -i content-length \
| cut -d' ' -f2 \
| tr -d '\r')
@ -37,37 +38,30 @@ test_api() {
fi
}
test_web() {
waitport 3001
curl -m 3 http://127.0.0.1:3001/onDemand?blockId=0 \
| grep -q '"status":"success"'
}
setup_api() {
export API_PORT=3000
export API_URL=http://localhost:3000
timeout 10 npm run start
timeout 10 pnpm run --prefix api start &
API_PID=$!
}
setup_web() {
export WEB_PORT=3001
export WEB_URL=http://localhost:3001
export API_URL=http://localhost:3000
timeout 5 npm run start
pnpm run --prefix web build
}
cd "$(git rev-parse --show-toplevel)"
npm i
pnpm install --frozen-lockfile
if [ "$1" = "api" ]; then
setup_api &
setup_api
test_api
[ "$API_PID" != "" ] \
&& kill "$API_PID"
elif [ "$1" = "web" ]; then
setup_web &
test_web
setup_web
else
echo "usage: $0 <api/web>" >&2
exit 1
fi
wait || exit $?
wait || exit $?

View File

@ -32,7 +32,7 @@ jobs:
- name: Get release metadata
id: release-meta
run: |
version=$(cat package.json | jq -r .version)
version=$(cat api/package.json | jq -r .version)
echo "commit_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
echo "version=$version" >> $GITHUB_OUTPUT
echo "major_version=$(echo "$version" | cut -d. -f1)" >> $GITHUB_OUTPUT

33
.github/workflows/test-services.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Run service tests
on:
pull_request:
push:
paths:
- api/**
- packages/**
jobs:
check-services:
name: test service functionality
runs-on: ubuntu-latest
outputs:
services: ${{ steps.checkServices.outputs.service_list }}
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- id: checkServices
run: pnpm i --frozen-lockfile && echo "service_list=$(node api/src/util/test-ci get-services)" >> "$GITHUB_OUTPUT"
test-services:
needs: check-services
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: ${{ fromJson(needs.check-services.outputs.services) }}
name: "test service: ${{ matrix.service }}"
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- run: pnpm i --frozen-lockfile && node api/src/util/test-ci run-tests-for ${{ matrix.service }}

View File

@ -3,60 +3,32 @@ name: Run tests
on:
pull_request:
push:
branches: [ current ]
jobs:
check-lockfile:
name: check lockfile correctness
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- name: Check that lockfile does not need an update
run: |
cp package-lock.json before.json
npm ci
npm i --package-lock-only
diff before.json package-lock.json
run: pnpm install --frozen-lockfile
test-web:
name: web sanity check
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run test script
run: .github/test.sh web
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 'lts/*'
- uses: pnpm/action-setup@v4
- run: .github/test.sh web
test-api:
name: api sanity check
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run test script
run: .github/test.sh api
check-services:
name: test service functionality
runs-on: ubuntu-latest
outputs:
services: ${{ steps.checkServices.outputs.service_list }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- id: checkServices
run: npm ci && echo "service_list=$(node src/util/test-ci get-services)" >> "$GITHUB_OUTPUT"
test-services:
needs: check-services
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: ${{ fromJson(needs.check-services.outputs.services) }}
name: "test service: ${{ matrix.service }}"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- run: npm ci && node src/util/test-ci run-tests-for ${{ matrix.service }}
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- run: .github/test.sh api

19
.gitignore vendored
View File

@ -1,21 +1,22 @@
# os stuff
# OS directory info files
.DS_Store
desktop.ini
# npm
# node
node_modules
# static build
build
# secrets
.env
.env.*
!.env.example
cookies.json
keys.json
# docker
docker-compose.yml
# vscode
# ide
.vscode
# cookie file
cookies.json
# page build
build

View File

@ -1,15 +1,25 @@
FROM node:18-bullseye-slim
FROM node:20-bullseye-slim AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
FROM base AS build
WORKDIR /app
COPY . /app
RUN corepack enable
RUN apt-get update && \
apt-get install -y python3 build-essential
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
pnpm install --prod --frozen-lockfile
RUN pnpm deploy --filter=@imput/cobalt-api --prod /prod/api
FROM base AS api
WORKDIR /app
COPY package*.json ./
COPY --from=build /prod/api /app
COPY --from=build /app/.git /app/.git
RUN apt-get update && \
apt-get install -y git python3 build-essential && \
npm ci && \
npm cache clean --force && \
apt purge --autoremove -y python3 build-essential && \
rm -rf ~/.cache/ /var/lib/apt/lists/*
COPY . .
EXPOSE 9000
CMD [ "node", "src/cobalt" ]
CMD [ "node", "src/cobalt" ]

124
README.md
View File

@ -1,42 +1,57 @@
# cobalt
best way to save what you love: [cobalt.tools](https://cobalt.tools/)
<div align="center">
<br/>
<p>
<img src="web/static/favicon.png" title="cobalt" alt="cobalt logo" width="100" />
</p>
<p>
best way to save what you love
<br/>
<a href="https://cobalt.tools">
cobalt.tools
</a>
</p>
<p>
<a href="https://discord.gg/pQPt8HBUPu">
💬 community discord server
</a>
<a href="https://x.com/justusecobalt">
🐦 twitter/x
</a>
</p>
<br/>
</div>
![cobalt logo with repeated logo (double arrow) pattern background](/src/front/icons/pattern.png "cobalt logo with repeated logo (double arrow) pattern background")
[💬 community discord server](https://discord.gg/pQPt8HBUPu)
[🐦 twitter/x](https://x.com/justusecobalt)
## what's cobalt?
cobalt is a media downloader that doesn't piss you off. it's fast, friendly, and doesn't have any bullshit that modern web is filled with: ***no ads, trackers, or invasive analytics***.
cobalt is a media downloader that doesn't piss you off. it's fast, friendly, and doesn't have any bullshit that modern web is filled with: ***no ads, trackers, or paywalls***.
paste the link, get the file, move on. it's that simple. just how it should be.
## supported services
### supported services
this list is not final and keeps expanding over time. if support for a service you want is missing, create an issue (or a pull request 👀).
| service | video + audio | only audio | only video | metadata | rich file names |
| :-------- | :-----------: | :--------: | :--------: | :------: | :-------------: |
| bilibili.com & bilibili.tv | ✅ | ✅ | ✅ | | |
| dailymotion | ✅ | ✅ | ✅ | ✅ | ✅ |
| instagram posts & reels | ✅ | ✅ | ✅ | | |
| facebook videos | ✅ | ❌ | ❌ | | |
| loom | ✅ | ❌ | ✅ | ✅ | |
| ok video | ✅ | ❌ | ✅ | ✅ | ✅ |
| pinterest | ✅ | ✅ | ✅ | | |
| reddit | ✅ | ✅ | ✅ | ❌ | ❌ |
| rutube | ✅ | ✅ | ✅ | ✅ | ✅ |
| snapchat stories & spotlights | ✅ | ✅ | ✅ | | |
| soundcloud | | ✅ | | ✅ | ✅ |
| streamable | ✅ | ✅ | ✅ | | |
| threads posts | ✅ | ✅ | ✅ | | |
| tiktok | ✅ | ✅ | ✅ | ❌ | ❌ |
| tumblr | ✅ | ✅ | ✅ | | |
| twitch clips | ✅ | ✅ | ✅ | ✅ | ✅ |
| twitter/x | ✅ | ✅ | ✅ | | |
| vimeo | ✅ | ✅ | ✅ | ✅ | ✅ |
| vine archive | ✅ | ✅ | ✅ | | |
| vk videos & clips | ✅ | ❌ | ✅ | ✅ | ✅ |
| youtube videos, shorts & music | ✅ | ✅ | ✅ | ✅ | ✅ |
| service | video + audio | only audio | only video | metadata | rich file names |
| :-------- | :-----------: | :--------: | :--------: | :------: | :-------------: |
| bilibili | ✅ | ✅ | ✅ | | |
| bluesky | ✅ | ✅ | ✅ | | |
| dailymotion | ✅ | ✅ | ✅ | ✅ | ✅ |
| instagram | ✅ | ✅ | ✅ | | |
| facebook | ✅ | ❌ | ✅ | | |
| loom | ✅ | ❌ | ✅ | ✅ | |
| ok.ru | ✅ | ❌ | ✅ | ✅ | ✅ |
| pinterest | ✅ | ✅ | ✅ | | |
| reddit | ✅ | ✅ | ✅ | ❌ | ❌ |
| rutube | ✅ | ✅ | ✅ | ✅ | ✅ |
| snapchat | ✅ | ✅ | ✅ | | |
| soundcloud | | ✅ | | ✅ | ✅ |
| streamable | ✅ | ✅ | ✅ | | |
| threads posts | ✅ | ✅ | ✅ | | |
| tiktok | ✅ | ✅ | ✅ | ❌ | ❌ |
| tumblr | ✅ | ✅ | ✅ | | |
| twitch clips | ✅ | ✅ | ✅ | ✅ | ✅ |
| twitter/x | ✅ | ✅ | ✅ | | |
| vimeo | ✅ | ✅ | ✅ | ✅ | ✅ |
| vine | ✅ | ✅ | ✅ | | |
| vk videos & clips | ✅ | ❌ | ✅ | ✅ | ✅ |
| youtube | ✅ | ✅ | ✅ | ✅ | ✅ |
| emoji | meaning |
| :-----: | :---------------------- |
@ -60,46 +75,17 @@ this list is not final and keeps expanding over time. if support for a service y
| vimeo | audio downloads are only available for dash. |
| youtube | supports videos, music, and shorts. 8K, 4K, HDR, VR, and high FPS videos. rich metadata & dubs. h264/av1/vp9 codecs. |
## cobalt api
cobalt has an open api that you can use in your projects *for free~*. it's easy and straightforward to use, [check out the docs](/docs/api.md) to learn how to use it.
### partners
cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt), all main instances are currently hosted on their network :)
✅ you can use the main api instance ([api.cobalt.tools](https://api.cobalt.tools/)) in your **personal** projects.
❌ you cannot use the free api commercially (anywhere that's gated behind paywalls or ads). host your own instance for this.
we reserve the right to restrict abusive/excessive access to the main instance api.
## how to run your own instance
if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
it's *highly* recommended to use a docker compose method unless you run for developing/debugging purposes.
## partners
cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt), all main instances are currently hosted on their network :)
## ethics and disclaimer
### ethics and disclaimer
cobalt is a tool for easing content downloads from internet and takes ***zero liability***. you are responsible for what you download, how you use and distribute that content. please be mindful when using content of others and always credit original creators. fair use and credits benefit everyone.
cobalt is ***NOT*** a piracy tool and cannot be used as such. it can only download free, publicly accessible content. such content can be easily downloaded through any browser's dev tools. pressing one button is easier, so i made a convenient, ad-less tool for such repeated actions.
## cobalt license
cobalt code is licensed under [AGPL-3.0](/LICENSE).
cobalt branding, mascots, and other related assets included in the repo are ***copyrighted*** and not covered by the AGPL-3.0 license. you ***cannot*** use them under same terms.
you are allowed to host an ***unmodified*** instance of cobalt with branding, but this ***does not*** give you permission to use it anywhere else, or make derivatives of it in any way.
### notes:
- mascots and other assets are a part of the branding.
- when making an alternative version of the project, please replace or remove all branding (including the name).
- you **must** link the original repo when using any parts of code (such as using separate processing modules in your project) or forking the project.
- if you make a modified version of cobalt, the codebase **must** be published under the same license (according to AGPL-3.0).
## 3rd party licenses
- [Fluent Emoji by Microsoft](https://github.com/microsoft/fluentui-emoji) (used in cobalt) is under [MIT](https://github.com/microsoft/fluentui-emoji/blob/main/LICENSE) license.
- [Noto Sans Mono](https://fonts.google.com/noto/specimen/Noto+Sans+Mono/) fonts (used in cobalt) are licensed under the [OFL](https://fonts.google.com/noto/specimen/Noto+Sans+Mono/about) license.
- many update banners were taken from [tenor.com](https://tenor.com/).
### cobalt license
for relevant licensing information, see the [api](api/README.md) and [web](web/README.md) READMEs.
unless specified otherwise, the remainder of this repository is licensed under [AGPL-3.0](LICENSE).
## acknowledgements
### ffmpeg
@ -113,7 +99,7 @@ we use [ffmpeg-static](https://github.com/eugeneware/ffmpeg-static) to get binar
you can support the developer via various methods listed on their github page! (linked above)
### youtube.js
cobalt relies on [youtube.js](https://github.com/LuanRT/YouTube.js) for interacting with the innertube api, it wouldn't have been possible without it.
cobalt relies on [youtube.js](https://github.com/LuanRT/YouTube.js) for interacting with the innertube api, it wouldn't have been possible without it.
you can support the developer via various methods listed on their github page! (linked above)

661
api/LICENSE Normal file
View File

@ -0,0 +1,661 @@
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
of this license document, but changing it is not allowed.
Preamble
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,
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.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
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.
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.
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.
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.
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.
TERMS AND CONDITIONS
0. Definitions.
"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.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
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. 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 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 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 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 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 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 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.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
save what you love with cobalt.
Copyright (C) 2024 imput
This program is free software: you can redistribute it and/or modify
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 Affero General Public License for more details.
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 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 AGPL, see
<https://www.gnu.org/licenses/>.

22
api/README.md Normal file
View File

@ -0,0 +1,22 @@
# cobalt api
## license
cobalt api code is licensed under [AGPL-3.0](LICENSE).
this license allows you to modify, distribute and use the code for any purpose
as long as you:
- give appropriate credit to the original repo when using or modifying any parts of the code,
- provide a link to the license and indicate if changes to the code were made, and
- release the code under the **same license**
## running your own instance
if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
it's *highly* recommended to use a docker compose method unless you run for developing/debugging purposes.
## accessing the api
currently, there is no publicly accessible main api. we plan on providing a public api for
cobalt 10 in some form in the future. we recommend deploying your own instance if you wish
to use the latest api. you can access [the documentation](/docs/api.md) for it here.
if you are looking for the documentation for the old (7.x) api, you can find
it [here](https://github.com/imputnet/cobalt/blob/7/docs/api.md)

49
api/package.json Normal file
View File

@ -0,0 +1,49 @@
{
"name": "@imput/cobalt-api",
"description": "save what you love",
"version": "10.1.0",
"author": "imput",
"exports": "./src/cobalt.js",
"type": "module",
"engines": {
"node": ">=18"
},
"scripts": {
"start": "node src/cobalt",
"setup": "node src/util/setup",
"test": "node src/util/test",
"token:youtube": "node src/util/generate-youtube-tokens"
},
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme",
"dependencies": {
"@imput/version-info": "workspace:^",
"content-disposition-header": "0.6.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"esbuild": "^0.14.51",
"express": "^4.21.0",
"express-rate-limit": "^6.3.0",
"ffmpeg-static": "^5.1.0",
"hls-parser": "^0.10.7",
"ipaddr.js": "2.2.0",
"nanoid": "^4.0.2",
"node-cache": "^5.1.2",
"psl": "1.9.0",
"set-cookie-parser": "2.6.0",
"undici": "^5.19.1",
"url-pattern": "1.0.3",
"youtubei.js": "^10.5.0",
"zod": "^3.23.8"
},
"optionalDependencies": {
"freebind": "^0.2.2"
}
}

27
api/src/cobalt.js Normal file
View File

@ -0,0 +1,27 @@
import "dotenv/config";
import express from "express";
import path from 'path';
import { fileURLToPath } from 'url';
import { env } from "./config.js"
import { Bright, Green, Red } from "./misc/console-text.js";
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4);
app.disable('x-powered-by');
if (env.apiURL) {
const { runAPI } = await import('./core/api.js');
runAPI(express, app, __dirname)
} else {
console.log(
Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
+ Bright(`please run the setup script to fix this: `)
+ Green(`npm run setup`)
)
}

61
api/src/config.js Normal file
View File

@ -0,0 +1,61 @@
import { getVersion } from "@imput/version-info";
import { services } from "./processing/service-config.js";
const version = await getVersion();
const disabledServices = process.env.DISABLED_SERVICES?.split(',') || [];
const enabledServices = new Set(Object.keys(services).filter(e => {
if (!disabledServices.includes(e)) {
return e;
}
}));
const env = {
apiURL: process.env.API_URL || '',
apiPort: process.env.API_PORT || 9000,
listenAddress: process.env.API_LISTEN_ADDRESS,
freebindCIDR: process.platform === 'linux' && process.env.FREEBIND_CIDR,
corsWildcard: process.env.CORS_WILDCARD !== '0',
corsURL: process.env.CORS_URL,
cookiePath: process.env.COOKIE_PATH,
rateLimitWindow: (process.env.RATELIMIT_WINDOW && parseInt(process.env.RATELIMIT_WINDOW)) || 60,
rateLimitMax: (process.env.RATELIMIT_MAX && parseInt(process.env.RATELIMIT_MAX)) || 20,
durationLimit: (process.env.DURATION_LIMIT && parseInt(process.env.DURATION_LIMIT)) || 10800,
streamLifespan: (process.env.TUNNEL_LIFESPAN && parseInt(process.env.TUNNEL_LIFESPAN)) || 90,
processingPriority: process.platform !== 'win32'
&& process.env.PROCESSING_PRIORITY
&& parseInt(process.env.PROCESSING_PRIORITY),
externalProxy: process.env.API_EXTERNAL_PROXY,
turnstileSitekey: process.env.TURNSTILE_SITEKEY,
turnstileSecret: process.env.TURNSTILE_SECRET,
jwtSecret: process.env.JWT_SECRET,
jwtLifetime: process.env.JWT_EXPIRY || 120,
sessionEnabled: process.env.TURNSTILE_SITEKEY
&& process.env.TURNSTILE_SECRET
&& process.env.JWT_SECRET,
apiKeyURL: process.env.API_KEY_URL && new URL(process.env.API_KEY_URL),
authRequired: process.env.API_AUTH_REQUIRED === '1',
keyReloadInterval: 900,
enabledServices,
}
const genericUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36";
const cobaltUserAgent = `cobalt/${version} (+https://github.com/imputnet/cobalt)`;
export {
env,
genericUserAgent,
cobaltUserAgent,
}

366
api/src/core/api.js Normal file
View File

@ -0,0 +1,366 @@
import cors from "cors";
import rateLimit from "express-rate-limit";
import { setGlobalDispatcher, ProxyAgent } from "undici";
import { getCommit, getBranch, getRemote, getVersion } from "@imput/version-info";
import jwt from "../security/jwt.js";
import stream from "../stream/stream.js";
import match from "../processing/match.js";
import { env } from "../config.js";
import { extract } from "../processing/url.js";
import { languageCode } from "../misc/utils.js";
import { Bright, Cyan } from "../misc/console-text.js";
import { generateHmac, generateSalt } from "../misc/crypto.js";
import { randomizeCiphers } from "../misc/randomize-ciphers.js";
import { verifyTurnstileToken } from "../security/turnstile.js";
import { friendlyServiceName } from "../processing/service-alias.js";
import { verifyStream, getInternalStream } from "../stream/manage.js";
import { createResponse, normalizeRequest, getIP } from "../processing/request.js";
import * as APIKeys from "../security/api-keys.js";
const git = {
branch: await getBranch(),
commit: await getCommit(),
remote: await getRemote(),
}
const version = await getVersion();
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
const ipSalt = generateSalt();
const corsConfig = env.corsWildcard ? {} : {
origin: env.corsURL,
optionsSuccessStatus: 200
}
const fail = (res, code, context) => {
const { status, body } = createResponse("error", { code, context });
res.status(status).json(body);
}
export const runAPI = (express, app, __dirname) => {
const startTime = new Date();
const startTimestamp = startTime.getTime();
const serverInfo = JSON.stringify({
cobalt: {
version: version,
url: env.apiURL,
startTime: `${startTimestamp}`,
durationLimit: env.durationLimit,
turnstileSitekey: env.sessionEnabled ? env.turnstileSitekey : undefined,
services: [...env.enabledServices].map(e => {
return friendlyServiceName(e);
}),
},
git,
})
const handleRateExceeded = (_, res) => {
const { status, body } = createResponse("error", {
code: "error.api.rate_exceeded",
context: {
limit: env.rateLimitWindow
}
});
return res.status(status).json(body);
};
const sessionLimiter = rateLimit({
windowMs: 60000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: handleRateExceeded
});
const apiLimiter = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: (req) => req.rateLimitMax || env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => req.rateLimitKey || generateHmac(getIP(req), ipSalt),
handler: handleRateExceeded
})
const apiTunnelLimiter = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: (req) => req.rateLimitMax || env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => req.rateLimitKey || generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.sendStatus(429)
}
})
app.set('trust proxy', ['loopback', 'uniquelocal']);
app.use('/', cors({
methods: ['GET', 'POST'],
exposedHeaders: [
'Ratelimit-Limit',
'Ratelimit-Policy',
'Ratelimit-Remaining',
'Ratelimit-Reset'
],
...corsConfig,
}));
app.post('/', (req, res, next) => {
if (!acceptRegex.test(req.header('Accept'))) {
return fail(res, "error.api.header.accept");
}
if (!acceptRegex.test(req.header('Content-Type'))) {
return fail(res, "error.api.header.content_type");
}
next();
});
app.post('/', (req, res, next) => {
if (!env.apiKeyURL) {
return next();
}
const { success, error } = APIKeys.validateAuthorization(req);
if (!success) {
// We call next() here if either if:
// a) we have user sessions enabled, meaning the request
// will still need a Bearer token to not be rejected, or
// b) we do not require the user to be authenticated, and
// so they can just make the request with the regular
// rate limit configuration;
// otherwise, we reject the request.
if (
(env.sessionEnabled || !env.authRequired)
&& ['missing', 'not_api_key'].includes(error)
) {
return next();
}
return fail(res, `error.api.auth.key.${error}`);
}
return next();
});
app.post('/', (req, res, next) => {
if (!env.sessionEnabled || req.rateLimitKey) {
return next();
}
try {
const authorization = req.header("Authorization");
if (!authorization) {
return fail(res, "error.api.auth.jwt.missing");
}
if (!authorization.startsWith("Bearer ") || authorization.length > 256) {
return fail(res, "error.api.auth.jwt.invalid");
}
const verifyJwt = jwt.verify(
authorization.split("Bearer ", 2)[1]
);
if (!verifyJwt) {
return fail(res, "error.api.auth.jwt.invalid");
}
req.rateLimitKey = generateHmac(req.header("Authorization"), ipSalt);
} catch {
return fail(res, "error.api.generic");
}
next();
});
app.post('/', apiLimiter);
app.use('/', express.json({ limit: 1024 }));
app.use('/', (err, _, res, next) => {
if (err) {
const { status, body } = createResponse("error", {
code: "error.api.invalid_body",
});
return res.status(status).json(body);
}
next();
});
app.post("/session", sessionLimiter, async (req, res) => {
if (!env.sessionEnabled) {
return fail(res, "error.api.auth.not_configured")
}
const turnstileResponse = req.header("cf-turnstile-response");
if (!turnstileResponse) {
return fail(res, "error.api.auth.turnstile.missing");
}
const turnstileResult = await verifyTurnstileToken(
turnstileResponse,
req.ip
);
if (!turnstileResult) {
return fail(res, "error.api.auth.turnstile.invalid");
}
try {
res.json(jwt.generate());
} catch {
return fail(res, "error.api.generic");
}
});
app.post('/', async (req, res) => {
const request = req.body;
const lang = languageCode(req);
if (!request.url) {
return fail(res, "error.api.link.missing");
}
if (request.youtubeDubBrowserLang) {
request.youtubeDubLang = lang;
}
const { success, data: normalizedRequest } = await normalizeRequest(request);
if (!success) {
return fail(res, "error.api.invalid_body");
}
const parsed = extract(normalizedRequest.url);
if (!parsed) {
return fail(res, "error.api.link.invalid");
}
if ("error" in parsed) {
let context;
if (parsed?.context) {
context = parsed.context;
}
return fail(res, `error.api.${parsed.error}`, context);
}
try {
const result = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: normalizedRequest,
});
res.status(result.status).json(result.body);
} catch {
fail(res, "error.api.generic");
}
})
app.get('/tunnel', apiTunnelLimiter, (req, res) => {
const id = String(req.query.id);
const exp = String(req.query.exp);
const sig = String(req.query.sig);
const sec = String(req.query.sec);
const iv = String(req.query.iv);
const checkQueries = id && exp && sig && sec && iv;
const checkBaseLength = id.length === 21 && exp.length === 13;
const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
if (!checkQueries || !checkBaseLength || !checkSafeLength) {
return res.status(400).end();
}
if (req.query.p) {
return res.status(200).end();
}
const streamInfo = verifyStream(id, sig, exp, sec, iv);
if (!streamInfo?.service) {
return res.status(streamInfo.status).end();
}
if (streamInfo.type === 'proxy') {
streamInfo.range = req.headers['range'];
}
return stream(res, streamInfo);
})
app.get('/itunnel', (req, res) => {
if (!req.ip.endsWith('127.0.0.1')) {
return res.sendStatus(403);
}
if (String(req.query.id).length !== 21) {
return res.sendStatus(400);
}
const streamInfo = getInternalStream(req.query.id);
if (!streamInfo) {
return res.sendStatus(404);
}
streamInfo.headers = new Map([
...(streamInfo.headers || []),
...Object.entries(req.headers)
]);
return stream(res, { type: 'internal', ...streamInfo });
})
app.get('/', (_, res) => {
res.type('json');
res.status(200).send(serverInfo);
})
app.get('/favicon.ico', (req, res) => {
res.status(404).end();
})
app.get('/*', (req, res) => {
res.redirect('/');
})
// handle all express errors
app.use((_, __, res, ___) => {
return fail(res, "error.api.generic");
})
randomizeCiphers();
setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
if (env.externalProxy) {
if (env.freebindCIDR) {
throw new Error('Freebind is not available when external proxy is enabled')
}
setGlobalDispatcher(new ProxyAgent(env.externalProxy))
}
if (env.apiKeyURL) {
APIKeys.setup(env.apiKeyURL);
}
app.listen(env.apiPort, env.listenAddress, () => {
console.log(`\n` +
Bright(Cyan("cobalt ")) + Bright("API ^ω⁠^") + "\n" +
"~~~~~~\n" +
Bright("version: ") + version + "\n" +
Bright("commit: ") + git.commit + "\n" +
Bright("branch: ") + git.branch + "\n" +
Bright("remote: ") + git.remote + "\n" +
Bright("start time: ") + startTime.toUTCString() + "\n" +
"~~~~~~\n" +
Bright("url: ") + Bright(Cyan(env.apiURL)) + "\n" +
Bright("port: ") + env.apiPort + "\n"
)
})
}

View File

@ -5,12 +5,19 @@ function t(color, tt) {
export function Bright(tt) {
return t("\x1b[1m", tt)
}
export function Red(tt) {
return t("\x1b[31m", tt)
}
export function Green(tt) {
return t("\x1b[32m", tt)
}
export function Cyan(tt) {
return t("\x1b[36m", tt)
}
export function Yellow(tt) {
return t("\x1b[93m", tt)
}

View File

@ -0,0 +1,20 @@
import * as fs from "fs";
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(
dirname(fileURLToPath(import.meta.url)),
'../../'
);
export function loadFile(path) {
return fs.readFileSync(join(root, path), 'utf-8')
}
export function loadJSON(path) {
try {
return JSON.parse(loadFile(path))
} catch {
return false
}
}

View File

@ -1,10 +1,10 @@
import { normalizeRequest } from "../modules/processing/request.js";
import match from "./processing/match.js";
import { extract } from "./processing/url.js";
import { normalizeRequest } from "../processing/request.js";
import match from "../processing/match.js";
import { extract } from "../processing/url.js";
export async function runTest(url, params, expect) {
const normalized = normalizeRequest({ url, ...params });
if (!normalized) {
const { success, data: normalized } = await normalizeRequest({ url, ...params });
if (!success) {
throw "invalid request";
}
@ -13,9 +13,11 @@ export async function runTest(url, params, expect) {
throw `invalid url: ${normalized.url}`;
}
const result = await match(
parsed.host, parsed.patternMatch, "en", normalized
);
const result = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: normalized,
});
let error = [];
if (expect.status !== result.body.status) {
@ -36,7 +38,7 @@ export async function runTest(url, params, expect) {
throw error.join('\n');
}
if (result.body.status === 'stream') {
if (result.body.status === 'tunnel') {
// TODO: stream testing
}
}

View File

@ -65,3 +65,14 @@ export function merge(a, b) {
return a;
}
export function splitFilenameExtension(filename) {
const parts = filename.split('.');
const ext = parts.pop();
if (!parts.length) {
return [ ext, "" ]
} else {
return [ parts.join('.'), ext ]
}
}

View File

@ -1,7 +1,7 @@
import Cookie from './cookie.js';
import { readFile, writeFile } from 'fs/promises';
import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
import { env } from '../../../modules/config.js'
import { env } from '../../config.js';
const WRITE_INTERVAL = 60000,
cookiePath = env.cookiePath,

View File

@ -0,0 +1,56 @@
export default (f, style, isAudioOnly, isAudioMuted) => {
let filename = '';
let infoBase = [f.service, f.id];
let classicTags = [...infoBase];
let basicTags = [];
const title = `${f.title} - ${f.author}`;
if (f.resolution) {
classicTags.push(f.resolution);
}
if (f.qualityLabel) {
basicTags.push(f.qualityLabel);
}
if (f.youtubeFormat) {
classicTags.push(f.youtubeFormat);
basicTags.push(f.youtubeFormat);
}
if (isAudioMuted) {
classicTags.push("mute");
basicTags.push("mute");
} else if (f.youtubeDubName) {
classicTags.push(f.youtubeDubName);
basicTags.push(f.youtubeDubName);
}
switch (style) {
default:
case "classic":
if (isAudioOnly) {
if (f.youtubeDubName) {
infoBase.push(f.youtubeDubName);
}
return `${infoBase.join("_")}_audio`;
}
filename = classicTags.join("_");
break;
case "basic":
if (isAudioOnly) return title;
filename = `${title} (${basicTags.join(", ")})`;
break;
case "pretty":
if (isAudioOnly) return `${title} (${infoBase[0]})`;
filename = `${title} (${[...basicTags, infoBase[0]].join(", ")})`;
break;
case "nerdy":
if (isAudioOnly) return `${title} (${infoBase.join(", ")})`;
filename = `${title} (${basicTags.concat(infoBase).join(", ")})`;
break;
}
return `${filename}.${f.extension}`;
}

View File

@ -1,71 +1,77 @@
import { audioIgnore, services, supportedAudio } from "../config.js";
import { createResponse } from "../processing/request.js";
import loc from "../../localization/manager.js";
import createFilename from "./createFilename.js";
import { createStream } from "../stream/manage.js";
import createFilename from "./create-filename.js";
export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, disableMetadata, filenamePattern, toGif, requestIP) {
import { createResponse } from "./request.js";
import { audioIgnore } from "./service-config.js";
import { createStream } from "../stream/manage.js";
import { splitFilenameExtension } from "../misc/utils.js";
export default function({ r, host, audioFormat, isAudioOnly, isAudioMuted, disableMetadata, filenameStyle, twitterGif, requestIP, audioBitrate, alwaysProxy }) {
let action,
responseType = "stream",
responseType = "tunnel",
defaultParams = {
u: r.urls,
headers: r.headers,
service: host,
filename: r.filenameAttributes ?
createFilename(r.filenameAttributes, filenamePattern, isAudioOnly, isAudioMuted) : r.filename,
createFilename(r.filenameAttributes, filenameStyle, isAudioOnly, isAudioMuted) : r.filename,
fileMetadata: !disableMetadata ? r.fileMetadata : false,
requestIP
},
params = {},
audioFormat = String(userFormat);
params = {};
if (r.isPhoto) action = "photo";
else if (r.picker) action = "picker"
else if (r.isGif && toGif) action = "gif";
else if (isAudioMuted) action = "muteVideo";
else if (r.isGif && twitterGif) action = "gif";
else if (isAudioOnly) action = "audio";
else if (isAudioMuted) action = "muteVideo";
else if (r.isM3U8) action = "m3u8";
else action = "video";
if (action === "picker" || action === "audio") {
if (!r.filenameAttributes) defaultParams.filename = r.audioFilename;
defaultParams.isAudioOnly = true;
defaultParams.audioFormat = audioFormat;
}
if (isAudioMuted && !r.filenameAttributes) {
defaultParams.filename = r.filename.replace('.', '_mute.')
if (action === "muteVideo" && isAudioMuted && !r.filenameAttributes) {
const [ name, ext ] = splitFilenameExtension(r.filename);
defaultParams.filename = `${name}_mute.${ext}`;
} else if (action === "gif") {
const [ name ] = splitFilenameExtension(r.filename);
defaultParams.filename = `${name}.gif`;
}
switch (action) {
default:
return createResponse("error", { t: loc(lang, 'ErrorEmptyDownload') });
return createResponse("error", {
code: "error.api.fetch.empty"
});
case "photo":
responseType = "redirect";
break;
case "gif":
params = { type: "gif" }
params = { type: "gif" };
break;
case "m3u8":
params = {
type: Array.isArray(r.urls) ? "render" : "remux"
type: Array.isArray(r.urls) ? "merge" : "remux"
}
break;
case "muteVideo":
let muteType = "mute";
if (Array.isArray(r.urls) && !r.isM3U8) {
muteType = "bridge";
muteType = "proxy";
}
params = {
type: muteType,
u: Array.isArray(r.urls) ? r.urls[0] : r.urls,
mute: true
u: Array.isArray(r.urls) ? r.urls[0] : r.urls
}
if (host === "reddit" && r.typeId === "redirect")
if (host === "reddit" && r.typeId === "redirect") {
responseType = "redirect";
}
break;
case "picker":
@ -75,13 +81,15 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "twitter":
case "threads":
case "snapchat":
case "bsky":
params = { picker: r.picker };
break;
case "tiktok":
let audioStreamType = "render";
if (r.bestAudio === "mp3" && (audioFormat === "mp3" || audioFormat === "best")) {
let audioStreamType = "audio";
if (r.bestAudio === "mp3" && audioFormat === "best") {
audioFormat = "mp3";
audioStreamType = "bridge"
audioStreamType = "proxy"
}
params = {
picker: r.picker,
@ -93,27 +101,30 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
filename: r.audioFilename,
isAudioOnly: true,
audioFormat,
}),
copy: audioFormat === "best"
})
}
break;
}
break;
case "video":
switch (host) {
case "bilibili":
params = { type: "render" };
params = { type: "merge" };
break;
case "youtube":
params = { type: r.type };
break;
case "reddit":
responseType = r.typeId;
params = { type: r.type };
break;
case "vimeo":
if (Array.isArray(r.urls)) {
params = { type: "render" }
params = { type: "merge" }
} else {
responseType = "redirect";
}
@ -127,9 +138,10 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
}
break;
case "ok":
case "vk":
case "tiktok":
params = { type: "bridge" };
params = { type: "proxy" };
break;
case "facebook":
@ -141,64 +153,63 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "snapchat":
case "loom":
case "threads":
case "twitch":
responseType = "redirect";
break;
}
break;
case "audio":
if (audioIgnore.includes(host)
|| (host === "reddit" && r.typeId === "redirect")) {
return createResponse("error", { t: loc(lang, 'ErrorEmptyDownload') })
if (audioIgnore.includes(host) || (host === "reddit" && r.typeId === "redirect")) {
return createResponse("error", {
code: "error.api.fetch.empty"
})
}
let processType = "render",
copy = false;
let processType = "audio";
let copy = false;
if (!supportedAudio.includes(audioFormat)) {
audioFormat = "best"
}
if (audioFormat === "best") {
const serviceBestAudio = r.bestAudio;
const serviceBestAudio = r.bestAudio || services[host]["bestAudio"];
const isBestAudio = audioFormat === "best";
const isBestOrMp3 = isBestAudio || audioFormat === "mp3";
const isBestAudioDefined = isBestAudio && serviceBestAudio;
const isBestHostAudio = serviceBestAudio && (audioFormat === serviceBestAudio);
if (serviceBestAudio) {
audioFormat = serviceBestAudio;
processType = "proxy";
const isTumblrAudio = host === "tumblr" && !r.filename;
const isSoundCloud = host === "soundcloud";
const isTiktok = host === "tiktok";
if (isBestAudioDefined || isBestHostAudio) {
audioFormat = serviceBestAudio;
processType = "bridge";
if (isSoundCloud || (isTiktok && audioFormat === "m4a")) {
processType = "render"
copy = true
if (host === "soundcloud") {
processType = "audio";
copy = true;
}
} else {
audioFormat = "m4a";
copy = true;
}
} else if (isBestAudio && !isSoundCloud) {
audioFormat = "m4a";
copy = true
}
if (isTumblrAudio && isBestOrMp3) {
audioFormat = "mp3";
processType = "bridge"
}
if (r.isM3U8 || host === "vimeo") {
copy = false;
processType = "render"
processType = "audio";
}
params = {
type: processType,
u: Array.isArray(r.urls) ? r.urls[1] : r.urls,
audioFormat: audioFormat,
copy: copy
audioBitrate,
audioCopy: copy,
audioFormat,
}
break;
}
if (defaultParams.filename && (action === "picker" || action === "audio")) {
defaultParams.filename += `.${audioFormat}`;
}
if (alwaysProxy && responseType === "redirect") {
responseType = "tunnel";
params.type = "proxy";
}
return createResponse(responseType, {...defaultParams, ...params})
}

View File

@ -1,11 +1,12 @@
import { strict as assert } from "node:assert";
import { env } from '../config.js';
import { env } from "../config.js";
import { createResponse } from "../processing/request.js";
import loc from "../../localization/manager.js";
import { testers } from "./servicesPatternTesters.js";
import matchActionDecider from "./matchActionDecider.js";
import { testers } from "./service-patterns.js";
import matchAction from "./match-action.js";
import { friendlyServiceName } from "./service-alias.js";
import bilibili from "./services/bilibili.js";
import reddit from "./services/reddit.js";
@ -28,11 +29,12 @@ import snapchat from "./services/snapchat.js";
import loom from "./services/loom.js";
import threads from "./services/threads.js";
import facebook from "./services/facebook.js";
import bluesky from "./services/bluesky.js";
let freebind;
export default async function(host, patternMatch, lang, obj) {
const { url } = obj;
export default async function({ host, patternMatch, params }) {
const { url } = params;
assert(url instanceof URL);
let dispatcher, requestIP;
@ -47,17 +49,20 @@ export default async function(host, patternMatch, lang, obj) {
try {
let r,
isAudioOnly = !!obj.isAudioOnly,
disableMetadata = !!obj.disableMetadata;
isAudioOnly = params.downloadMode === "audio",
isAudioMuted = params.downloadMode === "mute";
if (!testers[host]) {
return createResponse("error", {
t: loc(lang, 'ErrorUnsupported')
code: "error.api.service.unsupported"
});
}
if (!(testers[host](patternMatch))) {
return createResponse("error", {
t: loc(lang, 'ErrorBrokenLink', host)
code: "error.api.link.unsupported",
context: {
service: friendlyServiceName(host),
}
});
}
@ -66,45 +71,52 @@ export default async function(host, patternMatch, lang, obj) {
r = await twitter({
id: patternMatch.id,
index: patternMatch.index - 1,
toGif: !!obj.twitterGif,
toGif: !!params.twitterGif,
alwaysProxy: params.alwaysProxy,
dispatcher
});
break;
case "vk":
r = await vk({
userId: patternMatch.userId,
videoId: patternMatch.videoId,
quality: obj.vQuality
quality: params.videoQuality
});
break;
case "ok":
r = await ok({
id: patternMatch.id,
quality: obj.vQuality
quality: params.videoQuality
});
break;
case "bilibili":
r = await bilibili(patternMatch);
break;
case "youtube":
let fetchInfo = {
id: patternMatch.id.slice(0, 11),
quality: obj.vQuality,
format: obj.vCodec,
isAudioOnly: isAudioOnly,
isAudioMuted: obj.isAudioMuted,
dubLang: obj.dubLang,
quality: params.videoQuality,
format: params.youtubeVideoCodec,
isAudioOnly,
isAudioMuted,
dubLang: params.youtubeDubLang,
dispatcher
}
if (url.hostname === 'music.youtube.com' || isAudioOnly === true) {
if (url.hostname === "music.youtube.com" || isAudioOnly) {
fetchInfo.quality = "max";
fetchInfo.format = "vp9";
fetchInfo.isAudioOnly = true
fetchInfo.isAudioOnly = true;
fetchInfo.isAudioMuted = false;
}
r = await youtube(fetchInfo);
break;
case "reddit":
r = await reddit({
sub: patternMatch.sub,
@ -112,15 +124,18 @@ export default async function(host, patternMatch, lang, obj) {
user: patternMatch.user
});
break;
case "tiktok":
r = await tiktok({
postId: patternMatch.postId,
id: patternMatch.id,
fullAudio: obj.isTTFullAudio,
isAudioOnly: isAudioOnly,
h265: obj.tiktokH265
fullAudio: params.tiktokFullAudio,
isAudioOnly,
h265: params.tiktokH265,
alwaysProxy: params.alwaysProxy,
});
break;
case "tumblr":
r = await tumblr({
id: patternMatch.id,
@ -128,80 +143,94 @@ export default async function(host, patternMatch, lang, obj) {
url
});
break;
case "vimeo":
r = await vimeo({
id: patternMatch.id.slice(0, 11),
password: patternMatch.password,
quality: obj.vQuality,
isAudioOnly: isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "soundcloud":
isAudioOnly = true;
isAudioMuted = false;
r = await soundcloud({
url,
author: patternMatch.author,
song: patternMatch.song,
format: obj.aFormat,
format: params.audioFormat,
shortLink: patternMatch.shortLink || false,
accessKey: patternMatch.accessKey || false
});
break;
case "instagram":
r = await instagram({
...patternMatch,
quality: obj.vQuality,
quality: params.videoQuality,
alwaysProxy: params.alwaysProxy,
dispatcher
})
break;
case "vine":
r = await vine({
id: patternMatch.id
});
break;
case "pinterest":
r = await pinterest({
id: patternMatch.id,
shortLink: patternMatch.shortLink || false
});
break;
case "streamable":
r = await streamable({
id: patternMatch.id,
quality: obj.vQuality,
isAudioOnly: isAudioOnly,
quality: params.videoQuality,
isAudioOnly,
});
break;
case "twitch":
r = await twitch({
clipId: patternMatch.clip || false,
quality: obj.vQuality,
isAudioOnly: obj.isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "rutube":
r = await rutube({
id: patternMatch.id,
yappyId: patternMatch.yappyId,
key: patternMatch.key,
quality: obj.vQuality,
isAudioOnly: isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "dailymotion":
r = await dailymotion(patternMatch);
break;
case "snapchat":
r = await snapchat({
hostname: url.hostname,
...patternMatch
...patternMatch,
alwaysProxy: params.alwaysProxy,
});
break;
case "loom":
r = await loom({
id: patternMatch.id
});
break;
case "threads":
r = await threads({
...patternMatch,
@ -209,42 +238,82 @@ export default async function(host, patternMatch, lang, obj) {
dispatcher
});
break;
case "facebook":
r = await facebook({
...patternMatch
});
break;
case "bsky":
r = await bluesky({
...patternMatch,
alwaysProxy: params.alwaysProxy
});
break;
default:
return createResponse("error", {
t: loc(lang, 'ErrorUnsupported')
code: "error.api.service.unsupported"
});
}
if (r.isAudioOnly) isAudioOnly = true;
let isAudioMuted = isAudioOnly ? false : obj.isAudioMuted;
if (r.isAudioOnly) {
isAudioOnly = true;
isAudioMuted = false;
}
if (r.error && r.critical) {
return createResponse("critical", {
t: loc(lang, r.error)
})
}
if (r.error) {
return createResponse("error", {
t: Array.isArray(r.error)
? loc(lang, r.error[0], r.error[1])
: loc(lang, r.error)
code: `error.api.${r.error}`,
})
}
return matchActionDecider(
r, host, obj.aFormat, isAudioOnly,
lang, isAudioMuted, disableMetadata,
obj.filenamePattern, obj.twitterGif,
requestIP
)
if (r.error) {
let context;
switch(r.error) {
case "content.too_long":
context = {
limit: env.durationLimit / 60,
}
break;
case "fetch.fail":
case "fetch.rate":
case "fetch.critical":
case "link.unsupported":
case "content.video.unavailable":
context = {
service: friendlyServiceName(host),
}
break;
}
return createResponse("error", {
code: `error.api.${r.error}`,
context,
})
}
return matchAction({
r,
host,
audioFormat: params.audioFormat,
isAudioOnly,
isAudioMuted,
disableMetadata: params.disableMetadata,
filenameStyle: params.filenameStyle,
twitterGif: params.twitterGif,
requestIP,
audioBitrate: params.audioBitrate,
alwaysProxy: params.alwaysProxy,
})
} catch {
return createResponse("error", {
t: loc(lang, 'ErrorBadFetch', host)
code: "error.api.fetch.critical",
context: {
service: friendlyServiceName(host),
}
})
}
}

View File

@ -0,0 +1,97 @@
import ipaddr from "ipaddr.js";
import { createStream } from "../stream/manage.js";
import { apiSchema } from "./schema.js";
export function createResponse(responseType, responseData) {
const internalError = (code) => {
return {
status: 500,
body: {
status: "error",
error: {
code: code || "error.api.fetch.critical",
},
critical: true
}
}
}
try {
let status = 200,
response = {};
if (responseType === "error") {
status = 400;
}
switch (responseType) {
case "error":
response = {
error: {
code: responseData?.code,
context: responseData?.context,
}
}
break;
case "redirect":
response = {
url: responseData?.u,
filename: responseData?.filename
}
break;
case "tunnel":
response = {
url: createStream(responseData),
filename: responseData?.filename
}
break;
case "picker":
response = {
picker: responseData?.picker,
audio: responseData?.u,
audioFilename: responseData?.filename
}
break;
case "critical":
return internalError(responseData?.code);
default:
throw "unreachable"
}
return {
status,
body: {
status: responseType,
...response
}
}
} catch {
return internalError()
}
}
export function normalizeRequest(request) {
return apiSchema.safeParseAsync(request).catch(() => (
{ success: false }
));
}
export function getIP(req) {
const strippedIP = req.ip.replace(/^::ffff:/, '');
const ip = ipaddr.parse(strippedIP);
if (ip.kind() === 'ipv4') {
return strippedIP;
}
const prefix = 56;
const v6Bytes = ip.toByteArray();
v6Bytes.fill(0, prefix / 8);
return ipaddr.fromByteArray(v6Bytes).toString();
}

View File

@ -0,0 +1,47 @@
import { z } from "zod";
import { normalizeURL } from "./url.js";
import { verifyLanguageCode } from "../misc/utils.js";
export const apiSchema = z.object({
url: z.string()
.min(1)
.transform(url => normalizeURL(url)),
audioBitrate: z.enum(
["320", "256", "128", "96", "64", "8"]
).default("128"),
audioFormat: z.enum(
["best", "mp3", "ogg", "wav", "opus"]
).default("mp3"),
downloadMode: z.enum(
["auto", "audio", "mute"]
).default("auto"),
filenameStyle: z.enum(
["classic", "pretty", "basic", "nerdy"]
).default("classic"),
youtubeVideoCodec: z.enum(
["h264", "av1", "vp9"]
).default("h264"),
videoQuality: z.enum(
["max", "4320", "2160", "1440", "1080", "720", "480", "360", "240", "144"]
).default("1080"),
youtubeDubLang: z.string()
.length(2)
.transform(verifyLanguageCode)
.optional(),
alwaysProxy: z.boolean().default(false),
disableMetadata: z.boolean().default(false),
tiktokFullAudio: z.boolean().default(false),
tiktokH265: z.boolean().default(false),
twitterGif: z.boolean().default(true),
youtubeDubBrowserLang: z.boolean().default(false),
})
.strict();

View File

@ -0,0 +1,10 @@
const friendlyNames = {
bsky: "bluesky",
}
export const friendlyServiceName = (service) => {
if (service in friendlyNames) {
return friendlyNames[service];
}
return service;
}

View File

@ -0,0 +1,183 @@
import UrlPattern from "url-pattern";
export const audioIgnore = ["vk", "ok", "loom"];
export const hlsExceptions = ["dailymotion", "vimeo", "rutube", "bsky"];
export const services = {
bilibili: {
patterns: [
"video/:comId",
"_shortLink/:comShortLink",
"_tv/:lang/video/:tvId",
"_tv/video/:tvId"
],
subdomains: ["m"],
},
bsky: {
patterns: [
"profile/:user/post/:post"
],
tld: "app",
},
dailymotion: {
patterns: ["video/:id"],
},
facebook: {
patterns: [
"_shortLink/:shortLink",
":username/videos/:caption/:id",
":username/videos/:id",
"reel/:id",
"share/:shareType/:id"
],
subdomains: ["web"],
altDomains: ["fb.watch"],
},
instagram: {
patterns: [
"reels/:postId",
":username/reel/:postId",
"reel/:postId",
"p/:postId",
":username/p/:postId",
"tv/:postId",
"stories/:username/:storyId"
],
altDomains: ["ddinstagram.com"],
},
loom: {
patterns: ["share/:id"],
},
ok: {
patterns: [
"video/:id",
"videoembed/:id"
],
tld: "ru",
},
pinterest: {
patterns: [
"pin/:id",
"pin/:id/:garbage",
"url_shortener/:shortLink"
],
},
reddit: {
patterns: [
"r/:sub/comments/:id/:title",
"user/:user/comments/:id/:title"
],
subdomains: "*",
},
rutube: {
patterns: [
"video/:id",
"play/embed/:id",
"shorts/:id",
"yappy/:yappyId",
"video/private/:id?p=:key",
"video/private/:id"
],
tld: "ru",
},
snapchat: {
patterns: [
":shortLink",
"spotlight/:spotlightId",
"add/:username/:storyId",
"u/:username/:storyId",
"add/:username",
"u/:username",
"t/:shortLink",
],
subdomains: ["t", "story"],
},
soundcloud: {
patterns: [
":author/:song/s-:accessKey",
":author/:song",
":shortLink"
],
subdomains: ["on", "m"],
},
streamable: {
patterns: [
":id",
"o/:id",
"e/:id",
"s/:id"
],
},
tiktok: {
patterns: [
":user/video/:postId",
":id",
"t/:id",
":user/photo/:postId",
"v/:id.html"
],
subdomains: ["vt", "vm", "m"],
},
tumblr: {
patterns: [
"post/:id",
"blog/view/:user/:id",
":user/:id",
":user/:id/:trackingId"
],
subdomains: "*",
},
twitch: {
patterns: [":channel/clip/:clip"],
tld: "tv",
},
twitter: {
patterns: [
":user/status/:id",
":user/status/:id/video/:index",
":user/status/:id/photo/:index",
":user/status/:id/mediaviewer",
":user/status/:id/mediaViewer",
"i/bookmarks?post_id=:id"
],
subdomains: ["mobile"],
altDomains: ["x.com", "vxtwitter.com", "fixvx.com"],
},
vine: {
patterns: ["v/:id"],
tld: "co",
},
vimeo: {
patterns: [
":id",
"video/:id",
":id/:password",
"/channels/:user/:id"
],
subdomains: ["player"],
},
vk: {
patterns: [
"video:userId_:videoId",
"clip:userId_:videoId",
"clips:duplicate?z=clip:userId_:videoId"
],
subdomains: ["m"],
},
youtube: {
patterns: [
"watch?v=:id",
"embed/:id",
"watch/:id"
],
subdomains: ["music", "m"],
}
}
Object.values(services).forEach(service => {
service.patterns = service.patterns.map(
pattern => new UrlPattern(pattern, {
segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.:'
})
)
})

View File

@ -0,0 +1,76 @@
export const testers = {
"bilibili": pattern =>
pattern.comId?.length <= 12 || pattern.comShortLink?.length <= 16
|| pattern.tvId?.length <= 24,
"dailymotion": pattern => pattern.id?.length <= 32,
"instagram": pattern =>
pattern.postId?.length <= 12
|| (pattern.username?.length <= 30 && pattern.storyId?.length <= 24),
"loom": pattern =>
pattern.id?.length <= 32,
"ok": pattern =>
pattern.id?.length <= 16,
"pinterest": pattern =>
pattern.id?.length <= 128 || pattern.shortLink?.length <= 32,
"reddit": pattern =>
(pattern.sub?.length <= 22 && pattern.id?.length <= 10)
|| (pattern.user?.length <= 22 && pattern.id?.length <= 10),
"rutube": pattern =>
(pattern.id?.length === 32 && pattern.key?.length <= 32) ||
pattern.id?.length === 32 || pattern.yappyId?.length === 32,
"soundcloud": pattern =>
(pattern.author?.length <= 255 && pattern.song?.length <= 255)
|| pattern.shortLink?.length <= 32,
"snapchat": pattern =>
(pattern.username?.length <= 32 && (!pattern.storyId || pattern.storyId?.length <= 255))
|| pattern.spotlightId?.length <= 255
|| pattern.shortLink?.length <= 16,
"streamable": pattern =>
pattern.id?.length === 6,
"tiktok": pattern =>
pattern.postId?.length <= 21 || pattern.id?.length <= 13,
"tumblr": pattern =>
pattern.id?.length < 21
|| (pattern.id?.length < 21 && pattern.user?.length <= 32),
"twitch": pattern =>
pattern.channel && pattern.clip?.length <= 100,
"twitter": pattern =>
pattern.id?.length < 20,
"vimeo": pattern =>
pattern.id?.length <= 11
&& (!pattern.password || pattern.password.length < 16),
"vine": pattern =>
pattern.id?.length <= 12,
"vk": pattern =>
pattern.userId?.length <= 10 && pattern.videoId?.length <= 10,
"youtube": pattern =>
pattern.id?.length <= 11,
"facebook": pattern =>
pattern.shortLink?.length <= 11
|| pattern.username?.length <= 30
|| pattern.caption?.length <= 255
|| pattern.id?.length <= 20 && !pattern.shareType
|| pattern.id?.length <= 20 && pattern.shareType?.length === 1,
"bsky": pattern =>
pattern.user?.length <= 128 && pattern.post?.length <= 128,
}

View File

@ -30,22 +30,29 @@ function extractBestQuality(dashData) {
async function com_download(id) {
let html = await fetch(`https://bilibili.com/video/${id}`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
headers: {
"user-agent": genericUserAgent
}
})
.then(r => r.text())
.catch(() => {});
if (!html) {
return { error: "fetch.fail" }
}
if (!(html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"'))) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
let streamData = JSON.parse(html.split('<script>window.__playinfo__=')[1].split('</script>')[0]);
if (streamData.data.timelength > env.durationLimit * 1000) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const [ video, audio ] = extractBestQuality(streamData.data.dash);
if (!video || !audio) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
return {
@ -66,7 +73,7 @@ async function tv_download(id) {
const { data } = await fetch(url).then(a => a.json());
if (!data?.playurl?.video) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
const [ video, audio ] = extractBestQuality({
@ -76,11 +83,11 @@ async function tv_download(id) {
});
if (!video || !audio) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
if (video.duration > env.durationLimit * 1000) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
return {
@ -101,5 +108,5 @@ export default async function({ comId, tvId, comShortLink }) {
return tv_download(tvId);
}
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}

View File

@ -0,0 +1,116 @@
import HLS from "hls-parser";
import { cobaltUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
const extractVideo = async ({ media, filename }) => {
const urlMasterHLS = media?.playlist;
if (!urlMasterHLS) return { error: "fetch.empty" };
if (!urlMasterHLS.startsWith("https://video.bsky.app/")) return { error: "fetch.empty" };
const masterHLS = await fetch(urlMasterHLS)
.then(r => {
if (r.status !== 200) return;
return r.text();
})
.catch(() => {});
if (!masterHLS) return { error: "fetch.empty" };
const video = HLS.parse(masterHLS)
?.variants
?.reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b);
const videoURL = new URL(video.uri, urlMasterHLS).toString();
return {
urls: videoURL,
filename: `${filename}.mp4`,
audioFilename: `${filename}_audio`,
isM3U8: true,
}
}
const extractImages = ({ getPost, filename, alwaysProxy }) => {
const images = getPost?.thread?.post?.embed?.images;
if (!images || images.length === 0) {
return { error: "fetch.empty" };
}
if (images.length === 1) return {
urls: images[0].fullsize,
isPhoto: true,
filename: `${filename}.jpg`,
}
const picker = images.map((image, i) => {
let url = image.fullsize;
let proxiedImage = createStream({
service: "bluesky",
type: "proxy",
u: url,
filename: `${filename}_${i + 1}.jpg`,
});
if (alwaysProxy) url = proxiedImage;
return {
type: "photo",
url,
thumb: proxiedImage,
}
});
return { picker };
}
export default async function ({ user, post, alwaysProxy }) {
const apiEndpoint = new URL("https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?depth=0&parentHeight=0");
apiEndpoint.searchParams.set(
"uri",
`at://${user}/app.bsky.feed.post/${post}`
);
const getPost = await fetch(apiEndpoint, {
headers: {
"user-agent": cobaltUserAgent
}
}).then(r => r.json()).catch(() => {});
if (!getPost) return { error: "fetch.empty" };
if (getPost.error) {
switch (getPost.error) {
case "NotFound":
case "InternalServerError":
return { error: "content.post.unavailable" };
case "InvalidRequest":
return { error: "link.unsupported" };
default:
return { error: "fetch.empty" };
}
}
const embedType = getPost?.thread?.post?.embed?.$type;
const filename = `bluesky_${user}_${post}`;
if (embedType === "app.bsky.embed.video#view") {
return extractVideo({
media: getPost.thread?.post?.embed,
filename,
})
}
if (embedType === "app.bsky.embed.recordWithMedia#view") {
return extractVideo({
media: getPost.thread?.post?.embed?.media,
filename,
})
}
if (embedType === "app.bsky.embed.images#view") {
return extractImages({ getPost, filename, alwaysProxy });
}
return { error: "fetch.empty" };
}

View File

@ -1,5 +1,5 @@
import HLSParser from 'hls-parser';
import { env } from '../../config.js';
import HLSParser from "hls-parser";
import { env } from "../../config.js";
let _token;
@ -31,7 +31,7 @@ const getToken = async () => {
export default async function({ id }) {
const token = await getToken();
if (!token) return { error: 'ErrorSomethingWentWrong' };
if (!token) return { error: "fetch.fail" };
const req = await fetch('https://graphql.api.dailymotion.com/',
{
@ -70,20 +70,20 @@ export default async function({ id }) {
const media = req?.data?.media;
if (media?.__typename !== 'Video' || !media.hlsURL) {
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}
if (media.duration > env.durationLimit) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const manifest = await fetch(media.hlsURL).then(r => r.text()).catch(() => {});
if (!manifest) return { error: 'ErrorSomethingWentWrong' };
if (!manifest) return { error: "fetch.fail" };
const bestQuality = HLSParser.parse(manifest).variants
.filter(v => v.codecs.includes('avc1'))
.reduce((a, b) => a.bandwidth > b.bandwidth ? a : b);
if (!bestQuality) return { error: 'ErrorEmptyDownload' }
if (!bestQuality) return { error: "fetch.empty" }
const fileMetadata = {
title: media.title,

View File

@ -33,7 +33,8 @@ export default async function({ id, shareType, shortLink }) {
.then(r => r.text())
.catch(() => false);
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html && shortLink) return { error: "fetch.short_link" }
if (!html) return { error: "fetch.fail" };
const urls = [];
const hd = html.match('"browser_native_hd_url":(".*?")');
@ -43,7 +44,7 @@ export default async function({ id, shareType, shortLink }) {
if (sd?.[1]) urls.push(JSON.parse(sd[1]));
if (!urls.length) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
const baseFilename = `facebook_${id || shortLink}`;

View File

@ -1,5 +1,5 @@
import { createStream } from "../../stream/manage.js";
import { genericUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
import { getCookie, updateCookie } from "../cookie/manager.js";
const commonHeaders = {
@ -163,23 +163,34 @@ export default function(obj) {
?.[0];
}
function extractOldPost(data, id) {
function extractOldPost(data, id, alwaysProxy) {
const sidecar = data?.gql_data?.shortcode_media?.edge_sidecar_to_children;
if (sidecar) {
const picker = sidecar.edges.filter(e => e.node?.display_url)
.map(e => {
.map((e, i) => {
const type = e.node?.is_video ? "video" : "photo";
const url = type === "video" ? e.node?.video_url : e.node?.display_url;
let itemExt = type === "video" ? "mp4" : "jpg";
let proxyFile;
if (alwaysProxy) proxyFile = createStream({
service: "instagram",
type: "proxy",
u: url,
filename: `instagram_${id}_${i + 1}.${itemExt}`
});
return {
type, url,
type,
url: proxyFile || url,
/* thumbnails have `Cross-Origin-Resource-Policy`
** set to `same-origin`, so we need to proxy them */
thumb: createStream({
service: "instagram",
type: "default",
type: "proxy",
u: e.node?.display_url,
filename: "image.jpg"
filename: `instagram_${id}_${i + 1}.jpg`
})
}
});
@ -199,29 +210,40 @@ export default function(obj) {
}
}
function extractNewPost(data, id) {
function extractNewPost(data, id, alwaysProxy) {
const carousel = data.carousel_media;
if (carousel) {
const picker = carousel.filter(e => e?.image_versions2)
.map(e => {
.map((e, i) => {
const type = e.video_versions ? "video" : "photo";
const imageUrl = e.image_versions2.candidates[0].url;
let url = imageUrl;
if (type === 'video') {
let itemExt = type === "video" ? "mp4" : "jpg";
if (type === "video") {
const video = e.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a);
url = video.url;
}
let proxyFile;
if (alwaysProxy) proxyFile = createStream({
service: "instagram",
type: "proxy",
u: url,
filename: `instagram_${id}_${i + 1}.${itemExt}`
});
return {
type, url,
type,
url: proxyFile || url,
/* thumbnails have `Cross-Origin-Resource-Policy`
** set to `same-origin`, so we need to proxy them */
** set to `same-origin`, so we need to always proxy them */
thumb: createStream({
service: "instagram",
type: "default",
type: "proxy",
u: imageUrl,
filename: "image.jpg"
filename: `instagram_${id}_${i + 1}.jpg`
})
}
});
@ -237,16 +259,17 @@ export default function(obj) {
} else if (data.image_versions2?.candidates) {
return {
urls: data.image_versions2.candidates[0].url,
isPhoto: true
isPhoto: true,
filename: `instagram_${id}.jpg`,
}
}
}
async function getPost(id) {
async function getPost(id, alwaysProxy) {
let data, result;
try {
const cookie = getCookie('instagram');
const bearer = getCookie('instagram_bearer');
const token = bearer?.values()?.token;
@ -271,16 +294,16 @@ export default function(obj) {
if (!data && cookie) data = await requestGQL(id, cookie);
} catch {}
if (!data) return { error: 'ErrorCouldntFetch' };
if (!data) return { error: "fetch.fail" };
if (data?.gql_data) {
result = extractOldPost(data, id)
result = extractOldPost(data, id, alwaysProxy)
} else {
result = extractNewPost(data, id)
result = extractNewPost(data, id, alwaysProxy)
}
if (result) return result;
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}
async function usernameToId(username, cookie) {
@ -295,11 +318,11 @@ export default function(obj) {
async function getStory(username, id) {
const cookie = getCookie('instagram');
if (!cookie) return { error: 'ErrorUnsupported' };
if (!cookie) return { error: "link.unsupported" };
const userId = await usernameToId(username, cookie);
if (!userId) return { error: 'ErrorEmptyDownload' };
if (!userId) return { error: "fetch.empty" };
const dtsgId = await findDtsgId(cookie);
const url = new URL('https://www.instagram.com/api/graphql/');
@ -320,8 +343,8 @@ export default function(obj) {
} catch {}
const item = media.items.find(m => m.pk === id);
if (!item) return { error: 'ErrorEmptyDownload' };
if (!item) return { error: "fetch.empty" };
if (item.video_versions) {
const video = item.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a)
return {
@ -338,12 +361,12 @@ export default function(obj) {
}
}
return { error: 'ErrorUnsupported' };
return { error: "link.unsupported" };
}
const { postId, storyId, username } = obj;
if (postId) return getPost(postId);
const { postId, storyId, username, alwaysProxy } = obj;
if (postId) return getPost(postId, alwaysProxy);
if (username && storyId) return getStory(username, storyId);
return { error: 'ErrorUnsupported' }
return { error: "fetch.empty" }
}

View File

@ -23,7 +23,7 @@ export default async function({ id }) {
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!gql) return { error: 'ErrorEmptyDownload' };
if (!gql) return { error: "fetch.empty" };
const videoUrl = gql?.url;
@ -35,5 +35,5 @@ export default async function({ id }) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@ -1,5 +1,5 @@
import { genericUserAgent, env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
const resolutions = {
"ultra": "2160",
@ -19,26 +19,26 @@ export default async function(o) {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
let videoData = html.match(/<div data-module="OKVideo" .*? data-options="({.*?})"( .*?)>/)
?.[1]
?.replaceAll("&quot;", '"');
if (!videoData) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
videoData = JSON.parse(JSON.parse(videoData).flashvars.metadata);
if (videoData.provider !== "UPLOADED_ODKL")
return { error: 'ErrorUnsupported' };
return { error: "link.unsupported" };
if (videoData.movie.is_live)
return { error: 'ErrorLiveVideo' };
return { error: "content.video.live" };
if (videoData.movie.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let videos = videoData.videos.filter(v => !v.disallowed);
let bestVideo = videos.find(v => resolutions[v.name] === quality) || videos[videos.length - 1];
@ -61,5 +61,5 @@ export default async function(o) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@ -12,15 +12,15 @@ export default async function(o) {
.catch(() => {});
}
if (id.includes("--")) id = id.split("--")[1];
if (!id) return { error: 'ErrorCouldntFetch' };
if (!id) return { error: "fetch.fail" };
let html = await fetch(`https://www.pinterest.com/pin/${id}/`, {
const html = await fetch(`https://www.pinterest.com/pin/${id}/`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
let videoLink = [...html.matchAll(videoRegex)]
const videoLink = [...html.matchAll(videoRegex)]
.map(([, link]) => link)
.find(a => a.endsWith('.mp4') && a.includes('720p'));
@ -30,14 +30,17 @@ export default async function(o) {
audioFilename: `pinterest_${o.id}_audio`
}
let imageLink = [...html.matchAll(imageRegex)]
const imageLink = [...html.matchAll(imageRegex)]
.map(([, link]) => link)
.find(a => a.endsWith('.jpg') || a.endsWith('.gif'));
const imageType = imageLink.endsWith(".gif") ? "gif" : "jpg"
if (imageLink) return {
urls: imageLink,
isPhoto: true
isPhoto: true,
filename: `pinterest_${o.id}.${imageType}`
}
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}

View File

@ -9,7 +9,7 @@ async function getAccessToken() {
* you can get these by making a reddit app and
* authenticating an account against reddit's oauth2 api
* see: https://github.com/reddit-archive/reddit/wiki/OAuth2
*
*
* any additional cookie fields are managed by this code and you
* should not touch them unless you know what you're doing. **/
const cookie = await getCookie('reddit');
@ -67,20 +67,25 @@ export default async function(obj) {
}
).then(r => r.json()).catch(() => {});
if (!data || !Array.isArray(data)) return { error: 'ErrorCouldntFetch' };
if (!data || !Array.isArray(data)) {
return { error: "fetch.fail" }
}
data = data[0]?.data?.children[0]?.data;
const id = `${String(obj.sub).toLowerCase()}_${obj.id}`;
if (data?.url?.endsWith('.gif')) return {
typeId: "redirect",
urls: data.url
urls: data.url,
filename: `reddit_${id}.gif`,
}
if (!data.secure_media?.reddit_video)
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
if (data.secure_media?.reddit_video?.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let audio = false,
video = data.secure_media?.reddit_video?.fallback_url?.split('?')[0],
@ -107,16 +112,14 @@ export default async function(obj) {
}).catch(() => {})
}
let id = `${String(obj.sub).toLowerCase()}_${obj.id}`;
if (!audio) return {
typeId: "redirect",
urls: video
}
return {
typeId: "stream",
type: "render",
typeId: "tunnel",
type: "merge",
urls: [video, audioFileLink],
audioFilename: `reddit_${id}_audio`,
filename: `reddit_${id}.mp4`

View File

@ -1,7 +1,7 @@
import HLS from 'hls-parser';
import HLS from "hls-parser";
import { env } from "../../config.js";
import { cleanString } from '../../sub/utils.js';
import { cleanString } from "../../misc/utils.js";
async function requestJSON(url) {
try {
@ -18,7 +18,7 @@ export default async function(obj) {
`https://rutube.ru/pangolin/api/web/yappy/yappypage/?client=wdp&videoId=${obj.yappyId}&page=1&page_size=15`
)
const yappyURL = yappy?.results?.find(r => r.id === obj.yappyId)?.link;
if (!yappyURL) return { error: 'ErrorEmptyDownload' };
if (!yappyURL) return { error: "fetch.empty" };
return {
urls: yappyURL,
@ -33,19 +33,19 @@ export default async function(obj) {
if (obj.key) requestURL.searchParams.set('p', obj.key);
const play = await requestJSON(requestURL);
if (!play) return { error: 'ErrorCouldntFetch' };
if (!play) return { error: "fetch.fail" };
if (play.detail || !play.video_balancer) return { error: 'ErrorEmptyDownload' };
if (play.live_streams?.hls) return { error: 'ErrorLiveVideo' };
if (play.detail || !play.video_balancer) return { error: "fetch.empty" };
if (play.live_streams?.hls) return { error: "content.video.live" };
if (play.duration > env.durationLimit * 1000)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let m3u8 = await fetch(play.video_balancer.m3u8)
.then(r => r.text())
.catch(() => {});
if (!m3u8) return { error: 'ErrorCouldntFetch' };
if (!m3u8) return { error: "fetch.fail" };
m3u8 = HLS.parse(m3u8).variants;

View File

@ -1,20 +1,23 @@
import { genericUserAgent } from "../../config.js";
import { getRedirectingURL } from "../../sub/utils.js";
import { extract, normalizeURL } from "../url.js";
import { genericUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
import { getRedirectingURL } from "../../misc/utils.js";
const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="preload" href="(https:\/\/cf-st\.sc-cdn\.net\/d\/[\w.?=]+&amp;uc=\d+)" as="video"\/>/;
const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="preload" href="([^"]+)" as="video"\/>/;
const NEXT_DATA_REGEX = /<script id="__NEXT_DATA__" type="application\/json">({.+})<\/script><\/body><\/html>$/;
async function getSpotlight(id) {
const html = await fetch(`https://www.snapchat.com/spotlight/${id}`, {
headers: { 'User-Agent': genericUserAgent }
headers: { 'user-agent': genericUserAgent }
}).then((r) => r.text()).catch(() => null);
if (!html) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
const videoURL = html.match(SPOTLIGHT_VIDEO_REGEX)?.[1];
if (videoURL) {
if (videoURL && new URL(videoURL).hostname.endsWith(".sc-cdn.net")) {
return {
urls: videoURL,
filename: `snapchat_${id}.mp4`,
@ -23,12 +26,16 @@ async function getSpotlight(id) {
}
}
async function getStory(username, storyId) {
const html = await fetch(`https://www.snapchat.com/add/${username}${storyId ? `/${storyId}` : ''}`, {
headers: { 'User-Agent': genericUserAgent }
}).then((r) => r.text()).catch(() => null);
async function getStory(username, storyId, alwaysProxy) {
const html = await fetch(
`https://www.snapchat.com/add/${username}${storyId ? `/${storyId}` : ''}`,
{ headers: { 'user-agent': genericUserAgent } }
)
.then((r) => r.text())
.catch(() => null);
if (!html) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
const nextDataString = html.match(NEXT_DATA_REGEX)?.[1];
@ -42,6 +49,7 @@ async function getStory(username, storyId) {
if (story.snapMediaType === 0) {
return {
urls: story.snapUrls.mediaUrl,
filename: `snapchat_${storyId}.jpg`,
isPhoto: true
}
}
@ -57,11 +65,33 @@ async function getStory(username, storyId) {
const defaultStory = data.props.pageProps.curatedHighlights[0];
if (defaultStory) {
return {
picker: defaultStory.snapList.map((snap) => ({
type: snap.snapMediaType === 0 ? 'photo' : 'video',
url: snap.snapUrls.mediaUrl,
thumb: snap.snapUrls.mediaPreviewUrl.value
}))
picker: defaultStory.snapList.map(snap => {
const snapType = snap.snapMediaType === 0 ? "photo" : "video";
const snapExt = snapType === "video" ? "mp4" : "jpg";
let snapUrl = snap.snapUrls.mediaUrl;
const proxy = createStream({
service: "snapchat",
type: "proxy",
u: snapUrl,
filename: `snapchat_${username}_${snap.timestampInSec.value}.${snapExt}`,
});
let thumbProxy;
if (snapType === "video") thumbProxy = createStream({
service: "snapchat",
type: "proxy",
u: snap.snapUrls.mediaPreviewUrl.value,
});
if (alwaysProxy) snapUrl = proxy;
return {
type: snapType,
url: snapUrl,
thumb: thumbProxy || proxy,
}
})
}
}
}
@ -69,16 +99,16 @@ async function getStory(username, storyId) {
export default async function (obj) {
let params = obj;
if (obj.hostname === 't.snapchat.com' && obj.shortLink) {
if (obj.shortLink) {
const link = await getRedirectingURL(`https://t.snapchat.com/${obj.shortLink}`);
if (!link?.startsWith('https://www.snapchat.com/')) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.short_link" };
}
const extractResult = extract(normalizeURL(link));
if (extractResult?.host !== 'snapchat') {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.short_link" };
}
params = extractResult.patternMatch;
@ -88,9 +118,9 @@ export default async function (obj) {
const result = await getSpotlight(params.spotlightId);
if (result) return result;
} else if (params.username) {
const result = await getStory(params.username, params.storyId);
const result = await getStory(params.username, params.storyId, obj.alwaysProxy);
if (result) return result;
}
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}

View File

@ -1,5 +1,5 @@
import { env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
const cachedID = {
version: '',
@ -39,7 +39,7 @@ async function findClientID() {
export default async function(obj) {
let clientId = await findClientID();
if (!clientId) return { error: 'ErrorSoundCloudNoClientId' };
if (!clientId) return { error: "fetch.fail" };
let link;
if (obj.url.hostname === 'on.soundcloud.com' && obj.shortLink) {
@ -54,15 +54,16 @@ export default async function(obj) {
link = `https://soundcloud.com/${obj.author}/${obj.song}${obj.accessKey ? `/s-${obj.accessKey}` : ''}`
}
if (!link) return { error: 'ErrorCouldntFetch' };
if (!link && obj.shortLink) return { error: "fetch.short_link" };
if (!link) return { error: "link.unsupported" };
let json = await fetch(`https://api-v2.soundcloud.com/resolve?url=${link}&client_id=${clientId}`)
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!json) return { error: 'ErrorCouldntFetch' };
if (!json) return { error: "fetch.fail" };
if (!json.media.transcodings) return { error: 'ErrorEmptyDownload' };
if (!json.media.transcodings) return { error: "fetch.empty" };
let bestAudio = "opus",
selectedStream = json.media.transcodings.find(v => v.preset === "opus_0_0"),
@ -78,15 +79,16 @@ export default async function(obj) {
let fileUrl = `${fileUrlBase}${fileUrlBase.includes("?") ? "&" : "?"}client_id=${clientId}&track_authorization=${json.track_authorization}`;
if (!fileUrl.startsWith("https://api-v2.soundcloud.com/media/soundcloud:tracks:"))
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
if (json.duration > env.durationLimit * 1000)
return { error: ['ErrorLengthAudioConvert', env.durationLimit / 60] };
if (json.duration > env.durationLimit * 1000) {
return { error: "content.too_long" };
}
let file = await fetch(fileUrl)
.then(async r => (await r.json()).url)
.catch(() => {});
if (!file) return { error: 'ErrorCouldntFetch' };
if (!file) return { error: "fetch.empty" };
let fileMetadata = {
title: cleanString(json.title.trim()),

View File

@ -3,9 +3,9 @@ export default async function(obj) {
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!video) return { error: 'ErrorEmptyDownload' };
if (!video) return { error: "fetch.empty" };
let best = video.files['mp4-mobile'];
let best = video.files["mp4-mobile"];
if (video.files.mp4 && (obj.isAudioOnly || obj.quality === "max" || obj.quality >= 720)) {
best = video.files.mp4;
}
@ -18,5 +18,5 @@ export default async function(obj) {
title: video.title
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.fail" }
}

View File

@ -103,4 +103,4 @@ export default async function({ user, id, quality, dispatcher }) {
}
return { error: 'ErrorUnsupported' };
}
}

View File

@ -1,7 +1,9 @@
import Cookie from "../cookie/cookie.js";
import { extract } from "../url.js";
import { genericUserAgent } from "../../config.js";
import { updateCookie } from "../cookie/manager.js";
import { extract } from "../url.js";
import Cookie from "../cookie/cookie.js";
import { createStream } from "../../stream/manage.js";
const shortDomain = "https://vt.tiktok.com/";
@ -17,7 +19,7 @@ export default async function(obj) {
}
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
if (html.startsWith('<a href="https://')) {
const extractedURL = html.split('<a href="')[1].split('?')[0];
@ -25,7 +27,7 @@ export default async function(obj) {
postId = patternMatch.postId
}
}
if (!postId) return { error: 'ErrorCantGetID' };
if (!postId) return { error: "fetch.short_link" };
// should always be /video/, even for photos
const res = await fetch(`https://tiktok.com/@i/video/${postId}`, {
@ -46,12 +48,12 @@ export default async function(obj) {
const data = JSON.parse(json)
detail = data["__DEFAULT_SCOPE__"]["webapp.video-detail"]["itemInfo"]["itemStruct"]
} catch {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
let video, videoFilename, audioFilename, audio, images,
filenameBase = `tiktok_${detail.author.uniqueId}_${postId}`,
bestAudio = 'm4a';
bestAudio; // will get defaulted to m4a later on in match-action
images = detail.imagePost?.images;
@ -96,7 +98,19 @@ export default async function(obj) {
if (images) {
let imageLinks = images
.map(i => i.imageURL.urlList.find(p => p.includes(".jpeg?")))
.map(url => ({ url }));
.map((url, i) => {
if (obj.alwaysProxy) url = createStream({
service: "tiktok",
type: "proxy",
u: url,
filename: `${filenameBase}_photo_${i + 1}.jpg`
})
return {
type: "photo",
url
}
});
return {
picker: imageLinks,

View File

@ -22,7 +22,7 @@ export default async function(input) {
let { subdomain } = psl.parse(input.url.hostname);
if (subdomain?.includes('.')) {
return { error: ['ErrorBrokenLink', 'tumblr'] }
return { error: "link.unsupported" };
} else if (subdomain === 'www' || subdomain === 'at') {
subdomain = undefined
}
@ -31,7 +31,7 @@ export default async function(input) {
const data = await request(domain, input.id);
const element = data?.response?.timeline?.elements?.[0];
if (!element) return { error: 'ErrorEmptyDownload' };
if (!element) return { error: "fetch.empty" };
const contents = [
...element.content,
@ -53,7 +53,8 @@ export default async function(input) {
title: fileMetadata.title,
author: fileMetadata.artist
},
isAudioOnly: true
isAudioOnly: true,
bestAudio: "mp3",
}
}
@ -66,5 +67,5 @@ export default async function(input) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "link.unsupported" }
}

View File

@ -1,11 +1,11 @@
import { env } from "../../config.js";
import { cleanString } from '../../sub/utils.js';
import { cleanString } from '../../misc/utils.js';
const gqlURL = "https://gql.twitch.tv/gql";
const clientIdHead = { "client-id": "kimne78kx3ncx6brgo4mv6wki5h1ko" };
export default async function (obj) {
let req_metadata = await fetch(gqlURL, {
const req_metadata = await fetch(gqlURL, {
method: "POST",
headers: clientIdHead,
body: JSON.stringify({
@ -30,16 +30,19 @@ export default async function (obj) {
}`
})
}).then(r => r.status === 200 ? r.json() : false).catch(() => {});
if (!req_metadata) return { error: 'ErrorCouldntFetch' };
let clipMetadata = req_metadata.data.clip;
if (!req_metadata) return { error: "fetch.fail" };
if (clipMetadata.durationSeconds > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
if (!clipMetadata.videoQualities || !clipMetadata.broadcaster)
return { error: 'ErrorEmptyDownload' };
const clipMetadata = req_metadata.data.clip;
let req_token = await fetch(gqlURL, {
if (clipMetadata.durationSeconds > env.durationLimit) {
return { error: "content.too_long" };
}
if (!clipMetadata.videoQualities || !clipMetadata.broadcaster) {
return { error: "fetch.empty" };
}
const req_token = await fetch(gqlURL, {
method: "POST",
headers: clientIdHead,
body: JSON.stringify([
@ -58,13 +61,13 @@ export default async function (obj) {
])
}).then(r => r.status === 200 ? r.json() : false).catch(() => {});
if (!req_token) return { error: 'ErrorCouldntFetch' };
if (!req_token) return { error: "fetch.fail" };
let formats = clipMetadata.videoQualities;
let format = formats.find(f => f.quality === obj.quality) || formats[0];
const formats = clipMetadata.videoQualities;
const format = formats.find(f => f.quality === obj.quality) || formats[0];
return {
type: "bridge",
type: "proxy",
urls: `${format.sourceURL}?${new URLSearchParams({
sig: req_token[0].data.clip.playbackAccessToken.signature,
token: req_token[0].data.clip.playbackAccessToken.value

View File

@ -101,11 +101,11 @@ const requestTweet = async(dispatcher, tweetId, token, cookie) => {
return result
}
export default async function({ id, index, toGif, dispatcher }) {
export default async function({ id, index, toGif, dispatcher, alwaysProxy }) {
const cookie = await getCookie('twitter');
let guestToken = await getGuestToken(dispatcher);
if (!guestToken) return { error: 'ErrorCouldntFetch' };
if (!guestToken) return { error: "fetch.fail" };
let tweet = await requestTweet(dispatcher, id, guestToken);
@ -119,22 +119,26 @@ export default async function({ id, index, toGif, dispatcher }) {
let tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
if (!tweetTypename) {
return { error: "fetch.empty" }
}
if (tweetTypename === "TweetUnavailable") {
const reason = tweet?.data?.tweetResult?.result?.reason;
switch(reason) {
case "Protected":
return { error: 'ErrorTweetProtected' }
return { error: "content.post.private" }
case "NsfwLoggedOut":
if (cookie) {
tweet = await requestTweet(dispatcher, id, guestToken, cookie);
tweet = await tweet.json();
tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
} else return { error: 'ErrorTweetNSFW' }
} else return { error: "content.post.age" }
}
}
if (!["Tweet", "TweetWithVisibilityResults"].includes(tweetTypename)) {
return { error: 'ErrorTweetUnavailable' }
return { error: "content.post.unavailable" }
}
let tweetResult = tweet.data.tweetResult.result,
@ -153,56 +157,77 @@ export default async function({ id, index, toGif, dispatcher }) {
media = [media[index]]
}
const getFileExt = (url) => new URL(url).pathname.split(".", 2)[1];
const proxyMedia = (u, filename) => createStream({
service: "twitter",
type: "proxy",
u, filename,
})
switch (media?.length) {
case undefined:
case 0:
return { error: 'ErrorNoVideosInTweet' };
return {
error: "fetch.empty"
}
case 1:
if (media[0].type === "photo") {
return {
type: "normal",
type: "proxy",
isPhoto: true,
filename: `twitter_${id}.${getFileExt(media[0].media_url_https)}`,
urls: `${media[0].media_url_https}?name=4096x4096`
}
}
return {
type: needsFixing(media[0]) ? "remux" : "normal",
type: needsFixing(media[0]) ? "remux" : "proxy",
urls: bestQuality(media[0].video_info.variants),
filename: `twitter_${id}.mp4`,
audioFilename: `twitter_${id}_audio`,
isGif: media[0].type === "animated_gif"
}
default:
const proxyThumb = (url, i) =>
proxyMedia(url, `twitter_${id}_${i + 1}.${getFileExt(url)}`);
const picker = media.map((content, i) => {
if (content.type === "photo") {
let url = `${content.media_url_https}?name=4096x4096`;
let proxiedImage = proxyThumb(url, i);
if (alwaysProxy) url = proxiedImage;
return {
type: "photo",
url,
thumb: url,
thumb: proxiedImage,
}
}
let url = bestQuality(content.video_info.variants);
const shouldRenderGif = content.type === 'animated_gif' && toGif;
const shouldRenderGif = content.type === "animated_gif" && toGif;
const videoFilename = `twitter_${id}_${i + 1}.mp4`;
let type = "video";
if (shouldRenderGif) type = "gif";
if (needsFixing(content) || shouldRenderGif) {
url = createStream({
service: 'twitter',
type: shouldRenderGif ? 'gif' : 'remux',
service: "twitter",
type: shouldRenderGif ? "gif" : "remux",
u: url,
filename: `twitter_${id}_${i + 1}.mp4`
filename: videoFilename,
})
} else if (alwaysProxy) {
url = proxyMedia(url, videoFilename);
}
return {
type,
url,
thumb: content.media_url_https
thumb: proxyThumb(content.media_url_https, i),
}
});
return { picker };

View File

@ -1,8 +1,8 @@
import { env } from "../../config.js";
import { cleanString, merge } from '../../sub/utils.js';
import HLS from "hls-parser";
import { env } from "../../config.js";
import { cleanString, merge } from '../../misc/utils.js';
const resolutionMatch = {
"3840": 2160,
"2732": 1440,
@ -63,7 +63,8 @@ const getDirectLink = (data, quality) => {
resolution: `${match.width}x${match.height}`,
qualityLabel: match.rendition,
extension: "mp4"
}
},
bestAudio: "mp3",
}
}
@ -73,25 +74,25 @@ const getHLS = async (configURL, obj) => {
const api = await fetch(configURL)
.then(r => r.json())
.catch(() => {});
if (!api) return { error: 'ErrorCouldntFetch' };
if (!api) return { error: "fetch.fail" };
if (api.video?.duration > env.durationLimit) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const urlMasterHLS = api.request?.files?.hls?.cdns?.akfire_interconnect_quic?.url;
if (!urlMasterHLS) return { error: 'ErrorCouldntFetch' }
if (!urlMasterHLS) return { error: "fetch.fail" };
const masterHLS = await fetch(urlMasterHLS)
.then(r => r.text())
.catch(() => {});
if (!masterHLS) return { error: 'ErrorCouldntFetch' };
if (!masterHLS) return { error: "fetch.fail" };
const variants = HLS.parse(masterHLS)?.variants?.sort(
(a, b) => Number(b.bandwidth) - Number(a.bandwidth)
);
if (!variants || variants.length === 0) return { error: 'ErrorEmptyDownload' };
if (!variants || variants.length === 0) return { error: "fetch.empty" };
let bestQuality;
@ -116,7 +117,7 @@ const getHLS = async (configURL, obj) => {
expandLink(audioPath)
]
} else if (obj.isAudioOnly) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
return {
@ -126,7 +127,8 @@ const getHLS = async (configURL, obj) => {
resolution: `${bestQuality.resolution.width}x${bestQuality.resolution.height}`,
qualityLabel: `${resolutionMatch[bestQuality.resolution.width]}p`,
extension: "mp4"
}
},
bestAudio: "mp3",
}
}
@ -143,7 +145,7 @@ export default async function(obj) {
}
if (!response) response = getDirectLink(info, quality);
if (!response) response = { error: 'ErrorEmptyDownload' };
if (!response) response = { error: "fetch.empty" };
if (response.error) {
return response;

View File

@ -3,7 +3,7 @@ export default async function(obj) {
.then(r => r.json())
.catch(() => {});
if (!post) return { error: 'ErrorEmptyDownload' };
if (!post) return { error: "fetch.empty" };
if (post.videoUrl) return {
urls: post.videoUrl.replace("http://", "https://"),
@ -11,5 +11,5 @@ export default async function(obj) {
audioFilename: `vine_${obj.id}_audio`
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@ -1,5 +1,5 @@
import { cleanString } from "../../misc/utils.js";
import { genericUserAgent, env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
const resolutions = ["2160", "1440", "1080", "720", "480", "360", "240"];
@ -7,22 +7,30 @@ export default async function(o) {
let html, url, quality = o.quality === "max" ? 2160 : o.quality;
html = await fetch(`https://vk.com/video${o.userId}_${o.videoId}`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.arrayBuffer()).catch(() => {});
headers: {
"user-agent": genericUserAgent
}
})
.then(r => r.arrayBuffer())
.catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
// decode cyrillic from windows-1251 because vk still uses apis from prehistoric times
let decoder = new TextDecoder('windows-1251');
html = decoder.decode(html);
if (!html.includes(`{"lang":`)) return { error: 'ErrorEmptyDownload' };
if (!html.includes(`{"lang":`)) return { error: "fetch.empty" };
let js = JSON.parse('{"lang":' + html.split(`{"lang":`)[1].split(']);')[0]);
if (Number(js.mvData.is_active_live) !== 0) return { error: 'ErrorLiveVideo' };
if (js.mvData.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
if (Number(js.mvData.is_active_live) !== 0) {
return { error: "content.video.live" };
}
if (js.mvData.duration > env.durationLimit) {
return { error: "content.too_long" };
}
for (let i in resolutions) {
if (js.player.params[0][`url${resolutions[i]}`]) {
@ -51,5 +59,5 @@ export default async function(o) {
extension: "mp4"
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@ -3,7 +3,7 @@ import { fetch } from "undici";
import { Innertube, Session } from "youtubei.js";
import { env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
import { getCookie, updateCookieValues } from "../cookie/manager.js";
const PLAYER_REFRESH_PERIOD = 1000 * 60 * 15; // ms
@ -18,8 +18,8 @@ const codecMatch = {
},
av1: {
videoCodec: "av01",
audioCodec: "mp4a",
container: "mp4"
audioCodec: "opus",
container: "webm"
},
vp9: {
videoCodec: "vp9",
@ -110,7 +110,9 @@ export default async function(o) {
);
} catch(e) {
if (e.message?.endsWith("decipher algorithm")) {
return { error: "ErrorYoutubeDecipher" }
return { error: "youtube.decipher" }
} else if (e.message?.includes("refresh access token")) {
return { error: "youtube.token_expired" }
} else throw e;
}
@ -130,44 +132,60 @@ export default async function(o) {
try {
info = await yt.getBasicInfo(o.id, yt.session.logged_in ? 'ANDROID' : 'IOS');
} catch(e) {
if (e?.message === 'This video is unavailable') {
return { error: 'ErrorCouldntFetch' };
if (e?.info?.reason === "This video is private") {
return { error: "content.video.private" };
} else if (e?.message === "This video is unavailable") {
return { error: "content.video.unavailable" };
} else {
return { error: 'ErrorCantConnectToServiceAPI' };
return { error: "fetch.fail" };
}
}
if (!info) return { error: 'ErrorCantConnectToServiceAPI' };
if (!info) return { error: "fetch.fail" };
const playability = info.playability_status;
const basicInfo = info.basic_info;
if (playability.status === 'LOGIN_REQUIRED') {
if (playability.reason.endsWith('bot')) {
return { error: 'ErrorYTLogin' }
if (playability.status === "LOGIN_REQUIRED") {
if (playability.reason.endsWith("bot")) {
return { error: "youtube.login" }
}
if (playability.reason.endsWith('age')) {
return { error: 'ErrorYTAgeRestrict' }
if (playability.reason.endsWith("age")) {
return { error: "content.video.age" }
}
if (playability?.error_screen?.reason?.text === "Private video") {
return { error: "content.video.private" }
}
}
if (playability.status === "UNPLAYABLE" && playability.reason.endsWith('request limit.')) {
return { error: 'ErrorYTRateLimit' }
}
if (playability.status !== 'OK') return { error: 'ErrorYTUnavailable' };
if (basicInfo.is_live) return { error: 'ErrorLiveVideo' };
if (playability.status === "UNPLAYABLE") {
if (playability?.reason?.endsWith("request limit.")) {
return { error: "fetch.rate" }
}
if (playability?.error_screen?.subreason?.text?.endsWith("in your country")) {
return { error: "content.video.region" }
}
if (playability?.error_screen?.reason?.text === "Private video") {
return { error: "content.video.private" }
}
}
if (playability.status !== "OK") {
return { error: "content.video.unavailable" };
}
if (basicInfo.is_live) {
return { error: "content.video.live" };
}
// return a critical error if returned video is "Video Not Available"
// or a similar stub by youtube
if (basicInfo.id !== o.id) {
return {
error: 'ErrorCantConnectToServiceAPI',
error: "fetch.fail",
critical: true
}
}
let bestQuality, hasAudio;
const filterByCodec = (formats) =>
formats
.filter(e =>
@ -183,16 +201,18 @@ export default async function(o) {
adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats)
}
bestQuality = adaptive_formats.find(i => i.has_video && i.content_length);
hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
let bestQuality;
if (bestQuality) bestQuality = qual(bestQuality);
const bestVideo = adaptive_formats.find(i => i.has_video && i.content_length);
const hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
if (bestVideo) bestQuality = qual(bestVideo);
if ((!bestQuality && !o.isAudioOnly) || !hasAudio)
return { error: 'ErrorYTTryOtherCodec' };
return { error: "youtube.codec" };
if (basicInfo.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
const checkBestAudio = (i) => (i.has_audio && !i.has_video);
@ -207,7 +227,7 @@ export default async function(o) {
&& i.audio_track
)
if (dubbedAudio) {
if (dubbedAudio && !dubbedAudio?.audio_track?.audio_is_default) {
audio = dubbedAudio;
isDubbed = true;
}
@ -223,11 +243,13 @@ export default async function(o) {
}
if (basicInfo?.short_description?.startsWith("Provided to YouTube by")) {
let descItems = basicInfo.short_description.split("\n\n");
fileMetadata.album = descItems[2];
fileMetadata.copyright = descItems[3];
if (descItems[4].startsWith("Released on:")) {
fileMetadata.date = descItems[4].replace("Released on: ", '').trim()
let descItems = basicInfo.short_description.split("\n\n", 5);
if (descItems.length === 5) {
fileMetadata.album = descItems[2];
fileMetadata.copyright = descItems[3];
if (descItems[4].startsWith("Released on:")) {
fileMetadata.date = descItems[4].replace("Released on: ", '').trim();
}
}
}
@ -240,7 +262,7 @@ export default async function(o) {
}
if (audio && o.isAudioOnly) return {
type: "render",
type: "audio",
isAudioOnly: true,
urls: audio.decipher(yt.session.player),
filenameAttributes: filenameAttributes,
@ -256,9 +278,10 @@ export default async function(o) {
let match, type, urls;
if (!o.isAudioOnly && !o.isAudioMuted && format === 'h264') {
// prefer good premuxed videos if available
if (!o.isAudioOnly && !o.isAudioMuted && format === "h264" && bestVideo.fps <= 30) {
match = info.streaming_data.formats.find(checkSingle);
type = "bridge";
type = "proxy";
urls = match?.decipher(yt.session.player);
}
@ -266,7 +289,7 @@ export default async function(o) {
if (!match && video && audio) {
match = video;
type = "render";
type = "merge";
urls = [
video.decipher(yt.session.player),
audio.decipher(yt.session.player)
@ -286,5 +309,5 @@ export default async function(o) {
}
}
return { error: 'ErrorYTTryOtherCodec' }
return { error: "fetch.fail" }
}

View File

@ -1,6 +1,9 @@
import { services } from "../config.js";
import { strict as assert } from "node:assert";
import psl from "psl";
import { strict as assert } from "node:assert";
import { env } from "../config.js";
import { services } from "./service-config.js";
import { friendlyServiceName } from "./service-alias.js";
function aliasURL(url) {
assert(url instanceof URL);
@ -54,6 +57,7 @@ function aliasURL(url) {
url = new URL(`https://bilibili.com/_tv${url.pathname}`);
}
break;
case "b23":
if (url.hostname === 'b23.tv' && parts.length === 2) {
url = new URL(`https://bilibili.com/_shortLink/${parts[1]}`)
@ -64,6 +68,7 @@ function aliasURL(url) {
if (url.hostname === 'dai.ly' && parts.length === 2) {
url = new URL(`https://dailymotion.com/video/${parts[1]}`)
}
break;
case "facebook":
case "fb":
@ -115,6 +120,11 @@ function cleanURL(url) {
limitQuery('p')
}
break;
case "twitter":
if (url.searchParams.get('post_id')) {
limitQuery('post_id')
}
break;
}
if (stripQuery) {
@ -159,8 +169,12 @@ export function extract(url) {
const host = getHostIfValid(url);
if (!host || !services[host].enabled) {
return null;
if (!host) {
return { error: "link.invalid" };
}
if (!env.enabledServices.has(host)) {
return { error: "service.disabled" };
}
let patternMatch;
@ -175,8 +189,13 @@ export function extract(url) {
}
if (!patternMatch) {
return null;
return {
error: "link.unsupported",
context: {
service: friendlyServiceName(host),
}
};
}
return { host, patternMatch };
}
}

View File

@ -0,0 +1,205 @@
import { env } from "../config.js";
import { readFile } from "node:fs/promises";
import { Yellow } from "../misc/console-text.js";
import ip from "ipaddr.js";
// this function is a modified variation of code
// from https://stackoverflow.com/a/32402438/14855621
const generateWildcardRegex = rule => {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$");
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
let keys = {};
const ALLOWED_KEYS = new Set(['name', 'ips', 'userAgents', 'limit']);
/* Expected format pseudotype:
** type KeyFileContents = Record<
** UUIDv4String,
** {
** name?: string,
** limit?: number | "unlimited",
** ips?: CIDRString[],
** userAgents?: string[]
** }
** >;
*/
const validateKeys = (input) => {
if (typeof input !== 'object' || input === null) {
throw "input is not an object";
}
if (Object.keys(input).some(x => !UUID_REGEX.test(x))) {
throw "key file contains invalid key(s)";
}
Object.values(input).forEach(details => {
if (typeof details !== 'object' || details === null) {
throw "some key(s) are incorrectly configured";
}
const unexpected_key = Object.keys(details).find(k => !ALLOWED_KEYS.has(k));
if (unexpected_key) {
throw "detail object contains unexpected key: " + unexpected_key;
}
if (details.limit && details.limit !== 'unlimited') {
if (typeof details.limit !== 'number')
throw "detail object contains invalid limit (not a number)";
else if (details.limit < 1)
throw "detail object contains invalid limit (not a positive number)";
}
if (details.ips) {
if (!Array.isArray(details.ips))
throw "details object contains value for `ips` which is not an array";
const invalid_ip = details.ips.find(
addr => typeof addr !== 'string' || (!ip.isValidCIDR(addr) && !ip.isValid(addr))
);
if (invalid_ip) {
throw "`ips` in details contains an invalid IP or CIDR range: " + invalid_ip;
}
}
if (details.userAgents) {
if (!Array.isArray(details.userAgents))
throw "details object contains value for `userAgents` which is not an array";
const invalid_ua = details.userAgents.find(ua => typeof ua !== 'string');
if (invalid_ua) {
throw "`userAgents` in details contains an invalid user agent: " + invalid_ua;
}
}
});
}
const formatKeys = (keyData) => {
const formatted = {};
for (let key in keyData) {
const data = keyData[key];
key = key.toLowerCase();
formatted[key] = {};
if (data.limit) {
if (data.limit === "unlimited") {
data.limit = Infinity;
}
formatted[key].limit = data.limit;
}
if (data.ips) {
formatted[key].ips = data.ips.map(addr => {
if (ip.isValid(addr)) {
return [ ip.parse(addr), 32 ];
}
return ip.parseCIDR(addr);
});
}
if (data.userAgents) {
formatted[key].userAgents = data.userAgents.map(generateWildcardRegex);
}
}
return formatted;
}
const loadKeys = async (source) => {
let updated;
if (source.protocol === 'file:') {
const pathname = source.pathname === '/' ? '' : source.pathname;
updated = JSON.parse(
await readFile(
decodeURIComponent(source.host + pathname),
'utf8'
)
);
} else {
updated = await fetch(source).then(a => a.json());
}
validateKeys(updated);
keys = formatKeys(updated);
}
const wrapLoad = (url) => {
loadKeys(url)
.then(() => {})
.catch((e) => {
console.error(`${Yellow('[!]')} Failed loading API keys at ${new Date().toISOString()}.`);
console.error('Error:', e);
})
}
const err = (reason) => ({ success: false, error: reason });
export const validateAuthorization = (req) => {
const authHeader = req.get('Authorization');
if (typeof authHeader !== 'string') {
return err("missing");
}
const [ authType, keyString ] = authHeader.split(' ', 2);
if (authType.toLowerCase() !== 'api-key') {
return err("not_api_key");
}
if (!UUID_REGEX.test(keyString) || `${authType} ${keyString}` !== authHeader) {
return err("invalid");
}
const matchingKey = keys[keyString.toLowerCase()];
if (!matchingKey) {
return err("not_found");
}
if (matchingKey.ips) {
let addr;
try {
addr = ip.parse(req.ip);
} catch {
return err("invalid_ip");
}
const ip_allowed = matchingKey.ips.some(
([ allowed, size ]) => {
return addr.kind() === allowed.kind()
&& addr.match(allowed, size);
}
);
if (!ip_allowed) {
return err("ip_not_allowed");
}
}
if (matchingKey.userAgents) {
const userAgent = req.get('User-Agent');
if (!matchingKey.userAgents.some(regex => regex.test(userAgent))) {
return err("ua_not_allowed");
}
}
req.rateLimitKey = keyString.toLowerCase();
req.rateLimitMax = matchingKey.limit;
return { success: true };
}
export const setup = (url) => {
wrapLoad(url);
if (env.keyReloadInterval > 0) {
setInterval(() => wrapLoad(url), env.keyReloadInterval * 1000);
}
}

59
api/src/security/jwt.js Normal file
View File

@ -0,0 +1,59 @@
import { nanoid } from "nanoid";
import { createHmac } from "crypto";
import { env } from "../config.js";
const toBase64URL = (b) => Buffer.from(b).toString("base64url");
const fromBase64URL = (b) => Buffer.from(b, "base64url").toString();
const makeHmac = (header, payload) =>
createHmac("sha256", env.jwtSecret)
.update(`${header}.${payload}`)
.digest("base64url");
const generate = () => {
const exp = Math.floor(new Date().getTime() / 1000) + env.jwtLifetime;
const header = toBase64URL(JSON.stringify({
alg: "HS256",
typ: "JWT"
}));
const payload = toBase64URL(JSON.stringify({
jti: nanoid(8),
exp,
}));
const signature = makeHmac(header, payload);
return {
token: `${header}.${payload}.${signature}`,
exp: env.jwtLifetime - 2,
};
}
const verify = (jwt) => {
const [header, payload, signature] = jwt.split(".", 3);
const timestamp = Math.floor(new Date().getTime() / 1000);
if ([header, payload, signature].join('.') !== jwt) {
return false;
}
const verifySignature = makeHmac(header, payload);
if (verifySignature !== signature) {
return false;
}
if (timestamp >= JSON.parse(fromBase64URL(payload)).exp) {
return false;
}
return true;
}
export default {
generate,
verify,
}

View File

@ -0,0 +1,19 @@
import { env } from "../config.js";
export const verifyTurnstileToken = async (turnstileResponse, ip) => {
const result = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
secret: env.turnstileSecret,
response: turnstileResponse,
remoteip: ip,
}),
})
.then(r => r.json())
.catch(() => {});
return !!result?.success;
}

View File

@ -1,5 +1,5 @@
import { createInternalStream } from './manage.js';
import HLS from 'hls-parser';
import HLS from "hls-parser";
import { createInternalStream } from "./manage.js";
function getURL(url) {
try {

View File

@ -1,7 +1,7 @@
import { request } from 'undici';
import { Readable } from 'node:stream';
import { closeRequest, getHeaders, pipe } from './shared.js';
import { handleHlsPlaylist, isHlsRequest } from './internal-hls.js';
import { request } from "undici";
import { Readable } from "node:stream";
import { closeRequest, getHeaders, pipe } from "./shared.js";
import { handleHlsPlaylist, isHlsRequest } from "./internal-hls.js";
const CHUNK_SIZE = BigInt(8e6); // 8 MB
const min = (a, b) => a < b ? a : b;
@ -28,7 +28,7 @@ async function* readChunks(streamInfo, size) {
if (received < expected / 2n) {
closeRequest(streamInfo.controller);
}
for await (const data of chunk.body) {
yield data;
}
@ -64,7 +64,7 @@ async function handleYoutubeStream(streamInfo, res) {
}
signal.addEventListener('abort', abortGenerator);
const stream = Readable.from(generator);
for (const headerName of ['content-type', 'content-length']) {
@ -119,4 +119,4 @@ export function internalStream(streamInfo, res) {
}
return handleGenericStream(streamInfo, res);
}
}

View File

@ -1,12 +1,13 @@
import NodeCache from "node-cache";
import { randomBytes } from "crypto";
import { nanoid } from "nanoid";
import { randomBytes } from "crypto";
import { strict as assert } from "assert";
import { setMaxListeners } from "node:events";
import { decryptStream, encryptStream, generateHmac } from "../sub/crypto.js";
import { env } from "../config.js";
import { strict as assert } from "assert";
import { closeRequest } from "./shared.js";
import { decryptStream, encryptStream, generateHmac } from "../misc/crypto.js";
// optional dependency
const freebind = env.freebindCIDR && await import('freebind').catch(() => {});
@ -21,7 +22,7 @@ streamCache.on("expired", (key) => {
streamCache.del(key);
})
const internalStreamCache = {};
const internalStreamCache = new Map();
const hmacSalt = randomBytes(64).toString('hex');
export function createStream(obj) {
@ -36,13 +37,15 @@ export function createStream(obj) {
urls: obj.u,
service: obj.service,
filename: obj.filename,
audioFormat: obj.audioFormat,
isAudioOnly: !!obj.isAudioOnly,
requestIP: obj.requestIP,
headers: obj.headers,
copy: !!obj.copy,
mute: !!obj.mute,
metadata: obj.fileMetadata || false,
requestIP: obj.requestIP
audioBitrate: obj.audioBitrate,
audioCopy: !!obj.audioCopy,
audioFormat: obj.audioFormat,
};
streamCache.set(
@ -50,7 +53,7 @@ export function createStream(obj) {
encryptStream(streamData, iv, secret)
)
let streamLink = new URL('/api/stream', env.apiURL);
let streamLink = new URL('/tunnel', env.apiURL);
const params = {
'id': streamID,
@ -68,7 +71,7 @@ export function createStream(obj) {
}
export function getInternalStream(id) {
return internalStreamCache[id];
return internalStreamCache.get(id);
}
export function createInternalStream(url, obj = {}) {
@ -83,7 +86,7 @@ export function createInternalStream(url, obj = {}) {
let controller = obj.controller;
if (!controller) {
controller = new AbortController();
controller = new AbortController();
setMaxListeners(Infinity, controller.signal);
}
@ -92,15 +95,15 @@ export function createInternalStream(url, obj = {}) {
headers = new Map(Object.entries(obj.headers));
}
internalStreamCache[streamID] = {
internalStreamCache.set(streamID, {
url,
service: obj.service,
headers,
controller,
dispatcher
};
});
let streamLink = new URL('/api/istream', `http://127.0.0.1:${env.apiPort}`);
let streamLink = new URL('/itunnel', `http://127.0.0.1:${env.apiPort}`);
streamLink.searchParams.set('id', streamID);
const cleanup = () => {
@ -121,9 +124,9 @@ export function destroyInternalStream(url) {
const id = url.searchParams.get('id');
if (internalStreamCache[id]) {
closeRequest(internalStreamCache[id].controller);
delete internalStreamCache[id];
if (internalStreamCache.has(id)) {
closeRequest(getInternalStream(id)?.controller);
internalStreamCache.delete(id);
}
}

View File

@ -42,4 +42,4 @@ export function pipe(from, to, done) {
.on('close', done);
from.pipe(to);
}
}

33
api/src/stream/stream.js Normal file
View File

@ -0,0 +1,33 @@
import stream from "./types.js";
import { closeResponse } from "./shared.js";
import { internalStream } from "./internal.js";
export default async function(res, streamInfo) {
try {
switch (streamInfo.type) {
case "proxy":
return await stream.proxy(streamInfo, res);
case "internal":
return internalStream(streamInfo, res);
case "merge":
return stream.merge(streamInfo, res);
case "remux":
case "mute":
return stream.remux(streamInfo, res);
case "audio":
return stream.convertAudio(streamInfo, res);
case "gif":
return stream.convertGif(streamInfo, res);
}
closeResponse(res);
} catch {
closeResponse(res);
}
}

View File

@ -3,35 +3,42 @@ import ffmpeg from "ffmpeg-static";
import { spawn } from "child_process";
import { create as contentDisposition } from "content-disposition-header";
import { metadataManager } from "../sub/utils.js";
import { env } from "../config.js";
import { metadataManager } from "../misc/utils.js";
import { destroyInternalStream } from "./manage.js";
import { env, ffmpegArgs, hlsExceptions } from "../config.js";
import { hlsExceptions } from "../processing/service-config.js";
import { getHeaders, closeRequest, closeResponse, pipe } from "./shared.js";
function toRawHeaders(headers) {
const ffmpegArgs = {
webm: ["-c:v", "copy", "-c:a", "copy"],
mp4: ["-c:v", "copy", "-c:a", "copy", "-movflags", "faststart+frag_keyframe+empty_moov"],
m4a: ["-movflags", "frag_keyframe+empty_moov"],
gif: ["-vf", "scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", "-loop", "0"]
}
const toRawHeaders = (headers) => {
return Object.entries(headers)
.map(([key, value]) => `${key}: ${value}\r\n`)
.join('');
}
function killProcess(p) {
// ask the process to terminate itself gracefully
p?.kill('SIGTERM');
const killProcess = (p) => {
p?.kill('SIGTERM'); // ask the process to terminate itself gracefully
setTimeout(() => {
if (p?.exitCode === null)
// brutally murder the process if it didn't quit
p?.kill('SIGKILL');
p?.kill('SIGKILL'); // brutally murder the process if it didn't quit
}, 5000);
}
function getCommand(args) {
const getCommand = (args) => {
if (typeof env.processingPriority === 'number' && !isNaN(env.processingPriority)) {
return ['nice', ['-n', env.processingPriority.toString(), ffmpeg, ...args]]
}
return [ffmpeg, args]
}
export async function streamDefault(streamInfo, res) {
const proxy = async (streamInfo, res) => {
const abortController = new AbortController();
const shutdown = () => (
closeRequest(abortController),
@ -40,19 +47,21 @@ export async function streamDefault(streamInfo, res) {
);
try {
let filename = streamInfo.filename;
if (streamInfo.isAudioOnly) {
filename = `${streamInfo.filename}.${streamInfo.audioFormat}`
}
res.setHeader('Content-disposition', contentDisposition(filename));
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.setHeader('Content-disposition', contentDisposition(streamInfo.filename));
const { body: stream, headers } = await request(streamInfo.urls, {
headers: getHeaders(streamInfo.service),
const { body: stream, headers, statusCode } = await request(streamInfo.urls, {
headers: {
...getHeaders(streamInfo.service),
Range: streamInfo.range
},
signal: abortController.signal,
maxRedirections: 16
});
for (const headerName of ['content-type', 'content-length']) {
res.status(statusCode);
for (const headerName of ['accept-ranges', 'content-type', 'content-length']) {
if (headers[headerName]) {
res.setHeader(headerName, headers[headerName]);
}
@ -64,7 +73,7 @@ export async function streamDefault(streamInfo, res) {
}
}
export function streamLiveRender(streamInfo, res) {
const merge = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
@ -124,61 +133,7 @@ export function streamLiveRender(streamInfo, res) {
}
}
export function streamAudioOnly(streamInfo, res) {
let process;
const shutdown = () => (
killProcess(process),
closeResponse(res),
destroyInternalStream(streamInfo.urls)
);
try {
let args = [
'-loglevel', '-8',
'-headers', toRawHeaders(getHeaders(streamInfo.service)),
]
if (streamInfo.service === "twitter") {
args.push('-seekable', '0');
}
args.push(
'-i', streamInfo.urls,
'-vn'
)
if (streamInfo.metadata) {
args = args.concat(metadataManager(streamInfo.metadata))
}
args = args.concat(ffmpegArgs[streamInfo.copy ? 'copy' : 'audio']);
if (ffmpegArgs[streamInfo.audioFormat]) {
args = args.concat(ffmpegArgs[streamInfo.audioFormat])
}
args.push('-f', streamInfo.audioFormat === "m4a" ? "ipod" : streamInfo.audioFormat, 'pipe:3');
process = spawn(...getCommand(args), {
windowsHide: true,
stdio: [
'inherit', 'inherit', 'inherit',
'pipe'
],
});
const [,,, muxOutput] = process.stdio;
res.setHeader('Connection', 'keep-alive');
res.setHeader('Content-Disposition', contentDisposition(`${streamInfo.filename}.${streamInfo.audioFormat}`));
pipe(muxOutput, res, shutdown);
res.on('finish', shutdown);
} catch {
shutdown();
}
}
export function streamVideoOnly(streamInfo, res) {
const remux = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
@ -198,15 +153,18 @@ export function streamVideoOnly(streamInfo, res) {
args.push(
'-i', streamInfo.urls,
'-c', 'copy'
'-c:v', 'copy',
)
if (streamInfo.mute) {
args.push('-an')
if (streamInfo.type === "mute") {
args.push('-an');
}
if (hlsExceptions.includes(streamInfo.service)) {
args.push('-bsf:a', 'aac_adtstoasc')
if (streamInfo.type !== "mute") {
args.push('-c:a', 'aac')
}
args.push('-bsf:a', 'aac_adtstoasc');
}
let format = streamInfo.filename.split('.')[streamInfo.filename.split('.').length - 1];
@ -238,7 +196,74 @@ export function streamVideoOnly(streamInfo, res) {
}
}
export function convertToGif(streamInfo, res) {
const convertAudio = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
closeResponse(res),
destroyInternalStream(streamInfo.urls)
);
try {
let args = [
'-loglevel', '-8',
'-headers', toRawHeaders(getHeaders(streamInfo.service)),
]
if (streamInfo.service === "twitter") {
args.push('-seekable', '0');
}
args.push(
'-i', streamInfo.urls,
'-vn'
)
if (streamInfo.audioCopy) {
args.push("-c:a", "copy")
} else {
args.push("-b:a", `${streamInfo.audioBitrate}k`)
}
if (streamInfo.audioFormat === "mp3" && streamInfo.audioBitrate === "8") {
args.push("-ar", "12000");
}
if (streamInfo.audioFormat === "opus") {
args.push("-vbr", "off")
}
if (ffmpegArgs[streamInfo.audioFormat]) {
args = args.concat(ffmpegArgs[streamInfo.audioFormat])
}
if (streamInfo.metadata) {
args = args.concat(metadataManager(streamInfo.metadata))
}
args.push('-f', streamInfo.audioFormat === "m4a" ? "ipod" : streamInfo.audioFormat, 'pipe:3');
process = spawn(...getCommand(args), {
windowsHide: true,
stdio: [
'inherit', 'inherit', 'inherit',
'pipe'
],
});
const [,,, muxOutput] = process.stdio;
res.setHeader('Connection', 'keep-alive');
res.setHeader('Content-Disposition', contentDisposition(streamInfo.filename));
pipe(muxOutput, res, shutdown);
res.on('finish', shutdown);
} catch {
shutdown();
}
}
const convertGif = (streamInfo, res) => {
let process;
const shutdown = () => (killProcess(process), closeResponse(res));
@ -252,7 +277,7 @@ export function convertToGif(streamInfo, res) {
}
args.push('-i', streamInfo.urls);
args = args.concat(ffmpegArgs["gif"]);
args = args.concat(ffmpegArgs.gif);
args.push('-f', "gif", 'pipe:3');
process = spawn(...getCommand(args), {
@ -266,7 +291,7 @@ export function convertToGif(streamInfo, res) {
const [,,, muxOutput] = process.stdio;
res.setHeader('Connection', 'keep-alive');
res.setHeader('Content-Disposition', contentDisposition(streamInfo.filename.split('.')[0] + ".gif"));
res.setHeader('Content-Disposition', contentDisposition(streamInfo.filename));
pipe(muxOutput, res, shutdown);
@ -276,3 +301,11 @@ export function convertToGif(streamInfo, res) {
shutdown();
}
}
export default {
proxy,
merge,
remux,
convertAudio,
convertGif,
}

View File

@ -1,5 +1,5 @@
import { Innertube } from 'youtubei.js';
import { Red } from '../modules/sub/consoleText.js'
import { Red } from '../misc/console-text.js'
const bail = (...msg) => {
console.error(...msg);

View File

@ -1,7 +1,7 @@
import { existsSync, unlinkSync, appendFileSync } from "fs";
import { createInterface } from "readline";
import { Cyan, Bright } from "./sub/consoleText.js";
import { loadJSON } from "./sub/loadFromFs.js";
import { Cyan, Bright } from "../misc/console-text.js";
import { loadJSON } from "../misc/load-from-fs.js";
import { execSync } from "child_process";
const { version } = loadJSON("./package.json");
@ -19,7 +19,7 @@ let final = () => {
}
console.log(Bright("\nAwesome! I've created a fresh .env file for you."));
console.log(`${Bright("Now I'll run")} ${Cyan("npm install")} ${Bright("to install all dependencies. It shouldn't take long.\n\n")}`);
execSync('npm install', { stdio: [0, 1, 2] });
execSync('pnpm install', { stdio: [0, 1, 2] });
console.log(`\n\n${Cyan("All done!\n")}`);
console.log(Bright("You can re-run this script at any time to update the configuration."));
console.log(Bright("\nYou're now ready to start cobalt. Simply run ") + Cyan("npm start") + Bright('!\nHave fun :)'));

View File

@ -1,20 +1,21 @@
import { env } from "../modules/config.js";
import { runTest } from "../modules/test.js";
import { loadLoc } from "../localization/manager.js";
import { loadJSON } from "../modules/sub/loadFromFs.js";
import { Red, Bright } from "../modules/sub/consoleText.js";
import { env } from "../config.js";
import { runTest } from "../misc/run-test.js";
import { loadJSON } from "../misc/load-from-fs.js";
import { Red, Bright } from "../misc/console-text.js";
import { randomizeCiphers } from "../misc/randomize-ciphers.js";
import { services } from "../processing/service-config.js";
const tests = loadJSON('./src/util/tests.json');
const services = loadJSON('./src/modules/processing/servicesConfig.json');
// services that are known to frequently fail due to external
// factors (e.g. rate limiting)
const finnicky = new Set(['bilibili', 'instagram', 'youtube'])
const finnicky = new Set(['bilibili', 'instagram', 'facebook', 'youtube'])
const action = process.argv[2];
switch (action) {
case "get-services":
const fromConfig = Object.keys(services.config);
const fromConfig = Object.keys(services);
const missingTests = fromConfig.filter(
service => !tests[service] || tests[service].length === 0
@ -38,9 +39,9 @@ switch (action) {
console.error('no such service:', service);
}
await loadLoc();
env.streamLifespan = 10000;
env.apiURL = 'http://x';
randomizeCiphers();
for (const test of tests[service]) {
const { name, url, params, expected } = test;
@ -78,4 +79,4 @@ switch (action) {
default:
console.error('invalid action:', action);
process.exitCode = 1;
}
}

View File

@ -1,12 +1,11 @@
import "dotenv/config";
import "../modules/sub/alias-envs.js";
import { services } from "../modules/config.js";
import { extract } from "../modules/processing/url.js";
import match from "../modules/processing/match.js";
import { loadJSON } from "../modules/sub/loadFromFs.js";
import { normalizeRequest } from "../modules/processing/request.js";
import { env } from "../modules/config.js";
import { services } from "../processing/service-config.js";
import { extract } from "../processing/url.js";
import match from "../processing/match.js";
import { loadJSON } from "../misc/load-from-fs.js";
import { normalizeRequest } from "../processing/request.js";
import { env } from "../config.js";
env.apiURL = 'http://localhost:9000'
let tests = loadJSON('./src/util/tests.json');
@ -29,20 +28,26 @@ for (let i in services) {
console.log(`\nRunning tests for ${i}...\n`)
for (let k = 0; k < tests[i].length; k++) {
let test = tests[i][k];
console.log(`Running test ${k+1}: ${test.name}`);
console.log('params:');
let params = {...{url: test.url}, ...test.params};
console.log(params);
let chck = normalizeRequest(params);
if (chck) {
let chck = await normalizeRequest(params);
if (chck.success) {
chck = chck.data;
const parsed = extract(chck.url);
if (parsed === null) {
throw `Invalid URL: ${chck.url}`
}
let j = await match(parsed.host, parsed.patternMatch, "en", chck);
let j = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: chck,
});
console.log('\nReceived:');
console.log(j)
if (j.status === test.expected.code && j.body.status === test.expected.status) {

1497
api/src/util/tests.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +1,110 @@
# cobalt api documentation
this document provides info about methods and acceptable variables for all cobalt api requests.
this document provides info about methods and acceptable variables for all cobalt api requests.
> if you are looking for the documentation for the old (7.x) api, you can find
> it [here](https://github.com/imputnet/cobalt/blob/7/docs/api.md)
<!-- TODO: authorization -->
## POST: `/`
cobalt's main processing endpoint.
request body type: `application/json`
response body type: `application/json`
```
👍 you can use api.cobalt.tools in your projects for free, just don't be an asshole.
```
## POST: `/api/json`
cobalt's main processing endpoint.
request body type: `application/json`
response body type: `application/json`
```
⚠️ you must include Accept and Content-Type headers with every POST /api/json request.
⚠️ you must include Accept and Content-Type headers with every `POST /` request.
Accept: application/json
Content-Type: application/json
```
### request body variables
| key | type | variables | default | description |
|:------------------|:----------|:-----------------------------------|:----------|:--------------------------------------------------------------------------------|
| `url` | `string` | URL encoded as URI | `null` | **must** be included in every request. |
| `vCodec` | `string` | `h264 / av1 / vp9` | `h264` | applies only to youtube downloads. `h264` is recommended for phones. |
| `vQuality` | `string` | `144 / ... / 2160 / max` | `720` | `720` quality is recommended for phones. |
| `aFormat` | `string` | `best / mp3 / ogg / wav / opus` | `mp3` | |
| `filenamePattern` | `string` | `classic / pretty / basic / nerdy` | `classic` | changes the way files are named. previews can be seen in the web app. |
| `isAudioOnly` | `boolean` | `true / false` | `false` | |
| `isTTFullAudio` | `boolean` | `true / false` | `false` | enables download of original sound used in a tiktok video. |
| `isAudioMuted` | `boolean` | `true / false` | `false` | disables audio track in video downloads. |
| `dubLang` | `boolean` | `true / false` | `false` | backend uses Accept-Language header for youtube video audio tracks when `true`. |
| `disableMetadata` | `boolean` | `true / false` | `false` | disables file metadata when set to `true`. |
| `twitterGif` | `boolean` | `true / false` | `false` | changes whether twitter gifs are converted to .gif |
| `tiktokH265` | `boolean` | `true / false` | `false` | changes whether 1080p h265 videos are preferred or not. |
### request body
| key | type | expected value(s) | default | description |
|:-----------------------------|:----------|:-----------------------------------|:----------|:--------------------------------------------------------------------------------|
| `url` | `string` | URL to download | -- | **must** be included in every request. |
| `videoQuality` | `string` | `144 / ... / 2160 / 4320 / max` | `1080` | `720` quality is recommended for phones. |
| `audioFormat` | `string` | `best / mp3 / ogg / wav / opus` | `mp3` | |
| `audioBitrate` | `string` | `320 / 256 / 128 / 96 / 64 / 8` | `128` | specifies the bitrate to use for the audio. applies only to audio conversion. |
| `filenameStyle` | `string` | `classic / pretty / basic / nerdy` | `classic` | changes the way files are named. previews can be seen in the web app. |
| `downloadMode` | `string` | `auto / audio / mute` | `auto` | `audio` downloads only the audio, `mute` skips the audio track in videos. |
| `youtubeVideoCodec` | `string` | `h264 / av1 / vp9` | `h264` | `h264` is recommended for phones. |
| `youtubeDubLang` | `string` | `en / ru / cs / ja / ...` | -- | specifies the language of audio to download, when the youtube video is dubbed |
| `youtubeDubBrowserLang` | `boolean` | `true / false` | `false` | uses value from the Accept-Language header for `youtubeDubLang`. |
| `alwaysProxy` | `boolean` | `true / false` | `false` | tunnels all downloads through the processing server, even when not necessary. |
| `disableMetadata` | `boolean` | `true / false` | `false` | disables file metadata when set to `true`. |
| `tiktokFullAudio` | `boolean` | `true / false` | `false` | enables download of original sound used in a tiktok video. |
| `tiktokH265` | `boolean` | `true / false` | `false` | changes whether 1080p h265 videos are preferred or not. |
| `twitterGif` | `boolean` | `true / false` | `true` | changes whether twitter gifs are converted to .gif |
### response body variables
| key | type | variables |
### response
the response will always be a JSON object containing the `status` key, which will be one of:
- `error` - something went wrong
- `picker` - we have multiple items to choose from
- `redirect` - you are being redirected to the direct service URL
- `tunnel` - cobalt is proxying the download for you
### tunnel/redirect response
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `status` | `string` | `error / redirect / stream / success / rate-limit / picker` |
| `text` | `string` | various text, mostly used for errors |
| `url` | `string` | direct link to a file or a link to cobalt's live render |
| `pickerType` | `string` | `various / images` |
| `picker` | `array` | array of picker items |
| `audio` | `string` | direct link to a file or a link to cobalt's live render |
| `status` | `string` | `tunnel / redirect` |
| `url` | `string` | url for the cobalt tunnel, or redirect to an external link |
| `filename` | `string` | cobalt-generated filename for the file being downloaded |
### picker item variables
item type: `object`
### picker response
| key | type | values |
|:----------------|:---------|:-------------------------------------------------------------------------------------------------|
| `status` | `string` | `picker` |
| `audio` | `string` | **optional** returned when an image slideshow (such as on tiktok) has a general background audio |
| `audioFilename` | `string` | **optional** cobalt-generated filename, returned if `audio` exists |
| `picker` | `array` | array of objects containing the individual media |
| key | type | variables | description |
|:--------|:---------|:--------------------------------------------------------|:---------------------------------------|
| `type` | `string` | `video / photo / gif` | used only if `pickerType` is `various` |
| `url` | `string` | direct link to a file or a link to cobalt's live render | |
| `thumb` | `string` | item thumbnail that's displayed in the picker | used for `video` and `gif` types |
#### picker object
| key | type | values |
|:-------------|:----------|:------------------------------------------------------------|
| `type` | `string` | `photo` / `video` / `gif` |
| `url` | `string` | |
| `thumb` | `string` | **optional** thumbnail url |
## GET: `/api/stream`
cobalt's live render (or stream) endpoint. usually, you will receive a url to this endpoint
from a successful call to `/api/json`. however, the parameters passed to it are **opaque**
and **unmodifiable** from your (the api client's) perspective, and can change between versions.
### error response
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `status` | `string` | `error` |
| `error` | `object` | contains more context about the error |
therefore you don't need to worry about what they mean - but if you really want to know, you can
[read the source code](/src/modules/stream/manage.js).
#### error object
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `code` | `string` | machine-readable error code explaining the failure reason |
| `context` | `object` | **optional** container for providing more context |
## GET: `/api/serverInfo`
returns current basic server info.
#### error.context object
| key | type | values |
|:-------------|:---------|:---------------------------------------------------------------------------------------------------------------|
| `service` | `string` | **optional**, stating which service was being downloaded from |
| `limit` | `number` | **optional** number providing the ratelimit maximum number of requests, or maximum downloadable video duration |
## GET: `/`
returns current basic server info.
response body type: `application/json`
### response body variables
### response body
| key | type | variables |
|:------------|:---------|:---------------------------------------------------------|
| `cobalt` | `object` | information about the cobalt instance |
| `git` | `object` | information about the codebase that is currently running |
#### cobalt object
| key | type | description |
|:----------------|:-----------|:-----------------------------------------------|
| `version` | `string` | current version |
| `url` | `string` | server url |
| `startTime` | `string` | server start time in unix milliseconds |
| `durationLimit` | `number` | maximum downloadable video length in seconds |
| `services` | `string[]` | array of services which this instance supports |
#### git object
| key | type | variables |
|:------------|:---------|:------------------|
| `version` | `string` | cobalt version |
| `commit` | `string` | git commit |
| `commit` | `string` | commit hash |
| `branch` | `string` | git branch |
| `name` | `string` | server name |
| `url` | `string` | server url |
| `cors` | `number` | cors status |
| `startTime` | `string` | server start time |
| `remote` | `string` | git remote |

View File

@ -1,16 +1,11 @@
version: '3.5'
services:
cobalt-api:
image: ghcr.io/imputnet/cobalt:7
image: ghcr.io/imputnet/cobalt:10
restart: unless-stopped
container_name: cobalt-api
init: true
# if container doesn't run detached on your machine, uncomment the next line
#tty: true
ports:
- 9000:9000/tcp
# if you're using a reverse proxy, uncomment the next line and remove the one above (9000:9000/tcp):
@ -19,8 +14,6 @@ services:
environment:
# replace https://api.cobalt.tools/ with your instance's target url in same format
API_URL: "https://api.cobalt.tools/"
# replace eu-nl with your instance's distinctive name
API_NAME: "eu-nl"
# if you want to use cookies when fetching data from services, uncomment the next line and the lines under volume
# COOKIE_PATH: "/cookies.json"
# see docs/run-an-instance.md for more information
@ -31,30 +24,6 @@ services:
#volumes:
#- ./cookies.json:/cookies.json
cobalt-web:
image: ghcr.io/imputnet/cobalt:7
restart: unless-stopped
container_name: cobalt-web
init: true
# if container doesn't run detached on your machine, uncomment the next line
#tty: true
ports:
- 9001:9001/tcp
# if you're using a reverse proxy, uncomment the next line and remove the one above (9001:9001/tcp):
#- 127.0.0.1:9001:9001
environment:
# replace https://cobalt.tools/ with your instance's target url in same format
WEB_URL: "https://cobalt.tools/"
# replace https://api.cobalt.tools/ with preferred api instance url
API_URL: "https://api.cobalt.tools/"
labels:
- com.centurylinklabs.watchtower.scope=cobalt
# update the cobalt image automatically with watchtower
watchtower:
image: ghcr.io/containrrr/watchtower

View File

@ -6,20 +6,20 @@ if you need help with installing docker, follow *only the first step* of these t
- [how to install docker](https://www.digitalocean.com/community/tutorial-collections/how-to-install-and-use-docker)
- [how to install docker compose](https://www.digitalocean.com/community/tutorial-collections/how-to-install-docker-compose)
## how to run a cobalt docker package:
1. create a folder for cobalt config file, something like this:
## how to run a cobalt docker package:
1. create a folder for cobalt config file, something like this:
```sh
mkdir cobalt
```
```
2. go to cobalt folder, and create a docker compose config file:
2. go to cobalt folder, and create a docker compose config file:
```sh
cd cobalt && nano docker-compose.yml
```
i'm using `nano` in this example, it may not be available in your distro. you can use any other text editor.
```
i'm using `nano` in this example, it may not be available in your distro. you can use any other text editor.
3. copy and paste the [sample config from here](examples/docker-compose.example.yml) for either web or api instance (or both, if you wish) and edit it to your needs.
make sure to replace default URLs with your own or cobalt won't work correctly.
3. copy and paste the [sample config from here](examples/docker-compose.example.yml) for either web or api instance (or both, if you wish) and edit it to your needs.
make sure to replace default URLs with your own or cobalt won't work correctly.
4. finally, start the cobalt container (from cobalt directory):
```sh
@ -32,13 +32,19 @@ cobalt package will update automatically thanks to watchtower.
it's highly recommended to use a reverse proxy (such as nginx) if you want your instance to face the public internet. look up tutorials online.
## using regular node.js (useful for local development)
setup script installs all needed `npm` dependencies, but you have to install `node.js` *(version 18 or above)* and `git` yourself.
## run cobalt api outside of docker (useful for local development)
requirements:
- node.js >= 18
- git
- pnpm
1. clone the repo: `git clone https://github.com/imputnet/cobalt`.
2. run setup script and follow instructions: `npm run setup`. you need to host api and web instances separately, so pick whichever applies.
3. run cobalt via `npm start`.
4. done.
2. go to api/src directory: `cd cobalt/api/src`.
3. install dependencies: `pnpm install`.
4. create `.env` file in the same directory.
5. add needed environment variables to `.env` file. only `API_URL` is required to run cobalt.
- if you don't know what api url to use for local development, use `http://localhost:9000/`.
6. run cobalt: `pnpm start`.
### ubuntu 22.04 workaround
`nscd` needs to be installed and running so that the `ffmpeg-static` binary can resolve DNS ([#101](https://github.com/imputnet/cobalt/issues/101#issuecomment-1494822258)):
@ -65,6 +71,9 @@ sudo service nscd start
| `RATELIMIT_WINDOW` | `60` | `120` | rate limit time window in **seconds**. |
| `RATELIMIT_MAX` | `20` | `30` | max requests per time window. requests above this amount will be blocked for the rate limit window duration. |
| `DURATION_LIMIT` | `10800` | `18000` | max allowed video duration in **seconds**. |
| `TUNNEL_LIFESPAN` | `90` | `120` | the duration for which tunnel info is stored in ram, **in seconds**. |
| `API_KEY_URL` | | `file://keys.json` | the location of the api key database. for loading API keys, cobalt supports HTTP(S) urls, or local files by specifying a local path using the `file://` protocol. see the "api key file format" below for more details. |
| `API_AUTH_REQUIRED` | | `1` | when set to `1`, the user always needs to be authenticated in some way before they can access the API (either via an api key or via turnstile, if enabled). |
\* the higher the nice value, the lower the priority. [read more here](https://en.wikipedia.org/wiki/Nice_(Unix)).
@ -74,14 +83,54 @@ requests it makes for that particular download. to use freebind in cobalt, you n
in a docker container, you also need to set the `API_LISTEN_ADDRESS` env to `127.0.0.1`, and set
`network_mode` for the container to `host`.
### variables for web
| variable name | default | example | description |
|:---------------------|:----------------------------|:----------------------------|:--------------------------------------------------------------------------------------|
| `WEB_PORT` | `9001` | `9001` | changes port from which frontend server is accessible. |
| `WEB_URL` | | `https://cobalt.tools/` | changes url from which frontend server is accessible. <br> ***REQUIRED TO RUN WEB***. |
| `API_URL` | `https://api.cobalt.tools/` | `https://api.cobalt.tools/` | changes url which is used for api requests by frontend clients. |
| `SHOW_SPONSORS` | `0` | `1` | toggles sponsor list in about popup. <br> `0`: disabled. `1`: enabled. |
| `IS_BETA` | `0` | `1` | toggles beta tag next to cobalt logo. <br> `0`: disabled. `1`: enabled. |
| `PLAUSIBLE_HOSTNAME` | | `plausible.io`* | enables plausible analytics with provided hostname as receiver backend. |
#### api key file format
the file is a JSON-serialized object with the following structure:
```typescript
\* don't use plausible.io as receiver backend unless you paid for their cloud service. use your own domain when hosting community edition of plausible. refer to their [docs](https://plausible.io/docs) when needed.
type KeyFileContents = Record<
UUIDv4String,
{
name?: string,
limit?: number | "unlimited",
ips?: (CIDRString | IPString)[],
userAgents?: string[]
}
>;
```
where *`UUIDv4String`* is a stringified version of a UUIDv4 identifier.
- **name** is a field for your own reference, it is not used by cobalt anywhere.
- **`limit`** specifies how many requests the API key can make during the window specified in the `RATELIMIT_WINDOW` env.
- when omitted, the limit specified in `RATELIMIT_MAX` will be used.
- it can be also set to `"unlimited"`, in which case the API key bypasses all rate limits.
- **`ips`** contains an array of allowlisted IP ranges, which can be specified both as individual ips or CIDR ranges (e.g. *`["192.168.42.69", "2001:db8::48", "10.0.0.0/8", "fe80::/10"]`*).
- when specified, only requests from these ip ranges can use the specified api key.
- when omitted, any IP can be used to make requests with that API key.
- **`userAgents`** contains an array of allowed user agents, with support for wildcards (e.g. *`["cobaltbot/1.0", "Mozilla/5.0 * Chrome/*"]`*).
- when specified, requests with a `user-agent` that does not appear in this array will be rejected.
- when omitted, any user agent can be specified to make requests with that API key.
- if both `ips` and `userAgents` are set, the tokens will be limited by both parameters.
- if cobalt detects any problem with your key file, it will be ignored and a warning will be printed to the console.
an example key file could look like this:
```json
{
"b5c7160a-b655-4c7a-b500-de839f094550": {
"limit": 10,
"ips": ["10.0.0.0/8", "192.168.42.42"],
"userAgents": ["*Chrome*"]
},
"b00b1234-a3e5-99b1-c6d1-dba4512ae190": {
"limit": "unlimited",
"ips": ["192.168.1.2"],
"userAgents": ["cobaltbot/1.0"]
}
}
```
if you are configuring a key file, **do not use the UUID from the example** but instead generate your own. you can do this by running the following command if you have node.js installed:
`node -e "console.log(crypto.randomUUID())"`

1142
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +1,7 @@
{
"name": "cobalt",
"description": "save what you love",
"version": "7.15",
"author": "imput",
"exports": "./src/cobalt.js",
"type": "module",
"packageManager": "pnpm@9.6.0",
"engines": {
"node": ">=18"
},
"scripts": {
"start": "node src/cobalt",
"setup": "node src/modules/setup",
"test": "node src/util/test",
"build": "node src/modules/buildStatic",
"token:youtube": "node src/util/generate-youtube-tokens"
},
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme",
"dependencies": {
"content-disposition-header": "0.6.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"esbuild": "^0.14.51",
"express": "^4.18.1",
"express-rate-limit": "^6.3.0",
"ffmpeg-static": "^5.1.0",
"hls-parser": "^0.10.7",
"ipaddr.js": "2.1.0",
"nanoid": "^4.0.2",
"node-cache": "^5.1.2",
"psl": "1.9.0",
"set-cookie-parser": "2.6.0",
"undici": "^5.19.1",
"url-pattern": "1.0.3",
"youtubei.js": "^10.3.0"
},
"optionalDependencies": {
"freebind": "^0.2.2"
"pnpm": ">=9"
}
}
}

1
packages/api-client/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,2 @@
# Ignore artifacts:
dist

View File

@ -0,0 +1,6 @@
{
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "none",
"arrowParens": "avoid"
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 imput
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,15 @@
{
"name": "@imput/cobalt-client",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {},
"keywords": [],
"author": "imput <meow@imput.net>",
"license": "MIT",
"devDependencies": {
"prettier": "3.3.3",
"tsup": "^8.3.0",
"typescript": "^5.4.5"
}
}

View File

@ -0,0 +1,14 @@
{
"include": ["src"],
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"outDir": "./dist"
}
}

6
packages/version-info/index.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
declare module "@imput/version-info" {
export function getCommit(): Promise<string | undefined>;
export function getBranch(): Promise<string | undefined>;
export function getRemote(): Promise<string>;
export function getVersion(): Promise<string>;
}

View File

@ -0,0 +1,78 @@
import { existsSync } from 'node:fs';
import { join, parse } from 'node:path';
import { cwd } from 'node:process';
import { readFile } from 'node:fs/promises';
const findFile = (file) => {
let dir = cwd();
while (dir !== parse(dir).root) {
if (existsSync(join(dir, file))) {
return dir;
}
dir = join(dir, '../');
}
}
const root = findFile('.git');
const pack = findFile('package.json');
const readGit = (filename) => {
if (!root) {
throw 'no git repository root found';
}
return readFile(join(root, filename), 'utf8');
}
export const getCommit = async () => {
return (await readGit('.git/logs/HEAD'))
?.split('\n')
?.filter(String)
?.pop()
?.split(' ')[1];
}
export const getBranch = async () => {
if (process.env.CF_PAGES_BRANCH) {
return process.env.CF_PAGES_BRANCH;
}
return (await readGit('.git/HEAD'))
?.replace(/^ref: refs\/heads\//, '')
?.trim();
}
export const getRemote = async () => {
let remote = (await readGit('.git/config'))
?.split('\n')
?.find(line => line.includes('url = '))
?.split('url = ')[1];
if (remote?.startsWith('git@')) {
remote = remote.split(':')[1];
} else if (remote?.startsWith('http')) {
remote = new URL(remote).pathname.substring(1);
}
remote = remote?.replace(/\.git$/, '');
if (!remote) {
throw 'could not parse remote';
}
return remote;
}
export const getVersion = async () => {
if (!pack) {
throw 'no package root found';
}
const { version } = JSON.parse(
await readFile(join(pack, 'package.json'), 'utf8')
);
return version;
}

View File

@ -0,0 +1,18 @@
{
"name": "@imput/version-info",
"version": "1.0.0",
"description": "helper package for cobalt that provides commit info & version from package file.",
"main": "index.js",
"types": "index.d.ts",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"author": "imput",
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme"
}

4218
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,4 @@
packages:
- "api"
- "web"
- "packages/*"

View File

@ -1,38 +0,0 @@
import "dotenv/config";
import "./modules/sub/alias-envs.js";
import express from "express";
import { Bright, Green, Red } from "./modules/sub/consoleText.js";
import { getCurrentBranch, shortCommit } from "./modules/sub/currentCommit.js";
import { loadLoc } from "./localization/manager.js";
import { mode } from "./modules/config.js"
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const gitCommit = shortCommit();
const gitBranch = getCurrentBranch();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4);
app.disable('x-powered-by');
await loadLoc();
if (mode === 'API') {
const { runAPI } = await import('./core/api.js');
runAPI(express, app, gitCommit, gitBranch, __dirname)
} else if (mode === 'WEB') {
const { runWeb } = await import('./core/web.js');
await runWeb(express, app, gitCommit, gitBranch, __dirname)
} else {
console.log(
Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
+ Bright(`please run the setup script to fix this: `)
+ Green(`npm run setup`)
)
}

View File

@ -1,103 +0,0 @@
{
"genericUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"authorInfo": {
"support": {
"default": {
"email": {
"emoji": "📧",
"url": "mailto:support@cobalt.tools",
"name": "support@cobalt.tools"
},
"twitter": {
"emoji": "🐦",
"url": "https://twitter.com/justusecobalt",
"name": "@justusecobalt"
},
"discord": {
"emoji": "👾",
"url": "https://discord.gg/pQPt8HBUPu",
"name": "cobalt discord server"
}
},
"ru": {
"telegram": {
"emoji": "📬",
"url": "https://t.me/justusecobalt_ru",
"name": "канал в telegram"
},
"email": {
"emoji": "📧",
"url": "mailto:support@cobalt.tools",
"name": "support@cobalt.tools"
}
}
}
},
"donations": {
"crypto": {
"monero": "4B1SNB6s8Pq1hxjNeKPEe8Qa8EP3zdL16Sqsa7QDoJcUecKQzEj9BMxWnEnTGu12doKLJBKRDUqnn6V9qfSdXpXi3Nw5Uod",
"litecoin": "ltc1qvp0xhrk2m7pa6p6z844qcslfyxv4p3vf95rhna",
"ethereum": "0x4B4cF23051c78c7A7E0eA09d39099621c46bc302",
"usdt-erc20": "0x4B4cF23051c78c7A7E0eA09d39099621c46bc302",
"usdt-trc20": "TVbx7YT3rBfu931Gxko6pRfXtedYqbgnBB",
"bitcoin": "bc1qlvcnlnyzfsgnuxyxsv3k0p0q0yln0azjpadyx4",
"bitcoin-alt": "18PKf6N2cHrmSzz9ZzTSvDd2jAkqGC7SxA",
"ton": "UQA3SO-hHZq1oCCT--u6or6ollB8fd2o52aD8mXiLk9iDZd3"
},
"links": {
"boosty": "https://boosty.to/wukko/donate"
}
},
"links": {
"saveToGalleryShortcut": "https://www.icloud.com/shortcuts/14e9aebf04b24156acc34ceccf7e6fcd",
"saveToFilesShortcut": "https://www.icloud.com/shortcuts/2134cd9d4d6b41448b2201f933542b2e",
"statusPage": "https://status.cobalt.tools/",
"troubleshootingGuide": "https://github.com/imputnet/cobalt/blob/current/docs/troubleshooting.md"
},
"celebrations": {
"01-01": "🎄",
"02-17": "😺",
"02-22": "😺",
"03-01": "😺",
"03-08": "💪",
"05-26": "🎂",
"08-08": "😺",
"08-26": "🐶",
"10-29": "😺",
"10-30": "🎃",
"10-31": "🎃",
"11-01": "🕯️",
"11-02": "🕯️",
"12-20": "🎄",
"12-21": "🎄",
"12-22": "🎄",
"12-23": "🎄",
"12-24": "🎄",
"12-25": "🎄",
"12-26": "🎄",
"12-27": "🎄",
"12-28": "🎄",
"12-29": "🎄",
"12-30": "🎄",
"12-31": "🎄"
},
"supportedAudio": ["mp3", "ogg", "wav", "opus"],
"ffmpegArgs": {
"webm": ["-c:v", "copy", "-c:a", "copy"],
"mp4": ["-c:v", "copy", "-c:a", "copy", "-movflags", "faststart+frag_keyframe+empty_moov"],
"copy": ["-c:a", "copy"],
"audio": ["-ar", "48000", "-ac", "2", "-b:a", "320k"],
"m4a": ["-movflags", "frag_keyframe+empty_moov"],
"gif": ["-vf", "scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", "-loop", "0"]
},
"sponsors": [{
"name": "royale",
"fullName": "RoyaleHosting",
"url": "https://royalehosting.net/?partner=cobalt",
"logo": {
"width": 605,
"height": 136,
"scale": 5
}
}]
}

View File

@ -1,228 +0,0 @@
import cors from "cors";
import rateLimit from "express-rate-limit";
import { setGlobalDispatcher, ProxyAgent } from "undici";
import { env, version } from "../modules/config.js";
import { generateHmac, generateSalt } from "../modules/sub/crypto.js";
import { Bright, Cyan } from "../modules/sub/consoleText.js";
import { languageCode } from "../modules/sub/utils.js";
import loc from "../localization/manager.js";
import { createResponse, normalizeRequest, getIP } from "../modules/processing/request.js";
import { verifyStream, getInternalStream } from "../modules/stream/manage.js";
import { randomizeCiphers } from '../modules/sub/randomize-ciphers.js';
import { extract } from "../modules/processing/url.js";
import match from "../modules/processing/match.js";
import stream from "../modules/stream/stream.js";
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
const ipSalt = generateSalt();
const corsConfig = env.corsWildcard ? {} : {
origin: env.corsURL,
optionsSuccessStatus: 200
}
export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
const startTime = new Date();
const startTimestamp = startTime.getTime();
const serverInfo = {
version: version,
commit: gitCommit,
branch: gitBranch,
name: env.apiName,
url: env.apiURL,
cors: Number(env.corsWildcard),
startTime: `${startTimestamp}`
}
const apiLimiter = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.status(429).json({
"status": "rate-limit",
"text": loc(languageCode(req), 'ErrorRateLimit', env.rateLimitWindow)
});
}
})
const apiLimiterStream = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.sendStatus(429)
}
})
app.set('trust proxy', ['loopback', 'uniquelocal']);
app.use('/api', cors({
methods: ['GET', 'POST'],
exposedHeaders: [
'Ratelimit-Limit',
'Ratelimit-Policy',
'Ratelimit-Remaining',
'Ratelimit-Reset'
],
...corsConfig,
}))
app.use('/api/json', apiLimiter);
app.use('/api/stream', apiLimiterStream);
app.use((req, res, next) => {
try {
decodeURIComponent(req.path)
} catch {
return res.redirect('/')
}
next();
})
app.use('/api/json', express.json({ limit: 1024 }));
app.use('/api/json', (err, _, res, next) => {
if (err) {
return res.status(400).json({
status: "error",
text: "invalid json body"
});
}
next();
});
app.post('/api/json', async (req, res) => {
const request = req.body;
const lang = languageCode(req);
const fail = (t) => {
const { status, body } = createResponse("error", { t: loc(lang, t) });
res.status(status).json(body);
}
if (!acceptRegex.test(req.header('Accept'))) {
return fail('ErrorInvalidAcceptHeader');
}
if (!acceptRegex.test(req.header('Content-Type'))) {
return fail('ErrorInvalidContentType');
}
if (!request.url) {
return fail('ErrorNoLink');
}
request.dubLang = request.dubLang ? lang : false;
const normalizedRequest = normalizeRequest(request);
if (!normalizedRequest) {
return fail('ErrorCantProcess');
}
const parsed = extract(normalizedRequest.url);
if (parsed === null) {
return fail('ErrorUnsupported');
}
try {
const result = await match(
parsed.host, parsed.patternMatch, lang, normalizedRequest
);
res.status(result.status).json(result.body);
} catch {
fail('ErrorSomethingWentWrong');
}
})
app.get('/api/stream', (req, res) => {
const id = String(req.query.id);
const exp = String(req.query.exp);
const sig = String(req.query.sig);
const sec = String(req.query.sec);
const iv = String(req.query.iv);
const checkQueries = id && exp && sig && sec && iv;
const checkBaseLength = id.length === 21 && exp.length === 13;
const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
if (!checkQueries || !checkBaseLength || !checkSafeLength) {
return res.sendStatus(400);
}
// rate limit probe, will not return json after 8.0
if (req.query.p) {
return res.status(200).json({
status: "continue"
})
}
const streamInfo = verifyStream(id, sig, exp, sec, iv);
if (!streamInfo?.service) {
return res.sendStatus(streamInfo.status);
}
return stream(res, streamInfo);
})
app.get('/api/istream', (req, res) => {
if (!req.ip.endsWith('127.0.0.1')) {
return res.sendStatus(403);
}
if (String(req.query.id).length !== 21) {
return res.sendStatus(400);
}
const streamInfo = getInternalStream(req.query.id);
if (!streamInfo) {
return res.sendStatus(404);
}
streamInfo.headers = new Map([
...(streamInfo.headers || []),
...Object.entries(req.headers)
]);
return stream(res, { type: 'internal', ...streamInfo });
})
app.get('/api/serverInfo', (_, res) => {
return res.status(200).json(serverInfo);
})
app.get('/favicon.ico', (req, res) => {
res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
})
app.get('/*', (req, res) => {
res.redirect('/api/serverInfo')
})
randomizeCiphers();
setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
if (env.externalProxy) {
if (env.freebindCIDR) {
throw new Error('Freebind is not available when external proxy is enabled')
}
setGlobalDispatcher(new ProxyAgent(env.externalProxy))
}
app.listen(env.apiPort, env.listenAddress, () => {
console.log(`\n` +
`${Cyan("cobalt")} API ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${env.apiURL}`)}\n` +
`Port: ${env.apiPort}\n`
)
})
}

View File

@ -1,97 +0,0 @@
import { Bright, Cyan } from "../modules/sub/consoleText.js";
import { languageCode } from "../modules/sub/utils.js";
import { version, env } from "../modules/config.js";
import { buildFront } from "../modules/build.js";
import findRendered from "../modules/pageRender/findRendered.js";
import { celebrationsEmoji } from "../modules/pageRender/elements.js";
import { changelogHistory } from "../modules/pageRender/onDemand.js";
import { createResponse } from "../modules/processing/request.js";
export async function runWeb(express, app, gitCommit, gitBranch, __dirname) {
const startTime = new Date();
const startTimestamp = Math.floor(startTime.getTime());
await buildFront(gitCommit, gitBranch);
app.use('/', express.static('./build/min'));
app.use('/', express.static('./src/front'));
app.use((req, res, next) => {
try { decodeURIComponent(req.path) } catch (e) { return res.redirect('/') }
next();
})
app.get('/onDemand', (req, res) => {
try {
if (typeof req.query.blockId !== 'string') {
return res.status(400).json({
status: "error",
text: "couldn't render this block, please try again!"
});
}
let blockId = req.query.blockId.slice(0, 3);
let blockData;
switch(blockId) {
// changelog history
case "0":
let history = changelogHistory();
if (history) {
blockData = createResponse("success", { t: history })
} else {
blockData = createResponse("error", {
t: "couldn't render this block, please try again!"
})
}
break;
// celebrations emoji
case "1":
let celebration = celebrationsEmoji();
if (celebration) {
blockData = createResponse("success", { t: celebration })
}
break;
default:
blockData = createResponse("error", {
t: "couldn't find a block with this id"
})
break;
}
if (blockData?.body) {
return res.status(blockData.status).json(blockData.body);
} else {
return res.status(204).end();
}
} catch {
return res.status(400).json({
status: "error",
text: "couldn't render this block, please try again!"
})
}
})
app.get("/", (req, res) => {
return res.sendFile(`${__dirname}/${findRendered(languageCode(req))}`)
})
app.get("/favicon.ico", (req, res) => {
return res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
})
app.get("/*", (req, res) => {
return res.redirect('/')
})
app.listen(env.webPort, () => {
console.log(`\n` +
`${Cyan("cobalt")} WEB ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${env.webURL}`)}\n` +
`Port: ${env.webPort}\n`
)
})
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Some files were not shown because too many files have changed in this diff Show More