@letsmoe/otter-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +184 -2
  2. package/package.json +40 -4
  3. package/src/aes-gcm.ts +189 -0
  4. package/src/client.ts +23 -0
  5. package/src/context.ts +74 -0
  6. package/src/definition.ts +81 -0
  7. package/src/errors.ts +61 -0
  8. package/src/extract.ts +134 -0
  9. package/src/generated/index.ts +79 -0
  10. package/src/generated/runtime/batcher.ts +275 -0
  11. package/src/generated/runtime/createClient.ts +68 -0
  12. package/src/generated/runtime/error.ts +29 -0
  13. package/src/generated/runtime/fetcher.ts +97 -0
  14. package/src/generated/runtime/generateGraphqlOperation.ts +225 -0
  15. package/src/generated/runtime/index.ts +13 -0
  16. package/src/generated/runtime/linkTypeMap.ts +156 -0
  17. package/src/generated/runtime/typeSelection.ts +95 -0
  18. package/src/generated/runtime/types.ts +69 -0
  19. package/src/generated/schema.graphql +657 -0
  20. package/src/generated/schema.ts +1338 -0
  21. package/src/generated/types.ts +1495 -0
  22. package/src/hosters/dead-link.ts +55 -0
  23. package/src/hosters/dood.ts +69 -0
  24. package/src/hosters/filemoon.ts +152 -0
  25. package/src/hosters/generic.ts +63 -0
  26. package/src/hosters/index.ts +14 -0
  27. package/src/hosters/recaptcha.ts +61 -0
  28. package/src/hosters/registry.ts +74 -0
  29. package/src/hosters/streamtape.ts +63 -0
  30. package/src/hosters/vidara.ts +48 -0
  31. package/src/hosters/vinovo.ts +55 -0
  32. package/src/hosters/voe-decoding.ts +131 -0
  33. package/src/hosters/voe-domains.ts +39 -0
  34. package/src/hosters/voe.ts +82 -0
  35. package/src/http-client.ts +295 -0
  36. package/src/http.ts +97 -0
  37. package/src/index.ts +9 -0
  38. package/src/languages.ts +73 -0
  39. package/src/match.ts +120 -0
  40. package/src/model.ts +110 -0
  41. package/src/packer.ts +106 -0
  42. package/src/plugin.ts +4 -0
  43. package/src/run.ts +74 -0
  44. package/src/runtime.ts +254 -0
  45. package/src/testing.ts +120 -0
  46. package/src/timing.ts +11 -0
  47. package/src/types.ts +122 -0
  48. package/src/url.ts +60 -0
@@ -0,0 +1,73 @@
1
+ // ISO 639-1 codes and the three-letter codes subtitle sources use for them.
2
+ // The first three-letter code of a row is the one sources are asked with.
3
+
4
+ const LANGUAGE_ROWS: string[][] = [
5
+ ["en", "eng"],
6
+ ["de", "ger", "deu"],
7
+ ["fr", "fre", "fra"],
8
+ ["es", "spa"],
9
+ ["it", "ita"],
10
+ ["pt", "por", "pob", "pb"],
11
+ ["nl", "dut", "nld"],
12
+ ["pl", "pol"],
13
+ ["ru", "rus"],
14
+ ["tr", "tur"],
15
+ ["sv", "swe"],
16
+ ["da", "dan"],
17
+ ["no", "nor", "nob"],
18
+ ["fi", "fin"],
19
+ ["cs", "cze", "ces"],
20
+ ["sk", "slo", "slk"],
21
+ ["hu", "hun"],
22
+ ["ro", "rum", "ron"],
23
+ ["bg", "bul"],
24
+ ["el", "ell", "gre"],
25
+ ["he", "heb"],
26
+ ["ar", "ara"],
27
+ ["zh", "chi", "zho", "zht", "zhc"],
28
+ ["ja", "jpn"],
29
+ ["ko", "kor"],
30
+ ["hi", "hin"],
31
+ ["th", "tha"],
32
+ ["vi", "vie"],
33
+ ["id", "ind"],
34
+ ["uk", "ukr"],
35
+ ["hr", "hrv"],
36
+ ["sr", "scc", "srp"],
37
+ ["sl", "slv"],
38
+ ["lt", "lit"],
39
+ ["lv", "lav"],
40
+ ["et", "est"],
41
+ ["fa", "per", "fas"],
42
+ ["ca", "cat"],
43
+ ["eu", "baq", "eus"],
44
+ ["gl", "glg"],
45
+ ["is", "ice", "isl"],
46
+ ["ms", "may", "msa"],
47
+ ["bn", "ben"],
48
+ ["ta", "tam"],
49
+ ["sq", "alb", "sqi"],
50
+ ["mk", "mac", "mkd"],
51
+ ["bs", "bos"],
52
+ ["hy", "arm", "hye"],
53
+ ["ka", "geo", "kat"],
54
+ ];
55
+
56
+ const THREE_LETTER_TO_TWO = new Map<string, string>();
57
+ const TWO_TO_THREE_LETTER = new Map<string, string>();
58
+ for (const [twoLetter, preferred, ...others] of LANGUAGE_ROWS) {
59
+ TWO_TO_THREE_LETTER.set(twoLetter, preferred);
60
+ for (const threeLetter of [preferred, ...others]) THREE_LETTER_TO_TWO.set(threeLetter, twoLetter);
61
+ }
62
+
63
+ /** "ger" or "deu" to "de"; undefined for a language the table does not know. */
64
+ export function toIso6391(code: string): string | undefined {
65
+ const lowered = code.trim().toLowerCase();
66
+ if (lowered.length === 2 && TWO_TO_THREE_LETTER.has(lowered)) return lowered;
67
+ return THREE_LETTER_TO_TWO.get(lowered);
68
+ }
69
+
70
+ /** "de" to the three-letter code subtitle sources are asked with ("ger"); undefined when unknown. */
71
+ export function toIso6392(code: string): string | undefined {
72
+ return TWO_TO_THREE_LETTER.get(code.trim().toLowerCase());
73
+ }
package/src/match.ts ADDED
@@ -0,0 +1,120 @@
1
+ import type { MediaRef, TitleFields } from "./model.ts";
2
+
3
+ // Letters NFD cannot split into base letter and accent.
4
+ const SPECIAL_LETTERS: Record<string, string> = {
5
+ ä: "ae",
6
+ ö: "oe",
7
+ ü: "ue",
8
+ ß: "ss",
9
+ æ: "ae",
10
+ œ: "oe",
11
+ ø: "o",
12
+ đ: "d",
13
+ ł: "l",
14
+ ð: "d",
15
+ þ: "th",
16
+ ı: "i",
17
+ };
18
+
19
+ const SPECIAL_LETTER_PATTERN = /[äöüßæœøđłðþı]/g;
20
+ const COMBINING_MARKS = /[\u0300-\u036f]/g;
21
+ const APOSTROPHES = /['\u2018\u2019`\u00b4]/g;
22
+ // Whitespace, ASCII punctuation, and the Latin-1 and general punctuation blocks.
23
+ const SEPARATORS = /[\s\u00a0-\u00bf\u2000-\u206f!-\/:-@\[-`{-~]+/g;
24
+ const TRAILING_YEAR = /\s*\(\d{4}\)\s*$/;
25
+ const FILLER_WORDS = ["and", "und"];
26
+ const LEADING_ARTICLES = ["the", "der", "die", "das"];
27
+
28
+ /**
29
+ * Lowercases, folds umlauts (ä -> ae, ß -> ss) and other diacritics (é -> e),
30
+ * drops apostrophes and collapses any other punctuation to single spaces.
31
+ */
32
+ export function normalize(title: string): string {
33
+ const lowered = title.toLowerCase();
34
+ const withSpecials = lowered.replace(SPECIAL_LETTER_PATTERN, (letter) => SPECIAL_LETTERS[letter]);
35
+ const unaccented = withSpecials.normalize("NFD").replace(COMBINING_MARKS, "");
36
+ const withoutApostrophes = unaccented.replace(APOSTROPHES, "");
37
+ return withoutApostrophes.replace(SEPARATORS, " ").trim();
38
+ }
39
+
40
+ /** Normalizes a title for comparing: no trailing "(1999)", no leading article, "&"/"and"/"und" dropped. */
41
+ function comparableTitle(title: string): string {
42
+ const words = normalize(title.replace(TRAILING_YEAR, "")).split(" ");
43
+ const withoutFillers = words.filter((word) => !FILLER_WORDS.includes(word));
44
+ if (withoutFillers.length > 1 && LEADING_ARTICLES.includes(withoutFillers[0])) {
45
+ withoutFillers.shift();
46
+ }
47
+ return withoutFillers.join(" ");
48
+ }
49
+
50
+ function titleFieldsOf(media: MediaRef): TitleFields {
51
+ if (media.object === "movie") return media;
52
+ return media.series;
53
+ }
54
+
55
+ function comparableTitlesOf(media: MediaRef): string[] {
56
+ const fields = titleFieldsOf(media);
57
+ const known = [fields.title, fields.original_title];
58
+ const comparable: string[] = [];
59
+ for (const title of known) {
60
+ if (title) comparable.push(comparableTitle(title));
61
+ }
62
+ return comparable;
63
+ }
64
+
65
+ /** Whether a title found on a site is the movie, or the series of the episode, being looked for. */
66
+ export function titles(candidateTitle: string, media: MediaRef): boolean {
67
+ const candidate = comparableTitle(candidateTitle);
68
+ if (candidate === "") return false;
69
+ return comparableTitlesOf(media).includes(candidate);
70
+ }
71
+
72
+ export interface BestOptions<Candidate> {
73
+ /** Reads a candidate's title; defaults to the candidate itself (string) or its `title`. */
74
+ title?: (candidate: Candidate) => string;
75
+ year?: (candidate: Candidate) => number | undefined;
76
+ }
77
+
78
+ function defaultTitleOf(candidate: unknown): string {
79
+ if (typeof candidate === "string") return candidate;
80
+ const title = (candidate as { title?: unknown }).title;
81
+ if (typeof title === "string") return title;
82
+ return "";
83
+ }
84
+
85
+ /** 0 is the best fit: same year, then one year off, then unknown, then further away. */
86
+ function yearRank(candidateYear: number | undefined, wantedYear: number | undefined): number {
87
+ if (candidateYear === undefined || wantedYear === undefined) return 2;
88
+ const distance = Math.abs(candidateYear - wantedYear);
89
+ if (distance === 0) return 0;
90
+ if (distance === 1) return 1;
91
+ return 3;
92
+ }
93
+
94
+ /**
95
+ * The candidate whose normalized title equals the media's title or original
96
+ * title. The year only decides between several such candidates.
97
+ */
98
+ export function best<Candidate>(
99
+ candidates: Candidate[],
100
+ media: MediaRef,
101
+ options: BestOptions<Candidate> = {},
102
+ ): Candidate | undefined {
103
+ const titleOf = options.title || defaultTitleOf;
104
+ const matching = candidates.filter((candidate) => titles(titleOf(candidate), media));
105
+ if (matching.length === 0) return undefined;
106
+ if (!options.year) return matching[0];
107
+
108
+ const wantedYear = titleFieldsOf(media).year;
109
+ const yearOf = options.year;
110
+ let winner = matching[0];
111
+ for (const candidate of matching) {
112
+ if (yearRank(yearOf(candidate), wantedYear) < yearRank(yearOf(winner), wantedYear)) {
113
+ winner = candidate;
114
+ }
115
+ }
116
+ return winner;
117
+ }
118
+
119
+ export const match = { normalize, titles, best };
120
+ export type Matcher = typeof match;
package/src/model.ts ADDED
@@ -0,0 +1,110 @@
1
+ // The v2 plugin objects. Every object carries an `object` tag, ids are
2
+ // strings and field names are snake_case. The backend still speaks the v1
3
+ // wire format (types.ts); runtime.ts converts between the two.
4
+
5
+ import type { ResolveResult } from "./types.ts";
6
+
7
+ export type MediaKind = "movie" | "episode";
8
+
9
+ export type MimeType = ResolveResult["mime_type"];
10
+
11
+ export interface List<Item> {
12
+ object: "list";
13
+ data: Item[];
14
+ }
15
+
16
+ /** What a title is known by, for movies and for the series an episode belongs to. */
17
+ export interface TitleFields {
18
+ title: string;
19
+ original_title?: string;
20
+ year?: number;
21
+ tmdb_id?: number;
22
+ imdb_id?: string;
23
+ }
24
+
25
+ export interface MovieRef extends TitleFields {
26
+ object: "movie";
27
+ /** "movie:<tmdb id>" */
28
+ id: string;
29
+ }
30
+
31
+ export interface SeriesRef extends TitleFields {
32
+ object: "series";
33
+ /** "series:<tmdb id>" */
34
+ id: string;
35
+ }
36
+
37
+ export interface EpisodeRef {
38
+ object: "episode";
39
+ /** "episode:<series tmdb id>:<season>:<episode>" */
40
+ id: string;
41
+ series: SeriesRef;
42
+ season_number: number;
43
+ episode_number: number;
44
+ }
45
+
46
+ export type MediaRef = MovieRef | EpisodeRef;
47
+
48
+ export interface StreamListParams {
49
+ media: MediaRef;
50
+ }
51
+
52
+ export interface SubtitleListParams {
53
+ media: MediaRef;
54
+ /** Preferred ISO 639-1 codes, most preferred first. Empty = any language. */
55
+ languages: string[];
56
+ }
57
+
58
+ export interface SourceRetrieveParams {
59
+ url: string;
60
+ }
61
+
62
+ /** What `streams.list` returns per link. The SDK completes it into a `Stream`. */
63
+ export interface StreamInput {
64
+ url: string;
65
+ /** Defaults to the hoster's name, else the link's domain. */
66
+ label?: string;
67
+ /** "4K" | "1080p" | "720p" | ... */
68
+ quality?: string;
69
+ /** "de" | "en" | "de-sub" | ... */
70
+ language?: string;
71
+ /** "mkv" | "mp4" | ... */
72
+ format?: string;
73
+ size_bytes?: number;
74
+ }
75
+
76
+ export interface Stream extends StreamInput {
77
+ object: "stream";
78
+ label: string;
79
+ }
80
+
81
+ /** What `sources.retrieve` returns: a playable media URL. */
82
+ export interface SourceInput {
83
+ url: string;
84
+ mime_type: MimeType;
85
+ headers?: Record<string, string>;
86
+ quality?: string;
87
+ }
88
+
89
+ export interface Source extends SourceInput {
90
+ object: "source";
91
+ }
92
+
93
+ /** What `subtitles.list` returns per file. The SDK completes it into a `Subtitle`. */
94
+ export interface SubtitleInput {
95
+ url: string;
96
+ /** ISO 639-1, e.g. "de". */
97
+ language: string;
98
+ /** Defaults to "srt". */
99
+ format?: "srt" | "vtt";
100
+ label?: string;
101
+ /** Release name the file was made for. */
102
+ release?: string;
103
+ hearing_impaired?: boolean;
104
+ headers?: Record<string, string>;
105
+ }
106
+
107
+ export interface Subtitle extends SubtitleInput {
108
+ object: "subtitle";
109
+ format: "srt" | "vtt";
110
+ }
package/src/packer.ts ADDED
@@ -0,0 +1,106 @@
1
+ // Decoder for Dean Edwards' packer: eval(function(p,a,c,k,e,d){...}('payload',radix,count,'words'.split('|'),0,{}))
2
+
3
+ const PACKER_SIGNATURE = /eval\(function\(p,a,c,k,e,[dr]\)/;
4
+ const PAYLOAD_START = /\}\(['"]/;
5
+ const RADIX_AND_COUNT = /^,\s*(\d+)\s*,\s*(\d+)\s*,\s*(?=['"])/;
6
+ const SPLIT_ON_PIPE = /^\s*\.split\(\s*['"]\|['"]\s*\)/;
7
+ const MAX_NESTED_LAYERS = 3;
8
+
9
+ interface QuotedString {
10
+ value: string;
11
+ /** Index right after the closing quote. */
12
+ end: number;
13
+ }
14
+
15
+ const ESCAPES: Record<string, string> = { n: "\n", t: "\t", r: "\r" };
16
+
17
+ /** Reads a JS string literal whose opening quote sits at `start`. */
18
+ function readQuotedString(source: string, start: number): QuotedString | undefined {
19
+ const quote = source[start];
20
+ let value = "";
21
+ let position = start + 1;
22
+ while (position < source.length) {
23
+ const character = source[position];
24
+ if (character === quote) return { value, end: position + 1 };
25
+ if (character !== "\\") {
26
+ value += character;
27
+ position += 1;
28
+ continue;
29
+ }
30
+ const escaped = source[position + 1];
31
+ value += ESCAPES[escaped] || escaped;
32
+ position += 2;
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ /** The packer's number encoding: digits 0-9a-z, then A-Z for radixes above 36. */
38
+ function encodeNumber(value: number, radix: number): string {
39
+ const remainder = value % radix;
40
+ const prefix = value < radix ? "" : encodeNumber(Math.floor(value / radix), radix);
41
+ if (remainder > 35) return prefix + String.fromCharCode(remainder + 29);
42
+ return prefix + remainder.toString(36);
43
+ }
44
+
45
+ function buildDictionary(words: string[], radix: number, count: number): Map<string, string> {
46
+ const dictionary = new Map<string, string>();
47
+ for (let index = 0; index < count; index++) {
48
+ const key = encodeNumber(index, radix);
49
+ dictionary.set(key, words[index] || key);
50
+ }
51
+ return dictionary;
52
+ }
53
+
54
+ interface PackedBlock {
55
+ payload: string;
56
+ radix: number;
57
+ count: number;
58
+ words: string[];
59
+ }
60
+
61
+ /** Reads the arguments of the first packed block in `source`. */
62
+ function readPackedBlock(source: string): PackedBlock | undefined {
63
+ const signature = PACKER_SIGNATURE.exec(source);
64
+ if (!signature) return undefined;
65
+ const payloadStart = source.slice(signature.index).search(PAYLOAD_START);
66
+ if (payloadStart === -1) return undefined;
67
+
68
+ const payload = readQuotedString(source, signature.index + payloadStart + 2);
69
+ if (!payload) return undefined;
70
+ const afterPayload = source.slice(payload.end);
71
+ const radixAndCount = RADIX_AND_COUNT.exec(afterPayload);
72
+ if (!radixAndCount) return undefined;
73
+ const wordList = readQuotedString(afterPayload, radixAndCount[0].length);
74
+ if (!wordList) return undefined;
75
+ if (!SPLIT_ON_PIPE.test(afterPayload.slice(wordList.end))) return undefined;
76
+
77
+ return {
78
+ payload: payload.value,
79
+ radix: parseInt(radixAndCount[1], 10),
80
+ count: parseInt(radixAndCount[2], 10),
81
+ words: wordList.value.split("|"),
82
+ };
83
+ }
84
+
85
+ function unpackOnce(source: string): string | undefined {
86
+ const block = readPackedBlock(source);
87
+ if (!block) return undefined;
88
+ const dictionary = buildDictionary(block.words, block.radix, block.count);
89
+ return block.payload.replace(/\b\w+\b/g, (word) => {
90
+ const replacement = dictionary.get(word);
91
+ if (replacement === undefined) return word;
92
+ return replacement;
93
+ });
94
+ }
95
+
96
+ /** Fully decoded source of the packed script in `source`, or undefined when nothing is packed. */
97
+ export function unpack(source: string): string | undefined {
98
+ let decoded = unpackOnce(source);
99
+ if (decoded === undefined) return undefined;
100
+ for (let layer = 1; layer < MAX_NESTED_LAYERS; layer++) {
101
+ const inner = unpackOnce(decoded);
102
+ if (inner === undefined) return decoded;
103
+ decoded = inner;
104
+ }
105
+ return decoded;
106
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { definePlugin } from "./definition.ts";
2
+ export type { PluginContext, PluginDefinition, SourcesCapability, StreamsCapability, SubtitlesCapability } from "./definition.ts";
3
+ export { runPlugin, type PluginHandlers } from "./run.ts";
4
+ export { toIso6391, toIso6392 } from "./languages.ts";
package/src/run.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { writeSync } from "fs";
2
+ import type { PluginDefinition } from "./definition.ts";
3
+ import { OtterError } from "./errors.ts";
4
+ import { handlersOf, isPluginDefinition, type PluginHandlers } from "./runtime.ts";
5
+ import type { PluginMeta, ResolveResult, StreamsArgs, StreamsResult, SubtitlesArgs, SubtitlesResult } from "./types.ts";
6
+
7
+ export type { PluginHandlers };
8
+
9
+ interface Invocation {
10
+ capability: string;
11
+ args?: Record<string, unknown>;
12
+ }
13
+
14
+ function respond<Result>(result: Result): never {
15
+ writeSync(1, JSON.stringify({ result }) + "\n");
16
+ process.exit(0);
17
+ }
18
+
19
+ function fail(message: string, code?: string): never {
20
+ writeSync(1, JSON.stringify({ error: message, code }) + "\n");
21
+ process.exit(0);
22
+ }
23
+
24
+ async function readInvocation(): Promise<Invocation> {
25
+ // The backend's embedded runtime provides Bun.stdin as well.
26
+ const raw = await Bun.stdin.text();
27
+ try {
28
+ return JSON.parse(raw);
29
+ } catch {
30
+ fail("invalid JSON on stdin");
31
+ }
32
+ }
33
+
34
+ async function dispatch(handlers: PluginHandlers, input: Invocation): Promise<never> {
35
+ if (input.capability === "meta") respond<PluginMeta>(handlers.meta);
36
+
37
+ if (input.capability === "streams") {
38
+ if (!handlers.streams) fail("streams not implemented");
39
+ respond<StreamsResult>(await handlers.streams(input.args as unknown as StreamsArgs));
40
+ }
41
+
42
+ if (input.capability === "subtitles") {
43
+ if (!handlers.subtitles) fail("subtitles not implemented");
44
+ respond<SubtitlesResult>(await handlers.subtitles(input.args as unknown as SubtitlesArgs));
45
+ }
46
+
47
+ if (input.capability === "resolve") {
48
+ if (!handlers.resolve) fail("resolve not implemented");
49
+ const url = input.args?.url;
50
+ if (!url) fail("args.url required for resolve");
51
+ respond<ResolveResult>(await handlers.resolve(String(url)));
52
+ }
53
+
54
+ fail(`unsupported capability: ${input.capability}`);
55
+ }
56
+
57
+ function failWith(error: unknown): never {
58
+ if (error instanceof OtterError) fail(error.message, error.code);
59
+ fail(error instanceof Error ? error.message : String(error));
60
+ }
61
+
62
+ /**
63
+ * Entry point of every plugin: reads one request from stdin and answers on
64
+ * stdout. Takes a `definePlugin` definition, or the older `{ meta, streams, resolve }` handlers.
65
+ */
66
+ export async function runPlugin(plugin: PluginDefinition | PluginHandlers): Promise<never> {
67
+ const input = await readInvocation();
68
+ try {
69
+ const handlers = isPluginDefinition(plugin) ? handlersOf(plugin) : plugin;
70
+ return await dispatch(handlers, input);
71
+ } catch (error) {
72
+ failWith(error);
73
+ }
74
+ }