Sync project files

This commit is contained in:
2026-08-12 19:38:47 -07:00
commit 6737ca6fb4
26 changed files with 2880 additions and 0 deletions

14
.env.example Normal file
View File

@@ -0,0 +1,14 @@
PROXY_URL=
PROXY_STREAMS=true
ENABLE_DEBUG_ROUTE=false
TMDB_API_KEY=
GA_MEASUREMENT_ID=
GA_API_SECRET=
TOKEN_SECRET=
BYPASS_AUTH=

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
*.wasm filter=lfs diff=lfs merge=lfs -text

49
.github/old_workflows/deploy_hf.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Deploy to Hugging Face Space
on:
push:
branches: ["main"]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Configure Git auth
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
set -e
git config --global user.email "github-actions@github.com"
git config --global user.name "github-actions"
git config --global credential.helper store
echo "https://hf:${HF_TOKEN}@huggingface.co" > ~/.git-credentials
- name: Clone HF Space
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
set -e
rm -rf hf-space
git clone https://huggingface.co/spaces/MissouriMonster/x hf-space
- name: Sync files
run: |
rsync -av --exclude='.git' ./ hf-space/
- name: Commit changes
run: |
cd hf-space
git add .
git commit -m "deploy" || echo "no changes"
- name: Push to Hugging Face
run: |
cd hf-space
git push https://hf:${{ secrets.HF_TOKEN }}@huggingface.co/spaces/MissouriMonster/x main

42
.github/workflows/deploy_vps.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: Deploy to VPS
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@v1.2.0
with:
host: ${{ secrets.VPS_HOST }}
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
set -e
git config --global --add safe.directory /var/www/stream-api
cd /var/www/stream-api
mkdir -p /var/backups/stream-api
if [ -f data/api_keys.db ]; then
cp data/api_keys.db "/var/backups/stream-api/api_keys-$(date +%Y%m%d%H%M%S).db"
ls -t /var/backups/stream-api/api_keys-*.db | tail -n +31 | xargs -r rm --
fi
git fetch origin main
git reset --hard origin/main
git clean -fd -e data
npm install
mkdir -p data
pm2 restart stream-api || pm2 start server.js --name stream-api
pm2 save

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
.wrangler
.dev.vars
node_modules/
.env
package-lock.json
data/
db.json

View File

@@ -0,0 +1,25 @@
Adding keys is easy.
For example:
```bash
node add-key.mjs standard 500 name
node add-key.mjs partner 1000 name
node add-key.mjs public 10 name
````
It generates a random 32-character hex key, prefixes it based on the type (`pk_` for partner, `pub_` for public, `sk_` for everything else to match the existing naming pattern), inserts it as an active key, and prints the generated key once so you can copy it.
You can also manage keys through `db.json`:
```bash
node export-db.mjs
```
Export the current SQLite database into `db.json`, edit the file manually, then apply changes with:
```bash
node update-db.mjs
```
Run the scripts directly on the VPS, or work locally with a copy of the database and sync the changes afterward.

7
Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM node:22-slim
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 7860
CMD ["node", "server.js"]

407
LICENSE Normal file
View File

@@ -0,0 +1,407 @@
Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

12
README.md Normal file
View File

@@ -0,0 +1,12 @@
# [DMCA](https://docs.vyla.cc/misc/dmca)
If your source is listed here, I sincerely apologize. I understand that its inclusion may be costing you a lot of money, and that was never my intention. Please contact me as soon as possible, and I'll remove it ASAP.
This is a small hobby project that I built for learning and personal interest, not for profit. I genuinely want to respect the wishes of source owners and will address any removal requests as quickly as I can.
This project is developed and maintained by [Vyla Entertainment](https://github.com/vyla-entertainment) (@vyla-entertainment).
Original work and core authorship: [@endoverdosing](https://github.com/EndOverdosing)
Full credits and acknowledgements:
https://docs.vyla.cc/misc/credit

31
add-key.mjs Normal file
View File

@@ -0,0 +1,31 @@
import { DatabaseSync } from 'node:sqlite';
import crypto from 'crypto';
const [, , type, rpmArg, label] = process.argv;
if (!type || !rpmArg) {
console.log('Usage: node database/add-key.mjs <type> <rpm> [label]');
console.log('Example: node database/add-key.mjs standard 500 flixora');
process.exit(1);
}
const rpm = parseInt(rpmArg, 10);
if (isNaN(rpm) || rpm <= 0) {
console.log('rpm must be a positive number');
process.exit(1);
}
const prefix = type === 'partner' ? 'pk' : type === 'public' ? 'pub' : 'sk';
const suffix = crypto.randomBytes(16).toString('hex');
const key = label ? `${prefix}_${label}_${suffix}` : `${prefix}_${suffix}`;
const db = new DatabaseSync('./data/api_keys.db');
db.exec('PRAGMA journal_mode = WAL;');
db.prepare(`
INSERT INTO api_keys (key, type, rpm, active)
VALUES (?, ?, ?, 1)
`).run(key, type, rpm);
console.log('Key created:');
console.log(key);

2
config.js Normal file
View File

@@ -0,0 +1,2 @@
export const ALLOWED_ORIGINS = [''];
export const CACHE_TTL = 5 * 60 * 1000;

60
db.js Normal file
View File

@@ -0,0 +1,60 @@
import { DatabaseSync } from 'node:sqlite';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DB_DIR = path.join(__dirname, 'data');
const DB_PATH = path.join(DB_DIR, 'api_keys.db');
if (!fs.existsSync(DB_DIR)) {
fs.mkdirSync(DB_DIR, { recursive: true });
}
const db = new DatabaseSync(DB_PATH);
db.exec('PRAGMA journal_mode = WAL;');
db.exec('PRAGMA busy_timeout = 5000;');
export async function ensureApiKeysTable() {
db.exec(`
CREATE TABLE IF NOT EXISTS api_keys (
key TEXT PRIMARY KEY,
type TEXT NOT NULL DEFAULT 'standard',
rpm INTEGER NOT NULL DEFAULT 100,
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
}
export async function fetchDisabledApiKeys() {
return db.prepare(`
SELECT key
FROM api_keys
WHERE active = 0
`).all();
}
export async function fetchActiveApiKeys() {
return db.prepare(`
SELECT key, type, rpm
FROM api_keys
WHERE active = 1
`).all();
}
export async function ensurePublicKey() {
const existing = db.prepare(`
SELECT key FROM api_keys WHERE key = 'public_api_key'
`).get();
if (!existing) {
db.prepare(`
INSERT INTO api_keys (key, type, rpm, active)
VALUES ('public_api_key', 'public', 10, 1)
`).run();
}
}
export default db;

23
export-db.mjs Normal file
View File

@@ -0,0 +1,23 @@
import { DatabaseSync } from "node:sqlite";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DB_PATH = path.join(__dirname, "data", "api_keys.db");
const OUTPUT = path.join(__dirname, "db.json");
const db = new DatabaseSync(DB_PATH);
const keys = db.prepare(`
SELECT *
FROM api_keys
`).all();
fs.writeFileSync(
OUTPUT,
JSON.stringify(keys, null, 4)
);
console.log(`Exported ${keys.length} API keys to db.json`);

11
package.json Normal file
View File

@@ -0,0 +1,11 @@
{
"name": "stream-api",
"version": "2.0.0",
"private": true,
"description": "Stream API — multi-provider stream scraper",
"type": "module",
"dependencies": {
"@vyla-entertainment/sdk": "^1.9.0",
"dotenv": "^17.4.2"
}
}

6
public/assets/title.txt Normal file
View File

@@ -0,0 +1,6 @@
██████╗ ██╗ ██╗██╗ ██╗██╗ █████╗ ███████╗███╗ ██╗████████╗███████╗██████╗ ████████╗ █████╗ ██╗███╗ ██╗███╗ ███╗███████╗███╗ ██╗████████╗
██╔═══██╗██║ ██║╚██╗ ██╔╝██║ ██╔══██╗ ██╔════╝████╗ ██║╚══██╔══╝██╔════╝██╔══██╗╚══██╔══╝██╔══██╗██║████╗ ██║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝
██║██╗██║██║ ██║ ╚████╔╝ ██║ ███████║ █████╗ ██╔██╗ ██║ ██║ █████╗ ██████╔╝ ██║ ███████║██║██╔██╗ ██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║
██║██║██║╚██╗ ██╔╝ ╚██╔╝ ██║ ██╔══██║ ██╔══╝ ██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗ ██║ ██╔══██║██║██║╚██╗██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║
╚█║████╔╝ ╚████╔╝ ██║ ███████╗██║ ██║ ███████╗██║ ╚████║ ██║ ███████╗██║ ██║ ██║ ██║ ██║██║██║ ╚████║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║
╚╝╚═══╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝

View File

@@ -0,0 +1 @@
v6.0.0

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

1258
server.js Normal file

File diff suppressed because it is too large Load Diff

363
src/middleware/auth.js Normal file
View File

@@ -0,0 +1,363 @@
import dotenv from 'dotenv';
import crypto from 'crypto';
import { ensureApiKeysTable, fetchActiveApiKeys, fetchDisabledApiKeys, ensurePublicKey } from '../../db.js';
dotenv.config();
const BYPASS_AUTH = process.env.BYPASS_AUTH === 'true';
const API_KEYS = new Map();
const DISABLED_KEYS = new Set();
const rateLimitMap = new Map();
const KEY_REFRESH_INTERVAL_MS = 5 * 60 * 1000;
function setKeysFromRows(rows) {
API_KEYS.clear();
for (const row of rows) {
API_KEYS.set(row.key, {
type: row.type,
rpm: Number(row.rpm) || 100
});
}
}
export async function loadKeysFromDB() {
try {
const [activeRows, disabledRows] = await Promise.all([
fetchActiveApiKeys(),
fetchDisabledApiKeys()
]);
setKeysFromRows(activeRows);
DISABLED_KEYS.clear();
for (const row of disabledRows) {
DISABLED_KEYS.add(row.key);
}
} catch (err) {
if (API_KEYS.size === 0) {
throw err;
}
}
}
let authInitialized = false;
export async function initAuth() {
if (authInitialized) return;
authInitialized = true;
await ensureApiKeysTable();
await ensurePublicKey();
await loadKeysFromDB();
setInterval(() => {
loadKeysFromDB().catch(console.error);
}, KEY_REFRESH_INTERVAL_MS);
}
const TOKEN_SECRET = process.env.TOKEN_SECRET;
if (!TOKEN_SECRET || TOKEN_SECRET.length < 32) {
throw new Error('TOKEN_SECRET must be set and at least 32 characters');
}
const TOKEN_TTL_MS = 30 * 60 * 1000;
const REFRESH_GRACE_MS = 10 * 60 * 1000;
const TOKEN_VERSION = 'v1';
function signPayload(payload) {
return crypto.createHmac('sha256', TOKEN_SECRET).update(payload).digest('hex');
}
function buildToken(expires, type, sourceKey, issuedAt) {
const payload = `${TOKEN_VERSION}.${expires}.${type}.${sourceKey}.${issuedAt}`;
const sig = signPayload(payload);
return `${TOKEN_VERSION}.${expires}.${type}.${sourceKey}.${issuedAt}.${sig}`;
}
export function issueSessionToken(type = 'player', sourceKey = '') {
const now = Date.now();
const expires = now + TOKEN_TTL_MS;
return buildToken(expires, type, sourceKey, now);
}
export function validateSessionToken(token) {
if (!token || typeof token !== 'string' || token.length > 512) return false;
try {
const parts = token.split('.');
if (parts.length !== 6) return false;
const [version, expires, type, sourceKey, issuedAt, sig] = parts;
if (version !== TOKEN_VERSION) return false;
if (!/^\d+$/.test(expires) || !/^\d+$/.test(issuedAt)) return false;
const expiresNum = Number(expires);
const issuedAtNum = Number(issuedAt);
if (issuedAtNum > Date.now()) return false;
if (expiresNum - issuedAtNum !== TOKEN_TTL_MS) return false;
const payload = `${version}.${expires}.${type}.${sourceKey}.${issuedAt}`;
const expected = signPayload(payload);
const sigBuf = Buffer.from(sig, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
if (sigBuf.length !== expectedBuf.length) return false;
if (!crypto.timingSafeEqual(sigBuf, expectedBuf)) return false;
if (Date.now() > expiresNum) return false;
return { type, sourceKey, expires: expiresNum, issuedAt: issuedAtNum };
} catch {
return false;
}
}
export function refreshSessionToken(token) {
if (!token || typeof token !== 'string' || token.length > 512) return null;
try {
const parts = token.split('.');
if (parts.length !== 6) return null;
const [version, expires, type, sourceKey, issuedAt, sig] = parts;
if (version !== TOKEN_VERSION) return null;
if (!/^\d+$/.test(expires) || !/^\d+$/.test(issuedAt)) return null;
const expiresNum = Number(expires);
const issuedAtNum = Number(issuedAt);
if (issuedAtNum > Date.now()) return null;
if (expiresNum - issuedAtNum !== TOKEN_TTL_MS) return null;
const payload = `${version}.${expires}.${type}.${sourceKey}.${issuedAt}`;
const expected = signPayload(payload);
const sigBuf = Buffer.from(sig, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
if (sigBuf.length !== expectedBuf.length) return null;
if (!crypto.timingSafeEqual(sigBuf, expectedBuf)) return null;
if (Date.now() > expiresNum + REFRESH_GRACE_MS) return null;
if (type !== 'player') {
const entry = API_KEYS.get(sourceKey);
if (!entry || entry.type !== type || DISABLED_KEYS.has(sourceKey)) return null;
}
return issueSessionToken(type, sourceKey);
} catch {
return null;
}
}
function parseKey(apiKey) {
if (!apiKey) return null;
return apiKey.includes(':') ? apiKey.split(':').pop().trim() : apiKey;
}
function isLocalRequest(req) {
const ip = req.socket.remoteAddress || '';
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
export function authenticateRequest(req) {
if (BYPASS_AUTH && isLocalRequest(req)) {
return {
valid: true,
error: null,
type: 'standard',
bypassed: true
};
}
let internalToken = null;
try {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
internalToken = url.searchParams.get('internal_token');
} catch { }
if (internalToken) {
const decoded = validateSessionToken(internalToken);
if (decoded && decoded.type === 'internal') {
return {
valid: true,
error: null,
type: 'standard',
key: decoded.sourceKey || null,
bypassed: false,
internal: true
};
}
return {
valid: false,
error: 'Invalid or expired internal token'
};
}
const sessionToken = req.headers['x-session-token']?.trim();
if (sessionToken) {
const decoded = validateSessionToken(sessionToken);
if (decoded) {
return {
valid: true,
error: null,
type: decoded.type,
key: decoded.sourceKey || null,
bypassed: false
};
}
return {
valid: false,
error: 'Invalid or expired session token'
};
}
const authHeader = req.headers.authorization;
const rawKey =
authHeader?.replace(/^Bearer\s+/i, '').trim() ||
req.headers['x-api-key']?.trim();
const cleanKey = parseKey(rawKey);
if (!cleanKey) {
return {
valid: false,
error: 'Missing API key. Provide via Authorization or X-API-Key. You can get one at https://docs.vyla.cc/authentication'
};
}
if (DISABLED_KEYS.has(cleanKey)) {
return {
valid: false,
error: 'This API key has been disabled. If you believe this is an error, please contact support at https://vyla.cc/discord for assistance.'
};
}
const entry = API_KEYS.get(cleanKey);
if (!entry) {
return {
valid: false,
error: 'Invalid API key. If you believe this is an error, please contact support at https://vyla.cc/discord for assistance.'
};
}
return {
valid: true,
error: null,
type: entry.type,
key: cleanKey
};
}
function isStreamProxy(req, pathname) {
if (pathname !== '/api' && pathname !== '/api/') return false;
const url = new URL(
req.url,
`http://${req.headers.host || 'localhost'}`
);
return (
url.searchParams.has('url') ||
url.searchParams.has('proxy')
);
}
export function canAccess(type, req, pathname) {
if (type === 'public') {
if (pathname === '/movie' || pathname === '/api/movie' ||
pathname === '/tv' || pathname === '/api/tv') {
return false;
}
if (isStreamProxy(req, pathname)) {
return false;
}
return true;
}
return (
type === 'standard' ||
type === 'partner' ||
type === 'player'
);
}
export function checkRateLimit(apiKey) {
if (!apiKey) {
return { allowed: true };
}
const cleanKey = parseKey(apiKey);
const entry = API_KEYS.get(cleanKey);
if (!entry) {
return {
allowed: false,
error: 'Invalid API key. If you believe this is an error, please contact support at https://vyla.cc/discord for assistance.'
};
}
const rpm = entry.rpm;
const window = 60_000;
const now = Date.now();
let current = rateLimitMap.get(cleanKey);
if (!current || now > current.resetAt) {
current = {
count: 0,
resetAt: now + window
};
}
if (current.count >= rpm) {
rateLimitMap.set(cleanKey, current);
return {
allowed: false,
error: 'Rate limit exceeded. If you believe this is an error, please contact support at https://vyla.cc/discord for assistance.',
resetAt: current.resetAt,
limit: rpm,
window
};
}
current.count++;
rateLimitMap.set(cleanKey, current);
return {
allowed: true,
remaining: rpm - current.count,
resetAt: current.resetAt
};
}
export function clearRateLimitCache() {
rateLimitMap.clear();
}
setInterval(() => {
const now = Date.now();
for (const [key, value] of rateLimitMap) {
if (now > value.resetAt) {
rateLimitMap.delete(key);
}
}
}, 60_000).unref();

View File

@@ -0,0 +1,19 @@
export const handleDownloadMovie = async (id, corsHeaders, sdk) =>
{
const dl = await sdk.getDownloads(id);
return {
status: 200,
body: JSON.stringify(dl),
headers: { 'Content-Type': 'application/json', ...corsHeaders },
};
}
export const handleDownloadTv = async (id, season, episode, corsHeaders, sdk) =>
{
const dl = await sdk.getDownloads(id, season, episode);
return {
status: 200,
body: JSON.stringify(dl),
headers: { 'Content-Type': 'application/json', ...corsHeaders },
};
}

31
src/routes/health.js Normal file
View File

@@ -0,0 +1,31 @@
import { HEALTH_PROBE_ID } from '@vyla-entertainment/sdk/src/config.js'
import VylaSDK from '@vyla-entertainment/sdk';
/**
* @param { VylaSDK } sdk
*/
export async function handleHealth(sdk, cache) {
const sourceList = sdk.getSources(true);
const sources = {};
for (const cfg of sourceList) {
const key = cfg.key;
const probeResult = await sdk.probeSource(cfg.key, cache);
sources[key] = probeResult;
}
const allOk = Object.values(sources).every(v => v.ok);
return {
status: allOk ? 200 : 207,
body: JSON.stringify({
note: 'This is a health check endpoint. This is extremely unreliable, be sure to test sources directly.',
status: allOk ? 'ok' : 'degraded',
timestamp: new Date().toISOString(),
tmdb: !!process.env.TMDB_API_KEY,
cache: cache.size,
probe_id: HEALTH_PROBE_ID,
sources,
}, null, 2),
headers: { 'Content-Type': 'application/json' },
};
}

19
src/routes/subtitles.js Normal file
View File

@@ -0,0 +1,19 @@
export async function handleSubtitleMovie(id, corsHeaders, sdk) {
try {
const subtitles = await sdk.getSubtitles(id);
if (!subtitles.length) return { status: 404, body: JSON.stringify({ error: 'no subtitles found' }), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
return { status: 200, body: JSON.stringify(subtitles, null, 2), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
} catch (e) {
return { status: 500, body: JSON.stringify({ error: e.message }), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
}
}
export async function handleSubtitleTv(id, season, episode, corsHeaders, sdk) {
try {
const subtitles = await sdk.getSubtitles(id, season, episode);
if (!subtitles.length) return { status: 404, body: JSON.stringify({ error: 'no subtitles found' }), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
return { status: 200, body: JSON.stringify(subtitles, null, 2), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
} catch (e) {
return { status: 500, body: JSON.stringify({ error: e.message }), headers: { 'Content-Type': 'application/json', ...corsHeaders } };
}
}

186
src/routes/test.js Normal file
View File

@@ -0,0 +1,186 @@
import { wrapUrl } from '../utils/proxy.js';
import { getUA } from '../utils/helpers.js';
export async function handleTestRoute(sdk, match, searchParams, clientIP, host, handleTestSource, googleAnalytic) {
const sources = sdk.getSources();
const source = searchParams.get('source');
const cfg = sources.find(src => src.key === source) || null;
if (!source || !cfg) return { status: 400, body: JSON.stringify({ error: 'Invalid or Missing Source' }) };
const result = await handleTestSource(
sdk,
source,
match[1],
searchParams.get('season') || searchParams.get('s') || null,
searchParams.get('episode') || searchParams.get('e') || null,
clientIP,
host
);
googleAnalytic('source_test', { source, id: match[1], ok: JSON.parse(result.body).ok });
return { status: result.status, body: result.body };
}
function headersToObject(h) {
const out = {};
if (!h) return out;
for (const [k, v] of h.entries()) out[k] = v;
return out;
}
function safeStack(err) {
if (!err) return null;
return String(err.stack || err.message || err).split('\n').slice(0, 10);
}
export async function handleDebugRoute(sdk, match, searchParams, absoluteBase, _nativeFetch, verifyPlayable) {
const id = match[1];
const s = searchParams.get('season') || searchParams.get('s') || null;
const e = searchParams.get('episode') || searchParams.get('e') || null;
const sourceKey = searchParams.get('source');
const maxCandidates = Math.min(parseInt(searchParams.get('limit') || '10', 10) || 10, 25);
const previewBytes = Math.min(parseInt(searchParams.get('preview') || '800', 10) || 800, 4000);
if (!sourceKey) return { status: 400, body: JSON.stringify({ error: 'missing source', usage: '/debug/:id?source=key&season=&episode=&limit=&preview=' }) };
const sources = sdk.getSources();
const cfg = sources.find(src => src.key === sourceKey) || null;
if (!cfg) return { status: 400, body: JSON.stringify({ error: `unknown source: ${sourceKey}` }) };
const t0 = Date.now();
let streamResult = null, streamError = null, streamErrorStack = null;
const fetchTrace = [];
const tracingFetch = async (url, opts = {}) => {
const start = Date.now();
const reqHeaders = headersToObject(new Headers(opts.headers || {}));
const entry = {
step: fetchTrace.length,
url: String(url).slice(0, 500),
method: opts.method || 'GET',
request_headers: reqHeaders,
};
try {
const r = await _nativeFetch(url, opts);
entry.status = r.status;
entry.ok = r.ok;
entry.redirected = r.redirected;
entry.final_url = r.url && r.url !== String(url) ? r.url : undefined;
entry.response_headers = headersToObject(r.headers);
entry.ms = Date.now() - start;
fetchTrace.push(entry);
return r;
} catch (err) {
entry.error = err.message;
entry.ms = Date.now() - start;
fetchTrace.push(entry);
throw err;
}
};
const prev = globalThis.fetch;
globalThis.fetch = tracingFetch;
try {
streamResult = await sdk.getStream(sourceKey, id, s, e);
} catch (err) {
streamError = err.message;
streamErrorStack = safeStack(err);
} finally {
globalThis.fetch = prev;
}
const candidates =
streamResult?.allUrls ||
streamResult?.streams ||
(streamResult?.url ? [streamResult] : []);
const checks = await Promise.all(candidates.slice(0, maxCandidates).map(async (raw, i) => {
const rawUrl = typeof raw === 'object'
? (raw.url || raw.file || raw.stream || raw.src)
: raw;
const rawHeaders = typeof raw === 'object' && raw.headers
? raw.headers
: {};
const wrappedUrl = wrapUrl(
typeof raw === 'object'
? raw
: { url: raw },
sourceKey,
absoluteBase,
sdk
);
const isSkippedProxy = !!raw?.skipProxy;
const fetchUrl = isSkippedProxy ? rawUrl : (wrappedUrl || rawUrl);
const fetchHeaders = isSkippedProxy || !wrappedUrl ? { 'User-Agent': getUA(), ...rawHeaders } : { 'User-Agent': getUA() };
let m3u8Preview = null, mp4Preview = null, playable_check = null;
let previewRequestHeaders = null, previewResponseHeaders = null, previewStatus = null, previewOk = null, previewFinalUrl = null;
try {
const previewHeaders = { ...fetchHeaders, Range: `bytes=0-${previewBytes - 1}` };
previewRequestHeaders = previewHeaders;
const r = await _nativeFetch(fetchUrl, { signal: AbortSignal.timeout(15_000), headers: previewHeaders });
previewStatus = r.status;
previewOk = r.ok || r.status === 206;
previewFinalUrl = r.url && r.url !== fetchUrl ? r.url : undefined;
previewResponseHeaders = headersToObject(r.headers);
const ct = (r.headers.get('content-type') || '').toLowerCase();
const isMp4 = /\.mp4(\?|$)/i.test(fetchUrl) || ct.includes('video/mp4') || ct.includes('video/mp2t') || ct.includes('octet-stream');
if (isMp4) {
const bytes = new Uint8Array(await r.arrayBuffer());
mp4Preview = Array.from(bytes.slice(0, 32)).map(b => b.toString(16).padStart(2, '0')).join(' ');
playable_check = { ok: previewOk, error: previewOk ? null : `mp4 fetch failed: ${r.status}` };
} else {
m3u8Preview = (await r.text()).slice(0, previewBytes);
playable_check = await verifyPlayable(fetchUrl, fetchHeaders, isSkippedProxy || !wrappedUrl);
}
} catch (err) {
playable_check = { ok: false, error: err.message };
}
return {
index: i,
raw_candidate: raw,
raw_url: rawUrl,
raw_headers: rawHeaders,
proxy_url: isSkippedProxy ? rawUrl : wrappedUrl,
skip_proxy: isSkippedProxy,
fetch_url_used: fetchUrl,
preview_request: { headers: previewRequestHeaders, method: 'GET' },
preview_response: {
status: previewStatus,
ok: previewOk,
final_url: previewFinalUrl,
headers: previewResponseHeaders,
},
playable_check,
m3u8_preview: m3u8Preview,
mp4_preview_hex: mp4Preview,
};
}));
return {
status: 200,
body: JSON.stringify({
source: sourceKey,
id,
season: s,
episode: e,
config_used: cfg,
candidates_total: candidates.length,
candidates_checked: checks.length,
checks,
elapsed_ms: Date.now() - t0,
stream_error: streamError,
stream_error_stack: streamErrorStack,
fetch_trace: fetchTrace,
fetch_count: fetchTrace.length,
got_result: streamResult !== null,
result_keys: streamResult ? Object.keys(streamResult) : null,
raw_stream_result: streamResult,
}, null, 2)
};
}

179
src/utils/helpers.js Normal file
View File

@@ -0,0 +1,179 @@
import crypto from 'node:crypto';
export const UA_LIST = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15',
'Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0',
];
export const getUA = () => UA_LIST[Math.floor(Math.random() * UA_LIST.length)];
export const USER_AGENT = UA_LIST[0];
let sharedDcKey = null;
export function decryptPartner(responseText, keyEnv) {
try {
const sep = responseText.indexOf(':');
if (sep === -1) return null;
const iv = Buffer.from(responseText.slice(0, sep), 'base64');
const encrypted = responseText.slice(sep + 1);
if (!sharedDcKey) sharedDcKey = crypto.createHash('sha256').update(keyEnv || '').digest();
const decipher = crypto.createDecipheriv('aes-256-cbc', sharedDcKey, iv);
return JSON.parse(decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8'));
} catch {
return null;
}
}
export async function fetchJson(url, options) {
const res = await fetch(url, options);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
export async function fetchText(url, options) {
const res = await fetch(url, options);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.text();
}
const tmdbInfoCache = new Map();
const anilistCache = new Map();
const tmdbValidationCache = new Map();
function pruneHelperCache(cache) {
const now = Date.now();
for (const [k, v] of cache) if (now - v.ts >= v.ttl) cache.delete(k);
if (cache.size > 3000) {
const overflow = cache.size - 3000;
const it = cache.keys();
for (let i = 0; i < overflow; i++) cache.delete(it.next().value);
}
}
setInterval(() => {
pruneHelperCache(tmdbValidationCache);
pruneHelperCache(tmdbInfoCache);
pruneHelperCache(anilistCache);
}, 60000).unref();
function cacheGet(cache, key) {
const entry = cache.get(key);
if (!entry) return undefined;
if (Date.now() - entry.ts >= entry.ttl) { cache.delete(key); return undefined; }
return entry.val;
}
function cacheSet(cache, key, val, ttl) { cache.set(key, { val, ts: Date.now(), ttl }); }
export async function validateTmdbId(tmdbId, mediaType = 'movie') {
const key = `${tmdbId}-${mediaType}`;
const cached = cacheGet(tmdbValidationCache, key);
if (cached !== undefined) return cached;
const k = process.env.TMDB_API_KEY;
if (!k) return { valid: false, error: 'TMDB API key not configured' };
try {
const res = await fetch(`https://api.themoviedb.org/3/${mediaType}/${tmdbId}?api_key=${k}`, { signal: AbortSignal.timeout(5000) });
if (res.ok) {
const data = await res.json();
const isValid = !!(data?.id && (data?.title || data?.name));
const result = { valid: isValid, error: isValid ? null : 'Invalid TMDB ID' };
cacheSet(tmdbValidationCache, key, result, 300000);
return result;
}
const result = { valid: false, error: `TMDB API error: ${res.status}` };
cacheSet(tmdbValidationCache, key, result, 60000);
return result;
} catch (error) {
const result = { valid: false, error: `Failed to validate TMDB ID: ${error.message}` };
cacheSet(tmdbValidationCache, key, result, 60000);
return result;
}
}
export async function getTmdbInfo(tmdbId, mediaType, season) {
const key = `${tmdbId}-${mediaType}-${season || ''}`;
const cached = cacheGet(tmdbInfoCache, key);
if (cached !== undefined) return cached;
const k = process.env.TMDB_API_KEY;
if (!k) return { isAnime: false, titles: [], year: null, imdbId: null };
try {
const [mainRes, seasonRes] = await Promise.all([
fetch(`https://api.themoviedb.org/3/${mediaType}/${tmdbId}?api_key=${k}&append_to_response=external_ids`, { signal: AbortSignal.timeout(5000) }),
season && mediaType === 'tv' ? fetch(`https://api.themoviedb.org/3/tv/${tmdbId}/season/${season}?api_key=${k}`, { signal: AbortSignal.timeout(5000) }) : Promise.resolve(null),
]);
let mainData = null, seasonData = null;
if (mainRes.ok) mainData = await mainRes.json(); else mainRes.body?.cancel();
if (seasonRes) { if (seasonRes.ok) seasonData = await seasonRes.json(); else seasonRes.body?.cancel(); }
const genres = mainData?.genres || [];
const isAnime = genres.some(g => g.id === 16) && ((mainData?.origin_country || []).includes('JP') || mainData?.original_language === 'ja');
const titles = [];
if (seasonData?.name) titles.push(seasonData.name);
const t = mainData?.title || mainData?.name || '';
const ot = mainData?.original_title || mainData?.original_name || '';
if (t) titles.push(t);
if (ot && ot !== t) titles.push(ot);
const dateStr = seasonData?.air_date || mainData?.release_date || mainData?.first_air_date || '';
const result = { isAnime, titles: [...new Set(titles.filter(Boolean))], year: dateStr ? parseInt(dateStr.slice(0, 4), 10) : null, imdbId: mainData?.imdb_id || mainData?.external_ids?.imdb_id || null };
cacheSet(tmdbInfoCache, key, result, 600000);
return result;
} catch { return { isAnime: false, titles: [], year: null, imdbId: null }; }
}
export async function tmdbToAnilist(tmdbId, mediaType, season, titles = [], year = null) {
const key = `${tmdbId}-${mediaType}-${season || ''}`;
const cached = cacheGet(anilistCache, key);
if (cached !== undefined) return cached;
try {
const res = await fetch(`https://api.ani.zip/mappings?tmdb_id=${tmdbId}&type=${mediaType}&season=${season || 1}`, { signal: AbortSignal.timeout(6000) });
if (res.ok) {
const id = (await res.json())?.mappings?.[0]?.anilist_id;
if (id) { cacheSet(anilistCache, key, id, 600000); return id; }
} else res.body?.cancel();
} catch { }
if (!titles.length) return null;
const query = `query ($s: String) { Page(page:1,perPage:10) { media(search:$s,type:ANIME) { id title { romaji english native } startDate { year } format } } }`;
let bestId = null, bestScore = -1;
for (const searchTitle of titles) {
try {
const res = await fetch('https://graphql.anilist.co', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ query, variables: { s: searchTitle } }), signal: AbortSignal.timeout(6000) });
if (!res.ok) { res.body?.cancel(); continue; }
for (const entry of (await res.json())?.data?.Page?.media || []) {
const entryTitles = [entry.title?.romaji, entry.title?.english, entry.title?.native].filter(Boolean).map(t => t.toLowerCase());
const sl = searchTitle.toLowerCase();
let score = 0;
if (entryTitles.some(t => t === sl)) score += 5;
else if (entryTitles.some(t => t.includes(sl) || sl.includes(t))) score += 3;
else if (entryTitles.some(t => { const w = sl.split(/\s+/).filter(x => x.length > 3); return w.length > 0 && w.every(x => t.includes(x)); })) score += 2;
else continue;
if (year && entry.startDate?.year) {
const diff = Math.abs(entry.startDate.year - year);
if (diff === 0) score += 3; else if (diff === 1) score += 1; else if (diff > 2) score -= 3;
}
if (mediaType === 'tv' && ['TV', 'TV_SHORT', 'ONA', 'OVA'].includes(entry.format)) score += 1;
if (mediaType === 'movie' && entry.format === 'MOVIE') score += 1;
if (score > bestScore) { bestScore = score; bestId = entry.id; }
}
if (bestScore >= 8) break;
} catch { }
}
if (bestId) cacheSet(anilistCache, key, bestId, 600000);
return bestId;
}
export async function imdbToTmdb(imdbId, mediaType = 'movie') {
const key = `imdb-${imdbId}`;
const cached = cacheGet(tmdbInfoCache, key);
if (cached !== undefined) return cached;
const k = process.env.TMDB_API_KEY;
if (!k) return null;
try {
const data = await fetchJson(`https://api.themoviedb.org/3/find/${imdbId}?api_key=${k}&external_source=imdb_id`, { signal: AbortSignal.timeout(5000) });
let result = null;
if (mediaType === 'movie' && data.movie_results?.length) result = data.movie_results[0].id;
else if (mediaType === 'tv' && data.tv_results?.length) result = data.tv_results[0].id;
if (result) cacheSet(tmdbInfoCache, key, result, 600000);
return result;
} catch { return null; }
}

53
src/utils/proxy.js Normal file
View File

@@ -0,0 +1,53 @@
import { issueSessionToken } from '../middleware/auth.js';
const PROXY_STREAMS = process.env.PROXY_STREAMS === "true";
const EXTERNAL_PROXY_URL = (process.env.PROXY_URL || "").replace(/\/+$/, "");
function buildProxyUrl(base, params) {
return `${base}?${params.toString()}`;
}
export function wrapUrl(rawUrl, sourceKey, absoluteBase, sdk) {
if (!rawUrl) return null;
const raw = typeof rawUrl === "object" ? rawUrl.url : rawUrl;
if (!raw) return null;
const cfg = sdk.getSources().find(c => c.key === sourceKey);
if (!cfg || cfg.skipProxy || rawUrl?.skipProxy) {
return raw;
}
const isLocalBase =
absoluteBase.includes("localhost") || absoluteBase.includes("127.0.0.1");
const safeBaseCheck = isLocalBase
? absoluteBase.replace(/^https:\/\//, "http://")
: absoluteBase.replace(/^http:\/\//, "https://");
if (raw.startsWith(`${safeBaseCheck}/api?`) || (EXTERNAL_PROXY_URL && raw.startsWith(`${EXTERNAL_PROXY_URL}?`))) {
return raw;
}
const proxyParam = cfg.proxyParam || "proxy";
if (PROXY_STREAMS) {
const isLocal = isLocalBase;
const safeBase = safeBaseCheck;
const normalized = isLocal ? raw : raw.replace(/^http:\/\//, "https://");
const params = new URLSearchParams({ url: normalized, [proxyParam]: "1" });
if (typeof rawUrl === "object" && rawUrl.headers) params.set("proxyHeaders", JSON.stringify(rawUrl.headers));
params.set("internal_token", issueSessionToken("internal", sourceKey));
return buildProxyUrl(`${safeBase}/api`, params);
}
if (EXTERNAL_PROXY_URL) {
const normalized = raw.replace(/^http:\/\//, "https://");
const params = new URLSearchParams({ url: normalized, [proxyParam]: "1" });
if (typeof rawUrl === "object" && rawUrl.headers) params.set("proxyHeaders", JSON.stringify(rawUrl.headers));
return buildProxyUrl(EXTERNAL_PROXY_URL, params);
}
return raw;
}

74
update-db.mjs Normal file
View File

@@ -0,0 +1,74 @@
import { DatabaseSync } from "node:sqlite";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DB_PATH = path.join(__dirname, "data", "api_keys.db");
const INPUT = path.join(__dirname, "db.json");
const db = new DatabaseSync(DB_PATH);
const data = JSON.parse(
fs.readFileSync(INPUT, "utf8")
);
db.exec('BEGIN TRANSACTION');
try {
const existing = db.prepare(`
SELECT key FROM api_keys
`).all().map(x => x.key);
const incoming = data.map(x => x.key);
for (const key of existing) {
if (!incoming.includes(key)) {
db.prepare(`
DELETE FROM api_keys
WHERE key = ?
`).run(key);
console.log(`Deleted ${key}`);
}
}
const upsert = db.prepare(`
INSERT INTO api_keys (
key,
type,
rpm,
active,
created_at
)
VALUES (
?,
?,
?,
?,
?
)
ON CONFLICT(key) DO UPDATE SET
type = excluded.type,
rpm = excluded.rpm,
active = excluded.active
`);
for (const row of data) {
upsert.run(
row.key,
row.type ?? "standard",
row.rpm ?? 100,
row.active ?? 1,
row.created_at ?? new Date().toISOString()
);
console.log(`Updated ${row.key}`);
}
db.exec('COMMIT');
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
console.log("Database synced from db.json");