``` ├── .deepsource.toml ├── .dockerignore ├── .github/ ├── ISSUE_TEMPLATE/ ├── bug-main-instance.yml ├── bug-report.yml ├── config.yml ├── feature-request.yml ├── hosting-help.yml ├── service-request.yml ├── test.sh ├── workflows/ ├── codeql.yml ├── docker-develop.yml ├── docker-staging.yml ├── docker.yml ├── fast-forward.yml ├── test-services.yml ├── test.yml ├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── api/ ├── LICENSE ├── README.md ├── package.json ├── src/ ├── cobalt.js ├── config.js ├── core/ ├── api.js ├── misc/ ├── cluster.js ├── console-text.js ├── crypto.js ├── load-from-fs.js ├── randomize-ciphers.js ├── run-test.js ├── utils.js ├── processing/ ├── cookie/ ├── cookie.js ├── manager.js ├── create-filename.js ├── helpers/ ├── youtube-session.js ├── match-action.js ├── match.js ├── request.js ├── schema.js ├── service-alias.js ├── service-config.js ├── service-patterns.js ├── services/ ├── bilibili.js ├── bluesky.js ├── dailymotion.js ├── facebook.js ├── instagram.js ├── loom.js ├── ok.js ├── pinterest.js ├── reddit.js ├── rutube.js ├── snapchat.js ├── soundcloud.js ├── streamable.js ├── tiktok.js ├── tumblr.js ├── twitch.js ├── twitter.js ├── vimeo.js ``` ## /.deepsource.toml ```toml path="/.deepsource.toml" version = 1 [[analyzers]] name = "javascript" [analyzers.meta] environment = ["nodejs"] ``` ## /.dockerignore ```dockerignore path="/.dockerignore" # 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 ``` ## /.github/ISSUE_TEMPLATE/bug-main-instance.yml ```yml path="/.github/ISSUE_TEMPLATE/bug-main-instance.yml" 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. ``` ## /.github/ISSUE_TEMPLATE/bug-report.yml ```yml path="/.github/ISSUE_TEMPLATE/bug-report.yml" 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. ``` ## /.github/ISSUE_TEMPLATE/config.yml ```yml path="/.github/ISSUE_TEMPLATE/config.yml" 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. ``` ## /.github/ISSUE_TEMPLATE/feature-request.yml ```yml path="/.github/ISSUE_TEMPLATE/feature-request.yml" 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. ``` ## /.github/ISSUE_TEMPLATE/hosting-help.yml ```yml path="/.github/ISSUE_TEMPLATE/hosting-help.yml" 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 ``` ## /.github/ISSUE_TEMPLATE/service-request.yml ```yml path="/.github/ISSUE_TEMPLATE/service-request.yml" 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. ``` ## /.github/test.sh ```sh path="/.github/test.sh" #!/bin/bash set -e # thx: https://stackoverflow.com/a/27601038 waitport() { ATTEMPTS=50 while [ $((ATTEMPTS-=1)) -gt 0 ] && ! nc -z localhost $1; do sleep 0.1 done [ "$ATTEMPTS" != 0 ] || exit 1 } test_api() { waitport 3000 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://garfield-69.tumblr.com/post/696499862852780032","alwaysProxy":true}') echo "API_RESPONSE=$API_RESPONSE" STATUS=$(echo "$API_RESPONSE" | jq -r .status) STREAM_URL=$(echo "$API_RESPONSE" | jq -r .url) [ "$STATUS" = tunnel ] || exit 1; S=$(curl -I -m 10 "$STREAM_URL") CONTENT_LENGTH=$(echo "$S" \ | grep -i content-length \ | cut -d' ' -f2 \ | tr -d '\r') echo "$CONTENT_LENGTH" [ "$CONTENT_LENGTH" = 0 ] && exit 1 if [ "$CONTENT_LENGTH" -lt 512 ]; then exit 1 fi } setup_api() { export API_PORT=3000 export API_URL=http://localhost:3000 timeout 10 pnpm run --prefix api start & API_PID=$! } setup_web() { pnpm run --prefix web check pnpm run --prefix web build } cd "$(git rev-parse --show-toplevel)" pnpm install --frozen-lockfile if [ "$1" = "api" ]; then setup_api test_api [ "$API_PID" != "" ] \ && kill "$API_PID" elif [ "$1" = "web" ]; then setup_web else echo "usage: $0 " >&2 exit 1 fi wait || exit $? ``` ## /.github/workflows/codeql.yml ```yml path="/.github/workflows/codeql.yml" # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: - '**' pull_request: branches: [ "main", "7" ] schedule: - cron: '33 7 * * 5' jobs: analyze: name: Analyze (${{ matrix.language }}) # Runner size impacts CodeQL analysis time. To learn more, please see: # - https://gh.io/recommended-hardware-resources-for-running-codeql # - https://gh.io/supported-runners-and-hardware-resources # - https://gh.io/using-larger-runners (GitHub.com only) # Consider using larger runners or machines with greater resources for possible analysis time improvements. runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} permissions: # required for all workflows security-events: write # required to fetch internal or private CodeQL packs packages: read # only required for workflows in private repositories actions: read contents: read strategy: fail-fast: false matrix: include: - language: javascript-typescript build-mode: none # CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' # Use `c-cpp` to analyze code written in C, C++ or both # Use 'java-kotlin' to analyze code written in Java, Kotlin or both # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # queries: security-extended,security-and-quality # If the analyze step fails for one of the languages you are analyzing with # "We were unable to automatically build your code", modify the matrix above # to set the build mode to "manual" for that language. Then modify this step # to build your code. # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - if: matrix.build-mode == 'manual' shell: bash run: | echo 'If you are using a "manual" build mode for one or more of the' \ 'languages you are analyzing, replace this with the commands to build' \ 'your code, for example:' echo ' make bootstrap' echo ' make release' exit 1 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" ``` ## /.github/workflows/docker-develop.yml ```yml path="/.github/workflows/docker-develop.yml" name: Build development Docker image on: workflow_dispatch: env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: build-and-push-image: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Get release metadata id: release-meta run: | version=$(cat 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 - name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: tags: type=raw,value=develop images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . platforms: linux/amd64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max ``` ## /.github/workflows/docker-staging.yml ```yml path="/.github/workflows/docker-staging.yml" name: Build staging Docker image on: workflow_dispatch: env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: build-and-push-image: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Get release metadata id: release-meta run: | version=$(cat 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 - name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: tags: type=raw,value=staging images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . platforms: linux/amd64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max ``` ## /.github/workflows/docker.yml ```yml path="/.github/workflows/docker.yml" name: Build release Docker image on: workflow_dispatch: env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: build-and-push-image: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Get release metadata id: release-meta run: | 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 - name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: tags: | type=raw,value=latest type=raw,value=${{ steps.release-meta.outputs.version }} type=raw,value=${{ steps.release-meta.outputs.major_version }} type=raw,value=${{ steps.release-meta.outputs.version }}-${{ steps.release-meta.outputs.commit_short }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - name: Build and push Docker image uses: docker/build-push-action@v6 with: context: . platforms: linux/amd64,linux/arm64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max ``` ## /.github/workflows/fast-forward.yml ```yml path="/.github/workflows/fast-forward.yml" name: fast-forward on: issue_comment: types: [created, edited] jobs: fast-forward: # Only run if the comment contains the /fast-forward command. if: ${{ contains(github.event.comment.body, '/fast-forward') && github.event.issue.pull_request }} runs-on: ubuntu-latest permissions: contents: write pull-requests: write issues: write steps: - name: Fast forwarding uses: sequoia-pgp/fast-forward@v1 with: merge: true comment: 'on-error' ``` ## /.github/workflows/test-services.yml ```yml path="/.github/workflows/test-services.yml" 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 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 run-tests-for ${{ matrix.service }} env: API_EXTERNAL_PROXY: ${{ secrets.API_EXTERNAL_PROXY }} TEST_IGNORE_SERVICES: ${{ vars.TEST_IGNORE_SERVICES }} ``` ## /.github/workflows/test.yml ```yml path="/.github/workflows/test.yml" name: Run tests on: pull_request: push: jobs: check-lockfile: name: check lockfile correctness runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - name: Check that lockfile does not need an update run: pnpm install --frozen-lockfile test-web: name: web sanity check runs-on: ubuntu-latest steps: - 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: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - run: .github/test.sh api ``` ## /.gitignore ```gitignore path="/.gitignore" # OS directory info files .DS_Store desktop.ini # node node_modules # static build build # secrets .env .env.* !.env.example cookies.json keys.json # docker docker-compose.yml # ide .vscode ``` ## /CONTRIBUTING.md # contributing to cobalt if you're reading this, you are probably interested in contributing to cobalt, which we are very thankful for :3 this document serves as a guide to help you make contributions that we can merge into the cobalt codebase. ## translations we are currently accepting translations via the [i18n platform](https://i18n.imput.net). thank you for showing interest in making cobalt more accessible around the world, we really appreciate it! here are some guidelines for how a cobalt translation should look: - cobalt's writing style is informal. please do not use formal language, unless there is no other way to express the same idea of the original text in your language. - all cobalt text is written in lowercase. this is a stylistic choice, please do not capitalize translated sentences. - do not translate the name "cobalt", or "imput" - you can translate "meowbalt" into whatever your language's equivalent of _meow_ is (e.g. _miaubalt_ in German) - **please don't translate cobalt into languages which you are not experienced in.** we can use google translate ourselves, but we would prefer cobalt to be translated by humans, not computers. if your language does not exist on the translation platform yet, you can request to add it by adding it to any of cobalt's components (e.g. [here](https://i18n.imput.net/projects/cobalt/about/)). before translating a piece of text, check that no one has made a translation yet. pending translations are displayed in the **Suggestions** tab on the translate page. if someone already made a suggestion, and you think it's correct, you can upvote it! this helps us distinguish that a translation is correct. if no one has submitted a translation, or the submitted translation seems wrong to you, you can submit your translation by clicking the **Suggest** button for each individual string, which sends it off for human review. we will then check it to to ensure no malicious translations are submitted, and add it to cobalt. if any translation string's meaning seems unclear to you, please leave a comment on the *Comments* tab, and we will either add an explanation or a screenshot. ## adding features or support for services before putting in the effort to implement a feature, it's worth considering whether it would be appropriate to add it to cobalt. the cobalt api is built to assist people **only with downloading freely accessible content**. other functionality, such as: - downloading paid / not publicly accessible content - downloading content protected by DRM - scraping unrelated information & exposing it outside of file metadata will not be reviewed or merged. if you plan on adding a feature or support for a service, but are unsure whether it would be appropriate, it's best to open an issue and discuss it beforehand. ## git when contributing code to cobalt, there are a few guidelines in place to ensure that the code history is readable and comprehensible. ### clean commit messages internally, we use a format similar to [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) - the first part signifies which part of the code you are changing (the *scope*), and the second part explains the change. for inspiration on how to write appropriate commit titles, you can take a look at the [commit history](https://github.com/imputnet/cobalt/commits/). the scope is not strictly defined, you can write whatever you find most fitting for the particular change. suppose you are changing a small part of a more significant part of the codebase. in that case, you can specify both the larger and smaller scopes in the commit message for clarity (e.g., if you were changing something in internal streams, the commit could be something like `api/stream: fix object not being handled properly`). if you think a change deserves further explanation, we encourage you to write a short explanation in the commit message ([example](https://github.com/imputnet/cobalt/commit/31be60484de8eaf63bba8a4f508e16438aa7ba6e)), which will save both you and us time having to enquire about the change, and you explaining the reason behind it. if your contribution has uninformative commit titles, you may be asked to interactively rebase your branch and amend each commit to include a meaningful title. ### clean commit history if your branch is out of date and/or has some merge conflicts with the `current` branch, you should **rebase** it instead of merging. this prevents meaningless merge commits from being included in your branch, which would then end up in the cobalt git history. if you find a mistake or bug in your code before it's merged or reviewed, instead of making a brand new commit to fix it, it would be preferable to amend that specific commit where the mistake was first introduced. this also helps us easily revert a commit if we discover that it introduced a bug or some unwanted behavior. - if the commit you are fixing is the latest one, you can add your files to staging and then use `git commit --amend` to apply the change. - if the commit is somewhere deeper in your branch, you can use `git commit --fixup=HASH`, where *`HASH`* is the commit you are fixing. - afterward, you must interactively rebase your branch with `git rebase -i current --autosquash`. this will open up an editor, but you don't need to do anything else except save the file and exit. - once you do either of these things, you will need to do a **force push** to your branch with `git push --force-with-lease`. ## /Dockerfile ``` path="/Dockerfile" FROM node:23-alpine AS base ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" FROM base AS build WORKDIR /app COPY . /app RUN corepack enable RUN apk add --no-cache python3 alpine-sdk 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 --from=build --chown=node:node /prod/api /app COPY --from=build --chown=node:node /app/.git /app/.git USER node EXPOSE 9000 CMD [ "node", "src/cobalt" ] ``` ## /LICENSE ``` path="/LICENSE" GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies 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 . 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 . ``` ## /README.md

cobalt logo

best way to save what you love
cobalt.tools

💬 community discord server
🐦 twitter 🦋 bluesky


cobalt is a media downloader that doesn't piss you off. it's friendly, efficient, and doesn't have ads, trackers, paywalls or other nonsense. paste the link, get the file, move on. that simple, just how it should be. ### cobalt monorepo this monorepo includes source code for api, frontend, and related packages: - [api tree & readme](/api/) - [web tree & readme](/web/) - [packages tree](/packages/) it also includes documentation in the [docs tree](/docs/): - [how to run a cobalt instance](/docs/run-an-instance.md) - [how to protect a cobalt instance](/docs/protect-an-instance.md) - [cobalt api instance environment variables](/docs/api-env-variables.md) - [cobalt api documentation](/docs/api.md) ### ethics cobalt is a tool that makes downloading public content easier. it takes **zero liability**. the end user is responsible for what they download, how they use and distribute that content. cobalt never caches any content, it [works like a fancy proxy](/api/src/stream/). cobalt is in no way a piracy tool and cannot be used as such. it can only download free & publicly accessible content. same content can be downloaded via dev tools of any modern web browser. ### contributing if you're considering contributing to cobalt, first of all, thank you! check the [contribution guidelines here](/CONTRIBUTING.md) before getting started, they'll help you do your best right away. ### thank you cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt). a part of our infrastructure is hosted on their network. we really appreciate their kindness and support! ### licenses 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). ## /api/LICENSE ``` path="/api/LICENSE" GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies 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 . 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 . ``` ## /api/README.md # cobalt api this directory includes the source code for cobalt api. it's made with [express.js](https://www.npmjs.com/package/express) and love! ## running your own instance if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md). we recommend to use docker compose unless you intend to run cobalt for developing/debugging purposes. ## accessing the api there is currently no publicly available pre-hosted api. we recommend [deploying your own instance](/docs/run-an-instance.md) if you wish to use the cobalt api. you can read [the api documentation here](/docs/api.md). ## supported services this list is not final and keeps expanding over time! if the desired service isn't supported yet, feel free to create an appropriate issue (or a pull request 👀). | 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 | ✅ | ✅ | ✅ | ➖ | ➖ | | tiktok | ✅ | ✅ | ✅ | ❌ | ❌ | | tumblr | ✅ | ✅ | ✅ | ➖ | ➖ | | twitch clips | ✅ | ✅ | ✅ | ✅ | ✅ | | twitter/x | ✅ | ✅ | ✅ | ➖ | ➖ | | vimeo | ✅ | ✅ | ✅ | ✅ | ✅ | | vk videos & clips | ✅ | ❌ | ✅ | ✅ | ✅ | | xiaohongshu | ✅ | ✅ | ✅ | ➖ | ➖ | | youtube | ✅ | ✅ | ✅ | ✅ | ✅ | | emoji | meaning | | :-----: | :---------------------- | | ✅ | supported | | ➖ | unreasonable/impossible | | ❌ | not supported | ### additional notes or features (per service) | service | notes or features | | :-------- | :----- | | instagram | supports reels, photos, and videos. lets you pick what to save from multi-media posts. | | facebook | supports public accessible videos content only. | | pinterest | supports photos, gifs, videos and stories. | | reddit | supports gifs and videos. | | snapchat | supports spotlights and stories. lets you pick what to save from stories. | | rutube | supports yappy & private links. | | soundcloud | supports private links. | | tiktok | supports videos with or without watermark, images from slideshow without watermark, and full (original) audios. | | twitter/x | lets you pick what to save from multi-media posts. may not be 100% reliable due to current management. | | 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. | ## 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** ## open source acknowledgements ### ffmpeg cobalt relies on ffmpeg for muxing and encoding media files. ffmpeg is absolutely spectacular and we're privileged to have an ability to use it for free, just like anyone else. we believe it should be way more recognized. you can [support ffmpeg here](https://ffmpeg.org/donations.html)! ### youtube.js cobalt relies on **[youtube.js](https://github.com/LuanRT/YouTube.js)** for interacting with youtube's innertube api, it wouldn't have been possible without this package. you can support the developer via various methods listed on their github page! (linked above) ### many others cobalt-api also depends on: - **[content-disposition-header](https://www.npmjs.com/package/content-disposition-header)** to simplify the provision of `content-disposition` headers. - **[cors](https://www.npmjs.com/package/cors)** to manage cross-origin resource sharing within expressjs. - **[dotenv](https://www.npmjs.com/package/dotenv)** to load environment variables from the `.env` file. - **[express](https://www.npmjs.com/package/express)** as the backbone of cobalt servers. - **[express-rate-limit](https://www.npmjs.com/package/express-rate-limit)** to rate limit api endpoints. - **[ffmpeg-static](https://www.npmjs.com/package/ffmpeg-static)** to get binaries for ffmpeg depending on the platform. - **[hls-parser](https://www.npmjs.com/package/hls-parser)** to parse HLS playlists according to spec (very impressive stuff). - **[ipaddr.js](https://www.npmjs.com/package/ipaddr.js)** to parse ip addresses (used for rate limiting). - **[nanoid](https://www.npmjs.com/package/nanoid)** to generate unique identifiers for each requested tunnel. - **[set-cookie-parser](https://www.npmjs.com/package/set-cookie-parser)** to parse cookies that cobalt receives from certain services. - **[undici](https://www.npmjs.com/package/undici)** for making http requests. - **[url-pattern](https://www.npmjs.com/package/url-pattern)** to match provided links with supported patterns. - **[zod](https://www.npmjs.com/package/zod)** to lock down the api request schema. - **[@datastructures-js/priority-queue](https://www.npmjs.com/package/@datastructures-js/priority-queue)** for sorting stream caches for future clean up (without redis). - **[@imput/psl](https://www.npmjs.com/package/@imput/psl)** as the domain name parser, our fork of [psl](https://www.npmjs.com/package/psl). ...and many other packages that these packages rely on. ## /api/package.json ```json path="/api/package.json" { "name": "@imput/cobalt-api", "description": "save what you love", "version": "10.9.3", "author": "imput", "exports": "./src/cobalt.js", "type": "module", "engines": { "node": ">=18" }, "scripts": { "start": "node src/cobalt", "test": "node src/util/test", "token:jwt": "node src/util/generate-jwt-secret" }, "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": { "@datastructures-js/priority-queue": "^6.3.1", "@imput/psl": "^2.0.4", "@imput/version-info": "workspace:^", "content-disposition-header": "0.6.0", "cors": "^2.8.5", "dotenv": "^16.0.1", "express": "^4.21.2", "express-rate-limit": "^7.4.1", "ffmpeg-static": "^5.1.0", "hls-parser": "^0.10.7", "ipaddr.js": "2.2.0", "nanoid": "^5.0.9", "set-cookie-parser": "2.6.0", "undici": "^5.19.1", "url-pattern": "1.0.3", "youtubei.js": "^13.4.0", "zod": "^3.23.8" }, "optionalDependencies": { "freebind": "^0.2.2", "rate-limit-redis": "^4.2.0", "redis": "^4.7.0" } } ``` ## /api/src/cobalt.js ```js path="/api/src/cobalt.js" import "dotenv/config"; import express from "express"; import cluster from "node:cluster"; import path from "path"; import { fileURLToPath } from "url"; import { env, isCluster } from "./config.js" import { Red } from "./misc/console-text.js"; import { initCluster } from "./misc/cluster.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"); if (isCluster) { await initCluster(); } runAPI(express, app, __dirname, cluster.isPrimary); } else { console.log( Red("API_URL env variable is missing, cobalt api can't start.") ) } ``` ## /api/src/config.js ```js path="/api/src/config.js" import { Constants } from "youtubei.js"; import { getVersion } from "@imput/version-info"; import { services } from "./processing/service-config.js"; import { supportsReusePort } from "./misc/cluster.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, tunnelPort: 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, sessionRateLimitWindow: (process.env.SESSION_RATELIMIT_WINDOW && parseInt(process.env.SESSION_RATELIMIT_WINDOW)) || 60, sessionRateLimit: (process.env.SESSION_RATELIMIT && parseInt(process.env.SESSION_RATELIMIT)) || 10, 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', redisURL: process.env.API_REDIS_URL, instanceCount: (process.env.API_INSTANCE_COUNT && parseInt(process.env.API_INSTANCE_COUNT)) || 1, keyReloadInterval: 900, enabledServices, customInnertubeClient: process.env.CUSTOM_INNERTUBE_CLIENT, ytSessionServer: process.env.YOUTUBE_SESSION_SERVER, ytSessionReloadInterval: 300, ytSessionInnertubeClient: process.env.YOUTUBE_SESSION_INNERTUBE_CLIENT, } 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 const setTunnelPort = (port) => env.tunnelPort = port; export const isCluster = env.instanceCount > 1; if (env.sessionEnabled && env.jwtSecret.length < 16) { throw new Error("JWT_SECRET env is too short (must be at least 16 characters long)"); } if (env.instanceCount > 1 && !env.redisURL) { throw new Error("API_REDIS_URL is required when API_INSTANCE_COUNT is >= 2"); } else if (env.instanceCount > 1 && !await supportsReusePort()) { console.error('API_INSTANCE_COUNT is not supported in your environment. to use this env, your node.js'); console.error('version must be >= 23.1.0, and you must be running a recent enough version of linux'); console.error('(or other OS that supports it). for more info, see `reusePort` option on'); console.error('https://nodejs.org/api/net.html#serverlistenoptions-callback'); throw new Error('SO_REUSEPORT is not supported'); } if (env.customInnertubeClient && !Constants.SUPPORTED_CLIENTS.includes(env.customInnertubeClient)) { console.error("CUSTOM_INNERTUBE_CLIENT is invalid. Provided client is not supported."); console.error(`Supported clients are: ${Constants.SUPPORTED_CLIENTS.join(', ')}\n`); throw new Error("Invalid CUSTOM_INNERTUBE_CLIENT"); } export { env, genericUserAgent, cobaltUserAgent, } ``` ## /api/src/core/api.js ```js path="/api/src/core/api.js" import cors from "cors"; import http from "node:http"; 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, isCluster, setTunnelPort } from "../config.js"; import { extract } from "../processing/url.js"; import { Green, Bright, Cyan } from "../misc/console-text.js"; import { hashHmac } from "../security/secrets.js"; import { createStore } from "../store/redis-ratelimit.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"; import * as Cookies from "../processing/cookie/manager.js"; import * as YouTubeSession from "../processing/helpers/youtube-session.js"; const git = { branch: await getBranch(), commit: await getCommit(), remote: await getRemote(), } const version = await getVersion(); const acceptRegex = /^application\/json(; charset=utf-8)?$/; 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 = async (express, app, __dirname, isPrimary = true) => { 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 keyGenerator = (req) => hashHmac(getIP(req), 'rate').toString('base64url'); const sessionLimiter = rateLimit({ windowMs: env.sessionRateLimitWindow * 1000, limit: env.sessionRateLimit, standardHeaders: 'draft-6', legacyHeaders: false, keyGenerator, store: await createStore('session'), handler: handleRateExceeded }); const apiLimiter = rateLimit({ windowMs: env.rateLimitWindow * 1000, limit: (req) => req.rateLimitMax || env.rateLimitMax, standardHeaders: 'draft-6', legacyHeaders: false, keyGenerator: req => req.rateLimitKey || keyGenerator(req), store: await createStore('api'), handler: handleRateExceeded }); const apiTunnelLimiter = rateLimit({ windowMs: env.rateLimitWindow * 1000, limit: (req) => req.rateLimitMax || env.rateLimitMax, standardHeaders: 'draft-6', legacyHeaders: false, keyGenerator: req => req.rateLimitKey || keyGenerator(req), store: await createStore('tunnel'), handler: (_, 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.length >= 256) { return fail(res, "error.api.auth.jwt.invalid"); } const [ type, token, ...rest ] = authorization.split(" "); if (!token || type.toLowerCase() !== 'bearer' || rest.length) { return fail(res, "error.api.auth.jwt.invalid"); } if (!jwt.verify(token, getIP(req, 32))) { return fail(res, "error.api.auth.jwt.invalid"); } req.rateLimitKey = hashHmac(token, 'rate'); } 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(getIP(req, 32))); } catch { return fail(res, "error.api.generic"); } }); app.post('/', async (req, res) => { const request = req.body; if (!request.url) { return fail(res, "error.api.link.missing"); } 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, async (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 = await 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); }) const itunnelHandler = (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', data: streamInfo }); }; app.get('/itunnel', itunnelHandler); 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)) } http.createServer(app).listen({ port: env.apiPort, host: env.listenAddress, reusePort: env.instanceCount > 1 || undefined }, () => { if (isPrimary) { 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" ); } if (env.apiKeyURL) { APIKeys.setup(env.apiKeyURL); } if (env.cookiePath) { Cookies.setup(env.cookiePath); } if (env.ytSessionServer) { YouTubeSession.setup(); } }); if (isCluster) { const istreamer = express(); istreamer.get('/itunnel', itunnelHandler); const server = istreamer.listen({ port: 0, host: '127.0.0.1', exclusive: true }, () => { const { port } = server.address(); console.log(`${Green('[✓]')} cobalt sub-instance running on 127.0.0.1:${port}`); setTunnelPort(port); }); } } ``` ## /api/src/misc/cluster.js ```js path="/api/src/misc/cluster.js" import cluster from "node:cluster"; import net from "node:net"; import { syncSecrets } from "../security/secrets.js"; import { env, isCluster } from "../config.js"; export { isPrimary, isWorker } from "node:cluster"; export const supportsReusePort = async () => { try { await new Promise((resolve, reject) => { const server = net.createServer().listen({ port: 0, reusePort: true }); server.on('listening', () => server.close(resolve)); server.on('error', (err) => (server.close(), reject(err))); }); return true; } catch { return false; } } export const initCluster = async () => { if (cluster.isPrimary) { for (let i = 1; i < env.instanceCount; ++i) { cluster.fork(); } } await syncSecrets(); } export const broadcast = (message) => { if (!isCluster || !cluster.isPrimary || !cluster.workers) { return; } for (const worker of Object.values(cluster.workers)) { worker.send(message); } } export const send = (message) => { if (!isCluster) { return; } if (cluster.isPrimary) { return broadcast(message); } else { return process.send(message); } } export const waitFor = (key) => { return new Promise(resolve => { const listener = (message) => { if (key in message) { process.off('message', listener); return resolve(message); } } process.on('message', listener); }); } export const mainOnMessage = (cb) => { for (const worker of Object.values(cluster.workers)) { worker.on('message', cb); } } ``` ## /api/src/misc/console-text.js ```js path="/api/src/misc/console-text.js" const ANSI = { RESET: "\x1b[0m", BRIGHT: "\x1b[1m", RED: "\x1b[31m", GREEN: "\x1b[32m", CYAN: "\x1b[36m", YELLOW: "\x1b[93m" } function wrap(color, text) { if (!ANSI[color.toUpperCase()]) { throw "invalid color"; } return ANSI[color.toUpperCase()] + text + ANSI.RESET; } export function Bright(text) { return wrap('bright', text); } export function Red(text) { return wrap('red', text); } export function Green(text) { return wrap('green', text); } export function Cyan(text) { return wrap('cyan', text); } export function Yellow(text) { return wrap('yellow', text); } ``` ## /api/src/misc/crypto.js ```js path="/api/src/misc/crypto.js" import { createCipheriv, createDecipheriv } from "crypto"; const algorithm = "aes256"; export function encryptStream(plaintext, iv, secret) { const buff = Buffer.from(JSON.stringify(plaintext)); const key = Buffer.from(secret, "base64url"); const cipher = createCipheriv(algorithm, key, Buffer.from(iv, "base64url")); return Buffer.concat([ cipher.update(buff), cipher.final() ]) } export function decryptStream(ciphertext, iv, secret) { const buff = Buffer.from(ciphertext); const key = Buffer.from(secret, "base64url"); const decipher = createDecipheriv(algorithm, key, Buffer.from(iv, "base64url")); return Buffer.concat([ decipher.update(buff), decipher.final() ]) } ``` ## /api/src/misc/load-from-fs.js ```js path="/api/src/misc/load-from-fs.js" 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 } } ``` ## /api/src/misc/randomize-ciphers.js ```js path="/api/src/misc/randomize-ciphers.js" import tls from 'node:tls'; import { randomBytes } from 'node:crypto'; const ORIGINAL_CIPHERS = tls.DEFAULT_CIPHERS; // How many ciphers from the top of the list to shuffle. // The remaining ciphers are left in the original order. const TOP_N_SHUFFLE = 8; // Modified variation of https://stackoverflow.com/a/12646864 const shuffleArray = (array) => { for (let i = array.length - 1; i > 0; i--) { const j = randomBytes(4).readUint32LE() % array.length; [array[i], array[j]] = [array[j], array[i]]; } return array; } export const randomizeCiphers = () => { do { const cipherList = ORIGINAL_CIPHERS.split(':'); const shuffled = shuffleArray(cipherList.slice(0, TOP_N_SHUFFLE)); const retained = cipherList.slice(TOP_N_SHUFFLE); tls.DEFAULT_CIPHERS = [ ...shuffled, ...retained ].join(':'); } while (tls.DEFAULT_CIPHERS === ORIGINAL_CIPHERS); } ``` ## /api/src/misc/run-test.js ```js path="/api/src/misc/run-test.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 { success, data: normalized } = await normalizeRequest({ url, ...params }); if (!success) { throw "invalid request"; } const parsed = extract(normalized.url); if (parsed === null) { throw `invalid url: ${normalized.url}`; } const result = await match({ host: parsed.host, patternMatch: parsed.patternMatch, params: normalized, }); let error = []; if (expect.status !== result.body.status) { const detail = `${expect.status} (expected) != ${result.body.status} (actual)`; error.push(`status mismatch: ${detail}`); if (result.body.status === 'error') { error.push(`error code: ${result.body?.error?.code}`); } } if (expect.errorCode && expect.errorCode !== result.body?.error?.code) { const detail = `${expect.errorCode} (expected) != ${result.body.error.code} (actual)` error.push(`error mismatch: ${detail}`); } if (expect.code !== result.status) { const detail = `${expect.code} (expected) != ${result.status} (actual)`; error.push(`status code mismatch: ${detail}`); } if (error.length) { if (result.body.text) { error.push(`error message: ${result.body.text}`); } throw error.join('\n'); } if (result.body.status === 'tunnel') { // TODO: stream testing } } ``` ## /api/src/misc/utils.js ```js path="/api/src/misc/utils.js" import { request } from 'undici'; const redirectStatuses = new Set([301, 302, 303, 307, 308]); export async function getRedirectingURL(url, dispatcher, headers) { const params = { dispatcher, method: 'HEAD', headers, redirect: 'manual' }; let location = await request(url, params).then(r => { if (redirectStatuses.has(r.statusCode) && r.headers['location']) { return r.headers['location']; } }).catch(() => null); location ??= await fetch(url, params).then(r => { if (redirectStatuses.has(r.status) && r.headers.has('location')) { return r.headers.get('location'); } }).catch(() => null); return location; } export function merge(a, b) { for (const k of Object.keys(b)) { if (Array.isArray(b[k])) { a[k] = [...(a[k] ?? []), ...b[k]]; } else if (typeof b[k] === 'object') { a[k] = merge(a[k], b[k]); } else { a[k] = b[k]; } } return a; } export function splitFilenameExtension(filename) { const parts = filename.split('.'); const ext = parts.pop(); if (!parts.length) { return [ ext, "" ] } else { return [ parts.join('.'), ext ] } } export function zip(a, b) { return a.map((value, i) => [ value, b[i] ]); } ``` ## /api/src/processing/cookie/cookie.js ```js path="/api/src/processing/cookie/cookie.js" import { strict as assert } from 'node:assert'; export default class Cookie { constructor(input) { assert(typeof input === 'object'); this._values = {}; for (const [ k, v ] of Object.entries(input)) this.set(k, v); } set(key, value) { const old = this._values[key]; if (old === value) return false; this._values[key] = value; return true; } unset(keys) { for (const key of keys) delete this._values[key] } static fromString(str) { const obj = {}; str.split('; ').forEach(cookie => { const key = cookie.split('=')[0]; const value = cookie.split('=').splice(1).join('='); obj[key] = value }) return new Cookie(obj) } toString() { return Object.entries(this._values).map(([ name, value ]) => `${name}=${value}`).join('; ') } toJSON() { return this.toString() } values() { return Object.freeze({ ...this._values }) } } ``` ## /api/src/processing/cookie/manager.js ```js path="/api/src/processing/cookie/manager.js" import Cookie from './cookie.js'; import { readFile, writeFile } from 'fs/promises'; import { Red, Green, Yellow } from '../../misc/console-text.js'; import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser'; import * as cluster from '../../misc/cluster.js'; import { isCluster } from '../../config.js'; const WRITE_INTERVAL = 60000; const VALID_SERVICES = new Set([ 'instagram', 'instagram_bearer', 'reddit', 'twitter', 'youtube', ]); const invalidCookies = {}; let cookies = {}, dirty = false, intervalId; function writeChanges(cookiePath) { if (!dirty) return; dirty = false; const cookieData = JSON.stringify({ ...cookies, ...invalidCookies }, null, 4); writeFile(cookiePath, cookieData).catch((e) => { console.warn(`${Yellow('[!]')} failed writing updated cookies to storage`); console.warn(e); clearInterval(intervalId); intervalId = null; }) } const setupMain = async (cookiePath) => { try { cookies = await readFile(cookiePath, 'utf8'); cookies = JSON.parse(cookies); for (const serviceName in cookies) { if (!VALID_SERVICES.has(serviceName)) { console.warn(`${Yellow('[!]')} ignoring unknown service in cookie file: ${serviceName}`); } else if (!Array.isArray(cookies[serviceName])) { console.warn(`${Yellow('[!]')} ${serviceName} in cookies file is not an array, ignoring it`); } else if (cookies[serviceName].some(c => typeof c !== 'string')) { console.warn(`${Yellow('[!]')} some cookie for ${serviceName} contains non-string value in cookies file`); } else continue; invalidCookies[serviceName] = cookies[serviceName]; delete cookies[serviceName]; } if (!intervalId) { intervalId = setInterval(() => writeChanges(cookiePath), WRITE_INTERVAL); } cluster.broadcast({ cookies }); console.log(`${Green('[✓]')} cookies loaded successfully!`); } catch (e) { console.error(`${Yellow('[!]')} failed to load cookies.`); console.error('error:', e); } } const setupWorker = async () => { cookies = (await cluster.waitFor('cookies')).cookies; } export const loadFromFile = async (path) => { if (cluster.isPrimary) { await setupMain(path); } else if (cluster.isWorker) { await setupWorker(); } dirty = false; } export const setup = async (path) => { await loadFromFile(path); if (isCluster) { const messageHandler = (message) => { if ('cookieUpdate' in message) { const { cookieUpdate } = message; if (cluster.isPrimary) { dirty = true; cluster.broadcast({ cookieUpdate }); } const { service, idx, cookie } = cookieUpdate; cookies[service][idx] = cookie; } } if (cluster.isPrimary) { cluster.mainOnMessage(messageHandler); } else { process.on('message', messageHandler); } } } export function getCookie(service) { if (!VALID_SERVICES.has(service)) { console.error( `${Red('[!]')} ${service} not in allowed services list for cookies.` + ' if adding a new cookie type, include it there.' ); return; } if (!cookies[service] || !cookies[service].length) return; const idx = Math.floor(Math.random() * cookies[service].length); const cookie = cookies[service][idx]; if (typeof cookie === 'string') { cookies[service][idx] = Cookie.fromString(cookie); } cookies[service][idx].meta = { service, idx }; return cookies[service][idx]; } export function updateCookieValues(cookie, values) { let changed = false; for (const [ key, value ] of Object.entries(values)) { changed = cookie.set(key, value) || changed; } if (changed && cookie.meta) { dirty = true; if (isCluster) { const message = { cookieUpdate: { ...cookie.meta, cookie } }; cluster.send(message); } } return changed; } export function updateCookie(cookie, headers) { if (!cookie) return; const parsed = parseSetCookie( splitCookiesString(headers.get('set-cookie')), { decodeValues: false } ), values = {} cookie.unset(parsed.filter(c => c.expires < new Date()).map(c => c.name)); parsed.filter(c => !c.expires || c.expires > new Date()).forEach(c => values[c.name] = c.value); updateCookieValues(cookie, values); } ``` ## /api/src/processing/create-filename.js ```js path="/api/src/processing/create-filename.js" const illegalCharacters = ['}', '{', '%', '>', '<', '^', ';', ':', '`', '$', '"', "@", '=', '?', '|', '*']; const sanitizeString = (string) => { for (const i in illegalCharacters) { string = string.replaceAll("/", "_").replaceAll("\\", "_") .replaceAll(illegalCharacters[i], '') } return string; } export default (f, style, isAudioOnly, isAudioMuted) => { let filename = ''; let infoBase = [f.service, f.id]; let classicTags = [...infoBase]; let basicTags = []; let title = sanitizeString(f.title); if (f.author) { title += ` - ${sanitizeString(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}`; } ``` ## /api/src/processing/helpers/youtube-session.js ```js path="/api/src/processing/helpers/youtube-session.js" import * as cluster from "../../misc/cluster.js"; import { Agent } from "undici"; import { env } from "../../config.js"; import { Green, Yellow } from "../../misc/console-text.js"; const defaultAgent = new Agent(); let session; const validateSession = (sessionResponse) => { if (!sessionResponse.potoken) { throw "no poToken in session response"; } if (!sessionResponse.visitor_data) { throw "no visitor_data in session response"; } if (!sessionResponse.updated) { throw "no last update timestamp in session response"; } // https://github.com/iv-org/youtube-trusted-session-generator/blob/c2dfe3f/potoken_generator/main.py#L25 if (sessionResponse.potoken.length < 160) { console.error(`${Yellow('[!]')} poToken is too short and might not work (${new Date().toISOString()})`); } } const updateSession = (newSession) => { session = newSession; } const loadSession = async () => { const sessionServerUrl = new URL(env.ytSessionServer); sessionServerUrl.pathname = "/token"; const newSession = await fetch( sessionServerUrl, { dispatcher: defaultAgent } ).then(a => a.json()); validateSession(newSession); if (!session || session.updated < newSession?.updated) { cluster.broadcast({ youtube_session: newSession }); updateSession(newSession); } } const wrapLoad = (initial = false) => { loadSession() .then(() => { if (initial) { console.log(`${Green('[✓]')} poToken & visitor_data loaded successfully!`); } }) .catch((e) => { console.error(`${Yellow('[!]')} Failed loading poToken & visitor_data at ${new Date().toISOString()}.`); console.error('Error:', e); }) } export const getYouTubeSession = () => { return session; } export const setup = () => { if (cluster.isPrimary) { wrapLoad(true); if (env.ytSessionReloadInterval > 0) { setInterval(wrapLoad, env.ytSessionReloadInterval * 1000); } } else if (cluster.isWorker) { process.on('message', (message) => { if ('youtube_session' in message) { updateSession(message.youtube_session); } }); } } ``` ## /api/src/processing/match-action.js ```js path="/api/src/processing/match-action.js" import createFilename from "./create-filename.js"; 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 = "tunnel", defaultParams = { url: r.urls, headers: r.headers, service: host, filename: r.filenameAttributes ? createFilename(r.filenameAttributes, filenameStyle, isAudioOnly, isAudioMuted) : r.filename, fileMetadata: !disableMetadata ? r.fileMetadata : false, requestIP, originalRequest: r.originalRequest }, params = {}; if (r.isPhoto) action = "photo"; else if (r.picker) action = "picker" else if (r.isGif && twitterGif) action = "gif"; else if (isAudioOnly) action = "audio"; else if (isAudioMuted) action = "muteVideo"; else if (r.isHLS) action = "hls"; else action = "video"; if (action === "picker" || action === "audio") { if (!r.filenameAttributes) defaultParams.filename = r.audioFilename; defaultParams.audioFormat = audioFormat; } 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", { code: "error.api.fetch.empty" }); case "photo": params = { type: "proxy" }; break; case "gif": params = { type: "gif" }; break; case "hls": params = { type: Array.isArray(r.urls) ? "merge" : "remux", isHLS: true, } break; case "muteVideo": let muteType = "mute"; if (Array.isArray(r.urls) && !r.isHLS) { muteType = "proxy"; } params = { type: muteType, url: Array.isArray(r.urls) ? r.urls[0] : r.urls, isHLS: r.isHLS } if (host === "reddit" && r.typeId === "redirect") { responseType = "redirect"; } break; case "picker": responseType = "picker"; switch (host) { case "instagram": case "twitter": case "snapchat": case "bsky": case "xiaohongshu": params = { picker: r.picker }; break; case "tiktok": let audioStreamType = "audio"; if (r.bestAudio === "mp3" && audioFormat === "best") { audioFormat = "mp3"; audioStreamType = "proxy" } params = { picker: r.picker, url: createStream({ service: "tiktok", type: audioStreamType, url: r.urls, headers: r.headers, filename: `${r.audioFilename}.${audioFormat}`, isAudioOnly: true, audioFormat, audioBitrate }) } break; } break; case "video": switch (host) { case "bilibili": 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: "merge" } } else { responseType = "redirect"; } break; case "twitter": if (r.type === "remux") { params = { type: r.type }; } else { responseType = "redirect"; } break; case "ok": case "vk": case "tiktok": case "xiaohongshu": params = { type: "proxy" }; break; case "facebook": case "instagram": case "tumblr": case "pinterest": case "streamable": case "snapchat": case "loom": case "twitch": responseType = "redirect"; break; } break; case "audio": if (audioIgnore.includes(host) || (host === "reddit" && r.typeId === "redirect")) { return createResponse("error", { code: "error.api.service.audio_not_supported" }) } let processType = "audio"; let copy = false; if (audioFormat === "best") { const serviceBestAudio = r.bestAudio; if (serviceBestAudio) { audioFormat = serviceBestAudio; processType = "proxy"; if (host === "soundcloud") { processType = "audio"; copy = true; } } else { audioFormat = "m4a"; copy = true; } } if (r.isHLS || host === "vimeo") { copy = false; processType = "audio"; } params = { type: processType, url: Array.isArray(r.urls) ? r.urls[1] : r.urls, audioBitrate, audioCopy: copy, audioFormat, isHLS: r.isHLS, } 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}) } ``` ## /api/src/processing/match.js ```js path="/api/src/processing/match.js" import { strict as assert } from "node:assert"; import { env } from "../config.js"; import { createResponse } from "../processing/request.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"; import twitter from "./services/twitter.js"; import youtube from "./services/youtube.js"; import vk from "./services/vk.js"; import ok from "./services/ok.js"; import tiktok from "./services/tiktok.js"; import tumblr from "./services/tumblr.js"; import vimeo from "./services/vimeo.js"; import soundcloud from "./services/soundcloud.js"; import instagram from "./services/instagram.js"; import pinterest from "./services/pinterest.js"; import streamable from "./services/streamable.js"; import twitch from "./services/twitch.js"; import rutube from "./services/rutube.js"; import dailymotion from "./services/dailymotion.js"; import snapchat from "./services/snapchat.js"; import loom from "./services/loom.js"; import facebook from "./services/facebook.js"; import bluesky from "./services/bluesky.js"; import xiaohongshu from "./services/xiaohongshu.js"; let freebind; export default async function({ host, patternMatch, params }) { const { url } = params; assert(url instanceof URL); let dispatcher, requestIP; if (env.freebindCIDR) { if (!freebind) { freebind = await import('freebind'); } requestIP = freebind.ip.random(env.freebindCIDR); dispatcher = freebind.dispatcherFromIP(requestIP, { strict: false }); } try { let r, isAudioOnly = params.downloadMode === "audio", isAudioMuted = params.downloadMode === "mute"; if (!testers[host]) { return createResponse("error", { code: "error.api.service.unsupported" }); } if (!(testers[host](patternMatch))) { return createResponse("error", { code: "error.api.link.unsupported", context: { service: friendlyServiceName(host), } }); } switch (host) { case "twitter": r = await twitter({ id: patternMatch.id, index: patternMatch.index - 1, toGif: !!params.twitterGif, alwaysProxy: params.alwaysProxy, dispatcher }); break; case "vk": r = await vk({ ownerId: patternMatch.ownerId, videoId: patternMatch.videoId, accessKey: patternMatch.accessKey, quality: params.videoQuality }); break; case "ok": r = await ok({ id: patternMatch.id, quality: params.videoQuality }); break; case "bilibili": r = await bilibili(patternMatch); break; case "youtube": let fetchInfo = { dispatcher, id: patternMatch.id.slice(0, 11), quality: params.videoQuality, format: params.youtubeVideoCodec, isAudioOnly, isAudioMuted, dubLang: params.youtubeDubLang, youtubeHLS: params.youtubeHLS, } if (url.hostname === "music.youtube.com" || isAudioOnly) { fetchInfo.quality = "1080"; fetchInfo.format = "vp9"; fetchInfo.isAudioOnly = true; fetchInfo.isAudioMuted = false; } r = await youtube(fetchInfo); break; case "reddit": r = await reddit({ ...patternMatch, dispatcher, }); break; case "tiktok": r = await tiktok({ postId: patternMatch.postId, shortLink: patternMatch.shortLink, fullAudio: params.tiktokFullAudio, isAudioOnly, h265: params.tiktokH265, alwaysProxy: params.alwaysProxy, }); break; case "tumblr": r = await tumblr({ id: patternMatch.id, user: patternMatch.user, url }); break; case "vimeo": r = await vimeo({ id: patternMatch.id.slice(0, 11), password: patternMatch.password, quality: params.videoQuality, isAudioOnly, }); break; case "soundcloud": isAudioOnly = true; isAudioMuted = false; r = await soundcloud({ url, author: patternMatch.author, song: patternMatch.song, format: params.audioFormat, shortLink: patternMatch.shortLink || false, accessKey: patternMatch.accessKey || false }); break; case "instagram": r = await instagram({ ...patternMatch, quality: params.videoQuality, alwaysProxy: params.alwaysProxy, dispatcher }) break; case "pinterest": r = await pinterest({ id: patternMatch.id, shortLink: patternMatch.shortLink || false }); break; case "streamable": r = await streamable({ id: patternMatch.id, quality: params.videoQuality, isAudioOnly, }); break; case "twitch": r = await twitch({ clipId: patternMatch.clip || false, quality: params.videoQuality, isAudioOnly, }); break; case "rutube": r = await rutube({ id: patternMatch.id, yappyId: patternMatch.yappyId, key: patternMatch.key, quality: params.videoQuality, isAudioOnly, }); break; case "dailymotion": r = await dailymotion(patternMatch); break; case "snapchat": r = await snapchat({ ...patternMatch, alwaysProxy: params.alwaysProxy, }); break; case "loom": r = await loom({ id: patternMatch.id }); break; case "facebook": r = await facebook({ ...patternMatch, dispatcher }); break; case "bsky": r = await bluesky({ ...patternMatch, alwaysProxy: params.alwaysProxy, dispatcher }); break; case "xiaohongshu": r = await xiaohongshu({ ...patternMatch, h265: params.tiktokH265, isAudioOnly, dispatcher, }); break; default: return createResponse("error", { code: "error.api.service.unsupported" }); } if (r.isAudioOnly) { isAudioOnly = true; isAudioMuted = false; } if (r.error && r.critical) { return createResponse("critical", { code: `error.api.${r.error}`, }) } 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", { code: "error.api.fetch.critical", context: { service: friendlyServiceName(host), } }) } } ``` ## /api/src/processing/request.js ```js path="/api/src/processing/request.js" 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?.url, filename: responseData?.filename } break; case "tunnel": response = { url: createStream(responseData), filename: responseData?.filename } break; case "picker": response = { picker: responseData?.picker, audio: responseData?.url, 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, prefix = 56) { const strippedIP = req.ip.replace(/^::ffff:/, ''); const ip = ipaddr.parse(strippedIP); if (ip.kind() === 'ipv4') { return strippedIP; } const v6Bytes = ip.toByteArray(); v6Bytes.fill(0, prefix / 8); return ipaddr.fromByteArray(v6Bytes).toString(); } ``` ## /api/src/processing/schema.js ```js path="/api/src/processing/schema.js" import { z } from "zod"; import { normalizeURL } from "./url.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() .min(2) .max(8) .regex(/^[0-9a-zA-Z\-]+$/) .optional(), // TODO: remove this variable as it's no longer used // and is kept for schema compatibility reasons youtubeDubBrowserLang: z.boolean().default(false), 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), youtubeHLS: z.boolean().default(false), }) .strict(); ``` ## /api/src/processing/service-alias.js ```js path="/api/src/processing/service-alias.js" const friendlyNames = { bsky: "bluesky", } export const friendlyServiceName = (service) => { if (service in friendlyNames) { return friendlyNames[service]; } return service; } ``` ## /api/src/processing/service-config.js ```js path="/api/src/processing/service-config.js" import UrlPattern from "url-pattern"; export const audioIgnore = ["vk", "ok", "loom"]; export const hlsExceptions = ["dailymotion", "vimeo", "rutube", "bsky", "youtube"]; 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", "m"], altDomains: ["fb.watch"], }, instagram: { patterns: [ "p/:postId", "tv/:postId", "reel/:postId", "reels/:postId", "stories/:username/:storyId", /* share & username links use the same url pattern, so we test the share pattern first, cuz id type is different. however, if someone has the "share" username and the user somehow gets a link of this ancient style, it's joever. */ "share/:shareId", "share/p/:shareId", "share/reel/:shareId", ":username/p/:postId", ":username/reel/:postId", ], altDomains: ["ddinstagram.com"], }, loom: { patterns: ["share/:id", "embed/:id"], }, ok: { patterns: [ "video/:id", "videoembed/:id" ], tld: "ru", }, pinterest: { patterns: [ "pin/:id", "pin/:id/:garbage", "url_shortener/:shortLink" ], }, reddit: { patterns: [ "comments/:id", "r/:sub/comments/:id", "r/:sub/comments/:id/:title", "r/:sub/comments/:id/comment/:commentId", "user/:user/comments/:id", "user/:user/comments/:id/:title", "user/:user/comments/:id/comment/:commentId", "r/u_:user/comments/:id", "r/u_:user/comments/:id/:title", "r/u_:user/comments/:id/comment/:commentId", "r/:sub/s/:shareId", "video/:shortId", ], 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", "o/:spotlightId", ], 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", "i18n/share/video/:postId", ":shortLink", "t/:shortLink", ":user/photo/:postId", "v/:postId.html" ], subdomains: ["vt", "vm", "m", "t"], }, 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"], }, vimeo: { patterns: [ ":id", "video/:id", ":id/:password", "/channels/:user/:id" ], subdomains: ["player"], }, vk: { patterns: [ "video:ownerId_:videoId", "clip:ownerId_:videoId", "clips:duplicate?z=clip:ownerId_:videoId", "videos:duplicate?z=video:ownerId_:videoId", "video:ownerId_:videoId_:accessKey", "clip:ownerId_:videoId_:accessKey", "clips:duplicate?z=clip:ownerId_:videoId_:accessKey", "videos:duplicate?z=video:ownerId_:videoId_:accessKey" ], subdomains: ["m"], altDomains: ["vkvideo.ru", "vk.ru"], }, xiaohongshu: { patterns: [ "explore/:id?xsec_token=:token", "discovery/item/:id?xsec_token=:token", "a/:shareId" ], altDomains: ["xhslink.com"], }, 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 + '@\\.:' }) ) }) ``` ## /api/src/processing/service-patterns.js ```js path="/api/src/processing/service-patterns.js" 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 <= 48 || pattern.shareId?.length <= 16 || (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.id?.length <= 16 && !pattern.sub && !pattern.user || (pattern.sub?.length <= 22 && pattern.id?.length <= 16) || (pattern.user?.length <= 22 && pattern.id?.length <= 16) || (pattern.sub?.length <= 22 && pattern.shareId?.length <= 16) || (pattern.shortId?.length <= 16), "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.shortLink?.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), "vk": pattern => (pattern.ownerId?.length <= 10 && pattern.videoId?.length <= 10) || (pattern.ownerId?.length <= 10 && pattern.videoId?.length <= 10 && pattern.videoId?.accessKey <= 18), "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, "xiaohongshu": pattern => pattern.id?.length <= 24 && pattern.token?.length <= 64 || pattern.shareId?.length <= 24, } ``` ## /api/src/processing/services/bilibili.js ```js path="/api/src/processing/services/bilibili.js" import { genericUserAgent, env } from "../../config.js"; import { resolveRedirectingURL } from "../url.js"; // TO-DO: higher quality downloads (currently requires an account) function getBest(content) { return content?.filter(v => v.baseUrl || v.url) .map(v => (v.baseUrl = v.baseUrl || v.url, v)) .reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b); } function extractBestQuality(dashData) { const bestVideo = getBest(dashData.video), bestAudio = getBest(dashData.audio); if (!bestVideo || !bestAudio) return []; return [ bestVideo, bestAudio ]; } 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: "fetch.fail" } } if (!(html.includes('')[0]); if (streamData.data.timelength > env.durationLimit * 1000) { return { error: "content.too_long" }; } const [ video, audio ] = extractBestQuality(streamData.data.dash); if (!video || !audio) { return { error: "fetch.empty" }; } return { urls: [video.baseUrl, audio.baseUrl], audioFilename: `bilibili_${id}_audio`, filename: `bilibili_${id}_${video.width}x${video.height}.mp4` }; } async function tv_download(id) { const url = new URL( 'https://api.bilibili.tv/intl/gateway/web/playurl' + '?s_locale=en_US&platform=web&qn=64&type=0&device=wap' + '&tf=0&spm_id=bstar-web.ugc-video-detail.0.0&from_spm_id=' ); url.searchParams.set('aid', id); const { data } = await fetch(url).then(a => a.json()); if (!data?.playurl?.video) { return { error: "fetch.empty" }; } const [ video, audio ] = extractBestQuality({ video: data.playurl.video.map(s => s.video_resource) .filter(s => s.codecs.includes('avc1')), audio: data.playurl.audio_resource }); if (!video || !audio) { return { error: "fetch.empty" }; } if (video.duration > env.durationLimit * 1000) { return { error: "content.too_long" }; } return { urls: [video.url, audio.url], audioFilename: `bilibili_tv_${id}_audio`, filename: `bilibili_tv_${id}.mp4` }; } export default async function({ comId, tvId, comShortLink }) { if (comShortLink) { const patternMatch = await resolveRedirectingURL(`https://b23.tv/${comShortLink}`); comId = patternMatch?.comId; } if (comId) { return com_download(comId); } else if (tvId) { return tv_download(tvId); } return { error: "fetch.fail" }; } ``` ## /api/src/processing/services/bluesky.js ```js path="/api/src/processing/services/bluesky.js" import HLS from "hls-parser"; import { cobaltUserAgent } from "../../config.js"; import { createStream } from "../../stream/manage.js"; const extractVideo = async ({ media, filename, dispatcher }) => { let urlMasterHLS = media?.playlist; if (!urlMasterHLS || !urlMasterHLS.startsWith("https://video.bsky.app/")) { return { error: "fetch.empty" }; } urlMasterHLS = urlMasterHLS.replace( "video.bsky.app/watch/", "video.cdn.bsky.app/hls/" ); const masterHLS = await fetch(urlMasterHLS, { dispatcher }) .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`, isHLS: 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", url, filename: `${filename}_${i + 1}.jpg`, }); if (alwaysProxy) url = proxiedImage; return { type: "photo", url, thumb: proxiedImage, } }); return { picker }; } const extractGif = ({ url, filename }) => { const gifUrl = new URL(url); if (!gifUrl || gifUrl.hostname !== "media.tenor.com") { return { error: "fetch.empty" }; } // remove downscaling params from gif url // such as "?hh=498&ww=498" gifUrl.search = ""; return { urls: gifUrl, isPhoto: true, filename: `${filename}.gif`, } } export default async function ({ user, post, alwaysProxy, dispatcher }) { 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, }, dispatcher }).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: "content.post.unavailable" }; } } const embedType = getPost?.thread?.post?.embed?.$type; const filename = `bluesky_${user}_${post}`; switch (embedType) { case "app.bsky.embed.video#view": return extractVideo({ media: getPost.thread?.post?.embed, filename, }); case "app.bsky.embed.images#view": return extractImages({ getPost, filename, alwaysProxy }); case "app.bsky.embed.external#view": return extractGif({ url: getPost?.thread?.post?.embed?.external?.uri, filename, }); case "app.bsky.embed.recordWithMedia#view": if (getPost?.thread?.post?.embed?.media?.$type === "app.bsky.embed.external#view") { return extractGif({ url: getPost?.thread?.post?.embed?.media?.external?.uri, filename, }); } return extractVideo({ media: getPost.thread?.post?.embed?.media, filename, }); } return { error: "fetch.empty" }; } ``` ## /api/src/processing/services/dailymotion.js ```js path="/api/src/processing/services/dailymotion.js" import HLSParser from "hls-parser"; import { env } from "../../config.js"; let _token; function getExp(token) { return JSON.parse( Buffer.from(token.split('.')[1], 'base64') ).exp * 1000; } const getToken = async () => { if (_token && getExp(_token) > new Date().getTime()) { return _token; } const req = await fetch('https://graphql.api.dailymotion.com/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': 'dailymotion/240213162706 CFNetwork/1492.0.1 Darwin/23.3.0', 'Authorization': 'Basic MGQyZDgyNjQwOWFmOWU3MmRiNWQ6ODcxNmJmYTVjYmEwMmUwMGJkYTVmYTg1NTliNDIwMzQ3NzIyYWMzYQ==' }, body: 'traffic_segment=&grant_type=client_credentials' }).then(r => r.json()).catch(() => {}); if (req.access_token) { return _token = req.access_token; } } export default async function({ id }) { const token = await getToken(); if (!token) return { error: "fetch.fail" }; const req = await fetch('https://graphql.api.dailymotion.com/', { method: 'POST', headers: { 'User-Agent': 'dailymotion/240213162706 CFNetwork/1492.0.1 Darwin/23.3.0', Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', 'X-DM-AppInfo-Version': '7.16.0_240213162706', 'X-DM-AppInfo-Type': 'iosapp', 'X-DM-AppInfo-Id': 'com.dailymotion.dailymotion' }, body: JSON.stringify({ operationName: "Media", query: ` query Media($xid: String!, $password: String) { media(xid: $xid, password: $password) { __typename ... on Video { xid hlsURL duration title channel { displayName } } } } `, variables: { xid: id } }) } ).then(r => r.status === 200 && r.json()).catch(() => {}); const media = req?.data?.media; if (media?.__typename !== 'Video' || !media.hlsURL) { return { error: "fetch.empty" } } if (media.duration > env.durationLimit) { return { error: "content.too_long" }; } const manifest = await fetch(media.hlsURL).then(r => r.text()).catch(() => {}); 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: "fetch.empty" } const fileMetadata = { title: media.title, artist: media.channel.displayName } return { urls: bestQuality.uri, isHLS: true, filenameAttributes: { service: 'dailymotion', id: media.xid, title: fileMetadata.title, author: fileMetadata.artist, resolution: `${bestQuality.resolution.width}x${bestQuality.resolution.height}`, qualityLabel: `${bestQuality.resolution.height}p`, extension: 'mp4' }, fileMetadata } } ``` ## /api/src/processing/services/facebook.js ```js path="/api/src/processing/services/facebook.js" import { genericUserAgent } from "../../config.js"; const headers = { 'User-Agent': genericUserAgent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', } const resolveUrl = (url, dispatcher) => { return fetch(url, { headers, dispatcher }) .then(r => { if (r.headers.get('location')) { return decodeURIComponent(r.headers.get('location')); } if (r.headers.get('link')) { const linkMatch = r.headers.get('link').match(/<(.*?)\/>/); return decodeURIComponent(linkMatch[1]); } return false; }) .catch(() => false); } export default async function({ id, shareType, shortLink, dispatcher }) { let url = `https://web.facebook.com/i/videos/${id}`; if (shareType) url = `https://web.facebook.com/share/${shareType}/${id}`; if (shortLink) url = await resolveUrl(`https://fb.watch/${shortLink}`, dispatcher); const html = await fetch(url, { headers, dispatcher }) .then(r => r.text()) .catch(() => false); if (!html && shortLink) return { error: "fetch.short_link" } if (!html) return { error: "fetch.fail" }; const urls = []; const hd = html.match('"browser_native_hd_url":(".*?")'); const sd = html.match('"browser_native_sd_url":(".*?")'); if (hd?.[1]) urls.push(JSON.parse(hd[1])); if (sd?.[1]) urls.push(JSON.parse(sd[1])); if (!urls.length) { return { error: "fetch.empty" }; } const baseFilename = `facebook_${id || shortLink}`; return { urls: urls[0], filename: `${baseFilename}.mp4`, audioFilename: `${baseFilename}_audio`, }; } ``` ## /api/src/processing/services/instagram.js ```js path="/api/src/processing/services/instagram.js" import { randomBytes } from "node:crypto"; import { resolveRedirectingURL } from "../url.js"; import { genericUserAgent } from "../../config.js"; import { createStream } from "../../stream/manage.js"; import { getCookie, updateCookie } from "../cookie/manager.js"; const commonHeaders = { "user-agent": genericUserAgent, "sec-gpc": "1", "sec-fetch-site": "same-origin", "x-ig-app-id": "936619743392459" } const mobileHeaders = { "x-ig-app-locale": "en_US", "x-ig-device-locale": "en_US", "x-ig-mapped-locale": "en_US", "user-agent": "Instagram 275.0.0.27.98 Android (33/13; 280dpi; 720x1423; Xiaomi; Redmi 7; onclite; qcom; en_US; 458229237)", "accept-language": "en-US", "x-fb-http-engine": "Liger", "x-fb-client-ip": "True", "x-fb-server-cluster": "True", "content-length": "0", } const embedHeaders = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", "Accept-Language": "en-GB,en;q=0.9", "Cache-Control": "max-age=0", "Dnt": "1", "Priority": "u=0, i", "Sec-Ch-Ua": 'Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99', "Sec-Ch-Ua-Mobile": "?0", "Sec-Ch-Ua-Platform": "macOS", "Sec-Fetch-Dest": "document", "Sec-Fetch-Mode": "navigate", "Sec-Fetch-Site": "none", "Sec-Fetch-User": "?1", "Upgrade-Insecure-Requests": "1", "User-Agent": genericUserAgent, } const cachedDtsg = { value: '', expiry: 0 } const getNumberFromQuery = (name, data) => { const s = data?.match(new RegExp(name + '=(\\d+)'))?.[1]; if (+s) return +s; } const getObjectFromEntries = (name, data) => { const obj = data?.match(new RegExp('\\["' + name + '",.*?,({.*?}),\\d+\\]'))?.[1]; return obj && JSON.parse(obj); } export default function instagram(obj) { const dispatcher = obj.dispatcher; async function findDtsgId(cookie) { try { if (cachedDtsg.expiry > Date.now()) return cachedDtsg.value; const data = await fetch('https://www.instagram.com/', { headers: { ...commonHeaders, cookie }, dispatcher }).then(r => r.text()); const token = data.match(/"dtsg":{"token":"(.*?)"/)[1]; cachedDtsg.value = token; cachedDtsg.expiry = Date.now() + 86390000; if (token) return token; return false; } catch {} } async function request(url, cookie, method = 'GET', requestData) { let headers = { ...commonHeaders, 'x-ig-www-claim': cookie?._wwwClaim || '0', 'x-csrftoken': cookie?.values()?.csrftoken, cookie } if (method === 'POST') { headers['content-type'] = 'application/x-www-form-urlencoded'; } const data = await fetch(url, { method, headers, body: requestData && new URLSearchParams(requestData), dispatcher }); if (data.headers.get('X-Ig-Set-Www-Claim') && cookie) cookie._wwwClaim = data.headers.get('X-Ig-Set-Www-Claim'); updateCookie(cookie, data.headers); return data.json(); } async function getMediaId(id, { cookie, token } = {}) { const oembedURL = new URL('https://i.instagram.com/api/v1/oembed/'); oembedURL.searchParams.set('url', `https://www.instagram.com/p/${id}/`); const oembed = await fetch(oembedURL, { headers: { ...mobileHeaders, ...( token && { authorization: `Bearer ${token}` } ), cookie }, dispatcher }).then(r => r.json()).catch(() => {}); return oembed?.media_id; } async function requestMobileApi(mediaId, { cookie, token } = {}) { const mediaInfo = await fetch(`https://i.instagram.com/api/v1/media/${mediaId}/info/`, { headers: { ...mobileHeaders, ...( token && { authorization: `Bearer ${token}` } ), cookie }, dispatcher }).then(r => r.json()).catch(() => {}); return mediaInfo?.items?.[0]; } async function requestHTML(id, cookie) { const data = await fetch(`https://www.instagram.com/p/${id}/embed/captioned/`, { headers: { ...embedHeaders, cookie }, dispatcher }).then(r => r.text()).catch(() => {}); let embedData = JSON.parse(data?.match(/"init",\[\],\[(.*?)\]\],/)[1]); if (!embedData || !embedData?.contextJSON) return false; embedData = JSON.parse(embedData.contextJSON); return embedData; } async function getGQLParams(id, cookie) { const req = await fetch(`https://www.instagram.com/p/${id}/`, { headers: { ...embedHeaders, cookie }, dispatcher }); const html = await req.text(); const siteData = getObjectFromEntries('SiteData', html); const polarisSiteData = getObjectFromEntries('PolarisSiteData', html); const webConfig = getObjectFromEntries('DGWWebConfig', html); const pushInfo = getObjectFromEntries('InstagramWebPushInfo', html); const lsd = getObjectFromEntries('LSD', html)?.token || randomBytes(8).toString('base64url'); const csrf = getObjectFromEntries('InstagramSecurityConfig', html)?.csrf_token; const anon_cookie = [ csrf && "csrftoken=" + csrf, polarisSiteData?.device_id && "ig_did=" + polarisSiteData?.device_id, "wd=1280x720", "dpr=2", polarisSiteData?.machine_id && "mid=" + polarisSiteData.machine_id, "ig_nrcb=1" ].filter(a => a).join('; '); return { headers: { 'x-ig-app-id': webConfig?.appId || '936619743392459', 'X-FB-LSD': lsd, 'X-CSRFToken': csrf, 'X-Bloks-Version-Id': getObjectFromEntries('WebBloksVersioningID', html)?.versioningID, 'x-asbd-id': 129477, cookie: anon_cookie }, body: { __d: 'www', __a: '1', __s: '::' + Math.random().toString(36).substring(2).replace(/\d/g, '').slice(0, 6), __hs: siteData?.haste_session || '20126.HYP:instagram_web_pkg.2.1...0', __req: 'b', __ccg: 'EXCELLENT', __rev: pushInfo?.rollout_hash || '1019933358', __hsi: siteData?.hsi || '7436540909012459023', __dyn: randomBytes(154).toString('base64url'), __csr: randomBytes(154).toString('base64url'), __user: '0', __comet_req: getNumberFromQuery('__comet_req', html) || '7', av: '0', dpr: '2', lsd, jazoest: getNumberFromQuery('jazoest', html) || Math.floor(Math.random() * 10000), __spin_r: siteData?.__spin_r || '1019933358', __spin_b: siteData?.__spin_b || 'trunk', __spin_t: siteData?.__spin_t || Math.floor(new Date().getTime() / 1000), } }; } async function requestGQL(id, cookie) { const { headers, body } = await getGQLParams(id, cookie); const req = await fetch('https://www.instagram.com/graphql/query', { method: 'POST', dispatcher, headers: { ...embedHeaders, ...headers, cookie, 'content-type': 'application/x-www-form-urlencoded', 'X-FB-Friendly-Name': 'PolarisPostActionLoadPostQueryQuery', }, body: new URLSearchParams({ ...body, fb_api_caller_class: 'RelayModern', fb_api_req_friendly_name: 'PolarisPostActionLoadPostQueryQuery', variables: JSON.stringify({ shortcode: id, fetch_tagged_user_count: null, hoisted_comment_id: null, hoisted_reply_id: null }), server_timestamps: true, doc_id: '8845758582119845' }).toString() }); return { gql_data: await req.json() .then(r => r.data) .catch(() => null) }; } async function getErrorContext(id) { try { const { headers, body } = await getGQLParams(id); const req = await fetch('https://www.instagram.com/ajax/bulk-route-definitions/', { method: 'POST', dispatcher, headers: { ...embedHeaders, ...headers, 'content-type': 'application/x-www-form-urlencoded', 'X-Ig-D': 'www', }, body: new URLSearchParams({ 'route_urls[0]': `/p/${id}/`, routing_namespace: 'igx_www', ...body }).toString() }); const response = await req.text(); if (response.includes('"tracePolicy":"polaris.privatePostPage"')) return { error: 'content.post.private' }; const [, mediaId, mediaOwnerId] = response.match( /"media_id":\s*?"(\d+)","media_owner_id":\s*?"(\d+)"/ ) || []; if (mediaId && mediaOwnerId) { const rulingURL = new URL('https://www.instagram.com/api/v1/web/get_ruling_for_media_content_logged_out'); rulingURL.searchParams.set('media_id', mediaId); rulingURL.searchParams.set('owner_id', mediaOwnerId); const rulingResponse = await fetch(rulingURL, { headers: { ...headers, ...commonHeaders }, dispatcher, }).then(a => a.json()).catch(() => ({})); if (rulingResponse?.title?.includes('Restricted')) return { error: "content.post.age" }; } } catch { return { error: "fetch.fail" }; } return { error: "fetch.empty" }; } function extractOldPost(data, id, alwaysProxy) { const shortcodeMedia = data?.gql_data?.shortcode_media || data?.gql_data?.xdt_shortcode_media; const sidecar = shortcodeMedia?.edge_sidecar_to_children; if (sidecar) { const picker = sidecar.edges.filter(e => e.node?.display_url) .map((e, i) => { const type = e.node?.is_video && e.node?.video_url ? "video" : "photo"; let url; if (type === "video") { url = e.node?.video_url; } else if (type === "photo") { url = e.node?.display_url; } let itemExt = type === "video" ? "mp4" : "jpg"; let proxyFile; if (alwaysProxy) proxyFile = createStream({ service: "instagram", type: "proxy", url, filename: `instagram_${id}_${i + 1}.${itemExt}` }); return { 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: "proxy", url: e.node?.display_url, filename: `instagram_${id}_${i + 1}.jpg` }) } }); if (picker.length) return { picker } } if (shortcodeMedia?.video_url) { return { urls: shortcodeMedia.video_url, filename: `instagram_${id}.mp4`, audioFilename: `instagram_${id}_audio` } } if (shortcodeMedia?.display_url) { return { urls: shortcodeMedia.display_url, isPhoto: true, filename: `instagram_${id}.jpg`, } } } function extractNewPost(data, id, alwaysProxy) { const carousel = data.carousel_media; if (carousel) { const picker = carousel.filter(e => e?.image_versions2) .map((e, i) => { const type = e.video_versions ? "video" : "photo"; const imageUrl = e.image_versions2.candidates[0].url; let url = imageUrl; 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", url, filename: `instagram_${id}_${i + 1}.${itemExt}` }); return { type, url: proxyFile || url, /* thumbnails have `Cross-Origin-Resource-Policy` ** set to `same-origin`, so we need to always proxy them */ thumb: createStream({ service: "instagram", type: "proxy", url: imageUrl, filename: `instagram_${id}_${i + 1}.jpg` }) } }); if (picker.length) return { picker } } else if (data.video_versions) { const video = data.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a) return { urls: video.url, filename: `instagram_${id}.mp4`, audioFilename: `instagram_${id}_audio` } } else if (data.image_versions2?.candidates) { return { urls: data.image_versions2.candidates[0].url, isPhoto: true, filename: `instagram_${id}.jpg`, } } } async function getPost(id, alwaysProxy) { const hasData = (data) => data && data.gql_data !== null && data?.gql_data?.xdt_shortcode_media !== null; let data, result; try { const cookie = getCookie('instagram'); const bearer = getCookie('instagram_bearer'); const token = bearer?.values()?.token; // get media_id for mobile api, three methods let media_id = await getMediaId(id); if (!media_id && token) media_id = await getMediaId(id, { token }); if (!media_id && cookie) media_id = await getMediaId(id, { cookie }); // mobile api (bearer) if (media_id && token) data = await requestMobileApi(media_id, { token }); // mobile api (no cookie, cookie) if (media_id && !hasData(data)) data = await requestMobileApi(media_id); if (media_id && cookie && !hasData(data)) data = await requestMobileApi(media_id, { cookie }); // html embed (no cookie, cookie) if (!hasData(data)) data = await requestHTML(id); if (!hasData(data) && cookie) data = await requestHTML(id, cookie); // web app graphql api (no cookie, cookie) if (!hasData(data)) data = await requestGQL(id); if (!hasData(data) && cookie) data = await requestGQL(id, cookie); } catch {} if (!hasData(data)) { return getErrorContext(id); } if (data?.gql_data) { result = extractOldPost(data, id, alwaysProxy) } else { result = extractNewPost(data, id, alwaysProxy) } if (result) return result; return { error: "fetch.empty" } } async function usernameToId(username, cookie) { const url = new URL('https://www.instagram.com/api/v1/users/web_profile_info/'); url.searchParams.set('username', username); try { const data = await request(url, cookie); return data?.data?.user?.id; } catch {} } async function getStory(username, id) { const cookie = getCookie('instagram'); if (!cookie) return { error: "link.unsupported" }; const userId = await usernameToId(username, cookie); if (!userId) return { error: "fetch.empty" }; const dtsgId = await findDtsgId(cookie); const url = new URL('https://www.instagram.com/api/graphql/'); const requestData = { fb_dtsg: dtsgId, jazoest: '26438', variables: JSON.stringify({ reel_ids_arr : [ userId ], }), server_timestamps: true, doc_id: '25317500907894419' }; let media; try { const data = (await request(url, cookie, 'POST', requestData)); media = data?.data?.xdt_api__v1__feed__reels_media?.reels_media?.find(m => m.id === userId); } catch {} const item = media.items.find(m => m.pk === id); 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 { urls: video.url, filename: `instagram_${id}.mp4`, audioFilename: `instagram_${id}_audio` } } if (item.image_versions2?.candidates) { return { urls: item.image_versions2.candidates[0].url, isPhoto: true, filename: `instagram_${id}.jpg`, } } return { error: "link.unsupported" }; } const { postId, shareId, storyId, username, alwaysProxy } = obj; if (shareId) { return resolveRedirectingURL( `https://www.instagram.com/share/${shareId}/`, dispatcher, // for some reason instagram decides to return HTML // instead of a redirect when requesting with a normal // browser user-agent {'User-Agent': 'curl/7.88.1'} ).then(match => instagram({ ...obj, ...match, shareId: undefined })); } if (postId) return getPost(postId, alwaysProxy); if (username && storyId) return getStory(username, storyId); return { error: "fetch.empty" } } ``` ## /api/src/processing/services/loom.js ```js path="/api/src/processing/services/loom.js" import { genericUserAgent } from "../../config.js"; export default async function({ id }) { const gql = await fetch(`https://www.loom.com/api/campaigns/sessions/${id}/transcoded-url`, { method: "POST", headers: { "user-agent": genericUserAgent, origin: "https://www.loom.com", referer: `https://www.loom.com/share/${id}`, cookie: `loom_referral_video=${id};`, "apollographql-client-name": "web", "apollographql-client-version": "14c0b42", "x-loom-request-source": "loom_web_14c0b42", }, body: JSON.stringify({ force_original: false, password: null, anonID: null, deviceID: null }) }) .then(r => r.status === 200 ? r.json() : false) .catch(() => {}); if (!gql) return { error: "fetch.empty" }; const videoUrl = gql?.url; if (videoUrl?.includes('.mp4?')) { return { urls: videoUrl, filename: `loom_${id}.mp4`, audioFilename: `loom_${id}_audio` } } return { error: "fetch.empty" } } ``` ## /api/src/processing/services/ok.js ```js path="/api/src/processing/services/ok.js" import { genericUserAgent, env } from "../../config.js"; const resolutions = { "ultra": "2160", "quad": "1440", "full": "1080", "hd": "720", "sd": "480", "low": "360", "lowest": "240", "mobile": "144" } export default async function(o) { let quality = o.quality === "max" ? "2160" : o.quality; let html = await fetch(`https://ok.ru/video/${o.id}`, { headers: { "user-agent": genericUserAgent } }).then(r => r.text()).catch(() => {}); if (!html) return { error: "fetch.fail" }; let videoData = html.match(/
/) ?.[1] ?.replaceAll(""", '"'); if (!videoData) { return { error: "fetch.empty" }; } videoData = JSON.parse(JSON.parse(videoData).flashvars.metadata); if (videoData.provider !== "UPLOADED_ODKL") return { error: "link.unsupported" }; if (videoData.movie.is_live) return { error: "content.video.live" }; if (videoData.movie.duration > env.durationLimit) 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]; let fileMetadata = { title: videoData.movie.title.trim(), author: (videoData.author?.name || videoData.compilationTitle)?.trim(), } if (bestVideo) return { urls: bestVideo.url, filenameAttributes: { service: "ok", id: o.id, title: fileMetadata.title, author: fileMetadata.author, resolution: `${resolutions[bestVideo.name]}p`, qualityLabel: `${resolutions[bestVideo.name]}p`, extension: "mp4" } } return { error: "fetch.empty" } } ``` ## /api/src/processing/services/pinterest.js ```js path="/api/src/processing/services/pinterest.js" import { genericUserAgent } from "../../config.js"; import { resolveRedirectingURL } from "../url.js"; const videoRegex = /"url":"(https:\/\/v1\.pinimg\.com\/videos\/.*?)"/g; const imageRegex = /src="(https:\/\/i\.pinimg\.com\/.*\.(jpg|gif))"/g; export default async function(o) { let id = o.id; if (!o.id && o.shortLink) { const patternMatch = await resolveRedirectingURL(`https://api.pinterest.com/url_shortener/${o.shortLink}/redirect/`); id = patternMatch?.id; } if (id.includes("--")) id = id.split("--")[1]; if (!id) return { error: "fetch.fail" }; const html = await fetch(`https://www.pinterest.com/pin/${id}/`, { headers: { "user-agent": genericUserAgent } }).then(r => r.text()).catch(() => {}); if (!html) return { error: "fetch.fail" }; const videoLink = [...html.matchAll(videoRegex)] .map(([, link]) => link) .find(a => a.endsWith('.mp4')); if (videoLink) return { urls: videoLink, filename: `pinterest_${id}.mp4`, audioFilename: `pinterest_${id}_audio` } 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, filename: `pinterest_${id}.${imageType}` } return { error: "fetch.empty" }; } ``` ## /api/src/processing/services/reddit.js ```js path="/api/src/processing/services/reddit.js" import { resolveRedirectingURL } from "../url.js"; import { genericUserAgent, env } from "../../config.js"; import { getCookie, updateCookieValues } from "../cookie/manager.js"; async function getAccessToken() { /* "cookie" in cookiefile needs to contain: * client_id, client_secret, refresh_token * e.g. client_id=bla; client_secret=bla; refresh_token=bla * * 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'); if (!cookie) return; const values = cookie.values(), needRefresh = !values.access_token || !values.expiry || Number(values.expiry) < new Date().getTime(); if (!needRefresh) return values.access_token; const data = await fetch('https://www.reddit.com/api/v1/access_token', { method: 'POST', headers: { 'authorization': `Basic ${Buffer.from( [values.client_id, values.client_secret].join(':') ).toString('base64')}`, 'content-type': 'application/x-www-form-urlencoded', 'user-agent': genericUserAgent, 'accept': 'application/json' }, body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(values.refresh_token)}` }).then(r => r.json()).catch(() => {}); if (!data) return; const { access_token, refresh_token, expires_in } = data; if (!access_token) return; updateCookieValues(cookie, { ...cookie.values(), access_token, refresh_token, expiry: new Date().getTime() + (expires_in * 1000), }); return access_token; } export default async function(obj) { let params = obj; const accessToken = await getAccessToken(); const headers = { 'user-agent': genericUserAgent, authorization: accessToken && `Bearer ${accessToken}`, accept: 'application/json' }; if (params.shortId) { params = await resolveRedirectingURL( `https://www.reddit.com/video/${params.shortId}`, obj.dispatcher, headers ); } if (!params.id && params.shareId) { params = await resolveRedirectingURL( `https://www.reddit.com/r/${params.sub}/s/${params.shareId}`, obj.dispatcher, headers ); } if (!params?.id) return { error: "fetch.short_link" }; const url = new URL(`https://www.reddit.com/comments/${params.id}.json`); if (accessToken) url.hostname = 'oauth.reddit.com'; let data = await fetch( url, { headers } ).then(r => r.json()).catch(() => {}); if (!data || !Array.isArray(data)) { return { error: "fetch.fail" } } data = data[0]?.data?.children[0]?.data; let sourceId; if (params.sub || params.user) { sourceId = `${String(params.sub || params.user).toLowerCase()}_${params.id}`; } else { sourceId = params.id; } if (data?.url?.endsWith('.gif')) return { typeId: "redirect", urls: data.url, filename: `reddit_${sourceId}.gif`, } if (!data.secure_media?.reddit_video) return { error: "fetch.empty" }; if (data.secure_media?.reddit_video?.duration > env.durationLimit) return { error: "content.too_long" }; const video = data.secure_media?.reddit_video?.fallback_url?.split('?')[0]; let audio = false, audioFileLink = `${data.secure_media?.reddit_video?.fallback_url?.split('DASH')[0]}audio`; if (video.match('.mp4')) { audioFileLink = `${video.split('_')[0]}_audio.mp4` } // test the existence of audio await fetch(audioFileLink, { method: "HEAD" }).then(r => { if (Number(r.status) === 200) { audio = true } }).catch(() => {}) // fallback for videos with variable audio quality if (!audio) { audioFileLink = `${video.split('_')[0]}_AUDIO_128.mp4` await fetch(audioFileLink, { method: "HEAD" }).then(r => { if (Number(r.status) === 200) { audio = true } }).catch(() => {}) } if (!audio) return { typeId: "redirect", urls: video } return { typeId: "tunnel", type: "merge", urls: [video, audioFileLink], audioFilename: `reddit_${sourceId}_audio`, filename: `reddit_${sourceId}.mp4` } } ``` ## /api/src/processing/services/rutube.js ```js path="/api/src/processing/services/rutube.js" import HLS from "hls-parser"; import { env } from "../../config.js"; async function requestJSON(url) { try { const r = await fetch(url); return await r.json(); } catch {} } const delta = (a, b) => Math.abs(a - b); export default async function(obj) { if (obj.yappyId) { const yappy = await requestJSON( `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: "fetch.empty" }; return { urls: yappyURL, filename: `rutube_yappy_${obj.yappyId}.mp4`, audioFilename: `rutube_yappy_${obj.yappyId}_audio` } } const quality = Number(obj.quality) || 9000; const requestURL = new URL(`https://rutube.ru/api/play/options/${obj.id}/?no_404=true&referer&pver=v2`); if (obj.key) requestURL.searchParams.set('p', obj.key); const play = await requestJSON(requestURL); if (!play) return { error: "fetch.fail" }; if (play.detail?.type === "blocking_rule") { return { error: "content.video.region" }; } 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: "content.too_long" }; let m3u8 = await fetch(play.video_balancer.m3u8) .then(r => r.text()) .catch(() => {}); if (!m3u8) return { error: "fetch.fail" }; m3u8 = HLS.parse(m3u8).variants; const matchingQuality = m3u8.reduce((prev, next) => { const diff = { prev: delta(quality, prev.resolution.height), next: delta(quality, next.resolution.height) }; return diff.prev < diff.next ? prev : next; }); const fileMetadata = { title: play.title.trim(), artist: play.author.name.trim(), } return { urls: matchingQuality.uri, isHLS: true, filenameAttributes: { service: "rutube", id: obj.id, title: fileMetadata.title, author: fileMetadata.artist, resolution: `${matchingQuality.resolution.width}x${matchingQuality.resolution.height}`, qualityLabel: `${matchingQuality.resolution.height}p`, extension: "mp4" }, fileMetadata: fileMetadata } } ``` ## /api/src/processing/services/snapchat.js ```js path="/api/src/processing/services/snapchat.js" import { resolveRedirectingURL } from "../url.js"; import { genericUserAgent } from "../../config.js"; import { createStream } from "../../stream/manage.js"; const SPOTLIGHT_VIDEO_REGEX = //; const NEXT_DATA_REGEX = /')[0]; const data = JSON.parse(json); const videoDetail = data["__DEFAULT_SCOPE__"]["webapp.video-detail"]; if (!videoDetail) throw "no video detail found"; // status_deleted or etc if (videoDetail.statusMsg) { return { error: "content.post.unavailable"}; } detail = videoDetail?.itemInfo?.itemStruct; } catch { return { error: "fetch.fail" }; } if (detail.isContentClassified) { return { error: "content.post.age" }; } if (!detail.author) { return { error: "fetch.empty" }; } let video, videoFilename, audioFilename, audio, images, filenameBase = `tiktok_${detail.author?.uniqueId}_${postId}`, bestAudio; // will get defaulted to m4a later on in match-action images = detail.imagePost?.images; let playAddr = detail.video?.playAddr; if (obj.h265) { const h265PlayAddr = detail?.video?.bitrateInfo?.find(b => b.CodecType.includes("h265"))?.PlayAddr.UrlList[0] playAddr = h265PlayAddr || playAddr } if (!obj.isAudioOnly && !images) { video = playAddr; videoFilename = `${filenameBase}.mp4`; } else { audio = playAddr; audioFilename = `${filenameBase}_audio`; if (obj.fullAudio || !audio) { audio = detail.music.playUrl; audioFilename += `_original` } if (audio.includes("mime_type=audio_mpeg")) bestAudio = 'mp3'; } if (video) { return { urls: video, filename: videoFilename, headers: { cookie } } } if (images && obj.isAudioOnly) { return { urls: audio, audioFilename: audioFilename, isAudioOnly: true, bestAudio, headers: { cookie } } } if (images) { let imageLinks = images .map(i => i.imageURL.urlList.find(p => p.includes(".jpeg?"))) .map((url, i) => { if (obj.alwaysProxy) url = createStream({ service: "tiktok", type: "proxy", url, filename: `${filenameBase}_photo_${i + 1}.jpg` }) return { type: "photo", url } }); return { picker: imageLinks, urls: audio, audioFilename: audioFilename, isAudioOnly: true, bestAudio, headers: { cookie } } } if (audio) { return { urls: audio, audioFilename: audioFilename, isAudioOnly: true, bestAudio, headers: { cookie } } } } ``` ## /api/src/processing/services/tumblr.js ```js path="/api/src/processing/services/tumblr.js" import psl from "@imput/psl"; const API_KEY = 'jrsCWX1XDuVxAFO4GkK147syAoN8BJZ5voz8tS80bPcj26Vc5Z'; const API_BASE = 'https://api-http2.tumblr.com'; function request(domain, id) { const url = new URL(`/v2/blog/${domain}/posts/${id}/permalink`, API_BASE); url.searchParams.set('api_key', API_KEY); url.searchParams.set('fields[blogs]', 'uuid,name,avatar,?description,?can_message,?can_be_followed,?is_adult,?reply_conditions,' + '?theme,?title,?url,?is_blocked_from_primary,?placement_id,?primary,?updated,?followed,' + '?ask,?can_subscribe,?paywall_access,?subscription_plan,?is_blogless_advertiser,?tumblrmart_accessories'); return fetch(url, { headers: { 'User-Agent': 'Tumblr/iPhone/33.3/333010/17.3.1/tumblr', 'X-Version': 'iPhone/33.3/333010/17.3.1/tumblr' } }).then(a => a.json()).catch(() => {}); } export default async function(input) { let { subdomain } = psl.parse(input.url.hostname); if (subdomain?.includes('.')) { return { error: "link.unsupported" }; } else if (subdomain === 'www' || subdomain === 'at') { subdomain = undefined } const domain = `${subdomain ?? input.user}.tumblr.com`; const data = await request(domain, input.id); const element = data?.response?.timeline?.elements?.[0]; if (!element) return { error: "fetch.empty" }; const contents = [ ...element.content, ...element?.trail?.map(t => t.content).flat() ] const audio = contents.find(c => c.type === 'audio'); if (audio && audio.provider === 'tumblr') { const fileMetadata = { title: audio?.title, artist: audio?.artist }; return { urls: audio.media.url, filenameAttributes: { service: 'tumblr', id: input.id, title: fileMetadata.title, author: fileMetadata.artist }, isAudioOnly: true, bestAudio: "mp3", } } const video = contents.find(c => c.type === 'video'); if (video && video.provider === 'tumblr') { return { urls: video.media.url, filename: `tumblr_${input.id}.mp4`, audioFilename: `tumblr_${input.id}_audio` } } return { error: "link.unsupported" } } ``` ## /api/src/processing/services/twitch.js ```js path="/api/src/processing/services/twitch.js" import { env } from "../../config.js"; const gqlURL = "https://gql.twitch.tv/gql"; const clientIdHead = { "client-id": "kimne78kx3ncx6brgo4mv6wki5h1ko" }; export default async function (obj) { const req_metadata = await fetch(gqlURL, { method: "POST", headers: clientIdHead, body: JSON.stringify({ query: `{ clip(slug: "${obj.clipId}") { broadcaster { login } createdAt curator { login } durationSeconds id medium: thumbnailURL(width: 480, height: 272) title videoQualities { quality sourceURL } } }` }) }).then(r => r.status === 200 ? r.json() : false).catch(() => {}); if (!req_metadata) return { error: "fetch.fail" }; const clipMetadata = req_metadata.data.clip; 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([ { "operationName": "VideoAccessToken_Clip", "variables": { "slug": obj.clipId }, "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11" } } } ]) }).then(r => r.status === 200 ? r.json() : false).catch(() => {}); if (!req_token) return { error: "fetch.fail" }; const formats = clipMetadata.videoQualities; const format = formats.find(f => f.quality === obj.quality) || formats[0]; return { type: "proxy", urls: `${format.sourceURL}?${new URLSearchParams({ sig: req_token[0].data.clip.playbackAccessToken.signature, token: req_token[0].data.clip.playbackAccessToken.value })}`, fileMetadata: { title: clipMetadata.title.trim(), artist: `Twitch Clip by @${clipMetadata.broadcaster.login}, clipped by @${clipMetadata.curator.login}`, }, filenameAttributes: { service: "twitch", id: clipMetadata.id, title: clipMetadata.title.trim(), author: `${clipMetadata.broadcaster.login}, clipped by ${clipMetadata.curator.login}`, qualityLabel: `${format.quality}p`, extension: 'mp4' }, filename: `twitchclip_${clipMetadata.id}_${format.quality}p.mp4`, audioFilename: `twitchclip_${clipMetadata.id}_audio` } } ``` ## /api/src/processing/services/twitter.js ```js path="/api/src/processing/services/twitter.js" import { genericUserAgent } from "../../config.js"; import { createStream } from "../../stream/manage.js"; import { getCookie, updateCookie } from "../cookie/manager.js"; const graphqlURL = 'https://api.x.com/graphql/I9GDzyCGZL2wSoYFFrrTVw/TweetResultByRestId'; const tokenURL = 'https://api.x.com/1.1/guest/activate.json'; const tweetFeatures = JSON.stringify({"creator_subscriptions_tweet_preview_api_enabled":true,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"articles_preview_enabled":true,"tweetypie_unmention_optimization_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"rweb_video_timestamps_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"rweb_tipjar_consumption_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":false,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_enhance_cards_enabled":false}); const tweetFieldToggles = JSON.stringify({"withArticleRichContentState":true,"withArticlePlainText":false,"withGrokAnalyze":false}); const commonHeaders = { "user-agent": genericUserAgent, "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA", "x-twitter-client-language": "en", "x-twitter-active-user": "yes", "accept-language": "en" } // fix all videos affected by the container bug in twitter muxer (took them over two weeks to fix it????) const TWITTER_EPOCH = 1288834974657n; const badContainerStart = new Date(1701446400000); const badContainerEnd = new Date(1702605600000); function needsFixing(media) { const representativeId = media.source_status_id_str ?? media.id_str; // syndication api doesn't have media ids in its response, // so we just assume it's all good if (!representativeId) return false; const mediaTimestamp = new Date( Number((BigInt(representativeId) >> 22n) + TWITTER_EPOCH) ); return mediaTimestamp > badContainerStart && mediaTimestamp < badContainerEnd } function bestQuality(arr) { return arr.filter(v => v.content_type === "video/mp4") .reduce((a, b) => Number(a?.bitrate) > Number(b?.bitrate) ? a : b) .url } let _cachedToken; const getGuestToken = async (dispatcher, forceReload = false) => { if (_cachedToken && !forceReload) { return _cachedToken; } const tokenResponse = await fetch(tokenURL, { method: 'POST', headers: commonHeaders, dispatcher }).then(r => r.status === 200 && r.json()).catch(() => {}) if (tokenResponse?.guest_token) { return _cachedToken = tokenResponse.guest_token } } const requestSyndication = async(dispatcher, tweetId) => { // thank you // https://github.com/yt-dlp/yt-dlp/blob/05c8023a27dd37c49163c0498bf98e3e3c1cb4b9/yt_dlp/extractor/twitter.py#L1334 const token = (id) => ((Number(id) / 1e15) * Math.PI).toString(36).replace(/(0+|\.)/g, ''); const syndicationUrl = new URL("https://cdn.syndication.twimg.com/tweet-result"); syndicationUrl.searchParams.set("id", tweetId); syndicationUrl.searchParams.set("token", token(tweetId)); const result = await fetch(syndicationUrl, { headers: { "user-agent": genericUserAgent }, dispatcher }); return result; } const requestTweet = async(dispatcher, tweetId, token, cookie) => { const graphqlTweetURL = new URL(graphqlURL); let headers = { ...commonHeaders, 'content-type': 'application/json', 'x-guest-token': token, cookie: `guest_id=${encodeURIComponent(`v1:${token}`)}` } if (cookie) { headers = { ...commonHeaders, 'content-type': 'application/json', 'X-Twitter-Auth-Type': 'OAuth2Session', 'x-csrf-token': cookie.values().ct0, cookie } } graphqlTweetURL.searchParams.set('variables', JSON.stringify({ tweetId, withCommunity: false, includePromotedContent: false, withVoice: false }) ); graphqlTweetURL.searchParams.set('features', tweetFeatures); graphqlTweetURL.searchParams.set('fieldToggles', tweetFieldToggles); let result = await fetch(graphqlTweetURL, { headers, dispatcher }); updateCookie(cookie, result.headers); // we might have been missing the ct0 cookie, retry if (result.status === 403 && result.headers.get('set-cookie')) { const cookieValues = cookie?.values(); if (cookieValues?.ct0) { result = await fetch(graphqlTweetURL, { headers: { ...headers, 'x-csrf-token': cookieValues.ct0 }, dispatcher }); } } return result } const extractGraphqlMedia = async (tweet, dispatcher, id, guestToken, cookie) => { 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: "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: "content.post.age" }; } } if (!["Tweet", "TweetWithVisibilityResults"].includes(tweetTypename)) { return { error: "content.post.unavailable" } } let tweetResult = tweet.data.tweetResult.result, baseTweet = tweetResult.legacy, repostedTweet = baseTweet?.retweeted_status_result?.result.legacy.extended_entities; if (tweetTypename === "TweetWithVisibilityResults") { baseTweet = tweetResult.tweet.legacy; repostedTweet = baseTweet?.retweeted_status_result?.result.tweet.legacy.extended_entities; } return (repostedTweet?.media || baseTweet?.extended_entities?.media); } const testResponse = (result) => { const contentLength = result.headers.get("content-length"); if (!contentLength || contentLength === '0') { return false; } if (!result.headers.get("content-type").startsWith("application/json")) { return false; } return true; } export default async function({ id, index, toGif, dispatcher, alwaysProxy }) { const cookie = await getCookie('twitter'); let syndication = false; let guestToken = await getGuestToken(dispatcher); if (!guestToken) return { error: "fetch.fail" }; // for now we assume that graphql api will come back after some time, // so we try it first let tweet = await requestTweet(dispatcher, id, guestToken); // get new token & retry if old one expired if ([403, 429].includes(tweet.status)) { guestToken = await getGuestToken(dispatcher, true); if (cookie) { tweet = await requestTweet(dispatcher, id, guestToken, cookie); } else { tweet = await requestTweet(dispatcher, id, guestToken); } } const testGraphql = testResponse(tweet); // if graphql requests fail, then resort to tweet embed api if (!testGraphql) { syndication = true; tweet = await requestSyndication(dispatcher, id); const testSyndication = testResponse(tweet); // if even syndication request failed, then cry out loud if (!testSyndication) { return { error: "fetch.fail" }; } } tweet = await tweet.json(); let media = syndication ? tweet.mediaDetails : await extractGraphqlMedia(tweet, dispatcher, id, guestToken, cookie); if (!media) return { error: "fetch.empty" }; // check if there's a video at given index (/video/) if (index >= 0 && index < media?.length) { media = [media[index]] } const getFileExt = (url) => new URL(url).pathname.split(".", 2)[1]; const proxyMedia = (url, filename) => createStream({ service: "twitter", type: "proxy", url, filename, }); switch (media?.length) { case undefined: case 0: return { error: "fetch.empty" } case 1: if (media[0].type === "photo") { return { 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" : "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: proxiedImage, } } let url = bestQuality(content.video_info.variants); const shouldRenderGif = content.type === "animated_gif" && toGif; const videoFilename = `twitter_${id}_${i + 1}.${shouldRenderGif ? "gif" : "mp4"}`; let type = "video"; if (shouldRenderGif) type = "gif"; if (needsFixing(content) || shouldRenderGif) { url = createStream({ service: "twitter", type: shouldRenderGif ? "gif" : "remux", url, filename: videoFilename, }) } else if (alwaysProxy) { url = proxyMedia(url, videoFilename); } return { type, url, thumb: proxyThumb(content.media_url_https, i), } }); return { picker }; } } ``` The content has been capped at 50000 tokens, and files over NaN bytes have been omitted. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.