Merge pull request #51 from movie-web/dev

Version 2.0.0
This commit is contained in:
mrjvs
2023-12-29 18:06:08 +01:00
committed by GitHub
122 changed files with 3330 additions and 1038 deletions

View File

@@ -8,7 +8,7 @@ layout: page
---
cta:
- Get Started
- /guide/usage
- /get-started/introduction
secondary:
- Open on GitHub →
- https://github.com/movie-web/providers

View File

@@ -1,13 +0,0 @@
# Targets
When making an instance of the library using `makeProviders()`. It will immediately require choosing a target.
::alert{type="info"}
A target is the device where the stream will be played on.
**Where the scraping is run has nothing to do with the target**, only where the stream is finally played in the end is significant in choosing a target.
::
#### Possible targets
- **`targets.BROWSER`** Stream will be played in a browser with CORS
- **`targets.NATIVE`** Stream will be played natively
- **`targets.ALL`** Stream will be played on a device with no restrictions of any kind

View File

@@ -1,2 +0,0 @@
icon: ph:book-open-fill
navigation.redirect: /guide/usage

View File

@@ -0,0 +1,14 @@
# Introduction
## What is `@movie-web/providers`?
`@movie-web/providers` is the soul of [movie-web.app](https://movie-web.app). It's a collection of scrapers of various streaming sites. It extracts the raw streams from those sites, so you can watch them without any extra fluff from the original sites.
## What can I use this on?
We support many different environments, here are a few examples:
- In browser, watch streams without needing a server to scrape (does need a proxy)
- In a native app, scrape in the app itself
- In a backend server, scrape on the server and give the streams to the client to watch.
To find out how to configure the library for your environment, You can read [How to use on X](../2.essentials/0.usage-on-x.md).

View File

@@ -1,4 +1,6 @@
# Usage
# Quick start
## Installation
Let's get started with `@movie-web/providers`. First lets install the package.
@@ -18,11 +20,15 @@ Let's get started with `@movie-web/providers`. First lets install the package.
To get started with scraping on the **server**, first you have to make an instance of the providers.
```ts
import { makeProviders, makeDefaultFetcher, targets } from '@movie-web/providers';
::alert{type="warning"}
This snippet will only work on a **server**, for other environments, check out [Usage on X](../2.essentials/0.usage-on-x.md).
::
```ts [index.ts (server)]
import { makeProviders, makeStandardFetcher, targets } from '@movie-web/providers';
// this is how the library will make http requests
const myFetcher = makeDefaultFetcher(fetch);
const myFetcher = makeStandardFetcher(fetch);
// make an instance of the providers library
const providers = makeProviders({
@@ -33,7 +39,8 @@ const providers = makeProviders({
})
```
Perfect, now we can start scraping a stream:
Perfect, this instance of the providers you can reuse everywhere where you need to.
Now lets actually scrape an item:
```ts [index.ts (server)]
// fetch some data from TMDB
@@ -47,7 +54,7 @@ const media = {
const output = await providers.runAll({
media: media
})
if (!output) console.log("No stream found")
console.log(`stream url: ${output.stream.playlist}`)
```
Now we have our stream in the output variable. (If the output is `null` then nothing could be found.)
To find out how to use the streams, check out [Using streams](../2.essentials/4.using-streams.md).

View File

@@ -0,0 +1,5 @@
# Examples
::alert{type="warning"}
There are no examples yet, stay tuned!
::

View File

@@ -0,0 +1,30 @@
---
title: 'Changelog'
---
# Version 2.0.0
::alert{type="warning"}
There are breaking changes in this list, make sure to read them thoroughly if you plan on updating.
::
**Development tooling:**
- Added integration test for browser. To make sure the package keeps working in the browser
- Add type checking when building, previously it ignored them
- Refactored the main folder, now called entrypoint.
- Dev-cli code has been split up a bit more, a bit cleaner to navigate
- Dev-cli is now moved to `npm run cli`
- Dev-cli has now has support for running in a headless browser using a proxy URL.
- Fetchers can now return a full response with headers and everything
**New features:**
- Added system to allow scraping ip locked sources through the consistentIpforRequests option.
- There is now a `buildProviders()` function that gives a builder for the `ProviderControls`. It's an alternative to `makeProviders()`.
- Streams can now return a headers object and a `preferredHeaders` object. which is required and optional headers for when using the stream.
**Notable changes:**
- Renamed the NO_CORS flag to CORS_ALLOWED (meaning that resource sharing is allowed)
- Export Fetcher and Stream types with all types related to it
- Providers can now return a list of streams instead of just one.
- Captions now have identifiers returned with them. Just generally useful to have
- New targets and some of them renamed

View File

@@ -0,0 +1,2 @@
icon: ph:shooting-star-fill
navigation.redirect: /get-started/introduction

View File

@@ -1,20 +0,0 @@
# `makeStandardFetcher`
Make a fetcher from a `fetch()` API. It is used for making a instance of providers with `makeProviders()`.
## Example
```ts
import { targets, makeProviders, makeDefaultFetcher } from "@movie-web/providers";
const providers = makeProviders({
fetcher: makeDefaultFetcher(fetch),
target: targets.NATIVE,
});
```
## Type
```ts
function makeDefaultFetcher(fetchApi: typeof fetch): Fetcher;
```

View File

@@ -1,2 +0,0 @@
icon: ph:file-code-fill
navigation.redirect: /api/makeproviders

View File

@@ -0,0 +1,50 @@
# How to use on X
The library can run in many environments, so it can be tricky to figure out how to set it up.
So here is a checklist, for more specific environments, keep reading below:
- When requests are very restricted (like browser client-side). Configure a proxied fetcher.
- When your requests come from the same device it will be streamed on (Not compatible with proxied fetcher). Set `consistentIpForRequests: true`.
- To set a target. Consult [Targets](./1.targets.md).
To make use of the examples below, You check check out the following pages:
- [Quick start](../1.get-started/1.quick-start.md)
- [Using streams](../2.essentials/4.using-streams.md)
## NodeJs server
```ts
import { makeProviders, makeStandardFetcher, targets } from '@movie-web/providers';
const providers = makeProviders({
fetcher: makeStandardFetcher(fetch),
target: chooseYourself, // check out https://providers.docs.movie-web.app/essentials/targets
})
```
## Browser client-side
Using the provider package client-side requires a hosted version of simple-proxy.
Read more [about proxy fetchers](./2.fetchers.md#using-fetchers-on-the-browser).
```ts
import { makeProviders, makeStandardFetcher, targets } from '@movie-web/providers';
const proxyUrl = "https://your.proxy.workers.dev/";
const providers = makeProviders({
fetcher: makeStandardFetcher(fetch),
proxiedFetcher: makeSimpleProxyFetcher(proxyUrl, fetch),
target: target.BROWSER,
})
```
## React native
```ts
import { makeProviders, makeStandardFetcher, targets } from '@movie-web/providers';
const providers = makeProviders({
fetcher: makeStandardFetcher(fetch),
target: target.NATIVE,
consistentIpForRequests: true,
})
```

View File

@@ -0,0 +1,14 @@
# Targets
When creating provider controls, you will immediately be required to choose a target.
::alert{type="warning"}
A target is the device where the stream will be played on.
**Where the scraping is run has nothing to do with the target**, only where the stream is finally played in the end is significant in choosing a target.
::
#### Possible targets
- **`targets.BROWSER`** Stream will be played in a browser with CORS
- **`targets.BROWSER_EXTENSION`** Stream will be played in a browser using the movie-web extension (WIP)
- **`targets.NATIVE`** Stream will be played on a native video player
- **`targets.ANY`** No restrictions for selecting streams, will just give all of them

View File

@@ -1,13 +1,13 @@
# Fetchers
When making an instance of the library using `makeProviders()`. It will immediately make a fetcher.
When creating provider controls, it will need you to configure a fetcher.
This comes with some considerations depending on the environment youre running.
## Using `fetch()`
In most cases, you can use the `fetch()` API. This will work in newer versions of Node.js (18 and above) and on the browser.
```ts
const fetcher = makeDefaultFetcher(fetch);
const fetcher = makeStandardFetcher(fetch);
```
If you using older version of Node.js. You can use the npm package `node-fetch` to polyfill fetch:
@@ -15,7 +15,7 @@ If you using older version of Node.js. You can use the npm package `node-fetch`
```ts
import fetch from "node-fetch";
const fetcher = makeDefaultFetcher(fetch);
const fetcher = makeStandardFetcher(fetch);
```
## Using fetchers on the browser
@@ -29,7 +29,7 @@ const fetcher = makeSimpleProxyFetcher("https://your.proxy.workers.dev/", fetch)
If you aren't able to use this specific proxy and need to use a different one, you can make your own fetcher in the next section.
## Making a custom fetcher
## Making a derived fetcher
In some rare cases, a custom fetcher will need to be made. This can be quite difficult to do from scratch so it's recommended to base it off an existing fetcher and building your own functionality around it.
@@ -37,6 +37,7 @@ In some rare cases, a custom fetcher will need to be made. This can be quite dif
export function makeCustomFetcher(): Fetcher {
const fetcher = makeStandardFetcher(f);
const customFetcher: Fetcher = (url, ops) => {
// Do something with the options and url here
return fetcher(url, ops);
};
@@ -44,4 +45,30 @@ export function makeCustomFetcher(): Fetcher {
}
```
If you need to make your own fetcher for a proxy. Make sure you make it compatible with the following headers: `Cookie`, `Referer`, `Origin`. Proxied fetchers need to be able to write those headers when making a request.
If you need to make your own fetcher for a proxy. Make sure you make it compatible with the following headers: `Set-Cookie`, `Cookie`, `Referer`, `Origin`. Proxied fetchers need to be able to write/read those headers when making a request.
## Making a fetcher from scratch
In some even rare cases, you need to make one completely from scratch.
This is the list of features it needs:
- Send/read every header
- Parse JSON, otherwise parse as text
- Send JSON, Formdata or normal strings
- get final destination url
It's not recommended to do this at all, but if you have to. You can base your code on the original implementation of `makeStandardFetcher`. Check the out [source code for it here](https://github.com/movie-web/providers/blob/dev/src/fetchers/standardFetch.ts).
Here is a basic template on how to make your own custom fetcher:
```ts
const myFetcher: Fetcher = (url, ops) => {
// Do some fetching
return {
body: {},
finalUrl: '',
headers: new Headers(), // should only contain headers from ops.readHeaders
statusCode: 200,
};
}
```

View File

@@ -0,0 +1,74 @@
# Customize providers
You make a provider controls in two ways. Either with `makeProviders()` (the simpler option) or with `buildProviders()` (more elaborate and extensive option).
## `makeProviders()` (simple)
To know what to set the configuration to, you can read [How to use on X](./0.usage-on-x.md) for a detailed guide on how to configure your controls.
```ts
const providers = makeProviders({
// fetcher, every web request gets called through here
fetcher: makeStandardFetcher(fetch),
// proxied fetcher, if the scraper needs to access a CORS proxy. this fetcher will be called instead
// of the normal fetcher. Defaults to the normal fetcher.
proxiedFetcher: undefined;
// target of where the streams will be used
target: targets.NATIVE;
// Set this to true, if the requests will have the same IP as
// the device that the stream will be played on.
consistentIpForRequests: false;
})
```
## `buildProviders()` (advanced)
To know what to set the configuration to, you can read [How to use on X](./0.usage-on-x.md) for a detailed guide on how to configure your controls.
### Standard setup
```ts
const providers = buildProviders()
.setTarget(targets.NATIVE) // target of where the streams will be used
.setFetcher(makeStandardFetcher(fetch)) // fetcher, every web request gets called through here
.addBuiltinProviders() // add all builtin providers, if this is not called, no providers will be added to the controls
.build();
```
### Adding only select few providers
Not all providers are great quality, so you can make a instance of the controls with only the providers you want.
```ts
const providers = buildProviders()
.setTarget(targets.NATIVE) // target of where the streams will be used
.setFetcher(makeStandardFetcher(fetch)) // fetcher, every web request gets called through here
.addSource('showbox') // only add showbox source
.addEmbed('febbox-hls') // add febbox-hls embed, which is returned by showbox
.build();
```
### Adding your own scrapers to the providers
If you have your own scraper and still want to use the nice utils of the provider library or just want to add on to the builtin providers. You can add your own custom source.
```ts
const providers = buildProviders()
.setTarget(targets.NATIVE) // target of where the streams will be used
.setFetcher(makeStandardFetcher(fetch)) // fetcher, every web request gets called through here
.addSource({ // add your own source
id: 'my-scraper',
name: 'My scraper',
rank: 800,
flags: [],
scrapeMovie(ctx) {
throw new Error('Not implemented');
}
})
.build();
```

View File

@@ -0,0 +1,84 @@
# Using streams
Streams can sometimes be quite picky on how they can be used. So here is a guide on how to use them.
## Essentials
All streams have the same common parameters:
- `Stream.type`: The type of stream. Either `hls` or `file`
- `Stream.id`: The id of this stream, unique per scraper output.
- `Stream.flags`: A list of flags that apply to this stream. Most people won't need to use it.
- `Stream.captions`: A list of captions/subtitles for this stream.
- `Stream.headers`: Either undefined or a key value object of headers you must set to use the stream.
- `Stream.preferredHeaders`: Either undefined or a key value object of headers you may want to set if you want optimal playback - but not required.
Now let's delve deeper into how to actually watch these streams!
## Streams with type `hls`
HLS streams can be tough to watch, it's not a normal file you can just use.
These streams have an extra property `Stream.playlist` which contains the m3u8 playlist.
Here is a code sample of how to use HLS streams in web context using hls.js
```html
<script src="https://cdn.jsdelivr.net/npm/hls.js@1"></script>
<video id="video"></video>
<script>
const stream = null; // add your stream here
if (Hls.isSupported()) {
var video = document.getElementById('video');
var hls = new Hls();
hls.loadSource(stream.playlist);
hls.attachMedia(video);
}
</script>
```
## Streams with type `file`
File streams are quite easy to use, it just returns a new property: `Stream.qualities`.
This property is a map of quality and a stream file. So if you want to get 1080p quality you do `stream["1080"]` to get your stream file. It will return undefined if there is no quality like that.
The possibly qualities are: `unknown`, `360`, `480`, `720`, `1080`, `4k`.
File based streams are garuanteed to always have one quality.
Once you get a streamfile, you have the following parameters:
- `StreamFile.type`: Right now it can only be `mp4`.
- `StreamFile.url`: The URL linking to the video file.
Here is a code sample of how to watch a file based stream the video in a browser:
```html
<video id="video"></video>
<script>
const stream = null; // add your stream here
const video = document.getElementById('video');
const qualityEntries = Object.keys(stream.qualities);
const firstQuality = qualityEntries[0];
video.src = firstQuality.url;
</script>
```
## Streams with headers
Streams have both a `Stream.headers` and a `Stream.preferredHeaders`.
The difference between the two is that `Stream.headers` **must** be set in other for the stream to work. While the other one is optional, and can only enhance the quality or performance.
If your target is set to `BROWSER`. There will never be required headers, as it's not possible to do.
## Using captions/subtitles
All streams have a list of captions at `Stream.captions`. The structure looks like this:
```ts
type Caption = {
type: CaptionType; // Language type, either "srt" or "vtt"
id: string; // Unique per stream
url: string; // The url pointing to the subtitle file
hasCorsRestrictions: boolean; // If true, you will need to proxy it if you're running in a browser
language: string; // Language code of the caption
};
```

View File

@@ -0,0 +1,3 @@
icon: ph:info-fill
navigation.redirect: /essentials/usage
navigation.title: "Get started"

View File

@@ -0,0 +1,11 @@
# Sources vs embeds
::alert{type="warning"}
This page isn't quite done yet, stay tuned!
::
<!--
TODO
- How do sources and embeds differ
- How do sources and embeds interact
-->

View File

@@ -0,0 +1,12 @@
# New providers
::alert{type="warning"}
This page isn't quite done yet, stay tuned!
::
<!--
TODO
- How to make new sources or embeds
- Ranking
- Link to flags
-->

View File

@@ -0,0 +1,10 @@
# Flags
Flags is the primary way the library seperates entities between different environments.
For example some sources only give back content that has the CORS headers set to allow anyone, so that source gets the flag `CORS_ALLOWED`. Now if you set your target to `BROWSER`, sources without that flag won't even get listed.
This concept is applied in multiple away across the library.
## Flag options
- `CORS_ALLOWED`: Headers from the output streams are set to allow any origin.
- `IP_LOCKED`: The streams are locked by ip, requester and watcher must be the same.

View File

@@ -0,0 +1,3 @@
icon: ph:atom-fill
navigation.redirect: /in-depth/sources-and-embeds
navigation.title: "In-depth"

View File

@@ -0,0 +1,72 @@
# Development / contributing
::alert{type="warning"}
This page isn't quite done yet, stay tuned!
::
<!--
TODO
- Development setup
- How to make new sources/embeds (link to the page)
- How to use the fetchers, when to use proxiedFetcher
- How to use the context
-->
## Testing using the CLI
Testing can be quite difficult for this library, unit tests can't really be made because of the unreliable nature of scrapers.
But manually testing by writing an entrypoint is also really annoying.
Our solution is to make a CLI that you can use to run the scrapers, for everything else there are unit tests.
### Setup
Make a `.env` file in the root of the repository and add a TMDB api key: `MOVIE_WEB_TMDB_API_KEY=KEY_HERE`.
Then make sure you've ran `npm i` to get all the dependencies.
### Mode 1 - interactive
To run the CLI without needing to learn all the arguments, simply run the following command and go with the flow.
```sh
npm run cli
```
### Mode 2 - arguments
For repeatability, it can be useful to specify the arguments one by one.
To see all the arguments, you can run the help command:
```sh
npm run cli -- -h
```
Then just run it with your arguments, for example:
```sh
npm run cli -- -sid showbox -tid 556574
```
### Examples
```sh
# Spirited away - showbox
npm run cli -- -sid showbox -tid 129
# Hamilton - flixhq
npm run cli -- -sid flixhq -tid 556574
# Arcane S1E1 - showbox
npm run cli -- -sid zoechip -tid 94605 -s 1 -e 1
# febbox mp4 - get streams from an embed (gotten from a source output)
npm run cli -- -sid febbox-mp4 -u URL_HERE
```
### Fetcher options
The CLI comes with a few built-in fetchers:
- `node-fetch`: Fetch using the "node-fetch" library.
- `native`: Use the new fetch built into Node.JS (undici).
- `browser`: Start up headless chrome, and run the library in that context using a proxied fetcher.
::alert{type="warning"}
The browser fetcher will require you to run `npm run build` before running the CLI. Otherwise you will get outdated results.
::

View File

@@ -0,0 +1,3 @@
icon: ph:aperture-fill
navigation.redirect: /extra-topics/development
navigation.title: "Extra topics"

View File

@@ -1,12 +1,12 @@
# `makeProviders`
Make an instance of providers with configuration.
Make an instance of provider controls with configuration.
This is the main entrypoint of the library. It is recommended to make one instance globally and reuse it throughout your application.
## Example
```ts
import { targets, makeProviders, makeDefaultFetcher } from "@movie-web/providers";
import { targets, makeProviders, makeDefaultFetcher } from '@movie-web/providers';
const providers = makeProviders({
fetcher: makeDefaultFetcher(fetch),
@@ -25,7 +25,7 @@ interface ProviderBuilderOptions {
// instance of a fetcher, in case the request has cors restrictions.
// this fetcher will be called instead of normal fetcher.
// if your environment doesnt have cors restrictions (like nodejs), there is no need to set this.
// if your environment doesnt have cors restrictions (like Node.JS), there is no need to set this.
proxiedFetcher?: Fetcher;
// target to get streams for

View File

@@ -9,9 +9,9 @@ You can attach events if you need to know what is going on while its processing.
// media from TMDB
const media = {
type: 'movie',
title: "Hamilton",
title: 'Hamilton',
releaseYear: 2020,
tmdbId: "556574"
tmdbId: '556574'
}
// scrape a stream

View File

@@ -5,14 +5,14 @@ Run a specific source scraper and get its outputted streams.
## Example
```ts
import { SourcererOutput, NotFoundError } from "@movie-web/providers";
import { SourcererOutput, NotFoundError } from '@movie-web/providers';
// media from TMDB
const media = {
type: 'movie',
title: "Hamilton",
title: 'Hamilton',
releaseYear: 2020,
tmdbId: "556574"
tmdbId: '556574'
}
// scrape a stream from flixhq
@@ -24,15 +24,15 @@ try {
})
} catch (err) {
if (err instanceof NotFoundError) {
console.log("source doesnt have this media");
console.log('source doesnt have this media');
} else {
console.log("failed to scrape")
console.log('failed to scrape')
}
return;
}
if (!output.stream && output.embeds.length === 0) {
console.log("no streams found");
console.log('no streams found');
}
```

View File

@@ -5,17 +5,17 @@ Run a specific embed scraper and get its outputted streams.
## Example
```ts
import { SourcererOutput } from "@movie-web/providers";
import { SourcererOutput } from '@movie-web/providers';
// scrape a stream from upcloud
let output: EmbedOutput;
try {
output = await providers.runSourceScraper({
output = await providers.runEmbedScraper({
id: 'upcloud',
url: 'https://example.com/123',
})
} catch (err) {
console.log("failed to scrape")
console.log('failed to scrape')
return;
}

View File

@@ -0,0 +1,20 @@
# `makeStandardFetcher`
Make a fetcher from a `fetch()` API. It is used for making a instance of provider controls.
## Example
```ts
import { targets, makeProviders, makeDefaultFetcher } from '@movie-web/providers';
const providers = makeProviders({
fetcher: makeStandardFetcher(fetch),
target: targets.ANY,
});
```
## Type
```ts
function makeStandardFetcher(fetchApi: typeof fetch): Fetcher;
```

View File

@@ -5,9 +5,9 @@ Make a fetcher to use with [movie-web/simple-proxy](https://github.com/movie-web
## Example
```ts
import { targets, makeProviders, makeDefaultFetcher, makeSimpleProxyFetcher } from "@movie-web/providers";
import { targets, makeProviders, makeDefaultFetcher, makeSimpleProxyFetcher } from '@movie-web/providers';
const proxyUrl = "https://your.proxy.workers.dev/"
const proxyUrl = 'https://your.proxy.workers.dev/'
const providers = makeProviders({
fetcher: makeDefaultFetcher(fetch),

View File

@@ -0,0 +1,3 @@
icon: ph:code-simple-fill
navigation.redirect: /api/makeproviders
navigation.title: "Api reference"

View File

@@ -3,7 +3,7 @@ module.exports = {
browser: true,
},
extends: ['airbnb-base', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'],
ignorePatterns: ['lib/*', 'tests/*', '/*.js', '/*.ts', '/**/*.test.ts', 'test/*'],
ignorePatterns: ['lib/*', 'tests/*', '/*.js', '/*.ts', '/src/__test__/*', '/**/*.test.ts', 'test/*'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',

21
LICENSE Normal file
View File

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

View File

@@ -9,27 +9,6 @@ features:
Visit documentation here: https://providers.docs.movie-web.app/
## Development
To make testing scrapers easier during development a CLI tool is available to run specific sources. To run the CLI testing tool, use `npm run test:dev`. The script supports 2 execution modes
## How to run locally or test my changes
- CLI Mode, for passing in arguments directly to the script
- Question Mode, where the script asks you questions about which source you wish to test
The following CLI Mode arguments are available
| Argument | Alias | Description | Default |
|---------------|--------|-------------------------------------------------------------------------|--------------|
| `--fetcher` | `-f` | Fetcher type. Either `node-fetch` or `native` | `node-fetch` |
| `--source-id` | `-sid` | Source ID for the source to be tested | |
| `--tmdb-id` | `-tid` | TMDB ID for the media to scrape. Only used if source is a provider | |
| `--type` | `-t` | Media type. Either `movie` or `show`. Only used if source is a provider | `movie` |
| `--season` | `-s` | Season number. Only used if type is `show` | `0` |
| `--episode` | `-e` | Episode number. Only used if type is `show` | `0` |
| `--url` | `-u` | URL to a video embed. Only used if source is an embed | |
| `--help` | `-h` | Shows help for the command arguments | |
Example testing the FlixHQ source on the movie "Spirited Away"
```bash
npm run test:dev -- -sid flixhq -tid 129 -t movie
```
These topics are also covered in the documentation, [read about it here](https://providers.docs.movie-web.app/extra-topics/development).

1035
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@movie-web/providers",
"version": "1.1.5",
"version": "2.0.0",
"description": "Package that contains all the providers of movie-web",
"main": "./lib/index.umd.js",
"types": "./lib/index.d.ts",
@@ -34,11 +34,11 @@
},
"homepage": "https://providers.docs.movie-web.app/",
"scripts": {
"build": "vite build",
"build": "vite build && tsc --noEmit",
"cli": "ts-node ./src/dev-cli/index.ts",
"test": "vitest run",
"test:dev": "ts-node ./src/dev-cli.ts",
"test:watch": "vitest",
"test:integration": "node ./tests/cjs && node ./tests/esm",
"test:integration": "node ./tests/cjs && node ./tests/esm && node ./tests/browser",
"test:coverage": "vitest run --coverage",
"lint": "eslint --ext .ts,.js src/",
"lint:fix": "eslint --fix --ext .ts,.js src/",
@@ -65,6 +65,7 @@
"eslint-plugin-prettier": "^4.2.1",
"node-fetch": "^2.7.0",
"prettier": "^2.6.2",
"puppeteer": "^21.6.1",
"spinnies": "^0.5.1",
"ts-node": "^10.9.1",
"tsc-alias": "^1.6.7",

View File

@@ -16,6 +16,8 @@ describe("makeSimpleProxyFetcher()", () => {
headers: new Headers({
"content-type": "text/plain",
}),
status: 204,
url: "test123",
text() {
return Promise.resolve(value);
},
@@ -24,6 +26,8 @@ describe("makeSimpleProxyFetcher()", () => {
headers: new Headers({
"content-type": "application/json",
}),
status: 204,
url: "test123",
json() {
return Promise.resolve(value);
},
@@ -31,7 +35,11 @@ describe("makeSimpleProxyFetcher()", () => {
}
function expectFetchCall(ops: { inputUrl: string, input: DefaultedFetcherOptions, outputUrl?: string, output: any, outputBody: any }) {
expect(fetcher(ops.inputUrl, ops.input)).resolves.toEqual(ops.outputBody);
const prom = fetcher(ops.inputUrl, ops.input);
expect((async () => (await prom).body)()).resolves.toEqual(ops.outputBody);
expect((async () => (await prom).headers.entries())()).resolves.toEqual((new Headers()).entries());
expect((async () => (await prom).statusCode)()).resolves.toEqual(204);
expect((async () => (await prom).finalUrl)()).resolves.toEqual("test123");
expect(fetch).toBeCalledWith(ops.outputUrl ?? ops.inputUrl, ops.output);
vi.clearAllMocks();
}
@@ -43,6 +51,7 @@ describe("makeSimpleProxyFetcher()", () => {
input: {
method: "GET",
query: {},
readHeaders: [],
headers: {
"X-Hello": "world",
},
@@ -62,6 +71,7 @@ describe("makeSimpleProxyFetcher()", () => {
input: {
method: "GET",
headers: {},
readHeaders: [],
query: {
"a": 'b',
}
@@ -79,6 +89,7 @@ describe("makeSimpleProxyFetcher()", () => {
input: {
method: "GET",
query: {},
readHeaders: [],
headers: {},
},
outputUrl: `https://example.com/proxy?destination=${encodeURIComponent('https://google.com/')}`,
@@ -97,6 +108,7 @@ describe("makeSimpleProxyFetcher()", () => {
input: {
method: "POST",
query: {},
readHeaders: [],
headers: {},
},
outputUrl: `https://example.com/proxy?destination=${encodeURIComponent('https://google.com/')}`,
@@ -112,6 +124,7 @@ describe("makeSimpleProxyFetcher()", () => {
input: {
method: "POST",
query: {},
readHeaders: [],
headers: {},
},
outputUrl: `https://example.com/proxy?destination=${encodeURIComponent('https://google.com/')}`,

View File

@@ -16,6 +16,8 @@ describe("makeStandardFetcher()", () => {
headers: new Headers({
"content-type": "text/plain",
}),
status: 204,
url: "test123",
text() {
return Promise.resolve(value);
},
@@ -24,6 +26,8 @@ describe("makeStandardFetcher()", () => {
headers: new Headers({
"content-type": "application/json",
}),
status: 204,
url: "test123",
json() {
return Promise.resolve(value);
},
@@ -31,7 +35,11 @@ describe("makeStandardFetcher()", () => {
}
function expectFetchCall(ops: { inputUrl: string, input: DefaultedFetcherOptions, outputUrl?: string, output: any, outputBody: any }) {
expect(fetcher(ops.inputUrl, ops.input)).resolves.toEqual(ops.outputBody);
const prom = fetcher(ops.inputUrl, ops.input);
expect((async () => (await prom).body)()).resolves.toEqual(ops.outputBody);
expect((async () => (await prom).headers.entries())()).resolves.toEqual((new Headers()).entries());
expect((async () => (await prom).statusCode)()).resolves.toEqual(204);
expect((async () => (await prom).finalUrl)()).resolves.toEqual("test123");
expect(fetch).toBeCalledWith(ops.outputUrl ?? ops.inputUrl, ops.output);
vi.clearAllMocks();
}
@@ -43,6 +51,7 @@ describe("makeStandardFetcher()", () => {
input: {
method: "GET",
query: {},
readHeaders: [],
headers: {
"X-Hello": "world",
},
@@ -53,6 +62,7 @@ describe("makeStandardFetcher()", () => {
headers: {
"X-Hello": "world",
},
body: undefined,
},
outputBody: "hello world"
})
@@ -62,6 +72,7 @@ describe("makeStandardFetcher()", () => {
input: {
method: "GET",
headers: {},
readHeaders: [],
query: {
"a": 'b',
}
@@ -79,6 +90,7 @@ describe("makeStandardFetcher()", () => {
input: {
query: {},
headers: {},
readHeaders: [],
method: "GET"
},
outputUrl: "https://google.com/",
@@ -97,6 +109,7 @@ describe("makeStandardFetcher()", () => {
input: {
query: {},
headers: {},
readHeaders: [],
method: "POST"
},
outputUrl: "https://google.com/",
@@ -112,6 +125,7 @@ describe("makeStandardFetcher()", () => {
input: {
query: {},
headers: {},
readHeaders: [],
method: "POST"
},
outputUrl: "https://google.com/",

View File

@@ -15,40 +15,52 @@ export function makeProviderMocks() {
const sourceA = {
id: 'a',
name: 'A',
rank: 1,
disabled: false,
flags: [],
} as Sourcerer;
const sourceB = {
id: 'b',
name: 'B',
rank: 2,
disabled: false,
flags: [],
} as Sourcerer;
const sourceCDisabled = {
id: 'c',
name: 'C',
rank: 3,
disabled: true,
flags: [],
} as Sourcerer;
const sourceAHigherRank = {
id: 'a',
name: 'A',
rank: 100,
disabled: false,
flags: [],
} as Sourcerer;
const sourceGSameRankAsA = {
id: 'g',
name: 'G',
rank: 1,
disabled: false,
flags: [],
} as Sourcerer;
const fullSourceYMovie = {
id: 'y',
name: 'Y',
rank: 105,
scrapeMovie: vi.fn(),
flags: [],
} as Sourcerer;
const fullSourceYShow = {
id: 'y',
name: 'Y',
rank: 105,
scrapeShow: vi.fn(),
flags: [],
} as Sourcerer;
const fullSourceZBoth = {
id: 'z',
@@ -56,6 +68,7 @@ const fullSourceZBoth = {
rank: 106,
scrapeMovie: vi.fn(),
scrapeShow: vi.fn(),
flags: [],
} as Sourcerer;
const embedD = {

View File

@@ -1,12 +1,15 @@
import { mockEmbeds, mockSources } from '@/__test__/providerTests';
import { getBuiltinEmbeds, getBuiltinSources } from '@/entrypoint/providers';
import { FeatureMap } from '@/entrypoint/utils/targets';
import { getProviders } from '@/providers/get';
import { vi, describe, it, expect, afterEach } from 'vitest';
const mocks = await vi.hoisted(async () => (await import('../providerTests.ts')).makeProviderMocks());
const mocks = await vi.hoisted(async () => (await import('../providerTests')).makeProviderMocks());
vi.mock('@/providers/all', () => mocks);
const features = {
const features: FeatureMap = {
requires: [],
disallowed: []
}
describe('getProviders()', () => {
@@ -17,7 +20,10 @@ describe('getProviders()', () => {
it('should return providers', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceA, mockSources.sourceB]);
expect(getProviders(features)).toEqual({
expect(getProviders(features, {
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toEqual({
sources: [mockSources.sourceA, mockSources.sourceB],
embeds: [mockEmbeds.embedD],
});
@@ -26,7 +32,10 @@ describe('getProviders()', () => {
it('should filter out disabled providers', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD, mockEmbeds.embedEDisabled]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceA, mockSources.sourceCDisabled, mockSources.sourceB]);
expect(getProviders(features)).toEqual({
expect(getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toEqual({
sources: [mockSources.sourceA, mockSources.sourceB],
embeds: [mockEmbeds.embedD],
});
@@ -35,31 +44,46 @@ describe('getProviders()', () => {
it('should throw on duplicate ids in sources', () => {
mocks.gatherAllEmbeds.mockReturnValue([]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceAHigherRank, mockSources.sourceA, mockSources.sourceB]);
expect(() => getProviders(features)).toThrowError();
expect(() => getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toThrowError();
});
it('should throw on duplicate ids in embeds', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD, mockEmbeds.embedDHigherRank, mockEmbeds.embedA]);
mocks.gatherAllSources.mockReturnValue([]);
expect(() => getProviders(features)).toThrowError();
expect(() => getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toThrowError();
});
it('should throw on duplicate ids between sources and embeds', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD, mockEmbeds.embedA]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceA, mockSources.sourceB]);
expect(() => getProviders(features)).toThrowError();
expect(() => getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toThrowError();
});
it('should throw on duplicate rank between sources and embeds', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD, mockEmbeds.embedA]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceA, mockSources.sourceB]);
expect(() => getProviders(features)).toThrowError();
expect(() => getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toThrowError();
});
it('should not throw with same rank between sources and embeds', () => {
mocks.gatherAllEmbeds.mockReturnValue([mockEmbeds.embedD, mockEmbeds.embedHSameRankAsSourceA]);
mocks.gatherAllSources.mockReturnValue([mockSources.sourceA, mockSources.sourceB]);
expect(getProviders(features)).toEqual({
expect(getProviders(features,{
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
})).toEqual({
sources: [mockSources.sourceA, mockSources.sourceB],
embeds: [mockEmbeds.embedD, mockEmbeds.embedHSameRankAsSourceA],
});

View File

@@ -1,6 +1,6 @@
import { mockEmbeds, mockSources } from '@/__test__/providerTests';
import { makeProviders } from '@/main/builder';
import { targets } from '@/main/targets.ts';
import { makeProviders } from '@/entrypoint/declare';
import { targets } from '@/entrypoint/utils/targets';
import { afterEach, describe, expect, it, vi } from 'vitest';
const mocks = await vi.hoisted(async () => (await import('../providerTests.ts')).makeProviderMocks());

View File

@@ -1,6 +1,6 @@
import { mockEmbeds, mockSources } from '@/__test__/providerTests';
import { makeProviders } from '@/main/builder';
import { targets } from '@/main/targets.ts';
import { makeProviders } from '@/entrypoint/declare';
import { targets } from '@/entrypoint/utils/targets';
import { afterEach, describe, expect, it, vi } from 'vitest';
const mocks = await vi.hoisted(async () => (await import('../providerTests.ts')).makeProviderMocks());

View File

@@ -0,0 +1,77 @@
import { FeatureMap, Flags, flags, flagsAllowedInFeatures } from "@/entrypoint/utils/targets";
import { describe, it, expect } from "vitest";
describe('flagsAllowedInFeatures()', () => {
function checkFeatures(featureMap: FeatureMap, flags: Flags[], output: boolean) {
expect(flagsAllowedInFeatures(featureMap, flags)).toEqual(output);
}
it('should check required correctly', () => {
checkFeatures({
requires: [],
disallowed: []
}, [], true);
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: []
}, [flags.CORS_ALLOWED], true);
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: []
}, [], false);
checkFeatures({
requires: [flags.CORS_ALLOWED, flags.IP_LOCKED],
disallowed: []
}, [flags.CORS_ALLOWED, flags.IP_LOCKED], true);
checkFeatures({
requires: [flags.IP_LOCKED],
disallowed: []
}, [flags.CORS_ALLOWED], false);
checkFeatures({
requires: [flags.IP_LOCKED],
disallowed: []
}, [], false);
});
it('should check disallowed correctly', () => {
checkFeatures({
requires: [],
disallowed: []
}, [], true);
checkFeatures({
requires: [],
disallowed: [flags.CORS_ALLOWED]
}, [], true);
checkFeatures({
requires: [],
disallowed: [flags.CORS_ALLOWED]
}, [flags.CORS_ALLOWED], false);
checkFeatures({
requires: [],
disallowed: [flags.CORS_ALLOWED]
}, [flags.IP_LOCKED], true);
checkFeatures({
requires: [],
disallowed: [flags.CORS_ALLOWED, flags.IP_LOCKED]
}, [flags.CORS_ALLOWED], false);
});
it('should pass mixed tests', () => {
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: [flags.IP_LOCKED]
}, [], false);
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: [flags.IP_LOCKED]
}, [flags.CORS_ALLOWED], true);
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: [flags.IP_LOCKED]
}, [flags.IP_LOCKED], false);
checkFeatures({
requires: [flags.CORS_ALLOWED],
disallowed: [flags.IP_LOCKED]
}, [flags.IP_LOCKED, flags.CORS_ALLOWED], false);
});
});

View File

@@ -9,7 +9,9 @@ describe('isValidStream()', () => {
it('should pass valid streams', () => {
expect(isValidStream({
type: "file",
id: "a",
flags: [],
captions: [],
qualities: {
"1080": {
type: "mp4",
@@ -19,7 +21,9 @@ describe('isValidStream()', () => {
})).toBe(true);
expect(isValidStream({
type: "hls",
id: "a",
flags: [],
captions: [],
playlist: "hello-world"
})).toBe(true);
});
@@ -27,7 +31,9 @@ describe('isValidStream()', () => {
it('should detect empty qualities', () => {
expect(isValidStream({
type: "file",
id: "a",
flags: [],
captions: [],
qualities: {}
})).toBe(false);
});
@@ -35,7 +41,9 @@ describe('isValidStream()', () => {
it('should detect empty stream urls', () => {
expect(isValidStream({
type: "file",
id: "a",
flags: [],
captions: [],
qualities: {
"1080": {
type: "mp4",
@@ -48,7 +56,9 @@ describe('isValidStream()', () => {
it('should detect emtpy HLS playlists', () => {
expect(isValidStream({
type: "hls",
id: "a",
flags: [],
captions: [],
playlist: "",
})).toBe(false);
});

View File

@@ -1,423 +0,0 @@
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import util from 'node:util';
import { program } from 'commander';
import dotenv from 'dotenv';
import { prompt } from 'enquirer';
import nodeFetch from 'node-fetch';
import Spinnies from 'spinnies';
import { MetaOutput, MovieMedia, ProviderControls, ShowMedia, makeProviders, makeStandardFetcher, targets } from '.';
dotenv.config();
type ProviderSourceAnswers = {
id: string;
type: string;
};
type EmbedSourceAnswers = {
url: string;
};
type CommonAnswers = {
fetcher: string;
source: string;
};
type ShowAnswers = {
season: string;
episode: string;
};
type CommandLineArguments = {
fetcher: string;
sourceId: string;
tmdbId: string;
type: string;
season: string;
episode: string;
url: string;
};
const TMDB_API_KEY = process.env.MOVIE_WEB_TMDB_API_KEY ?? '';
if (!TMDB_API_KEY?.trim()) {
throw new Error('Missing MOVIE_WEB_TMDB_API_KEY environment variable');
}
function logDeepObject(object: Record<any, any>) {
console.log(util.inspect(object, { showHidden: false, depth: null, colors: true }));
}
function getAllSources() {
// * The only way to get a list of all sources is to
// * create all these things. Maybe this should change
const providers = makeProviders({
fetcher: makeStandardFetcher(nodeFetch),
target: targets.NATIVE,
});
const combined = [...providers.listSources(), ...providers.listEmbeds()];
// * Remove dupes
const map = new Map(combined.map((source) => [source.id, source]));
return [...map.values()];
}
// * Defined here cuz ESLint didn't like the order these were defined in
const sources = getAllSources();
async function makeTMDBRequest(url: string): Promise<Response> {
const headers: {
accept: 'application/json';
authorization?: string;
} = {
accept: 'application/json',
};
// * Used to get around ESLint
// * Assignment to function parameter 'url'. eslint (no-param-reassign)
let requestURL = url;
// * JWT keys always start with ey and are ONLY valid as a header.
// * All other keys are ONLY valid as a query param.
// * Thanks TMDB.
if (TMDB_API_KEY.startsWith('ey')) {
headers.authorization = `Bearer ${TMDB_API_KEY}`;
} else {
requestURL += `?api_key=${TMDB_API_KEY}`;
}
return fetch(requestURL, {
method: 'GET',
headers,
});
}
async function getMovieMediaDetails(id: string): Promise<MovieMedia> {
const response = await makeTMDBRequest(`https://api.themoviedb.org/3/movie/${id}`);
const movie = await response.json();
if (movie.success === false) {
throw new Error(movie.status_message);
}
if (!movie.release_date) {
throw new Error(`${movie.title} has no release_date. Assuming unreleased`);
}
return {
type: 'movie',
title: movie.title,
releaseYear: Number(movie.release_date.split('-')[0]),
tmdbId: id,
};
}
async function getShowMediaDetails(id: string, seasonNumber: string, episodeNumber: string): Promise<ShowMedia> {
// * TV shows require the TMDB ID for the series, season, and episode
// * and the name of the series. Needs multiple requests
let response = await makeTMDBRequest(`https://api.themoviedb.org/3/tv/${id}`);
const series = await response.json();
if (series.success === false) {
throw new Error(series.status_message);
}
if (!series.first_air_date) {
throw new Error(`${series.name} has no first_air_date. Assuming unaired`);
}
response = await makeTMDBRequest(`https://api.themoviedb.org/3/tv/${id}/season/${seasonNumber}`);
const season = await response.json();
if (season.success === false) {
throw new Error(season.status_message);
}
response = await makeTMDBRequest(
`https://api.themoviedb.org/3/tv/${id}/season/${seasonNumber}/episode/${episodeNumber}`,
);
const episode = await response.json();
if (episode.success === false) {
throw new Error(episode.status_message);
}
return {
type: 'show',
title: series.name,
releaseYear: Number(series.first_air_date.split('-')[0]),
tmdbId: id,
episode: {
number: episode.episode_number,
tmdbId: episode.id,
},
season: {
number: season.season_number,
tmdbId: season.id,
},
};
}
function joinMediaTypes(mediaTypes: string[] | undefined) {
if (mediaTypes) {
const formatted = mediaTypes
.map((type: string) => {
return `${type[0].toUpperCase() + type.substring(1).toLowerCase()}s`;
})
.join(' / ');
return `(${formatted})`;
}
return ''; // * Embed sources pass through here too
}
async function runScraper(providers: ProviderControls, source: MetaOutput, options: CommandLineArguments) {
const spinnies = new Spinnies();
if (source.type === 'embed') {
spinnies.add('scrape', { text: `Running ${source.name} scraper on ${options.url}` });
try {
const result = await providers.runEmbedScraper({
url: options.url,
id: source.id,
});
spinnies.succeed('scrape', { text: 'Done!' });
logDeepObject(result);
} catch (error) {
let message = 'Unknown error';
if (error instanceof Error) {
message = error.message;
}
spinnies.fail('scrape', { text: `ERROR: ${message}` });
}
} else {
let media;
if (options.type === 'movie') {
media = await getMovieMediaDetails(options.tmdbId);
} else {
media = await getShowMediaDetails(options.tmdbId, options.season, options.episode);
}
spinnies.add('scrape', { text: `Running ${source.name} scraper on ${media.title}` });
try {
const result = await providers.runSourceScraper({
media,
id: source.id,
});
spinnies.succeed('scrape', { text: 'Done!' });
logDeepObject(result);
} catch (error) {
let message = 'Unknown error';
if (error instanceof Error) {
message = error.message;
}
spinnies.fail('scrape', { text: `ERROR: ${message}` });
}
}
}
async function processOptions(options: CommandLineArguments) {
if (options.fetcher !== 'node-fetch' && options.fetcher !== 'native') {
throw new Error("Fetcher must be either 'native' or 'node-fetch'");
}
if (!options.sourceId.trim()) {
throw new Error('Source ID must be provided');
}
const source = sources.find(({ id }) => id === options.sourceId);
if (!source) {
throw new Error('Invalid source ID. No source found');
}
if (source.type === 'embed' && !options.url.trim()) {
throw new Error('Must provide an embed URL for embed sources');
}
if (source.type === 'source') {
if (!options.tmdbId.trim()) {
throw new Error('Must provide a TMDB ID for provider sources');
}
if (Number.isNaN(Number(options.tmdbId)) || Number(options.tmdbId) < 0) {
throw new Error('TMDB ID must be a number greater than 0');
}
if (!options.type.trim()) {
throw new Error('Must provide a type for provider sources');
}
if (options.type !== 'movie' && options.type !== 'show') {
throw new Error("Invalid media type. Must be either 'movie' or 'show'");
}
if (options.type === 'show') {
if (!options.season.trim()) {
throw new Error('Must provide a season number for TV shows');
}
if (!options.episode.trim()) {
throw new Error('Must provide an episode number for TV shows');
}
if (Number.isNaN(Number(options.season)) || Number(options.season) <= 0) {
throw new Error('Season number must be a number greater than 0');
}
if (Number.isNaN(Number(options.episode)) || Number(options.episode) <= 0) {
throw new Error('Episode number must be a number greater than 0');
}
}
}
let fetcher;
if (options.fetcher === 'native') {
fetcher = makeStandardFetcher(fetch);
} else {
fetcher = makeStandardFetcher(nodeFetch);
}
const providers = makeProviders({
fetcher,
target: targets.NATIVE,
});
await runScraper(providers, source, options);
}
async function runQuestions() {
const options = {
fetcher: 'node-fetch',
sourceId: '',
tmdbId: '',
type: 'movie',
season: '0',
episode: '0',
url: '',
};
const answers = await prompt<CommonAnswers>([
{
type: 'select',
name: 'fetcher',
message: 'Select a fetcher',
choices: [
{
message: 'Native',
name: 'native',
},
{
message: 'Node fetch',
name: 'node-fetch',
},
],
},
{
type: 'select',
name: 'source',
message: 'Select a source',
choices: sources.map((source) => ({
message: `[${source.type.toLocaleUpperCase()}] ${source.name} ${joinMediaTypes(source.mediaTypes)}`.trim(),
name: source.id,
})),
},
]);
options.fetcher = answers.fetcher;
options.sourceId = answers.source;
const source = sources.find(({ id }) => id === answers.source);
if (!source) {
throw new Error(`No source with ID ${answers.source} found`);
}
if (source.type === 'embed') {
const sourceAnswers = await prompt<EmbedSourceAnswers>([
{
type: 'input',
name: 'url',
message: 'Embed URL',
},
]);
options.url = sourceAnswers.url;
} else {
const sourceAnswers = await prompt<ProviderSourceAnswers>([
{
type: 'input',
name: 'id',
message: 'TMDB ID',
},
{
type: 'select',
name: 'type',
message: 'Media type',
choices: [
{
message: 'Movie',
name: 'movie',
},
{
message: 'TV Show',
name: 'show',
},
],
},
]);
options.tmdbId = sourceAnswers.id;
options.type = sourceAnswers.type;
if (sourceAnswers.type === 'show') {
const seriesAnswers = await prompt<ShowAnswers>([
{
type: 'input',
name: 'season',
message: 'Season',
},
{
type: 'input',
name: 'episode',
message: 'Episode',
},
]);
options.season = seriesAnswers.season;
options.episode = seriesAnswers.episode;
}
}
await processOptions(options);
}
async function runCommandLine() {
program
.option('-f, --fetcher <fetcher>', "Fetcher to use. Either 'native' or 'node-fetch'", 'node-fetch')
.option('-sid, --source-id <id>', 'ID for the source to use. Either an embed or provider', '')
.option('-tid, --tmdb-id <id>', 'TMDB ID for the media to scrape. Only used if source is a provider', '')
.option('-t, --type <type>', "Media type. Either 'movie' or 'show'. Only used if source is a provider", 'movie')
.option('-s, --season <number>', "Season number. Only used if type is 'show'", '0')
.option('-e, --episode <number>', "Episode number. Only used if type is 'show'", '0')
.option('-u, --url <embed URL>', 'URL to a video embed. Only used if source is an embed', '');
program.parse();
await processOptions(program.opts());
}
if (process.argv.length === 2) {
runQuestions();
} else {
runCommandLine();
}

1
src/dev-cli/browser/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
dist

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scraper CLI</title>
</head>
<body>
<script src="./index.ts" type="module"></script>
</body>
</html>

View File

@@ -0,0 +1,17 @@
import { makeProviders, makeSimpleProxyFetcher, makeStandardFetcher, targets } from '../../../lib';
(window as any).scrape = (proxyUrl: string, type: 'source' | 'embed', input: any) => {
const providers = makeProviders({
fetcher: makeStandardFetcher(fetch),
target: targets.BROWSER,
proxiedFetcher: makeSimpleProxyFetcher(proxyUrl, fetch),
});
if (type === 'source') {
return providers.runSourceScraper(input);
}
if (type === 'embed') {
return providers.runEmbedScraper(input);
}
throw new Error('Input input type');
};

16
src/dev-cli/config.ts Normal file
View File

@@ -0,0 +1,16 @@
export function getConfig() {
let tmdbApiKey = process.env.MOVIE_WEB_TMDB_API_KEY ?? '';
tmdbApiKey = tmdbApiKey.trim();
if (!tmdbApiKey) {
throw new Error('Missing MOVIE_WEB_TMDB_API_KEY environment variable');
}
let proxyUrl: undefined | string = process.env.MOVIE_WEB_PROXY_URL;
proxyUrl = !proxyUrl ? undefined : proxyUrl;
return {
tmdbApiKey,
proxyUrl,
};
}

185
src/dev-cli/index.ts Normal file
View File

@@ -0,0 +1,185 @@
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import { program } from 'commander';
import dotenv from 'dotenv';
import { prompt } from 'enquirer';
import { runScraper } from '@/dev-cli/scraper';
import { processOptions } from '@/dev-cli/validate';
import { getBuiltinEmbeds, getBuiltinSources } from '..';
dotenv.config();
type ProviderSourceAnswers = {
id: string;
type: string;
};
type EmbedSourceAnswers = {
url: string;
};
type CommonAnswers = {
fetcher: string;
source: string;
};
type ShowAnswers = {
season: string;
episode: string;
};
const sourceScrapers = getBuiltinSources().sort((a, b) => b.rank - a.rank);
const embedScrapers = getBuiltinEmbeds().sort((a, b) => b.rank - a.rank);
const sources = [...sourceScrapers, ...embedScrapers];
function joinMediaTypes(mediaTypes: string[] | undefined) {
if (mediaTypes) {
const formatted = mediaTypes
.map((type: string) => {
return `${type[0].toUpperCase() + type.substring(1).toLowerCase()}s`;
})
.join(' / ');
return `(${formatted})`;
}
return ''; // * Embed sources pass through here too
}
async function runQuestions() {
const options = {
fetcher: 'node-fetch',
sourceId: '',
tmdbId: '',
type: 'movie',
season: '0',
episode: '0',
url: '',
};
const answers = await prompt<CommonAnswers>([
{
type: 'select',
name: 'fetcher',
message: 'Select a fetcher mode',
choices: [
{
message: 'Native',
name: 'native',
},
{
message: 'Node fetch',
name: 'node-fetch',
},
{
message: 'Browser',
name: 'browser',
},
],
},
{
type: 'select',
name: 'source',
message: 'Select a source',
choices: sources.map((source) => ({
message: `[${source.type.toLocaleUpperCase()}] ${source.name} ${joinMediaTypes(source.mediaTypes)}`.trim(),
name: source.id,
})),
},
]);
options.fetcher = answers.fetcher;
options.sourceId = answers.source;
const source = sources.find(({ id }) => id === answers.source);
if (!source) {
throw new Error(`No source with ID ${answers.source} found`);
}
if (source.type === 'embed') {
const sourceAnswers = await prompt<EmbedSourceAnswers>([
{
type: 'input',
name: 'url',
message: 'Embed URL',
},
]);
options.url = sourceAnswers.url;
} else {
const sourceAnswers = await prompt<ProviderSourceAnswers>([
{
type: 'input',
name: 'id',
message: 'TMDB ID',
},
{
type: 'select',
name: 'type',
message: 'Media type',
choices: [
{
message: 'Movie',
name: 'movie',
},
{
message: 'TV Show',
name: 'show',
},
],
},
]);
options.tmdbId = sourceAnswers.id;
options.type = sourceAnswers.type;
if (sourceAnswers.type === 'show') {
const seriesAnswers = await prompt<ShowAnswers>([
{
type: 'input',
name: 'season',
message: 'Season',
},
{
type: 'input',
name: 'episode',
message: 'Episode',
},
]);
options.season = seriesAnswers.season;
options.episode = seriesAnswers.episode;
}
}
const { providerOptions, source: validatedSource, options: validatedOps } = await processOptions(sources, options);
await runScraper(providerOptions, validatedSource, validatedOps);
}
async function runCommandLine() {
program
.option('-f, --fetcher <fetcher>', "Fetcher to use. Either 'native' or 'node-fetch'", 'node-fetch')
.option('-sid, --source-id <id>', 'ID for the source to use. Either an embed or provider', '')
.option('-tid, --tmdb-id <id>', 'TMDB ID for the media to scrape. Only used if source is a provider', '')
.option('-t, --type <type>', "Media type. Either 'movie' or 'show'. Only used if source is a provider", 'movie')
.option('-s, --season <number>', "Season number. Only used if type is 'show'", '0')
.option('-e, --episode <number>', "Episode number. Only used if type is 'show'", '0')
.option('-u, --url <embed URL>', 'URL to a video embed. Only used if source is an embed', '');
program.parse();
const {
providerOptions,
source: validatedSource,
options: validatedOps,
} = await processOptions(sources, program.opts());
await runScraper(providerOptions, validatedSource, validatedOps);
}
if (process.argv.length === 2) {
runQuestions().catch(() => console.error('Exited.'));
} else {
runCommandLine().catch(() => console.error('Exited.'));
}

5
src/dev-cli/logging.ts Normal file
View File

@@ -0,0 +1,5 @@
import { inspect } from 'node:util';
export function logDeepObject(object: Record<any, any>) {
console.log(inspect(object, { showHidden: false, depth: null, colors: true }));
}

136
src/dev-cli/scraper.ts Normal file
View File

@@ -0,0 +1,136 @@
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import { existsSync } from 'fs';
import { join } from 'path';
import puppeteer, { Browser } from 'puppeteer';
import Spinnies from 'spinnies';
import { PreviewServer, build, preview } from 'vite';
import { getConfig } from '@/dev-cli/config';
import { logDeepObject } from '@/dev-cli/logging';
import { getMovieMediaDetails, getShowMediaDetails } from '@/dev-cli/tmdb';
import { CommandLineArguments } from '@/dev-cli/validate';
import { MetaOutput, ProviderMakerOptions, makeProviders } from '..';
async function runBrowserScraping(
providerOptions: ProviderMakerOptions,
source: MetaOutput,
options: CommandLineArguments,
) {
if (!existsSync(join(__dirname, '../../lib/index.mjs')))
throw new Error('Please compile before running cli in browser mode');
const config = getConfig();
if (!config.proxyUrl)
throw new Error('Simple proxy url must be set in the environment (MOVIE_WEB_PROXY_URL) for browser mode to work');
const root = join(__dirname, 'browser');
let server: PreviewServer | undefined;
let browser: Browser | undefined;
try {
// setup browser
await build({
root,
});
server = await preview({
root,
});
browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
await page.goto(server.resolvedUrls.local[0]);
await page.waitForFunction('!!window.scrape', { timeout: 5000 });
// get input media
let input: any;
if (source.type === 'embed') {
input = {
url: options.url,
id: source.id,
};
} else if (source.type === 'source') {
let media;
if (options.type === 'movie') {
media = await getMovieMediaDetails(options.tmdbId);
} else {
media = await getShowMediaDetails(options.tmdbId, options.season, options.episode);
}
input = {
media,
id: source.id,
};
} else {
throw new Error('Wrong source input type');
}
return await page.evaluate(
async (proxy, type, inp) => {
return (window as any).scrape(proxy, type, inp);
},
config.proxyUrl,
source.type,
input,
);
} finally {
server?.httpServer.close();
await browser?.close();
}
}
async function runActualScraping(
providerOptions: ProviderMakerOptions,
source: MetaOutput,
options: CommandLineArguments,
): Promise<any> {
if (options.fetcher === 'browser') return runBrowserScraping(providerOptions, source, options);
const providers = makeProviders(providerOptions);
if (source.type === 'embed') {
return providers.runEmbedScraper({
url: options.url,
id: source.id,
});
}
if (source.type === 'source') {
let media;
if (options.type === 'movie') {
media = await getMovieMediaDetails(options.tmdbId);
} else {
media = await getShowMediaDetails(options.tmdbId, options.season, options.episode);
}
return providers.runSourceScraper({
media,
id: source.id,
});
}
throw new Error('Invalid source type');
}
export async function runScraper(
providerOptions: ProviderMakerOptions,
source: MetaOutput,
options: CommandLineArguments,
) {
const spinnies = new Spinnies();
spinnies.add('scrape', { text: `Running ${source.name} scraper` });
try {
const result = await runActualScraping(providerOptions, source, options);
spinnies.succeed('scrape', { text: 'Done!' });
logDeepObject(result);
} catch (error) {
let message = 'Unknown error';
if (error instanceof Error) {
message = error.message;
}
spinnies.fail('scrape', { text: `ERROR: ${message}` });
console.error(error);
}
}

95
src/dev-cli/tmdb.ts Normal file
View File

@@ -0,0 +1,95 @@
import { getConfig } from '@/dev-cli/config';
import { MovieMedia, ShowMedia } from '..';
export async function makeTMDBRequest(url: string): Promise<Response> {
const headers: {
accept: 'application/json';
authorization?: string;
} = {
accept: 'application/json',
};
let requestURL = url;
const key = getConfig().tmdbApiKey;
// * JWT keys always start with ey and are ONLY valid as a header.
// * All other keys are ONLY valid as a query param.
// * Thanks TMDB.
if (key.startsWith('ey')) {
headers.authorization = `Bearer ${key}`;
} else {
requestURL += `?api_key=${key}`;
}
return fetch(requestURL, {
method: 'GET',
headers,
});
}
export async function getMovieMediaDetails(id: string): Promise<MovieMedia> {
const response = await makeTMDBRequest(`https://api.themoviedb.org/3/movie/${id}`);
const movie = await response.json();
if (movie.success === false) {
throw new Error(movie.status_message);
}
if (!movie.release_date) {
throw new Error(`${movie.title} has no release_date. Assuming unreleased`);
}
return {
type: 'movie',
title: movie.title,
releaseYear: Number(movie.release_date.split('-')[0]),
tmdbId: id,
};
}
export async function getShowMediaDetails(id: string, seasonNumber: string, episodeNumber: string): Promise<ShowMedia> {
// * TV shows require the TMDB ID for the series, season, and episode
// * and the name of the series. Needs multiple requests
let response = await makeTMDBRequest(`https://api.themoviedb.org/3/tv/${id}`);
const series = await response.json();
if (series.success === false) {
throw new Error(series.status_message);
}
if (!series.first_air_date) {
throw new Error(`${series.name} has no first_air_date. Assuming unaired`);
}
response = await makeTMDBRequest(`https://api.themoviedb.org/3/tv/${id}/season/${seasonNumber}`);
const season = await response.json();
if (season.success === false) {
throw new Error(season.status_message);
}
response = await makeTMDBRequest(
`https://api.themoviedb.org/3/tv/${id}/season/${seasonNumber}/episode/${episodeNumber}`,
);
const episode = await response.json();
if (episode.success === false) {
throw new Error(episode.status_message);
}
return {
type: 'show',
title: series.name,
releaseYear: Number(series.first_air_date.split('-')[0]),
tmdbId: id,
episode: {
number: episode.episode_number,
tmdbId: episode.id,
},
season: {
number: season.season_number,
tmdbId: season.id,
},
};
}

91
src/dev-cli/validate.ts Normal file
View File

@@ -0,0 +1,91 @@
import nodeFetch from 'node-fetch';
import { Embed, Sourcerer } from '@/providers/base';
import { ProviderMakerOptions, makeStandardFetcher, targets } from '..';
export type CommandLineArguments = {
fetcher: string;
sourceId: string;
tmdbId: string;
type: string;
season: string;
episode: string;
url: string;
};
export async function processOptions(sources: Array<Embed | Sourcerer>, options: CommandLineArguments) {
const fetcherOptions = ['node-fetch', 'native', 'browser'];
if (!fetcherOptions.includes(options.fetcher)) {
throw new Error(`Fetcher must be any of: ${fetcherOptions.join()}`);
}
if (!options.sourceId.trim()) {
throw new Error('Source ID must be provided');
}
const source = sources.find(({ id }) => id === options.sourceId);
if (!source) {
throw new Error('Invalid source ID. No source found');
}
if (source.type === 'embed' && !options.url.trim()) {
throw new Error('Must provide an embed URL for embed sources');
}
if (source.type === 'source') {
if (!options.tmdbId.trim()) {
throw new Error('Must provide a TMDB ID for provider sources');
}
if (Number.isNaN(Number(options.tmdbId)) || Number(options.tmdbId) < 0) {
throw new Error('TMDB ID must be a number greater than 0');
}
if (!options.type.trim()) {
throw new Error('Must provide a type for provider sources');
}
if (options.type !== 'movie' && options.type !== 'show') {
throw new Error("Invalid media type. Must be either 'movie' or 'show'");
}
if (options.type === 'show') {
if (!options.season.trim()) {
throw new Error('Must provide a season number for TV shows');
}
if (!options.episode.trim()) {
throw new Error('Must provide an episode number for TV shows');
}
if (Number.isNaN(Number(options.season)) || Number(options.season) <= 0) {
throw new Error('Season number must be a number greater than 0');
}
if (Number.isNaN(Number(options.episode)) || Number(options.episode) <= 0) {
throw new Error('Episode number must be a number greater than 0');
}
}
}
let fetcher;
if (options.fetcher === 'native') {
fetcher = makeStandardFetcher(fetch);
} else {
fetcher = makeStandardFetcher(nodeFetch);
}
const providerOptions: ProviderMakerOptions = {
fetcher,
target: targets.ANY,
};
return {
providerOptions,
options,
source,
};
}

93
src/entrypoint/builder.ts Normal file
View File

@@ -0,0 +1,93 @@
import { ProviderControls, makeControls } from '@/entrypoint/controls';
import { getBuiltinEmbeds, getBuiltinSources } from '@/entrypoint/providers';
import { Targets, getTargetFeatures } from '@/entrypoint/utils/targets';
import { Fetcher } from '@/fetchers/types';
import { Embed, Sourcerer } from '@/providers/base';
import { getProviders } from '@/providers/get';
export type ProviderBuilder = {
setTarget(target: Targets): ProviderBuilder;
setFetcher(fetcher: Fetcher): ProviderBuilder;
setProxiedFetcher(fetcher: Fetcher): ProviderBuilder;
addSource(scraper: Sourcerer): ProviderBuilder;
addSource(name: string): ProviderBuilder;
addEmbed(scraper: Embed): ProviderBuilder;
addEmbed(name: string): ProviderBuilder;
addBuiltinProviders(): ProviderBuilder;
enableConsistentIpForRequests(): ProviderBuilder;
build(): ProviderControls;
};
export function buildProviders(): ProviderBuilder {
let consistentIpForRequests = false;
let target: Targets | null = null;
let fetcher: Fetcher | null = null;
let proxiedFetcher: Fetcher | null = null;
const embeds: Embed[] = [];
const sources: Sourcerer[] = [];
const builtinSources = getBuiltinSources();
const builtinEmbeds = getBuiltinEmbeds();
return {
enableConsistentIpForRequests() {
consistentIpForRequests = true;
return this;
},
setFetcher(f) {
fetcher = f;
return this;
},
setProxiedFetcher(f) {
proxiedFetcher = f;
return this;
},
setTarget(t) {
target = t;
return this;
},
addSource(input) {
if (typeof input !== 'string') {
sources.push(input);
return this;
}
const matchingSource = builtinSources.find((v) => v.id === input);
if (!matchingSource) throw new Error('Source not found');
sources.push(matchingSource);
return this;
},
addEmbed(input) {
if (typeof input !== 'string') {
embeds.push(input);
return this;
}
const matchingEmbed = builtinEmbeds.find((v) => v.id === input);
if (!matchingEmbed) throw new Error('Embed not found');
embeds.push(matchingEmbed);
return this;
},
addBuiltinProviders() {
sources.push(...builtinSources);
embeds.push(...builtinEmbeds);
return this;
},
build() {
if (!target) throw new Error('Target not set');
if (!fetcher) throw new Error('Fetcher not set');
const features = getTargetFeatures(target, consistentIpForRequests);
const list = getProviders(features, {
embeds,
sources,
});
return makeControls({
fetcher,
proxiedFetcher: proxiedFetcher ?? undefined,
embeds: list.embeds,
sources: list.sources,
features,
});
},
};
}

View File

@@ -1,24 +1,19 @@
import { makeFullFetcher } from '@/fetchers/common';
import { FullScraperEvents, IndividualScraperEvents } from '@/entrypoint/utils/events';
import { ScrapeMedia } from '@/entrypoint/utils/media';
import { MetaOutput, getAllEmbedMetaSorted, getAllSourceMetaSorted, getSpecificId } from '@/entrypoint/utils/meta';
import { FeatureMap } from '@/entrypoint/utils/targets';
import { makeFetcher } from '@/fetchers/common';
import { Fetcher } from '@/fetchers/types';
import { FullScraperEvents, IndividualScraperEvents } from '@/main/events';
import { scrapeIndividualEmbed, scrapeInvidualSource } from '@/main/individualRunner';
import { ScrapeMedia } from '@/main/media';
import { MetaOutput, getAllEmbedMetaSorted, getAllSourceMetaSorted, getSpecificId } from '@/main/meta';
import { RunOutput, runAllProviders } from '@/main/runner';
import { Targets, getTargetFeatures } from '@/main/targets';
import { EmbedOutput, SourcererOutput } from '@/providers/base';
import { getProviders } from '@/providers/get';
import { Embed, EmbedOutput, Sourcerer, SourcererOutput } from '@/providers/base';
import { scrapeIndividualEmbed, scrapeInvidualSource } from '@/runners/individualRunner';
import { RunOutput, runAllProviders } from '@/runners/runner';
export interface ProviderBuilderOptions {
// fetcher, every web request gets called through here
export interface ProviderControlsInput {
fetcher: Fetcher;
// proxied fetcher, if the scraper needs to access a CORS proxy. this fetcher will be called instead
// of the normal fetcher. Defaults to the normal fetcher.
proxiedFetcher?: Fetcher;
// target of where the streams will be used
target: Targets;
features: FeatureMap;
sources: Sourcerer[];
embeds: Embed[];
}
export interface RunnerOptions {
@@ -80,13 +75,16 @@ export interface ProviderControls {
listEmbeds(): MetaOutput[];
}
export function makeProviders(ops: ProviderBuilderOptions): ProviderControls {
const features = getTargetFeatures(ops.target);
const list = getProviders(features);
export function makeControls(ops: ProviderControlsInput): ProviderControls {
const list = {
embeds: ops.embeds,
sources: ops.sources,
};
const providerRunnerOps = {
features,
fetcher: makeFullFetcher(ops.fetcher),
proxiedFetcher: makeFullFetcher(ops.proxiedFetcher ?? ops.fetcher),
features: ops.features,
fetcher: makeFetcher(ops.fetcher),
proxiedFetcher: makeFetcher(ops.proxiedFetcher ?? ops.fetcher),
};
return {

37
src/entrypoint/declare.ts Normal file
View File

@@ -0,0 +1,37 @@
import { makeControls } from '@/entrypoint/controls';
import { getBuiltinEmbeds, getBuiltinSources } from '@/entrypoint/providers';
import { Targets, getTargetFeatures } from '@/entrypoint/utils/targets';
import { Fetcher } from '@/fetchers/types';
import { getProviders } from '@/providers/get';
export interface ProviderMakerOptions {
// fetcher, every web request gets called through here
fetcher: Fetcher;
// proxied fetcher, if the scraper needs to access a CORS proxy. this fetcher will be called instead
// of the normal fetcher. Defaults to the normal fetcher.
proxiedFetcher?: Fetcher;
// target of where the streams will be used
target: Targets;
// Set this to true, if the requests will have the same IP as
// the device that the stream will be played on
consistentIpForRequests?: boolean;
}
export function makeProviders(ops: ProviderMakerOptions) {
const features = getTargetFeatures(ops.target, ops.consistentIpForRequests ?? false);
const list = getProviders(features, {
embeds: getBuiltinEmbeds(),
sources: getBuiltinSources(),
});
return makeControls({
embeds: list.embeds,
sources: list.sources,
features,
fetcher: ops.fetcher,
proxiedFetcher: ops.proxiedFetcher,
});
}

View File

@@ -0,0 +1,10 @@
import { gatherAllEmbeds, gatherAllSources } from '@/providers/all';
import { Embed, Sourcerer } from '@/providers/base';
export function getBuiltinSources(): Sourcerer[] {
return gatherAllSources();
}
export function getBuiltinEmbeds(): Embed[] {
return gatherAllEmbeds();
}

View File

@@ -1,4 +1,4 @@
import { MediaTypes } from '@/main/media';
import { MediaTypes } from '@/entrypoint/utils/media';
import { Embed, Sourcerer } from '@/providers/base';
import { ProviderList } from '@/providers/get';

View File

@@ -0,0 +1,64 @@
export const flags = {
// CORS are set to allow any origin
CORS_ALLOWED: 'cors-allowed',
// the stream is locked on IP, so only works if
// request maker is same as player (not compatible with proxies)
IP_LOCKED: 'ip-locked',
} as const;
export type Flags = (typeof flags)[keyof typeof flags];
export const targets = {
// browser with CORS restrictions
BROWSER: 'browser',
// browser, but no CORS restrictions through a browser extension
BROWSER_EXTENSION: 'browser-extension',
// native app, so no restrictions in what can be played
NATIVE: 'native',
// any target, no target restrictions
ANY: 'any',
} as const;
export type Targets = (typeof targets)[keyof typeof targets];
export type FeatureMap = {
requires: Flags[];
disallowed: Flags[];
};
export const targetToFeatures: Record<Targets, FeatureMap> = {
browser: {
requires: [flags.CORS_ALLOWED],
disallowed: [],
},
'browser-extension': {
requires: [],
disallowed: [],
},
native: {
requires: [],
disallowed: [],
},
any: {
requires: [],
disallowed: [],
},
};
export function getTargetFeatures(target: Targets, consistentIpForRequests: boolean): FeatureMap {
const features = targetToFeatures[target];
if (!consistentIpForRequests) features.disallowed.push(flags.IP_LOCKED);
return features;
}
export function flagsAllowedInFeatures(features: FeatureMap, inputFlags: Flags[]): boolean {
const hasAllFlags = features.requires.every((v) => inputFlags.includes(v));
if (!hasAllFlags) return false;
const hasDisallowedFlag = features.disallowed.some((v) => inputFlags.includes(v));
if (hasDisallowedFlag) return false;
return true;
}

View File

@@ -26,14 +26,18 @@ export function makeFullUrl(url: string, ops?: FullUrlOptions): string {
return parsedUrl.toString();
}
export function makeFullFetcher(fetcher: Fetcher): UseableFetcher {
return (url, ops) => {
export function makeFetcher(fetcher: Fetcher): UseableFetcher {
const newFetcher = (url: string, ops?: FetcherOptions) => {
return fetcher(url, {
headers: ops?.headers ?? {},
method: ops?.method ?? 'GET',
query: ops?.query ?? {},
baseUrl: ops?.baseUrl ?? '',
readHeaders: ops?.readHeaders ?? [],
body: ops?.body,
});
};
const output: UseableFetcher = async (url, ops) => (await newFetcher(url, ops)).body;
output.full = newFetcher;
return output;
}

View File

@@ -11,12 +11,17 @@ export type FetchOps = {
export type FetchHeaders = {
get(key: string): string | null;
set(key: string, value: string): void;
};
export type FetchReply = {
text(): Promise<string>;
json(): Promise<any>;
extraHeaders?: FetchHeaders;
extraUrl?: string;
headers: FetchHeaders;
url: string;
status: number;
};
export type FetchLike = (url: string, ops?: FetchOps | undefined) => Promise<FetchReply>;

View File

@@ -9,9 +9,28 @@ const headerMap: Record<string, string> = {
origin: 'X-Origin',
};
const responseHeaderMap: Record<string, string> = {
'x-set-cookie': 'Set-Cookie',
};
export function makeSimpleProxyFetcher(proxyUrl: string, f: FetchLike): Fetcher {
const fetcher = makeStandardFetcher(f);
const proxiedFetch: Fetcher = async (url, ops) => {
const fetcher = makeStandardFetcher(async (a, b) => {
const res = await f(a, b);
// set extra headers that cant normally be accessed
res.extraHeaders = new Headers();
Object.entries(responseHeaderMap).forEach((entry) => {
const value = res.headers.get(entry[0]);
if (!value) return;
res.extraHeaders?.set(entry[0].toLowerCase(), value);
});
// set correct final url
res.extraUrl = res.headers.get('X-Final-Destination') ?? res.url;
return res;
});
const fullUrl = makeFullUrl(url, ops);
const headerEntries = Object.entries(ops.headers).map((entry) => {

View File

@@ -1,8 +1,20 @@
import { serializeBody } from '@/fetchers/body';
import { makeFullUrl } from '@/fetchers/common';
import { FetchLike } from '@/fetchers/fetch';
import { FetchLike, FetchReply } from '@/fetchers/fetch';
import { Fetcher } from '@/fetchers/types';
function getHeaders(list: string[], res: FetchReply): Headers {
const output = new Headers();
list.forEach((header) => {
const realHeader = header.toLowerCase();
const value = res.headers.get(realHeader);
const extraValue = res.extraHeaders?.get(realHeader);
if (!value) return;
output.set(realHeader, extraValue ?? value);
});
return output;
}
export function makeStandardFetcher(f: FetchLike): Fetcher {
const normalFetch: Fetcher = async (url, ops) => {
const fullUrl = makeFullUrl(url, ops);
@@ -17,9 +29,17 @@ export function makeStandardFetcher(f: FetchLike): Fetcher {
body: seralizedBody.body,
});
let body: any;
const isJson = res.headers.get('content-type')?.includes('application/json');
if (isJson) return res.json();
return res.text();
if (isJson) body = await res.json();
else body = await res.text();
return {
body,
finalUrl: res.extraUrl ?? res.url,
headers: getHeaders(ops.readHeaders, res),
statusCode: res.status,
};
};
return normalFetch;

View File

@@ -5,22 +5,35 @@ export type FetcherOptions = {
headers?: Record<string, string>;
query?: Record<string, string>;
method?: 'GET' | 'POST';
readHeaders?: string[];
body?: Record<string, any> | string | FormData | URLSearchParams;
};
// Version of the options that always has the defaults set
// This is to make making fetchers yourself easier
export type DefaultedFetcherOptions = {
baseUrl?: string;
body?: Record<string, any> | string | FormData;
headers: Record<string, string>;
query: Record<string, string>;
readHeaders: string[];
method: 'GET' | 'POST';
};
export type Fetcher<T = any> = {
(url: string, ops: DefaultedFetcherOptions): Promise<T>;
export type FetcherResponse<T = any> = {
statusCode: number;
headers: Headers;
finalUrl: string;
body: T;
};
// this feature has some quality of life features
export type UseableFetcher<T = any> = {
(url: string, ops?: FetcherOptions): Promise<T>;
// This is the version that will be inputted by library users
export type Fetcher = {
<T = any>(url: string, ops: DefaultedFetcherOptions): Promise<FetcherResponse<T>>;
};
// This is the version that scrapers will be interacting with
export type UseableFetcher = {
<T = any>(url: string, ops?: FetcherOptions): Promise<T>;
full: <T = any>(url: string, ops?: FetcherOptions) => Promise<FetcherResponse<T>>;
};

View File

@@ -1,19 +1,21 @@
export type { EmbedOutput, SourcererOutput } from '@/providers/base';
export type { RunOutput } from '@/main/runner';
export type { MetaOutput } from '@/main/meta';
export type { FullScraperEvents } from '@/main/events';
export type { Targets, Flags } from '@/main/targets';
export type { MediaTypes, ShowMedia, ScrapeMedia, MovieMedia } from '@/main/media';
export type {
ProviderBuilderOptions,
ProviderControls,
RunnerOptions,
EmbedRunnerOptions,
SourceRunnerOptions,
} from '@/main/builder';
export type { Stream, StreamFile, FileBasedStream, HlsBasedStream, Qualities } from '@/providers/streams';
export type { Fetcher, DefaultedFetcherOptions, FetcherOptions, FetcherResponse } from '@/fetchers/types';
export type { RunOutput } from '@/runners/runner';
export type { MetaOutput } from '@/entrypoint/utils/meta';
export type { FullScraperEvents } from '@/entrypoint/utils/events';
export type { Targets, Flags } from '@/entrypoint/utils/targets';
export type { MediaTypes, ShowMedia, ScrapeMedia, MovieMedia } from '@/entrypoint/utils/media';
export type { ProviderControls, RunnerOptions, EmbedRunnerOptions, SourceRunnerOptions } from '@/entrypoint/controls';
export type { ProviderBuilder } from '@/entrypoint/builder';
export type { ProviderMakerOptions } from '@/entrypoint/declare';
export type { MovieScrapeContext, ShowScrapeContext, EmbedScrapeContext, ScrapeContext } from '@/utils/context';
export type { SourcererOptions, EmbedOptions } from '@/providers/base';
export { NotFoundError } from '@/utils/errors';
export { makeProviders } from '@/main/builder';
export { makeProviders } from '@/entrypoint/declare';
export { buildProviders } from '@/entrypoint/builder';
export { getBuiltinEmbeds, getBuiltinSources } from '@/entrypoint/providers';
export { makeStandardFetcher } from '@/fetchers/standardFetch';
export { makeSimpleProxyFetcher } from '@/fetchers/simpleProxy';
export { flags, targets } from '@/main/targets';
export { flags, targets } from '@/entrypoint/utils/targets';

View File

@@ -1,40 +0,0 @@
export const flags = {
NO_CORS: 'no-cors',
IP_LOCKED: 'ip-locked',
} as const;
export type Flags = (typeof flags)[keyof typeof flags];
export const targets = {
BROWSER: 'browser',
NATIVE: 'native',
ALL: 'all',
} as const;
export type Targets = (typeof targets)[keyof typeof targets];
export type FeatureMap = {
requires: readonly Flags[];
};
export const targetToFeatures: Record<Targets, FeatureMap> = {
browser: {
requires: [flags.NO_CORS],
},
native: {
requires: [],
},
all: {
requires: [],
},
} as const;
export function getTargetFeatures(target: Targets): FeatureMap {
return targetToFeatures[target];
}
export function flagsAllowedInFeatures(features: FeatureMap, inputFlags: Flags[]): boolean {
const hasAllFlags = features.requires.every((v) => inputFlags.includes(v));
if (!hasAllFlags) return false;
return true;
}

View File

@@ -1,5 +1,6 @@
import { Embed, Sourcerer } from '@/providers/base';
import { febBoxScraper } from '@/providers/embeds/febBox';
import { febboxHlsScraper } from '@/providers/embeds/febbox/hls';
import { febboxMp4Scraper } from '@/providers/embeds/febbox/mp4';
import { mixdropScraper } from '@/providers/embeds/mixdrop';
import { mp4uploadScraper } from '@/providers/embeds/mp4upload';
import { streamsbScraper } from '@/providers/embeds/streamsb';
@@ -10,10 +11,12 @@ import { goMoviesScraper } from '@/providers/sources/gomovies/index';
import { kissAsianScraper } from '@/providers/sources/kissasian/index';
import { lookmovieScraper } from '@/providers/sources/lookmovie';
import { remotestreamScraper } from '@/providers/sources/remotestream';
import { superStreamScraper } from '@/providers/sources/superstream/index';
import { showboxScraper } from '@/providers/sources/showbox/index';
import { zoechipScraper } from '@/providers/sources/zoechip';
import { showBoxScraper } from './sources/showbox';
import { smashyStreamDScraper } from './embeds/smashystream/dued';
import { smashyStreamFScraper } from './embeds/smashystream/video1';
import { smashyStreamScraper } from './sources/smashystream';
export function gatherAllSources(): Array<Sourcerer> {
// all sources are gathered here
@@ -21,15 +24,25 @@ export function gatherAllSources(): Array<Sourcerer> {
flixhqScraper,
remotestreamScraper,
kissAsianScraper,
superStreamScraper,
showboxScraper,
goMoviesScraper,
zoechipScraper,
lookmovieScraper,
showBoxScraper,
smashyStreamScraper,
];
}
export function gatherAllEmbeds(): Array<Embed> {
// all embeds are gathered here
return [upcloudScraper, mp4uploadScraper, streamsbScraper, upstreamScraper, febBoxScraper, mixdropScraper];
return [
upcloudScraper,
mp4uploadScraper,
streamsbScraper,
upstreamScraper,
febboxMp4Scraper,
febboxHlsScraper,
mixdropScraper,
smashyStreamFScraper,
smashyStreamDScraper,
];
}

View File

@@ -1,35 +1,52 @@
import { MovieMedia, ShowMedia } from '@/main/media';
import { Flags } from '@/main/targets';
import { Flags } from '@/entrypoint/utils/targets';
import { Stream } from '@/providers/streams';
import { EmbedScrapeContext, ScrapeContext } from '@/utils/context';
import { EmbedScrapeContext, MovieScrapeContext, ShowScrapeContext } from '@/utils/context';
export type SourcererOutput = {
embeds: {
export type MediaScraperTypes = 'show' | 'movie';
export type SourcererEmbed = {
embedId: string;
url: string;
}[];
stream?: Stream;
};
export type Sourcerer = {
export type SourcererOutput = {
embeds: SourcererEmbed[];
stream?: Stream[];
};
export type SourcererOptions = {
id: string;
name: string; // displayed in the UI
rank: number; // the higher the number, the earlier it gets put on the queue
disabled?: boolean;
flags: Flags[];
scrapeMovie?: (input: ScrapeContext & { media: MovieMedia }) => Promise<SourcererOutput>;
scrapeShow?: (input: ScrapeContext & { media: ShowMedia }) => Promise<SourcererOutput>;
scrapeMovie?: (input: MovieScrapeContext) => Promise<SourcererOutput>;
scrapeShow?: (input: ShowScrapeContext) => Promise<SourcererOutput>;
};
export function makeSourcerer(state: Sourcerer): Sourcerer {
return state;
export type Sourcerer = SourcererOptions & {
type: 'source';
disabled: boolean;
mediaTypes: MediaScraperTypes[];
};
export function makeSourcerer(state: SourcererOptions): Sourcerer {
const mediaTypes: MediaScraperTypes[] = [];
if (state.scrapeMovie) mediaTypes.push('movie');
if (state.scrapeShow) mediaTypes.push('show');
return {
...state,
type: 'source',
disabled: state.disabled ?? false,
mediaTypes,
};
}
export type EmbedOutput = {
stream: Stream;
stream: Stream[];
};
export type Embed = {
export type EmbedOptions = {
id: string;
name: string; // displayed in the UI
rank: number; // the higher the number, the earlier it gets put on the queue
@@ -37,6 +54,17 @@ export type Embed = {
scrape: (input: EmbedScrapeContext) => Promise<EmbedOutput>;
};
export function makeEmbed(state: Embed): Embed {
return state;
export type Embed = EmbedOptions & {
type: 'embed';
disabled: boolean;
mediaTypes: undefined;
};
export function makeEmbed(state: EmbedOptions): Embed {
return {
...state,
type: 'embed',
disabled: state.disabled ?? false,
mediaTypes: undefined,
};
}

View File

@@ -8,6 +8,7 @@ export type CaptionType = keyof typeof captionTypes;
export type Caption = {
type: CaptionType;
id: string; // only unique per stream
url: string;
hasCorsRestrictions: boolean;
language: string;

View File

@@ -1,74 +0,0 @@
import { flags } from '@/main/targets';
import { makeEmbed } from '@/providers/base';
import { StreamFile } from '@/providers/streams';
import { NotFoundError } from '@/utils/errors';
const febBoxBase = `https://www.febbox.com`;
const allowedQualities = ['360', '480', '720', '1080'];
export const febBoxScraper = makeEmbed({
id: 'febbox',
name: 'FebBox',
rank: 160,
async scrape(ctx) {
const shareKey = ctx.url.split('/')[4];
const streams = await ctx.proxiedFetcher<{
data?: {
file_list?: {
fid?: string;
}[];
};
}>('/file/file_share_list', {
headers: {
'accept-language': 'en', // without this header, the request is marked as a webscraper
},
baseUrl: febBoxBase,
query: {
share_key: shareKey,
pwd: '',
},
});
const fid = streams?.data?.file_list?.[0]?.fid;
if (!fid) throw new NotFoundError('no result found');
const formParams = new URLSearchParams();
formParams.append('fid', fid);
formParams.append('share_key', shareKey);
const player = await ctx.proxiedFetcher<string>('/file/player', {
baseUrl: febBoxBase,
body: formParams,
method: 'POST',
headers: {
'accept-language': 'en', // without this header, the request is marked as a webscraper
},
});
const sourcesMatch = player?.match(/var sources = (\[[^\]]+\]);/);
const qualities = sourcesMatch ? JSON.parse(sourcesMatch[0].replace('var sources = ', '').replace(';', '')) : null;
const embedQualities: Record<string, StreamFile> = {};
qualities.forEach((quality: { file: string; label: string }) => {
const normalizedLabel = quality.label.toLowerCase().replace('p', '');
if (allowedQualities.includes(normalizedLabel)) {
if (!quality.file) return;
embedQualities[normalizedLabel] = {
type: 'mp4',
url: quality.file,
};
}
});
return {
stream: {
type: 'file',
captions: [],
flags: [flags.NO_CORS],
qualities: embedQualities,
},
};
},
});

View File

@@ -0,0 +1,24 @@
import { MediaTypes } from '@/entrypoint/utils/media';
export const febBoxBase = `https://www.febbox.com`;
export interface FebboxFileList {
file_name: string;
ext: string;
fid: number;
oss_fid: number;
is_dir: 0 | 1;
}
export function parseInputUrl(url: string) {
const [type, id, seasonId, episodeId] = url.slice(1).split('/');
const season = seasonId ? parseInt(seasonId, 10) : undefined;
const episode = episodeId ? parseInt(episodeId, 10) : undefined;
return {
type: type as MediaTypes,
id,
season,
episode,
};
}

View File

@@ -0,0 +1,69 @@
import { MediaTypes } from '@/entrypoint/utils/media';
import { FebboxFileList, febBoxBase } from '@/providers/embeds/febbox/common';
import { EmbedScrapeContext } from '@/utils/context';
export async function getFileList(
ctx: EmbedScrapeContext,
shareKey: string,
parentId?: number,
): Promise<FebboxFileList[]> {
const query: Record<string, string> = {
share_key: shareKey,
pwd: '',
};
if (parentId) {
query.parent_id = parentId.toString();
query.page = '1';
}
const streams = await ctx.proxiedFetcher<{
data?: {
file_list?: FebboxFileList[];
};
}>('/file/file_share_list', {
headers: {
'accept-language': 'en', // without this header, the request is marked as a webscraper
},
baseUrl: febBoxBase,
query,
});
return streams.data?.file_list ?? [];
}
function isValidStream(file: FebboxFileList): boolean {
return file.ext === 'mp4' || file.ext === 'mkv';
}
export async function getStreams(
ctx: EmbedScrapeContext,
shareKey: string,
type: MediaTypes,
season?: number,
episode?: number,
): Promise<FebboxFileList[]> {
const streams = await getFileList(ctx, shareKey);
if (type === 'show') {
const seasonFolder = streams.find((v) => {
if (!v.is_dir) return false;
return v.file_name.toLowerCase() === `season ${season}`;
});
if (!seasonFolder) return [];
const episodes = await getFileList(ctx, shareKey, seasonFolder.fid);
const s = season?.toString() ?? '0';
const e = episode?.toString() ?? '0';
const episodeRegex = new RegExp(`[Ss]0*${s}[Ee]0*${e}`);
return episodes
.filter((file) => {
if (file.is_dir) return false;
const match = file.file_name.match(episodeRegex);
if (!match) return false;
return true;
})
.filter(isValidStream);
}
return streams.filter((v) => !v.is_dir).filter(isValidStream);
}

View File

@@ -0,0 +1,50 @@
import { MediaTypes } from '@/entrypoint/utils/media';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
import { parseInputUrl } from '@/providers/embeds/febbox/common';
import { getStreams } from '@/providers/embeds/febbox/fileList';
import { getSubtitles } from '@/providers/embeds/febbox/subtitles';
import { showboxBase } from '@/providers/sources/showbox/common';
// structure: https://www.febbox.com/share/<random_key>
export function extractShareKey(url: string): string {
const parsedUrl = new URL(url);
const shareKey = parsedUrl.pathname.split('/')[2];
return shareKey;
}
export const febboxHlsScraper = makeEmbed({
id: 'febbox-hls',
name: 'Febbox (HLS)',
rank: 160,
async scrape(ctx) {
const { type, id, season, episode } = parseInputUrl(ctx.url);
const sharelinkResult = await ctx.proxiedFetcher<{
data?: { link?: string };
}>('/index/share_link', {
baseUrl: showboxBase,
query: {
id,
type: type === 'movie' ? '1' : '2',
},
});
if (!sharelinkResult?.data?.link) throw new Error('No embed url found');
ctx.progress(30);
const shareKey = extractShareKey(sharelinkResult.data.link);
const fileList = await getStreams(ctx, shareKey, type, season, episode);
const firstStream = fileList[0];
if (!firstStream) throw new Error('No playable mp4 stream found');
ctx.progress(70);
return {
stream: [
{
id: 'primary',
type: 'hls',
flags: [flags.CORS_ALLOWED],
captions: await getSubtitles(ctx, id, firstStream.fid, type as MediaTypes, season, episode),
playlist: `https://www.febbox.com/hls/main/${firstStream.oss_fid}.m3u8`,
},
],
};
},
});

View File

@@ -0,0 +1,53 @@
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
import { parseInputUrl } from '@/providers/embeds/febbox/common';
import { getStreamQualities } from '@/providers/embeds/febbox/qualities';
import { getSubtitles } from '@/providers/embeds/febbox/subtitles';
export const febboxMp4Scraper = makeEmbed({
id: 'febbox-mp4',
name: 'Febbox (MP4)',
rank: 190,
async scrape(ctx) {
const { type, id, season, episode } = parseInputUrl(ctx.url);
let apiQuery: object | null = null;
if (type === 'movie') {
apiQuery = {
uid: '',
module: 'Movie_downloadurl_v3',
mid: id,
oss: '1',
group: '',
};
} else if (type === 'show') {
apiQuery = {
uid: '',
module: 'TV_downloadurl_v3',
tid: id,
season,
episode,
oss: '1',
group: '',
};
}
if (!apiQuery) throw Error('Incorrect type');
const { qualities, fid } = await getStreamQualities(ctx, apiQuery);
if (fid === undefined) throw new Error('No streamable file found');
ctx.progress(70);
return {
stream: [
{
id: 'primary',
captions: await getSubtitles(ctx, id, fid, type, episode, season),
qualities,
type: 'file',
flags: [flags.CORS_ALLOWED],
},
],
};
},
});

View File

@@ -1,13 +1,11 @@
import { sendRequest } from '@/providers/sources/showbox/sendRequest';
import { StreamFile } from '@/providers/streams';
import { ScrapeContext } from '@/utils/context';
import { sendRequest } from './sendRequest';
const allowedQualities = ['360', '480', '720', '1080'];
const allowedQualities = ['360', '480', '720', '1080', '4k'];
export async function getStreamQualities(ctx: ScrapeContext, apiQuery: object) {
const mediaRes: { list: { path: string; quality: string; fid?: number }[] } = (await sendRequest(ctx, apiQuery)).data;
ctx.progress(66);
const qualityMap = mediaRes.list
.filter((file) => allowedQualities.includes(file.quality.replace('p', '')))

View File

@@ -1,9 +1,8 @@
import { Caption, getCaptionTypeFromUrl, isValidLanguageCode } from '@/providers/captions';
import { sendRequest } from '@/providers/sources/superstream/sendRequest';
import { captionsDomains } from '@/providers/sources/showbox/common';
import { sendRequest } from '@/providers/sources/showbox/sendRequest';
import { ScrapeContext } from '@/utils/context';
import { captionsDomains } from './common';
interface CaptionApiResponse {
data: {
list: {
@@ -55,6 +54,7 @@ export async function getSubtitles(
if (!validCode) return;
output.push({
id: subtitleFilePath,
language: subtitle.lang,
hasCorsRestrictions: true,
type: subtitleType,

View File

@@ -33,7 +33,9 @@ export const mixdropScraper = makeEmbed({
const url = link[1];
return {
stream: {
stream: [
{
id: 'primary',
type: 'file',
flags: [],
captions: [],
@@ -48,6 +50,7 @@ export const mixdropScraper = makeEmbed({
},
},
},
],
};
},
});

View File

@@ -1,4 +1,4 @@
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
export const mp4uploadScraper = makeEmbed({
@@ -15,9 +15,11 @@ export const mp4uploadScraper = makeEmbed({
if (!streamUrl) throw new Error('Stream url not found in embed code');
return {
stream: {
stream: [
{
id: 'primary',
type: 'file',
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
captions: [],
qualities: {
'1080': {
@@ -26,6 +28,7 @@ export const mp4uploadScraper = makeEmbed({
},
},
},
],
};
},
});

View File

@@ -0,0 +1,71 @@
import { load } from 'cheerio';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
type DPlayerSourcesResponse = {
title: string;
id: string;
file: string;
}[];
export const smashyStreamDScraper = makeEmbed({
id: 'smashystream-d',
name: 'SmashyStream (D)',
rank: 71,
async scrape(ctx) {
const mainPageRes = await ctx.proxiedFetcher<string>(ctx.url, {
headers: {
Referer: ctx.url,
},
});
const mainPageRes$ = load(mainPageRes);
const iframeUrl = mainPageRes$('iframe').attr('src');
if (!iframeUrl) throw new Error(`[${this.name}] failed to find iframe url`);
const mainUrl = new URL(iframeUrl);
const iframeRes = await ctx.proxiedFetcher<string>(iframeUrl, {
headers: {
Referer: ctx.url,
},
});
const textFilePath = iframeRes.match(/"file":"([^"]+)"/)?.[1];
const csrfToken = iframeRes.match(/"key":"([^"]+)"/)?.[1];
if (!textFilePath || !csrfToken) throw new Error(`[${this.name}] failed to find text file url or token`);
const textFileUrl = `${mainUrl.origin}${textFilePath}`;
const textFileRes = await ctx.proxiedFetcher<DPlayerSourcesResponse>(textFileUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-TOKEN': csrfToken,
Referer: iframeUrl,
},
});
// Playlists in Hindi, English, Tamil and Telugu are available. We only get the english one.
const textFilePlaylist = textFileRes.find((x) => x.title === 'English')?.file;
if (!textFilePlaylist) throw new Error(`[${this.name}] failed to find an english playlist`);
const playlistRes = await ctx.proxiedFetcher<string>(
`${mainUrl.origin}/playlist/${textFilePlaylist.slice(1)}.txt`,
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-TOKEN': csrfToken,
Referer: iframeUrl,
},
},
);
return {
stream: [
{
id: 'primary',
playlist: playlistRes,
type: 'hls',
flags: [flags.CORS_ALLOWED],
captions: [],
},
],
};
},
});

View File

@@ -0,0 +1,57 @@
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
import { Caption, getCaptionTypeFromUrl, labelToLanguageCode } from '@/providers/captions';
type FPlayerResponse = {
sourceUrls: string[];
subtitleUrls: string;
};
export const smashyStreamFScraper = makeEmbed({
id: 'smashystream-f',
name: 'SmashyStream (F)',
rank: 70,
async scrape(ctx) {
const res = await ctx.proxiedFetcher<FPlayerResponse>(ctx.url, {
headers: {
Referer: ctx.url,
},
});
const captions: Caption[] =
res.subtitleUrls
.match(/\[([^\]]+)\](https?:\/\/\S+?)(?=,\[|$)/g)
?.map<Caption | null>((entry: string) => {
const match = entry.match(/\[([^\]]+)\](https?:\/\/\S+?)(?=,\[|$)/);
if (match) {
const [, language, url] = match;
if (language && url) {
const languageCode = labelToLanguageCode(language);
const captionType = getCaptionTypeFromUrl(url);
if (!languageCode || !captionType) return null;
return {
id: url,
url: url.replace(',', ''),
language: languageCode,
type: captionType,
hasCorsRestrictions: false,
};
}
}
return null;
})
.filter((x): x is Caption => x !== null) ?? [];
return {
stream: [
{
id: 'primary',
playlist: res.sourceUrls[0],
type: 'hls',
flags: [flags.CORS_ALLOWED],
captions,
},
],
};
},
});

View File

@@ -3,7 +3,7 @@ import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
import FormData from 'form-data';
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
import { StreamFile } from '@/providers/streams';
import { EmbedScrapeContext } from '@/utils/context';
@@ -155,12 +155,15 @@ export const streamsbScraper = makeEmbed({
}, {} as Record<string, StreamFile>);
return {
stream: {
stream: [
{
id: 'primary',
type: 'file',
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
qualities,
captions: [],
},
],
};
},
});

View File

@@ -1,6 +1,6 @@
import crypto from 'crypto-js';
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
import { Caption, getCaptionTypeFromUrl, labelToLanguageCode } from '@/providers/captions';
@@ -110,6 +110,7 @@ export const upcloudScraper = makeEmbed({
const language = labelToLanguageCode(track.label);
if (!language) return;
captions.push({
id: track.file,
language,
hasCorsRestrictions: false,
type,
@@ -118,12 +119,15 @@ export const upcloudScraper = makeEmbed({
});
return {
stream: {
stream: [
{
id: 'primary',
type: 'hls',
playlist: sources.file,
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
captions,
},
],
};
},
});

View File

@@ -1,6 +1,6 @@
import * as unpacker from 'unpacker';
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeEmbed } from '@/providers/base';
const packedRegex = /(eval\(function\(p,a,c,k,e,d\).*\)\)\))/;
@@ -21,12 +21,15 @@ export const upstreamScraper = makeEmbed({
if (link) {
return {
stream: {
stream: [
{
id: 'primary',
type: 'hls',
playlist: link[1],
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
captions: [],
},
],
};
}
}

View File

@@ -1,5 +1,4 @@
import { FeatureMap, flagsAllowedInFeatures } from '@/main/targets';
import { gatherAllEmbeds, gatherAllSources } from '@/providers/all';
import { FeatureMap, flagsAllowedInFeatures } from '@/entrypoint/utils/targets';
import { Embed, Sourcerer } from '@/providers/base';
import { hasDuplicates } from '@/utils/predicates';
@@ -8,9 +7,9 @@ export interface ProviderList {
embeds: Embed[];
}
export function getProviders(features: FeatureMap): ProviderList {
const sources = gatherAllSources().filter((v) => !v?.disabled);
const embeds = gatherAllEmbeds().filter((v) => !v?.disabled);
export function getProviders(features: FeatureMap, list: ProviderList): ProviderList {
const sources = list.sources.filter((v) => !v?.disabled);
const embeds = list.embeds.filter((v) => !v?.disabled);
const combined = [...sources, ...embeds];
const anyDuplicateId = hasDuplicates(combined.map((v) => v.id));

View File

@@ -1,4 +1,4 @@
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeSourcerer } from '@/providers/base';
import { upcloudScraper } from '@/providers/embeds/upcloud';
import { getFlixhqMovieSources, getFlixhqShowSources, getFlixhqSourceDetails } from '@/providers/sources/flixhq/scrape';
@@ -9,7 +9,7 @@ export const flixhqScraper = makeSourcerer({
id: 'flixhq',
name: 'FlixHQ',
rank: 100,
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
async scrapeMovie(ctx) {
const id = await getFlixhqId(ctx, ctx.media);
if (!id) throw new NotFoundError('no search results match');

View File

@@ -1,6 +1,6 @@
import { load } from 'cheerio';
import { MovieMedia, ShowMedia } from '@/main/media';
import { MovieMedia, ShowMedia } from '@/entrypoint/utils/media';
import { flixHqBase } from '@/providers/sources/flixhq/common';
import { ScrapeContext } from '@/utils/context';
import { NotFoundError } from '@/utils/errors';

View File

@@ -1,8 +1,8 @@
import { load } from 'cheerio';
import { MovieMedia, ShowMedia } from '@/main/media';
import { MovieMedia, ShowMedia } from '@/entrypoint/utils/media';
import { flixHqBase } from '@/providers/sources/flixhq/common';
import { compareMedia } from '@/utils/compare';
import { compareMedia, compareTitle } from '@/utils/compare';
import { ScrapeContext } from '@/utils/context';
export async function getFlixhqId(ctx: ScrapeContext, media: MovieMedia | ShowMedia): Promise<string | null> {
@@ -18,16 +18,26 @@ export async function getFlixhqId(ctx: ScrapeContext, media: MovieMedia | ShowMe
const id = query.find('div.film-poster > a').attr('href')?.slice(1);
const title = query.find('div.film-detail > h2 > a').attr('title');
const year = query.find('div.film-detail > div.fd-infor > span:nth-child(1)').text();
const seasons = year.includes('SS') ? year.split('SS')[1] : '0';
if (!id || !title || !year) return null;
return {
id,
title,
year: parseInt(year, 10),
seasons: parseInt(seasons, 10),
};
});
const matchingItem = items.find((v) => v && compareMedia(media, v.title, v.year));
const matchingItem = items.find((v) => {
if (!v) return false;
if (media.type === 'movie') {
return compareMedia(media, v.title, v.year);
}
return compareTitle(media.title, v.title) && media.season.number < v.seasons + 1;
});
if (!matchingItem) return null;
return matchingItem.id;

View File

@@ -1,6 +1,6 @@
import { load } from 'cheerio';
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeSourcerer } from '@/providers/base';
import { upcloudScraper } from '@/providers/embeds/upcloud';
import { NotFoundError } from '@/utils/errors';
@@ -13,7 +13,7 @@ export const goMoviesScraper = makeSourcerer({
id: 'gomovies',
name: 'GOmovies',
rank: 110,
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
async scrapeShow(ctx) {
const search = await ctx.proxiedFetcher<string>(`/ajax/search`, {
method: 'POST',

View File

@@ -1,6 +1,6 @@
import { load } from 'cheerio';
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeSourcerer } from '@/providers/base';
import { NotFoundError } from '@/utils/errors';
@@ -13,7 +13,7 @@ export const kissAsianScraper = makeSourcerer({
id: 'kissasian',
name: 'KissAsian',
rank: 130,
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
disabled: true,
async scrapeShow(ctx) {

View File

@@ -1,11 +1,11 @@
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { SourcererOutput, makeSourcerer } from '@/providers/base';
import { MovieScrapeContext, ShowScrapeContext } from '@/utils/context';
import { NotFoundError } from '@/utils/errors';
import { scrape, searchAndFindMedia } from './util';
import { MovieContext, ShowContext } from '../zoechip/common';
async function universalScraper(ctx: ShowContext | MovieContext): Promise<SourcererOutput> {
async function universalScraper(ctx: MovieScrapeContext | ShowScrapeContext): Promise<SourcererOutput> {
const lookmovieData = await searchAndFindMedia(ctx, ctx.media);
if (!lookmovieData) throw new NotFoundError('Media not found');
@@ -17,12 +17,15 @@ async function universalScraper(ctx: ShowContext | MovieContext): Promise<Source
return {
embeds: [],
stream: {
stream: [
{
id: 'primary',
playlist: videoUrl,
type: 'hls',
flags: [flags.IP_LOCKED],
captions: [],
},
],
};
}

View File

@@ -1,4 +1,4 @@
import { MovieMedia } from '@/main/media';
import { MovieMedia } from '@/entrypoint/utils/media';
// ! Types
interface BaseConfig {

View File

@@ -1,4 +1,4 @@
import { MovieMedia, ShowMedia } from '@/main/media';
import { MovieMedia, ShowMedia } from '@/entrypoint/utils/media';
import { compareMedia } from '@/utils/compare';
import { ScrapeContext } from '@/utils/context';
import { NotFoundError } from '@/utils/errors';

View File

@@ -1,4 +1,4 @@
import { MovieMedia, ShowMedia } from '@/main/media';
import { MovieMedia, ShowMedia } from '@/entrypoint/utils/media';
import { ScrapeContext } from '@/utils/context';
import { StreamsDataResult } from './type';

View File

@@ -1,4 +1,4 @@
import { flags } from '@/main/targets';
import { flags } from '@/entrypoint/utils/targets';
import { makeSourcerer } from '@/providers/base';
import { NotFoundError } from '@/utils/errors';
@@ -8,7 +8,7 @@ export const remotestreamScraper = makeSourcerer({
id: 'remotestream',
name: 'Remote Stream',
rank: 55,
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
async scrapeShow(ctx) {
const seasonNumber = ctx.media.season.number;
const episodeNumber = ctx.media.episode.number;
@@ -22,12 +22,15 @@ export const remotestreamScraper = makeSourcerer({
return {
embeds: [],
stream: {
stream: [
{
id: 'primary',
captions: [],
playlist: playlistLink,
type: 'hls',
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
},
],
};
},
async scrapeMovie(ctx) {
@@ -40,12 +43,15 @@ export const remotestreamScraper = makeSourcerer({
return {
embeds: [],
stream: {
stream: [
{
id: 'primary',
captions: [],
playlist: playlistLink,
type: 'hls',
flags: [flags.NO_CORS],
flags: [flags.CORS_ALLOWED],
},
],
};
},
});

View File

@@ -12,3 +12,5 @@ export const apiUrls = [
export const appKey = atob('bW92aWVib3g=');
export const appId = atob('Y29tLnRkby5zaG93Ym94');
export const captionsDomains = [atob('bWJwaW1hZ2VzLmNodWF4aW4uY29t'), atob('aW1hZ2VzLnNoZWd1Lm5ldA==')];
export const showboxBase = 'https://www.showbox.media';

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