@letsmoe/otter-sdk 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -90,9 +90,10 @@ The SDK adds `object: "stream"` / `"source"` and converts to the backend's wire
90
90
 
91
91
  ### `ctx`
92
92
 
93
- - **`ctx.http`**: `get(url, options?)`, `post(url, { body | json, ... })`, `finalUrl(url)`, `absolute(path)`. Options: `headers`, `referer`, `timeout_ms` (15 s), `retries` (2, for network errors and 5xx, never 4xx), `allow_error_status`, `follow_redirects`. Responses have `.text()`, `.json()`, `.html()` (node-html-parser root), `.response()`, `.status`, `.url`. Browser User-Agent and an Accept-Language from `languages` are set. A Cloudflare challenge throws `PluginBlockedError` (or goes through FlareSolverr when `FLARESOLVERR_URL` is set); 429 throws `PluginRateLimitError`; 5xx and unreachable sites throw `PluginSourceError("source_offline")`; other 4xx throw `HttpError`.
93
+ - **`ctx.http`**: `get(url, options?)`, `post(url, { body | json, ... })`, `finalUrl(url)`, `absolute(path)`. Options: `headers`, `referer`, `timeout_ms` (15 s), `retries` (2, for network errors and 5xx, never 4xx), `allow_error_status`, `follow_redirects`. Responses have `.text()`, `.json()`, `.html()` (node-html-parser root), `.response()`, `.status`, `.url`. Browser User-Agent and an Accept-Language from `languages` are set. A Cloudflare challenge is passed by the Otter app's WebView when the plugin runs in the app's own backend (the request is sent again with its cookies), and otherwise throws `PluginBlockedError` (or goes through FlareSolverr when `FLARESOLVERR_URL` is set); 429 throws `PluginRateLimitError`; 5xx and unreachable sites throw `PluginSourceError("source_offline")`; other 4xx throw `HttpError`.
94
94
  - **`ctx.match`**: `normalize(title)` lowercases, folds umlauts (ä to ae, ß to ss) and accents, drops apostrophes, collapses punctuation. `titles(candidate, media)` compares against the title and original title (of the series for an episode), ignoring a trailing "(1999)", a leading the/der/die/das and and/und/&. `best(candidates, media, { title?, year? })` returns the candidate with an exactly matching title; the year (plus or minus one) only decides between several.
95
95
  - **`ctx.extract`**: `mediaUrls(html)` (m3u8/mpd/mp4/webm, also inside packed scripts), `unpack(html)` (Dean Edwards packer), `iframes(html, pageUrl)`, `scriptJson(html, name)`, `base64(text)` (URL-safe and unpadded too), `mimeType(url, fallback?)`.
96
+ - **`ctx.browser`**: `open(url)` opens a page in the Otter app's WebView, passes any captcha on it and resolves with the first URL off the page's site, e.g. the hoster a captcha-gated link page redirects to. The app tries hidden first and shows the page only while the user waits to play that link. Throws `PluginBlockedError` where no app can open pages (a NAS backend, tests without `testPlugin(..., { browser })`). Store such link pages as-is when listing and call `open` in `sources.retrieve`, so the captcha only comes up on play.
96
97
  - **`ctx.hosters`**: see below. **`ctx.settings`**: declared settings by key. **`ctx.log(message, data?)`**: stderr. **`ctx.list(items)`**.
97
98
 
98
99
  ### Hosters
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letsmoe/otter-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "author": {
6
6
  "name": "Letsmoe",
package/src/browser.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { PluginBlockedError } from "./errors.ts";
2
+
3
+ /** Pages that need a real browser, opened in the Otter app's WebView. */
4
+ export interface Browser {
5
+ /**
6
+ * Opens `url` in the app, passes any captcha on the way (hidden when it can, shown to
7
+ * the user only while they wait to play this link) and resolves with the first URL off
8
+ * the page's site, e.g. the hoster a captcha-gated link page redirects to. Throws
9
+ * PluginBlockedError where no app can do that (a NAS backend, tests).
10
+ */
11
+ open(url: string): Promise<string>;
12
+ }
13
+
14
+ // Installed by the backend's embedded runtime while the phone app listens for challenges.
15
+ declare const __otterBrowse: ((url: string) => Promise<string>) | undefined;
16
+
17
+ const BLOCKED_PREFIX = "blocked: ";
18
+
19
+ export function createBrowser(): Browser {
20
+ return {
21
+ async open(url: string): Promise<string> {
22
+ if (typeof __otterBrowse !== "function") {
23
+ throw new PluginBlockedError(`Opening ${url} needs the Otter app`);
24
+ }
25
+ try {
26
+ return await __otterBrowse(url);
27
+ } catch (error) {
28
+ throw browseError(error);
29
+ }
30
+ },
31
+ };
32
+ }
33
+
34
+ // The runtime prefixes failures to pass the page with "blocked: ".
35
+ function browseError(error: unknown): unknown {
36
+ const message = error instanceof Error ? error.message : String(error);
37
+ if (!message.startsWith(BLOCKED_PREFIX)) return error;
38
+ return new PluginBlockedError(message.slice(BLOCKED_PREFIX.length));
39
+ }
package/src/context.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import { type Browser, createBrowser } from "./browser.ts";
1
2
  import type { PluginContext, PluginDefinition } from "./definition.ts";
2
3
  import { extract } from "./extract.ts";
3
4
  import { hosters } from "./hosters/index.ts";
4
5
  import { createHttpClient } from "./http-client.ts";
5
6
  import { match } from "./match.ts";
6
7
  import type { List } from "./model.ts";
8
+ import { ACCOUNT_SESSION_ENV_KEY, ACCOUNT_USERNAME_ENV_KEY } from "./types.ts";
7
9
 
8
10
  /** Env var through which the backend passes the user's override of base_url. */
9
11
  export const BASE_URL_ENV_KEY = "OTTER_BASE_URL";
@@ -13,6 +15,8 @@ export interface ContextOptions {
13
15
  fetch?: typeof fetch;
14
16
  /** Replaces process.env, for tests. */
15
17
  env?: Record<string, string | undefined>;
18
+ /** Replaces the app's WebView, for tests. */
19
+ browser?: Browser;
16
20
  }
17
21
 
18
22
  /** The user's override of base_url if set, else the declared one; without trailing slash. */
@@ -38,6 +42,13 @@ function settingsOf(
38
42
  return settings;
39
43
  }
40
44
 
45
+ /** The login the backend passes along, for plugins that declare an account. */
46
+ function accountOf(env: Record<string, string | undefined>): PluginContext["account"] {
47
+ const session = env[ACCOUNT_SESSION_ENV_KEY] || "";
48
+ if (session === "") return undefined;
49
+ return { username: env[ACCOUNT_USERNAME_ENV_KEY] || "", session };
50
+ }
51
+
41
52
  function describe(data: unknown): string {
42
53
  if (data === undefined) return "";
43
54
  try {
@@ -63,7 +74,9 @@ export function createContext(definition: PluginDefinition, options: ContextOpti
63
74
  match,
64
75
  extract,
65
76
  hosters,
77
+ browser: options.browser || createBrowser(),
66
78
  settings: settingsOf(definition, env),
79
+ account: accountOf(env),
67
80
  log(message: string, data?: unknown): void {
68
81
  console.error(`[${definition.id}] ${message}${describe(data)}`);
69
82
  },
package/src/definition.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Browser } from "./browser.ts";
1
2
  import type { HosterRegistry } from "./hosters/registry.ts";
2
3
  import type { Extractor } from "./extract.ts";
3
4
  import type { HttpClient } from "./http-client.ts";
@@ -12,7 +13,7 @@ import type {
12
13
  SubtitleInput,
13
14
  SubtitleListParams,
14
15
  } from "./model.ts";
15
- import type { PluginSettingField } from "./types.ts";
16
+ import type { LoginArgs, LoginResult, PluginSettingField } from "./types.ts";
16
17
 
17
18
  /** Everything a handler needs, so plugins don't carry their own copies of these helpers. */
18
19
  export interface PluginContext {
@@ -28,8 +29,16 @@ export interface PluginContext {
28
29
  match: Matcher;
29
30
  extract: Extractor;
30
31
  hosters: HosterRegistry;
32
+ /** Pages behind a captcha, opened in the Otter app's WebView. */
33
+ browser: Browser;
31
34
  /** Values of the settings the plugin declares (default applied), by key. */
32
35
  settings: Record<string, string>;
36
+ /** The user's login, for plugins that declare `account`; undefined until they logged in. */
37
+ account?: {
38
+ username: string;
39
+ /** Whatever the plugin's `login` returned, e.g. the site's cookies. */
40
+ session: string;
41
+ };
33
42
  /** Writes to stderr, prefixed with the plugin id. */
34
43
  log(message: string, data?: unknown): void;
35
44
  list<Item>(items: Item[]): List<Item>;
@@ -53,6 +62,18 @@ export interface SourcesCapability {
53
62
  retrieve(params: SourceRetrieveParams, ctx: PluginContext): Promise<SourceInput>;
54
63
  }
55
64
 
65
+ export interface AccountCapability {
66
+ /** Where users without an account can make one. */
67
+ signup_url?: string;
68
+ /**
69
+ * Logs in with the user's credentials and returns a session string the
70
+ * plugin can use later (ctx.account.session). Throw PluginLoginFailedError
71
+ * when the site refuses them; other handlers throw PluginLoggedOutError
72
+ * when the site no longer accepts the session.
73
+ */
74
+ login(credentials: LoginArgs, ctx: PluginContext): Promise<LoginResult>;
75
+ }
76
+
56
77
  export interface PluginDefinition {
57
78
  /** Stable identifier; the settings key and the folder name. */
58
79
  id: string;
@@ -73,6 +94,8 @@ export interface PluginDefinition {
73
94
  streams?: StreamsCapability;
74
95
  sources?: SourcesCapability;
75
96
  subtitles?: SubtitlesCapability;
97
+ /** The site only works with the user's login. */
98
+ account?: AccountCapability;
76
99
  }
77
100
 
78
101
  /** Declares a plugin. Does nothing else: `runPlugin(plugin)` in the bundle entry runs it. */
package/src/errors.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  /** Why a plugin call failed, in terms the backend can act on. */
2
- export type ErrorCode = "blocked" | "source_offline" | "extraction_failed" | "rate_limited" | "dead_link";
2
+ export type ErrorCode =
3
+ | "blocked"
4
+ | "source_offline"
5
+ | "extraction_failed"
6
+ | "rate_limited"
7
+ | "dead_link"
8
+ | "logged_out"
9
+ | "login_failed";
3
10
 
4
11
  export interface OtterErrorOptions {
5
12
  code?: ErrorCode;
@@ -53,6 +60,23 @@ export class PluginRateLimitError extends OtterError {
53
60
  }
54
61
  }
55
62
 
63
+ /**
64
+ * The site no longer accepts the session (it shows a login form or redirects
65
+ * to one). The backend logs in again with the saved password and retries once.
66
+ */
67
+ export class PluginLoggedOutError extends OtterError {
68
+ constructor(message = "the site asked to log in again", status?: number) {
69
+ super("logged_out_error", message, { code: "logged_out", status });
70
+ }
71
+ }
72
+
73
+ /** The site refused the username or password. The message is shown in the login form. */
74
+ export class PluginLoginFailedError extends OtterError {
75
+ constructor(message: string, status?: number) {
76
+ super("login_failed_error", message, { code: "login_failed", status });
77
+ }
78
+ }
79
+
56
80
  /** A response with a status the plugin did not expect, and no more specific meaning. */
57
81
  export class HttpError extends OtterError {
58
82
  constructor(message: string, status: number) {
@@ -56,6 +56,11 @@ type Title {
56
56
  progress(profileId: ID!): WatchProgress
57
57
  rating(profileId: ID!): Float
58
58
  inWatchlist(profileId: ID!): Boolean!
59
+
60
+ """
61
+ Whether the profile gets news about this title: the Notify me bell's choice, else whether it is on My List.
62
+ """
63
+ notifying(profileId: ID!): Boolean!
59
64
  }
60
65
 
61
66
  type Season {
@@ -324,6 +329,14 @@ type Settings {
324
329
  """Whether the first-run TMDB key dialog was answered."""
325
330
  tmdbKeyPromptSeen: Boolean!
326
331
  requireVpn: Boolean!
332
+
333
+ """Whether errors are sent to the developers (PostHog error tracking)."""
334
+ errorReporting: Boolean!
335
+
336
+ """
337
+ Whether every TV cast is logged in detail, not only failed ones (opt-in).
338
+ """
339
+ castLogs: Boolean!
327
340
  disabledPlugins: [String!]!
328
341
  }
329
342
 
@@ -332,6 +345,8 @@ input SettingsInput {
332
345
  tmdbLanguage: String
333
346
  tmdbKeyPromptSeen: Boolean
334
347
  requireVpn: Boolean
348
+ errorReporting: Boolean
349
+ castLogs: Boolean
335
350
  }
336
351
 
337
352
  type PluginSettingField {
@@ -363,11 +378,39 @@ type Plugin {
363
378
  """
364
379
  available: Boolean!
365
380
  settings: [PluginSettingField!]!
381
+
382
+ """Set when the plugin's site needs the user's account."""
383
+ account: PluginAccount
384
+ }
385
+
386
+ """A plugin's login on its site. The password is never returned."""
387
+ type PluginAccount {
388
+ """Where users without an account can make one."""
389
+ signupUrl: String
390
+
391
+ """Null while no account is saved."""
392
+ username: String
393
+ loggedIn: Boolean!
394
+
395
+ """Why the last login failed."""
396
+ error: String
366
397
  }
367
398
 
368
399
  type Status {
369
400
  tmdbConfigured: Boolean!
401
+
402
+ """
403
+ False while the last TMDB request got no answer (offline, or a VPN or DNS filter blocks it).
404
+ """
405
+ tmdbReachable: Boolean!
406
+
407
+ """Whether the backend's traffic to the internet goes through a VPN."""
370
408
  vpnConnected: Boolean!
409
+
410
+ """
411
+ A VPN is up, but Otter's traffic skips it (e.g. Otter is excluded by the VPN's split tunnelling).
412
+ """
413
+ vpnBypassed: Boolean!
371
414
  requireVpn: Boolean!
372
415
  }
373
416
 
@@ -582,9 +625,73 @@ type Query {
582
625
  checkTmdbKey(key: String!): Boolean!
583
626
  plugins: [Plugin!]!
584
627
  status: Status!
628
+
629
+ """
630
+ The household's Neoworks account, which syncs profiles, history, lists, ratings and settings between devices.
631
+ """
632
+ neoworksAccount: NeoworksAccount!
633
+ }
634
+
635
+ type NeoworksAccount {
636
+ signedIn: Boolean!
637
+
638
+ """Null while signed out, and when Neoworks didn't share it."""
639
+ email: String
640
+ name: String
641
+
642
+ """The last sync since the backend started; null before the first."""
643
+ lastSync: NeoworksSync
644
+ }
645
+
646
+ type NeoworksSync {
647
+ at: String!
648
+
649
+ """Local records changed by other devices."""
650
+ received: Int!
651
+
652
+ """Rows written from this device."""
653
+ sent: Int!
654
+
655
+ """Why the sync stopped; null when it worked."""
656
+ failure: String
657
+ }
658
+
659
+ enum ChallengeKind {
660
+ """Pass the check and send back the site's cookies."""
661
+ CLEARANCE
662
+
663
+ """
664
+ Open the page, pass any check, and send back the first URL off the site (e.g. the hoster a link page redirects to).
665
+ """
666
+ NAVIGATION
667
+ }
668
+
669
+ """
670
+ A site's bot check (Cloudflare, Turnstile) the phone app solves in a WebView, like FlareSolverr.
671
+ """
672
+ type Challenge {
673
+ id: ID!
674
+ kind: ChallengeKind!
675
+
676
+ """The page to open; the check passes on it."""
677
+ url: String!
678
+ domain: String!
679
+
680
+ """
681
+ Show the page to the user: the hidden attempt failed and they are waiting to play.
682
+ """
683
+ interactive: Boolean!
585
684
  }
586
685
 
587
686
  type Mutation {
687
+ """
688
+ The app passed a bot check: its cookies for the site, the WebView's user agent they are bound to, and for a NAVIGATION the URL it led to.
689
+ """
690
+ completeChallenge(id: ID!, cookies: String!, userAgent: String!, finalUrl: String): Boolean!
691
+
692
+ """The app couldn't pass a bot check, e.g. hidden while it wants a click."""
693
+ failChallenge(id: ID!, reason: String!): Boolean!
694
+
588
695
  """
589
696
  Ask every streams plugin again for a movie or episode, in the background.
590
697
  """
@@ -604,8 +711,18 @@ type Mutation {
604
711
  clearRating(profileId: ID!, mediaId: ID!): Boolean!
605
712
  addToWatchlist(profileId: ID!, mediaId: ID!): Boolean!
606
713
  removeFromWatchlist(profileId: ID!, mediaId: ID!): Boolean!
714
+
715
+ """
716
+ The Notify me bell: news about a movie or series on or off, on My List or not. Adding to or removing from My List resets it.
717
+ """
718
+ setNotifying(profileId: ID!, mediaId: ID!, notifying: Boolean!): Boolean!
607
719
  markNotificationsRead(profileId: ID!): Boolean!
608
720
 
721
+ """
722
+ Check every title on any My List for news now instead of at the next sweep; returns when done. Used by the phone's background check.
723
+ """
724
+ checkNotifications: Boolean!
725
+
609
726
  """
610
727
  Queue a movie or episode for download; a failed one is retried. streamId picks the link, otherwise the best ones are tried.
611
728
  """
@@ -633,6 +750,8 @@ type Mutation {
633
750
 
634
751
  """Send a JSON payload to everyone else in the room."""
635
752
  sendTogether(payload: String!): Boolean!
753
+
754
+ """The first profile's top language also becomes the TMDB language."""
636
755
  createProfile(name: String!, avatarUrl: String, pin: String, isChild: Boolean = false, languages: [String!]): Profile!
637
756
 
638
757
  """
@@ -642,8 +761,65 @@ type Mutation {
642
761
  deleteProfile(id: ID!): Boolean!
643
762
  verifyPin(profileId: ID!, pin: String!): PinCheck!
644
763
  updateSettings(input: SettingsInput!): Settings!
764
+
765
+ """
766
+ Asks TMDB right now whether it answers; also updates Status.tmdbReachable.
767
+ """
768
+ checkTmdbConnection: Boolean!
645
769
  setPluginEnabled(name: String!, enabled: Boolean!): Plugin!
646
770
  setPluginSettings(name: String!, values: [PluginSettingInput!]!): Plugin!
771
+
772
+ """
773
+ Logs in to a plugin's site; the account is saved only when the site accepts it.
774
+ """
775
+ loginPlugin(name: String!, username: String!, password: String!): Plugin!
776
+
777
+ """Forgets a plugin's account."""
778
+ logoutPlugin(name: String!): Plugin!
779
+
780
+ """
781
+ Check npm for newer plugin releases now and install them (local builds stay). Fails when PLUGIN_AUTO_UPDATE=false.
782
+ """
783
+ updatePlugins: PluginUpdateReport!
784
+
785
+ """
786
+ Starts signing in to Neoworks and returns the page to open in a browser. returnTo is the web app's origin (e.g. http://nas.local:3000); the Android app leaves it out.
787
+ """
788
+ startNeoworksSignIn(returnTo: String): String!
789
+
790
+ """
791
+ Finishes the sign-in with the code and state otter.letsmoe.com/auth/callback received.
792
+ """
793
+ completeNeoworksSignIn(code: String!, state: String!): NeoworksAccount!
794
+
795
+ """
796
+ Signs this device out; the household's data stays in Neoworks for its other devices.
797
+ """
798
+ signOutOfNeoworks: NeoworksAccount!
799
+
800
+ """
801
+ Syncs with Neoworks now; returns when done, with the result in lastSync.
802
+ """
803
+ syncNeoworks: NeoworksAccount!
804
+
805
+ """
806
+ Starts a sync in the background and returns at once; the apps call it when they open.
807
+ """
808
+ syncNeoworksSoon: Boolean!
809
+ }
810
+
811
+ type PluginUpdate {
812
+ """The plugin's name, as in Plugin.name"""
813
+ name: String!
814
+ fromVersion: String!
815
+ toVersion: String!
816
+ }
817
+
818
+ type PluginUpdateReport {
819
+ updated: [PluginUpdate!]!
820
+
821
+ """Plugin folders whose check, download or install failed"""
822
+ failed: [String!]!
647
823
  }
648
824
 
649
825
  type Subscription {
@@ -654,4 +830,9 @@ type Subscription {
654
830
 
655
831
  """The Watch Together room as it changes, and messages from the others."""
656
832
  together: TogetherUpdate!
833
+
834
+ """
835
+ Bot checks to solve, for the phone app; while it listens, plugins that need solving are available.
836
+ """
837
+ challenges: Challenge!
657
838
  }