mirror of
https://github.com/LuanRT/YouTube.js.git
synced 2026-06-16 19:12:24 +00:00
Compare commits
18 Commits
v6.2.0-den
...
v10.2.0-de
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
843ecd28e3 | ||
|
|
8293af93fa | ||
|
|
f3d43bd395 | ||
|
|
09e0f91b66 | ||
|
|
28e766779e | ||
|
|
a482556187 | ||
|
|
b063b2f4a8 | ||
|
|
299548f255 | ||
|
|
016a7aacae | ||
|
|
bd5b3470ec | ||
|
|
648488641d | ||
|
|
944f821d9a | ||
|
|
bd9ae29de3 | ||
|
|
1b159e5162 | ||
|
|
2b58b3887c | ||
|
|
2294bf7065 | ||
|
|
f2d673ac95 | ||
|
|
1b557f25e3 |
93
README.md
93
README.md
@@ -10,82 +10,55 @@
|
||||
[twitter]: https://twitter.com/thesciencephile
|
||||
[discord]: https://discord.gg/syDu7Yks54
|
||||
|
||||
<h1 align=center>YouTube.js</h1>
|
||||
|
||||
<p align=center>A full-featured wrapper around the InnerTube API</p>
|
||||
|
||||
<div align="center">
|
||||
<br/>
|
||||
<p>
|
||||
<a href="https://github.com/LuanRT/YouTube.js"><img src="https://luanrt.github.io/assets/img/ytjs.svg" title="youtube.js" alt="YouTube.js' Github Page" width="200" /></a>
|
||||
</p>
|
||||
<p align="center">A full-featured wrapper around the InnerTube API</p>
|
||||
|
||||
[][discord]
|
||||
[][actions]
|
||||
[][versions]
|
||||
[][codefactor]
|
||||
[][npm]
|
||||
[][discord]
|
||||
[][codefactor]
|
||||
|
||||
<h5>
|
||||
Sponsored by <a href="https://serpapi.com"><img src="https://luanrt.github.io/assets/img/serpapi.svg" alt="SerpApi - API to get search engine results with ease." height=35 valign="middle"></a>
|
||||
</h5>
|
||||
<br>
|
||||
[][collaborators]
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<p>
|
||||
<sup>Special thanks to:</sup>
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://serpapi.com" target="_blank">
|
||||
<img width="80" alt="SerpApi" src="https://luanrt.github.io/assets/img/serpapi.svg" />
|
||||
<br>
|
||||
<sub>
|
||||
API to get search engine results with ease.
|
||||
</sub>
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<br>
|
||||
<hr>
|
||||
<br>
|
||||
InnerTube is an API used by all YouTube clients. It was created to simplify the deployment of new features and experiments across the platform [^1]. This library manages all low-level communication with InnerTube, providing a simple and efficient way to interact with YouTube programmatically. Its design aims to closely emulate an actual client, including the parsing of API responses.
|
||||
|
||||
## Table of Contents
|
||||
If you have any questions or need help, feel free to reach out to us on our [Discord server][discord] or open an issue [here](https://github.com/LuanRT/YouTube.js/issues).
|
||||
|
||||
### Table of Contents
|
||||
<ol>
|
||||
<li>
|
||||
<a href="#description">Description</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#getting-started">Getting Started</a>
|
||||
<ul>
|
||||
<li><a href="#prerequisites">Prerequisites</a></li>
|
||||
<li><a href="#installation">Installation</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#prerequisites">Prerequisites</a></li>
|
||||
<li><a href="#installation">Installation</a></li>
|
||||
<li>
|
||||
<a href="#usage">Usage</a>
|
||||
<ul>
|
||||
<li><a href="#browser-usage">Browser Usage</a></li>
|
||||
<li><a href="#caching">Caching</a></li>
|
||||
<li><a href="#api">API</a></li>
|
||||
<li><a href="#extending-the-library">Extending the library</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#extending-the-library">Extending the library</a></li>
|
||||
<li><a href="#contributing">Contributing</a></li>
|
||||
<li><a href="#contact">Contact</a></li>
|
||||
<li><a href="#disclaimer">Disclaimer</a></li>
|
||||
<li><a href="#license">License</a></li>
|
||||
</ol>
|
||||
|
||||
## Description
|
||||
|
||||
InnerTube is an API used by all YouTube clients. It was created to simplify the deployment of new features and experiments across the platform [^1]. This library manages all low-level communication with InnerTube, providing a simple and efficient way to interact with YouTube programmatically. Its design aims to closely emulate an actual client, including the parsing of API responses.
|
||||
|
||||
If you have any questions or need help, feel free to reach out to us on our [Discord server][discord] or open an issue [here](https://github.com/LuanRT/YouTube.js/issues).
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
YouTube.js runs on Node.js, Deno, and modern browsers.
|
||||
|
||||
It requires a runtime with the following features:
|
||||
- [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
|
||||
- On Node, we use [undici](https://github.com/nodejs/undici)'s fetch implementation, which requires Node.js 16.8+. If you need to use an older version, you may provide your own fetch implementation. See [providing your own fetch implementation](#custom-fetch) for more information.
|
||||
- The `Response` object returned by fetch must thus be spec compliant and return a `ReadableStream` object if you want to use the `VideoInfo#download` method. (Implementations like `node-fetch` returns a non-standard `Readable` object.)
|
||||
- The `Response` object returned by fetch must thus be spec compliant and return a `ReadableStream` object if you want to use the `VideoInfo#download` method. (Implementations like `node-fetch` return a non-standard `Readable` object.)
|
||||
- [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) and [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) are required.
|
||||
|
||||
### Installation
|
||||
@@ -114,7 +87,7 @@ import { Innertube } from 'youtubei.js';
|
||||
const youtube = await Innertube.create(/* options */);
|
||||
```
|
||||
|
||||
### Initialization Options
|
||||
### Options
|
||||
<details>
|
||||
<summary>Click to expand</summary>
|
||||
|
||||
@@ -126,17 +99,18 @@ const youtube = await Innertube.create(/* options */);
|
||||
| `visitor_data` | `string` | Setting this to a valid and persistent visitor data string will allow YouTube to give this session tailored content even when not logged in. A good way to get a valid one is by either grabbing it from a browser or calling InnerTube's `/visitor_id` endpoint. | `undefined` |
|
||||
| `retrieve_player` | `boolean` | Specifies whether to retrieve the JS player. Disabling this will make session creation faster. **NOTE:** Deciphering formats is not possible without the JS player. | `true` |
|
||||
| `enable_safety_mode` | `boolean` | Specifies whether to enable safety mode. This will prevent the session from loading any potentially unsafe content. | `false` |
|
||||
| `generate_session_locally` | `boolean` | Specifies whether to generate the session data locally or retrieve it from YouTube. This can be useful if you need more performance. | `false` |
|
||||
| `generate_session_locally` | `boolean` | Specifies whether to generate the session data locally or retrieve it from YouTube. This can be useful if you need more performance. **NOTE:** If you are using the cache option and a session has already been generated, this will be ignored. If you want to force a new session to be generated, you must clear the cache or disable session caching. | `false` |
|
||||
| `enable_session_cache` | `boolean` | Specifies whether to cache the session data. | `true` |
|
||||
| `device_category` | `DeviceCategory` | Platform to use for the session. | `DESKTOP` |
|
||||
| `client_type` | `ClientType` | InnerTube client type. | `WEB` |
|
||||
| `timezone` | `string` | The time zone. | `*` |
|
||||
| `cache` | `ICache` | Used to cache the deciphering functions from the JS player. | `undefined` |
|
||||
| `cache` | `ICache` | Used to cache algorithms, session data, and OAuth2 tokens. | `undefined` |
|
||||
| `cookie` | `string` | YouTube cookies. | `undefined` |
|
||||
| `fetch` | `FetchFunction` | Fetch function to use. | `fetch` |
|
||||
|
||||
</details>
|
||||
|
||||
## Browser Usage
|
||||
### Browser Usage
|
||||
To use YouTube.js in the browser, you must proxy requests through your own server. You can see our simple reference implementation in Deno at [`examples/browser/proxy/deno.ts`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/proxy/deno.ts).
|
||||
|
||||
You may provide your own fetch implementation to be used by YouTube.js, which we will use to modify and send the requests through a proxy. See [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/web) for a simple example using [Vite](https://vitejs.dev/).
|
||||
@@ -171,7 +145,7 @@ import dashjs from 'dashjs';
|
||||
|
||||
const youtube = await Innertube.create({ /* setup - see above */ });
|
||||
|
||||
// get the video info
|
||||
// Get the video info
|
||||
const videoInfo = await youtube.getInfo('videoId');
|
||||
|
||||
// now convert to a dash manifest
|
||||
@@ -191,11 +165,11 @@ const player = dashjs.MediaPlayer().create();
|
||||
player.initialize(videoElement, uri, true);
|
||||
```
|
||||
|
||||
A fully working example can be found in [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/blob/main/examples/browser/web). Alternatively, you can view it live at [ytjsexample.pages.dev](https://ytjsexample.pages.dev/).
|
||||
A fully working example can be found in [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/blob/main/examples/browser/web).
|
||||
|
||||
<a name="custom-fetch"></a>
|
||||
|
||||
## Providing your own fetch implementation
|
||||
### Providing your own fetch implementation
|
||||
You may provide your own fetch implementation to be used by YouTube.js. This can be useful in some cases to modify the requests before they are sent and transform the responses before they are returned (eg. for proxies).
|
||||
```ts
|
||||
// provide a fetch implementation
|
||||
@@ -212,7 +186,7 @@ const yt = await Innertube.create({
|
||||
|
||||
<a name="caching"></a>
|
||||
|
||||
## Caching
|
||||
### Caching
|
||||
Caching the transformed player instance can greatly improve the performance. Our `UniversalCache` implementation uses different caching methods depending on the environment.
|
||||
|
||||
In Node.js, we use the `node:fs` module, `Deno.writeFile()` in Deno, and `indexedDB` in browsers.
|
||||
@@ -237,7 +211,7 @@ const yt = await Innertube.create({
|
||||
});
|
||||
```
|
||||
|
||||
## API
|
||||
### API
|
||||
|
||||
* `Innertube`
|
||||
|
||||
@@ -325,6 +299,9 @@ Retrieves video info.
|
||||
- `<info>#download(options)`
|
||||
- Downloads the video. See [download](#download).
|
||||
|
||||
- `<info>#getTranscript()`
|
||||
- Retrieves the video's transcript.
|
||||
|
||||
- `<info>#filters`
|
||||
- Returns filters that can be applied to the watch next feed.
|
||||
|
||||
@@ -694,7 +671,7 @@ Utility to call navigation endpoints.
|
||||
| endpoint | `NavigationEndpoint` | The target endpoint |
|
||||
| args? | `object` | Additional payload arguments |
|
||||
|
||||
## Extending the library
|
||||
### Extending the library
|
||||
|
||||
YouTube.js is modular and easy to extend. Most of the methods, classes, and utilities used internally are exposed and can be used to implement your own extensions without having to modify the library's source code.
|
||||
|
||||
@@ -802,6 +779,6 @@ As such, any usage of trademarks to refer to such services is considered nominat
|
||||
## License
|
||||
Distributed under the [MIT](https://choosealicense.com/licenses/mit/) License.
|
||||
|
||||
<p align=" right">
|
||||
<p align="right">
|
||||
(<a href="#top">back to top</a>)
|
||||
</p>
|
||||
</p>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "youtubei.js",
|
||||
"version": "6.2.0",
|
||||
"version": "10.2.0",
|
||||
"description": "A wrapper around YouTube's private API. Supports YouTube, YouTube Music, YouTube Kids and YouTube Studio (WIP).",
|
||||
"type": "module",
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
@@ -12,11 +12,17 @@
|
||||
"web": [
|
||||
"./dist/src/platform/lib.d.ts"
|
||||
],
|
||||
"react-native": [
|
||||
"./dist/src/platform/lib.d.ts"
|
||||
],
|
||||
"web.bundle": [
|
||||
"./dist/src/platform/lib.d.ts"
|
||||
],
|
||||
"web.bundle.min": [
|
||||
"./dist/src/platform/lib.d.ts"
|
||||
],
|
||||
"cf-worker": [
|
||||
"./dist/src/platform/lib.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -29,6 +35,7 @@
|
||||
"deno": "./dist/src/platform/deno.js",
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"browser": "./dist/src/platform/web.js",
|
||||
"react-native": "./dist/src/platform/react-native.js",
|
||||
"default": "./dist/src/platform/web.js"
|
||||
},
|
||||
"./agnostic": {
|
||||
@@ -39,6 +46,10 @@
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"default": "./dist/src/platform/web.js"
|
||||
},
|
||||
"./react-native": {
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"default": "./dist/src/platform/react-native.js"
|
||||
},
|
||||
"./web.bundle": {
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"default": "./bundle/browser.js"
|
||||
@@ -46,6 +57,10 @@
|
||||
"./web.bundle.min": {
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"default": "./bundle/browser.min.js"
|
||||
},
|
||||
"./cf-worker": {
|
||||
"types": "./dist/src/platform/lib.d.ts",
|
||||
"default": "./dist/src/platform/cf-worker.js"
|
||||
}
|
||||
},
|
||||
"author": "LuanRT <luan.lrt4@gmail.com> (https://github.com/LuanRT)",
|
||||
@@ -68,14 +83,17 @@
|
||||
"test": "npx jest --verbose",
|
||||
"lint": "npx eslint ./src",
|
||||
"lint:fix": "npx eslint --fix ./src",
|
||||
"build": "npm run build:parser-map && npm run build:proto && npm run build:esm && npm run bundle:node && npm run bundle:browser && npm run bundle:browser:prod",
|
||||
"build:parser-map": "node ./scripts/gen-parser-map.mjs",
|
||||
"clean": "npx rimraf ./dist/src ./dist/package.json ./bundle/browser.js ./bundle/browser.js.map ./bundle/browser.min.js ./bundle/browser.min.js.map ./bundle/node.cjs ./bundle/node.cjs.map ./bundle/cf-worker.js ./bundle/cf-worker.js.map ./bundle/react-native.js ./bundle/react-native.js.map ./deno",
|
||||
"build": "npm run clean && npm run build:parser-map && npm run build:proto && npm run build:esm && npm run bundle:node && npm run bundle:browser && npm run bundle:browser:prod && npm run bundle:cf-worker && npm run bundle:react-native",
|
||||
"build:parser-map": "node ./dev-scripts/gen-parser-map.mjs",
|
||||
"build:proto": "npx pb-gen-ts --entry-path=\"src/proto\" --out-dir=\"src/proto/generated\" --ext-in-import=\".js\"",
|
||||
"build:esm": "npx tsc",
|
||||
"build:esm": "npx tspc",
|
||||
"build:deno": "npx cpy ./src ./deno && npx esbuild ./src/utils/DashManifest.tsx --keep-names --format=esm --platform=neutral --target=es2020 --outfile=./deno/src/utils/DashManifest.js && npx cpy ./package.json ./deno && npx replace \".ts';\" \".ts';\" ./deno -r && npx replace '.js\";' '.ts\";' ./deno -r && npx replace \"'./DashManifest.js';\" \"'./DashManifest.js';\" ./deno -r && npx replace \"'https://esm.sh/jintr';\" \"'https://esm.sh/jintr';\" ./deno -r",
|
||||
"bundle:node": "npx esbuild ./dist/src/platform/node.js --bundle --target=node10 --keep-names --format=cjs --platform=node --outfile=./bundle/node.cjs --external:jintr --external:undici --external:linkedom --external:tslib --sourcemap --banner:js=\"/* eslint-disable */\"",
|
||||
"bundle:browser": "npx esbuild ./dist/src/platform/web.js --banner:js=\"/* eslint-disable */\" --bundle --target=chrome58 --keep-names --format=esm --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/browser.js --platform=browser",
|
||||
"bundle:react-native": "npx esbuild ./dist/src/platform/react-native.js --bundle --target=es2020 --keep-names --format=esm --platform=neutral --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/react-native.js",
|
||||
"bundle:browser:prod": "npm run bundle:browser -- --outfile=./bundle/browser.min.js --minify",
|
||||
"bundle:cf-worker": "npx esbuild ./dist/src/platform/cf-worker.js --banner:js=\"/* eslint-disable */\" --bundle --target=es2020 --keep-names --format=esm --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/cf-worker.js --platform=node",
|
||||
"prepare": "npm run build",
|
||||
"watch": "npx tsc --watch"
|
||||
},
|
||||
@@ -85,10 +103,13 @@
|
||||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jintr": "^1.1.0",
|
||||
"jintr": "^2.0.0",
|
||||
"tslib": "^2.5.0",
|
||||
"undici": "^5.19.1"
|
||||
},
|
||||
"overrides": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/glob": "^8.1.0",
|
||||
"@types/jest": "^28.1.7",
|
||||
@@ -100,10 +121,12 @@
|
||||
"eslint": "^8.19.0",
|
||||
"eslint-plugin-tsdoc": "^0.2.16",
|
||||
"glob": "^8.0.3",
|
||||
"jest": "^28.1.3",
|
||||
"jest": "^29.7.0",
|
||||
"pbkit": "^0.0.59",
|
||||
"replace": "^1.2.2",
|
||||
"ts-jest": "^28.0.8",
|
||||
"ts-jest": "^29.1.4",
|
||||
"ts-patch": "^3.0.2",
|
||||
"ts-transformer-inline-file": "^0.2.0",
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"bugs": {
|
||||
|
||||
@@ -1,28 +1,8 @@
|
||||
import type { SessionOptions } from './core/Session.ts';
|
||||
import Session from './core/Session.ts';
|
||||
|
||||
import NavigationEndpoint from './parser/classes/NavigationEndpoint.ts';
|
||||
import type Format from './parser/classes/misc/Format.ts';
|
||||
import Channel from './parser/youtube/Channel.ts';
|
||||
import Comments from './parser/youtube/Comments.ts';
|
||||
import Guide from './parser/youtube/Guide.ts';
|
||||
import HashtagFeed from './parser/youtube/HashtagFeed.ts';
|
||||
import History from './parser/youtube/History.ts';
|
||||
import HomeFeed from './parser/youtube/HomeFeed.ts';
|
||||
import Library from './parser/youtube/Library.ts';
|
||||
import NotificationsMenu from './parser/youtube/NotificationsMenu.ts';
|
||||
import Playlist from './parser/youtube/Playlist.ts';
|
||||
import Search from './parser/youtube/Search.ts';
|
||||
import VideoInfo from './parser/youtube/VideoInfo.ts';
|
||||
|
||||
import { Kids, Music, Studio } from './core/clients/index.ts';
|
||||
import { AccountManager, InteractionManager, PlaylistManager } from './core/managers/index.ts';
|
||||
import { Feed, TabbedFeed } from './core/mixins/index.ts';
|
||||
|
||||
import * as Proto from './proto/index.ts';
|
||||
import * as Constants from './utils/Constants.ts';
|
||||
import { InnertubeError, generateRandomString, throwIfMissing } from './utils/Utils.ts';
|
||||
|
||||
import {
|
||||
BrowseEndpoint,
|
||||
GetNotificationMenuEndpoint,
|
||||
@@ -30,15 +10,40 @@ import {
|
||||
NextEndpoint,
|
||||
PlayerEndpoint,
|
||||
ResolveURLEndpoint,
|
||||
SearchEndpoint
|
||||
SearchEndpoint,
|
||||
Reel,
|
||||
Notification
|
||||
} from './core/endpoints/index.ts';
|
||||
|
||||
import { GetUnseenCountEndpoint } from './core/endpoints/notification/index.ts';
|
||||
import {
|
||||
Channel,
|
||||
Comments,
|
||||
Guide,
|
||||
HashtagFeed,
|
||||
History,
|
||||
HomeFeed,
|
||||
Library,
|
||||
NotificationsMenu,
|
||||
Playlist,
|
||||
Search,
|
||||
VideoInfo
|
||||
} from './parser/youtube/index.ts';
|
||||
|
||||
import { VideoInfo as ShortsVideoInfo } from './parser/ytshorts/index.ts';
|
||||
|
||||
import NavigationEndpoint from './parser/classes/NavigationEndpoint.ts';
|
||||
|
||||
import * as Proto from './proto/index.ts';
|
||||
import * as Constants from './utils/Constants.ts';
|
||||
import { InnertubeError, generateRandomString, throwIfMissing } from './utils/Utils.ts';
|
||||
|
||||
|
||||
import type { ApiResponse } from './core/Actions.ts';
|
||||
import type { IBrowseResponse, IParsedResponse } from './parser/types/index.ts';
|
||||
import type { INextRequest } from './types/index.ts';
|
||||
import type { IBrowseResponse, IParsedResponse } from './parser/types/index.ts';
|
||||
import type { DownloadOptions, FormatOptions } from './types/FormatUtils.ts';
|
||||
import type { SessionOptions } from './core/Session.ts';
|
||||
import type Format from './parser/classes/misc/Format.ts';
|
||||
|
||||
export type InnertubeConfig = SessionOptions;
|
||||
|
||||
@@ -131,6 +136,32 @@ export default class Innertube {
|
||||
return new VideoInfo([ response ], this.actions, cpn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves shorts info.
|
||||
* @param short_id - The short id.
|
||||
* @param client - The client to use.
|
||||
*/
|
||||
async getShortsWatchItem(short_id: string, client?: InnerTubeClient): Promise<ShortsVideoInfo> {
|
||||
throwIfMissing({ short_id });
|
||||
|
||||
const watchResponse = this.actions.execute(
|
||||
Reel.WatchEndpoint.PATH, Reel.WatchEndpoint.build({
|
||||
short_id: short_id,
|
||||
client: client
|
||||
})
|
||||
);
|
||||
|
||||
const sequenceResponse = this.actions.execute(
|
||||
Reel.WatchSequenceEndpoint.PATH, Reel.WatchSequenceEndpoint.build({
|
||||
sequenceParams: Proto.encodeReelSequence(short_id)
|
||||
})
|
||||
);
|
||||
|
||||
const response = await Promise.all([ watchResponse, sequenceResponse ]);
|
||||
|
||||
return new ShortsVideoInfo(response, this.actions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches a given query.
|
||||
* @param query - The search query.
|
||||
@@ -232,7 +263,7 @@ export default class Innertube {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves trending content.
|
||||
* Retrieves Trending content.
|
||||
*/
|
||||
async getTrending(): Promise<TabbedFeed<IBrowseResponse>> {
|
||||
const response = await this.actions.execute(
|
||||
@@ -242,7 +273,7 @@ export default class Innertube {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves subscriptions feed.
|
||||
* Retrieves Subscriptions feed.
|
||||
*/
|
||||
async getSubscriptionsFeed(): Promise<Feed<IBrowseResponse>> {
|
||||
const response = await this.actions.execute(
|
||||
@@ -251,6 +282,16 @@ export default class Innertube {
|
||||
return new Feed(this.actions, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves Channels feed.
|
||||
*/
|
||||
async getChannelsFeed(): Promise<Feed<IBrowseResponse>> {
|
||||
const response = await this.actions.execute(
|
||||
BrowseEndpoint.PATH, { ...BrowseEndpoint.build({ browse_id: 'FEchannels' }), parse: true }
|
||||
);
|
||||
return new Feed(this.actions, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves contents for a given channel.
|
||||
* @param id - Channel id
|
||||
@@ -279,11 +320,21 @@ export default class Innertube {
|
||||
* Retrieves unseen notifications count.
|
||||
*/
|
||||
async getUnseenNotificationsCount(): Promise<number> {
|
||||
const response = await this.actions.execute(GetUnseenCountEndpoint.PATH);
|
||||
const response = await this.actions.execute(Notification.GetUnseenCountEndpoint.PATH);
|
||||
// TODO: properly parse this
|
||||
return response.data?.unseenCount || response.data?.actions?.[0].updateNotificationsUnseenCountAction?.unseenCount || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves playlists.
|
||||
*/
|
||||
async getPlaylists(): Promise<Feed<IBrowseResponse>> {
|
||||
const response = await this.actions.execute(
|
||||
BrowseEndpoint.PATH, { ...BrowseEndpoint.build({ browse_id: 'FEplaylist_aggregation' }), parse: true }
|
||||
);
|
||||
return new Feed(this.actions, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves playlist contents.
|
||||
* @param id - Playlist id
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Parser, { NavigateAction } from '../parser/index.ts';
|
||||
import { Parser, NavigateAction } from '../parser/index.ts';
|
||||
import { InnertubeError } from '../utils/Utils.ts';
|
||||
|
||||
import type Session from './Session.ts';
|
||||
import type { Session } from './index.ts';
|
||||
|
||||
import type {
|
||||
IBrowseResponse, IGetNotificationsMenuResponse,
|
||||
@@ -16,7 +16,7 @@ export interface ApiResponse {
|
||||
data: IRawResponse;
|
||||
}
|
||||
|
||||
export type InnertubeEndpoint = '/player' | '/search' | '/browse' | '/next' | '/updated_metadata' | '/notification/get_notification_menu' | string;
|
||||
export type InnertubeEndpoint = '/player' | '/search' | '/browse' | '/next' | '/reel' | '/updated_metadata' | '/notification/get_notification_menu' | string;
|
||||
|
||||
export type ParsedResponse<T> =
|
||||
T extends '/player' ? IPlayerResponse :
|
||||
@@ -29,14 +29,10 @@ export type ParsedResponse<T> =
|
||||
IParsedResponse;
|
||||
|
||||
export default class Actions {
|
||||
#session: Session;
|
||||
session: Session;
|
||||
|
||||
constructor(session: Session) {
|
||||
this.#session = session;
|
||||
}
|
||||
|
||||
get session(): Session {
|
||||
return this.#session;
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +65,7 @@ export default class Actions {
|
||||
s_url.searchParams.set(key, params[key]);
|
||||
}
|
||||
|
||||
const response = await this.#session.http.fetch(s_url);
|
||||
const response = await this.session.http.fetch(s_url);
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -88,7 +84,7 @@ export default class Actions {
|
||||
data = { ...args };
|
||||
|
||||
if (Reflect.has(data, 'browseId')) {
|
||||
if (this.#needsLogin(data.browseId) && !this.#session.logged_in)
|
||||
if (this.#needsLogin(data.browseId) && !this.session.logged_in)
|
||||
throw new InnertubeError('You must be signed in to perform this operation.');
|
||||
}
|
||||
|
||||
@@ -131,7 +127,7 @@ export default class Actions {
|
||||
|
||||
const target_endpoint = Reflect.has(args || {}, 'override_endpoint') ? args?.override_endpoint : endpoint;
|
||||
|
||||
const response = await this.#session.http.fetch(target_endpoint, {
|
||||
const response = await this.session.http.fetch(target_endpoint, {
|
||||
method: 'POST',
|
||||
body: args?.protobuf ? data : JSON.stringify((data || {})),
|
||||
headers: {
|
||||
@@ -167,6 +163,8 @@ export default class Actions {
|
||||
'FElibrary',
|
||||
'FEhistory',
|
||||
'FEsubscriptions',
|
||||
'FEchannels',
|
||||
'FEplaylist_aggregation',
|
||||
'FEmusic_listening_review',
|
||||
'FEmusic_library_landing',
|
||||
'SPaccount_overview',
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
import * as Constants from '../utils/Constants.ts';
|
||||
import { OAuthError, Platform } from '../utils/Utils.ts';
|
||||
import type Session from './Session.ts';
|
||||
|
||||
export interface Credentials {
|
||||
/**
|
||||
* Token used to sign in.
|
||||
*/
|
||||
access_token: string;
|
||||
/**
|
||||
* Token used to get a new access token.
|
||||
*/
|
||||
refresh_token: string;
|
||||
/**
|
||||
* Access token's expiration date, which is usually 24hrs-ish.
|
||||
*/
|
||||
expires: Date;
|
||||
}
|
||||
|
||||
// TODO: actual type info for this.
|
||||
export type OAuthAuthPendingData = any;
|
||||
|
||||
export type OAuthAuthEventHandler = (data: {
|
||||
credentials: Credentials;
|
||||
status: 'SUCCESS';
|
||||
}) => any;
|
||||
|
||||
export type OAuthAuthPendingEventHandler = (data: OAuthAuthPendingData) => any;
|
||||
export type OAuthAuthErrorEventHandler = (err: OAuthError) => any;
|
||||
|
||||
export default class OAuth {
|
||||
#identity?: Record<string, string>;
|
||||
#session: Session;
|
||||
#credentials?: Credentials;
|
||||
#polling_interval = 5;
|
||||
|
||||
constructor(session: Session) {
|
||||
this.#session = session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the auth flow in case no valid credentials are available.
|
||||
*/
|
||||
async init(credentials?: Credentials): Promise<void> {
|
||||
this.#credentials = credentials;
|
||||
|
||||
if (this.validateCredentials()) {
|
||||
if (!this.has_access_token_expired)
|
||||
this.#session.emit('auth', {
|
||||
credentials: this.#credentials,
|
||||
status: 'SUCCESS'
|
||||
});
|
||||
} else if (!(await this.#loadCachedCredentials())) {
|
||||
await this.#getUserCode();
|
||||
}
|
||||
}
|
||||
|
||||
async cacheCredentials(): Promise<void> {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(JSON.stringify(this.#credentials));
|
||||
await this.#session.cache?.set('youtubei_oauth_credentials', data.buffer);
|
||||
}
|
||||
|
||||
async #loadCachedCredentials(): Promise<boolean> {
|
||||
const data = await this.#session.cache?.get('youtubei_oauth_credentials');
|
||||
if (!data) return false;
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const credentials = JSON.parse(decoder.decode(data));
|
||||
|
||||
this.#credentials = {
|
||||
access_token: credentials.access_token,
|
||||
refresh_token: credentials.refresh_token,
|
||||
expires: new Date(credentials.expires)
|
||||
};
|
||||
|
||||
this.#session.emit('auth', {
|
||||
credentials: this.#credentials,
|
||||
status: 'SUCCESS'
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async removeCache(): Promise<void> {
|
||||
await this.#session.cache?.remove('youtubei_oauth_credentials');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the server for a user code and verification URL.
|
||||
*/
|
||||
async #getUserCode(): Promise<void> {
|
||||
this.#identity = await this.#getClientIdentity();
|
||||
|
||||
const data = {
|
||||
client_id: this.#identity.client_id,
|
||||
scope: Constants.OAUTH.SCOPE,
|
||||
device_id: Platform.shim.uuidv4(),
|
||||
device_model: Constants.OAUTH.MODEL_NAME
|
||||
};
|
||||
|
||||
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/device/code', Constants.URLS.YT_BASE), {
|
||||
body: JSON.stringify(data),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const response_data = await response.json();
|
||||
|
||||
this.#session.emit('auth-pending', response_data);
|
||||
this.#polling_interval = response_data.interval;
|
||||
this.#startPolling(response_data.device_code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls the authorization server until access is granted by the user.
|
||||
*/
|
||||
#startPolling(device_code: string): void {
|
||||
const poller = setInterval(async () => {
|
||||
const data = {
|
||||
...this.#identity,
|
||||
code: device_code,
|
||||
grant_type: Constants.OAUTH.GRANT_TYPE
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/token', Constants.URLS.YT_BASE), {
|
||||
body: JSON.stringify(data),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const response_data = await response.json();
|
||||
|
||||
if (response_data.error) {
|
||||
switch (response_data.error) {
|
||||
case 'access_denied':
|
||||
this.#session.emit('auth-error', new OAuthError('Access was denied.', { status: 'ACCESS_DENIED' }));
|
||||
break;
|
||||
case 'expired_token':
|
||||
this.#session.emit('auth-error', new OAuthError('The device code has expired, restarting auth flow.', { status: 'DEVICE_CODE_EXPIRED' }));
|
||||
clearInterval(poller);
|
||||
this.#getUserCode();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const expiration_date = new Date(new Date().getTime() + response_data.expires_in * 1000);
|
||||
|
||||
this.#credentials = {
|
||||
access_token: response_data.access_token,
|
||||
refresh_token: response_data.refresh_token,
|
||||
expires: expiration_date
|
||||
};
|
||||
|
||||
this.#session.emit('auth', {
|
||||
credentials: this.#credentials,
|
||||
status: 'SUCCESS'
|
||||
});
|
||||
|
||||
clearInterval(poller);
|
||||
} catch (err) {
|
||||
clearInterval(poller);
|
||||
return this.#session.emit('auth-error', new OAuthError('Could not obtain user code.', { status: 'FAILED', error: err }));
|
||||
}
|
||||
}, this.#polling_interval * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh access token if the same has expired.
|
||||
*/
|
||||
async refreshIfRequired(): Promise<void> {
|
||||
if (this.has_access_token_expired) {
|
||||
await this.#refreshAccessToken();
|
||||
}
|
||||
}
|
||||
|
||||
async #refreshAccessToken(): Promise<void> {
|
||||
if (!this.#credentials) return;
|
||||
this.#identity = await this.#getClientIdentity();
|
||||
|
||||
const data = {
|
||||
...this.#identity,
|
||||
refresh_token: this.#credentials.refresh_token,
|
||||
grant_type: 'refresh_token'
|
||||
};
|
||||
|
||||
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/token', Constants.URLS.YT_BASE), {
|
||||
body: JSON.stringify(data),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const response_data = await response.json();
|
||||
const expiration_date = new Date(new Date().getTime() + response_data.expires_in * 1000);
|
||||
|
||||
this.#credentials = {
|
||||
access_token: response_data.access_token,
|
||||
refresh_token: response_data.refresh_token || this.#credentials.refresh_token,
|
||||
expires: expiration_date
|
||||
};
|
||||
|
||||
this.#session.emit('update-credentials', {
|
||||
credentials: this.#credentials,
|
||||
status: 'SUCCESS'
|
||||
});
|
||||
}
|
||||
|
||||
async revokeCredentials(): Promise<Response | undefined> {
|
||||
if (!this.#credentials) return;
|
||||
await this.removeCache();
|
||||
return this.#session.http.fetch_function(new URL(`/o/oauth2/revoke?token=${encodeURIComponent(this.#credentials.access_token)}`, Constants.URLS.YT_BASE), {
|
||||
method: 'post'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves client identity from YouTube TV.
|
||||
*/
|
||||
async #getClientIdentity(): Promise<{ [key: string]: string; }> {
|
||||
const response = await this.#session.http.fetch_function(new URL('/tv', Constants.URLS.YT_BASE), { headers: Constants.OAUTH.HEADERS });
|
||||
|
||||
const response_data = await response.text();
|
||||
const url_body = Constants.OAUTH.REGEX.AUTH_SCRIPT.exec(response_data)?.[1];
|
||||
|
||||
if (!url_body)
|
||||
throw new OAuthError('Could not obtain script url.', { status: 'FAILED' });
|
||||
|
||||
const script = await this.#session.http.fetch(url_body, { baseURL: Constants.URLS.YT_BASE });
|
||||
|
||||
const client_identity = (await script.text())
|
||||
.replace(/\n/g, '')
|
||||
.match(Constants.OAUTH.REGEX.CLIENT_IDENTITY);
|
||||
|
||||
const groups = client_identity?.groups;
|
||||
|
||||
if (!groups)
|
||||
throw new OAuthError('Could not obtain client identity.', { status: 'FAILED' });
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
get credentials(): Credentials | undefined {
|
||||
return this.#credentials;
|
||||
}
|
||||
|
||||
get has_access_token_expired(): boolean {
|
||||
const timestamp = this.#credentials ? new Date(this.#credentials.expires).getTime() : -Infinity;
|
||||
return new Date().getTime() > timestamp;
|
||||
}
|
||||
|
||||
validateCredentials(): this is this & { credentials: Credentials } {
|
||||
return this.#credentials &&
|
||||
Reflect.has(this.#credentials, 'access_token') &&
|
||||
Reflect.has(this.#credentials, 'refresh_token') &&
|
||||
Reflect.has(this.#credentials, 'expires') || false;
|
||||
}
|
||||
}
|
||||
338
deno/src/core/OAuth2.ts
Normal file
338
deno/src/core/OAuth2.ts
Normal file
@@ -0,0 +1,338 @@
|
||||
import { OAuth2Error, Platform } from '../utils/Utils.ts';
|
||||
import { Log, Constants } from '../utils/index.ts';
|
||||
import type Session from './Session.ts';
|
||||
|
||||
const TAG = 'OAuth2';
|
||||
|
||||
export type OAuth2ClientID = {
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
};
|
||||
|
||||
export type OAuth2Tokens = {
|
||||
access_token: string;
|
||||
expiry_date: string;
|
||||
expires_in?: number;
|
||||
refresh_token: string;
|
||||
scope?: string;
|
||||
token_type?: string;
|
||||
client?: OAuth2ClientID;
|
||||
};
|
||||
|
||||
export type DeviceAndUserCode = {
|
||||
device_code: string;
|
||||
expires_in: number;
|
||||
interval: number;
|
||||
user_code: string;
|
||||
verification_url: string;
|
||||
error_code?: string;
|
||||
};
|
||||
|
||||
export type OAuth2AuthEventHandler = (data: { credentials: OAuth2Tokens; }) => void;
|
||||
export type OAuth2AuthPendingEventHandler = (data: DeviceAndUserCode) => void;
|
||||
export type OAuth2AuthErrorEventHandler = (err: OAuth2Error) => void;
|
||||
|
||||
export default class OAuth2 {
|
||||
#session: Session;
|
||||
|
||||
YTTV_URL: URL;
|
||||
AUTH_SERVER_CODE_URL: URL;
|
||||
AUTH_SERVER_TOKEN_URL: URL;
|
||||
AUTH_SERVER_REVOKE_TOKEN_URL: URL;
|
||||
|
||||
client_id: OAuth2ClientID | undefined;
|
||||
oauth2_tokens: OAuth2Tokens | undefined;
|
||||
|
||||
constructor(session: Session) {
|
||||
this.#session = session;
|
||||
this.YTTV_URL = new URL('/tv', Constants.URLS.YT_BASE);
|
||||
this.AUTH_SERVER_CODE_URL = new URL('/o/oauth2/device/code', Constants.URLS.YT_BASE);
|
||||
this.AUTH_SERVER_TOKEN_URL = new URL('/o/oauth2/token', Constants.URLS.YT_BASE);
|
||||
this.AUTH_SERVER_REVOKE_TOKEN_URL = new URL('/o/oauth2/revoke', Constants.URLS.YT_BASE);
|
||||
}
|
||||
|
||||
async init(tokens?: OAuth2Tokens): Promise<void> {
|
||||
if (tokens) {
|
||||
this.setTokens(tokens);
|
||||
|
||||
if (this.shouldRefreshToken()) {
|
||||
await this.refreshAccessToken();
|
||||
}
|
||||
|
||||
this.#session.emit('auth', { credentials: this.oauth2_tokens });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const loaded_from_cache = await this.#loadFromCache();
|
||||
|
||||
if (loaded_from_cache) {
|
||||
Log.info(TAG, 'Loaded OAuth2 tokens from cache.', this.oauth2_tokens);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.client_id)
|
||||
this.client_id = await this.getClientID();
|
||||
|
||||
// Initialize OAuth2 flow
|
||||
const device_and_user_code = await this.getDeviceAndUserCode();
|
||||
|
||||
this.#session.emit('auth-pending', device_and_user_code);
|
||||
|
||||
this.pollForAccessToken(device_and_user_code);
|
||||
}
|
||||
|
||||
setTokens(tokens: OAuth2Tokens): void {
|
||||
const tokensMod = tokens;
|
||||
|
||||
// Convert access token remaining lifetime to ISO string
|
||||
if (tokensMod.expires_in) {
|
||||
tokensMod.expiry_date = new Date(Date.now() + tokensMod.expires_in * 1000).toISOString();
|
||||
delete tokensMod.expires_in; // We don't need this anymore
|
||||
}
|
||||
|
||||
if (!this.validateTokens(tokensMod))
|
||||
throw new OAuth2Error('Invalid tokens provided.');
|
||||
|
||||
this.oauth2_tokens = tokensMod;
|
||||
|
||||
if (tokensMod.client) {
|
||||
Log.info(TAG, 'Using provided client id and secret.');
|
||||
this.client_id = tokensMod.client;
|
||||
}
|
||||
}
|
||||
|
||||
async cacheCredentials(): Promise<void> {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(JSON.stringify(this.oauth2_tokens));
|
||||
await this.#session.cache?.set('youtubei_oauth_credentials', data.buffer);
|
||||
}
|
||||
|
||||
async #loadFromCache(): Promise<boolean> {
|
||||
const data = await this.#session.cache?.get('youtubei_oauth_credentials');
|
||||
if (!data)
|
||||
return false;
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const credentials = JSON.parse(decoder.decode(data));
|
||||
|
||||
this.setTokens(credentials);
|
||||
|
||||
this.#session.emit('auth', { credentials });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async removeCache(): Promise<void> {
|
||||
await this.#session.cache?.remove('youtubei_oauth_credentials');
|
||||
}
|
||||
|
||||
async pollForAccessToken(device_and_user_code: DeviceAndUserCode): Promise<void> {
|
||||
if (!this.client_id)
|
||||
throw new OAuth2Error('Client ID is missing.');
|
||||
|
||||
const { device_code, interval } = device_and_user_code;
|
||||
const { client_id, client_secret } = this.client_id;
|
||||
|
||||
const payload = {
|
||||
client_id,
|
||||
client_secret,
|
||||
code: device_code,
|
||||
grant_type: 'http://oauth.net/grant_type/device/1.0'
|
||||
};
|
||||
|
||||
const connInterval = setInterval(async () => {
|
||||
const response = await this.#http.fetch_function(this.AUTH_SERVER_TOKEN_URL, {
|
||||
body: JSON.stringify(payload),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const response_data = await response.json();
|
||||
|
||||
if (response_data.error) {
|
||||
switch (response_data.error) {
|
||||
case 'access_denied':
|
||||
this.#session.emit('auth-error', new OAuth2Error('Access was denied.', response_data));
|
||||
clearInterval(connInterval);
|
||||
break;
|
||||
case 'expired_token':
|
||||
this.#session.emit('auth-error', new OAuth2Error('The device code has expired.', response_data));
|
||||
clearInterval(connInterval);
|
||||
break;
|
||||
case 'authorization_pending':
|
||||
case 'slow_down':
|
||||
Log.info(TAG, 'Polling for access token...');
|
||||
break;
|
||||
default:
|
||||
this.#session.emit('auth-error', new OAuth2Error('Server returned an unexpected error.', response_data));
|
||||
clearInterval(connInterval);
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.setTokens(response_data);
|
||||
|
||||
this.#session.emit('auth', { credentials: this.oauth2_tokens });
|
||||
|
||||
clearInterval(connInterval);
|
||||
}, interval * 1000);
|
||||
}
|
||||
|
||||
async revokeCredentials(): Promise<Response | undefined> {
|
||||
if (!this.oauth2_tokens)
|
||||
throw new OAuth2Error('Access token not found');
|
||||
|
||||
await this.removeCache();
|
||||
|
||||
const url = this.AUTH_SERVER_REVOKE_TOKEN_URL;
|
||||
url.searchParams.set('token', this.oauth2_tokens.access_token);
|
||||
|
||||
return this.#session.http.fetch_function(url, { method: 'POST' });
|
||||
}
|
||||
|
||||
async refreshAccessToken(): Promise<void> {
|
||||
if (!this.client_id)
|
||||
this.client_id = await this.getClientID();
|
||||
|
||||
if (!this.oauth2_tokens)
|
||||
throw new OAuth2Error('No tokens available to refresh.');
|
||||
|
||||
const { client_id, client_secret } = this.client_id;
|
||||
const { refresh_token } = this.oauth2_tokens;
|
||||
|
||||
const payload = {
|
||||
client_id,
|
||||
client_secret,
|
||||
refresh_token,
|
||||
grant_type: 'refresh_token'
|
||||
};
|
||||
|
||||
const response = await this.#http.fetch_function(this.AUTH_SERVER_TOKEN_URL, {
|
||||
body: JSON.stringify(payload),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok)
|
||||
throw new OAuth2Error(`Failed to refresh access token: ${response.status}`);
|
||||
|
||||
const response_data = await response.json();
|
||||
|
||||
if (response_data.error_code)
|
||||
throw new OAuth2Error('Authorization server returned an error', response_data);
|
||||
|
||||
this.oauth2_tokens.access_token = response_data.access_token;
|
||||
this.oauth2_tokens.expiry_date = new Date(Date.now() + response_data.expires_in * 1000).toISOString();
|
||||
|
||||
this.#session.emit('update-credentials', { credentials: this.oauth2_tokens });
|
||||
}
|
||||
|
||||
async getDeviceAndUserCode(): Promise<DeviceAndUserCode> {
|
||||
if (!this.client_id)
|
||||
throw new OAuth2Error('Client ID is missing.');
|
||||
|
||||
const { client_id } = this.client_id;
|
||||
|
||||
const payload = {
|
||||
client_id,
|
||||
scope: 'http://gdata.youtube.com https://www.googleapis.com/auth/youtube-paid-content',
|
||||
device_id: Platform.shim.uuidv4(),
|
||||
device_model: 'ytlr::'
|
||||
};
|
||||
|
||||
const response = await this.#http.fetch_function(this.AUTH_SERVER_CODE_URL, {
|
||||
body: JSON.stringify(payload),
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok)
|
||||
throw new OAuth2Error(`Failed to get device/user code: ${response.status}`);
|
||||
|
||||
const response_data = await response.json();
|
||||
|
||||
if (response_data.error_code)
|
||||
throw new OAuth2Error('Authorization server returned an error', response_data);
|
||||
|
||||
return response_data;
|
||||
}
|
||||
|
||||
async getClientID(): Promise<OAuth2ClientID> {
|
||||
const yttv_response = await this.#http.fetch_function(this.YTTV_URL, {
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version',
|
||||
'Referer': 'https://www.youtube.com/tv',
|
||||
'Accept-Language': 'en-US'
|
||||
}
|
||||
});
|
||||
|
||||
if (!yttv_response.ok)
|
||||
throw new OAuth2Error(`Failed to get client ID: ${yttv_response.status}`);
|
||||
|
||||
const yttv_response_data = await yttv_response.text();
|
||||
|
||||
let script_url_body: RegExpExecArray | null;
|
||||
|
||||
if ((script_url_body = Constants.OAUTH.REGEX.TV_SCRIPT.exec(yttv_response_data)) !== null) {
|
||||
Log.info(TAG, `Got YouTubeTV script URL (${script_url_body[1]})`);
|
||||
|
||||
const script_response = await this.#http.fetch(script_url_body[1], { baseURL: Constants.URLS.YT_BASE });
|
||||
|
||||
if (!script_response.ok)
|
||||
throw new OAuth2Error(`TV script request failed with status code ${script_response.status}`);
|
||||
|
||||
const script_response_data = await script_response.text();
|
||||
|
||||
const client_identity = script_response_data
|
||||
.match(Constants.OAUTH.REGEX.CLIENT_IDENTITY);
|
||||
|
||||
if (!client_identity || !client_identity.groups)
|
||||
throw new OAuth2Error('Could not obtain client ID.');
|
||||
|
||||
const { client_id, client_secret } = client_identity.groups;
|
||||
|
||||
Log.info(TAG, `Client identity retrieved (clientId=${client_id}, clientSecret=${client_secret}).`);
|
||||
|
||||
return {
|
||||
client_id,
|
||||
client_secret
|
||||
};
|
||||
}
|
||||
|
||||
throw new OAuth2Error('Could not obtain script URL.');
|
||||
}
|
||||
|
||||
shouldRefreshToken(): boolean {
|
||||
if (!this.oauth2_tokens)
|
||||
return false;
|
||||
return Date.now() > new Date(this.oauth2_tokens.expiry_date).getTime();
|
||||
}
|
||||
|
||||
validateTokens(tokens: OAuth2Tokens): boolean {
|
||||
const propertiesAreValid = (
|
||||
Boolean(tokens.access_token) &&
|
||||
Boolean(tokens.expiry_date) &&
|
||||
Boolean(tokens.refresh_token)
|
||||
);
|
||||
|
||||
const typesAreValid = (
|
||||
typeof tokens.access_token === 'string' &&
|
||||
typeof tokens.expiry_date === 'string' &&
|
||||
typeof tokens.refresh_token === 'string'
|
||||
);
|
||||
|
||||
return typesAreValid && propertiesAreValid;
|
||||
}
|
||||
|
||||
get #http() {
|
||||
return this.#session.http;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,23 @@
|
||||
import { Log, LZW, Constants } from '../utils/index.ts';
|
||||
import { Platform, getRandomUserAgent, getStringBetweenStrings, PlayerError } from '../utils/Utils.ts';
|
||||
import type { ICache, FetchFunction } from '../types/index.ts';
|
||||
|
||||
import * as Constants from '../utils/Constants.ts';
|
||||
|
||||
import type { ICache } from '../types/Cache.ts';
|
||||
import type { FetchFunction } from '../types/PlatformShim.ts';
|
||||
const TAG = 'Player';
|
||||
|
||||
/**
|
||||
* Represents YouTube's player script. This is required to decipher signatures.
|
||||
*/
|
||||
export default class Player {
|
||||
#nsig_sc;
|
||||
#sig_sc;
|
||||
#sig_sc_timestamp;
|
||||
#player_id;
|
||||
nsig_sc;
|
||||
sig_sc;
|
||||
sts;
|
||||
player_id;
|
||||
|
||||
constructor(signature_timestamp: number, sig_sc: string, nsig_sc: string, player_id: string) {
|
||||
this.#nsig_sc = nsig_sc;
|
||||
this.#sig_sc = sig_sc;
|
||||
|
||||
this.#sig_sc_timestamp = signature_timestamp;
|
||||
|
||||
this.#player_id = player_id;
|
||||
this.nsig_sc = nsig_sc;
|
||||
this.sig_sc = sig_sc;
|
||||
this.sts = signature_timestamp;
|
||||
this.player_id = player_id;
|
||||
}
|
||||
|
||||
static async create(cache: ICache | undefined, fetch: FetchFunction = Platform.shim.fetch): Promise<Player> {
|
||||
@@ -34,18 +31,24 @@ export default class Player {
|
||||
|
||||
const player_id = getStringBetweenStrings(js, 'player\\/', '\\/');
|
||||
|
||||
Log.info(TAG, `Got player id (${player_id}). Checking for cached players..`);
|
||||
|
||||
if (!player_id)
|
||||
throw new PlayerError('Failed to get player id');
|
||||
|
||||
// We have the playerID now we can check if we have a cached player
|
||||
// We have the player id, now we can check if we have a cached player.
|
||||
if (cache) {
|
||||
const cached_player = await Player.fromCache(cache, player_id);
|
||||
if (cached_player)
|
||||
if (cached_player) {
|
||||
Log.info(TAG, 'Found up-to-date player data in cache.');
|
||||
return cached_player;
|
||||
}
|
||||
}
|
||||
|
||||
const player_url = new URL(`/s/player/${player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE);
|
||||
|
||||
Log.info(TAG, `Could not find any cached player. Will download a new player from ${player_url}.`);
|
||||
|
||||
const player_res = await fetch(player_url, {
|
||||
headers: {
|
||||
'user-agent': getRandomUserAgent('desktop')
|
||||
@@ -59,14 +62,15 @@ export default class Player {
|
||||
const player_js = await player_res.text();
|
||||
|
||||
const sig_timestamp = this.extractSigTimestamp(player_js);
|
||||
|
||||
const sig_sc = this.extractSigSourceCode(player_js);
|
||||
const nsig_sc = this.extractNSigSourceCode(player_js);
|
||||
|
||||
Log.info(TAG, `Got signature timestamp (${sig_timestamp}) and algorithms needed to decipher signatures.`);
|
||||
|
||||
return await Player.fromSource(cache, sig_timestamp, sig_sc, nsig_sc, player_id);
|
||||
}
|
||||
|
||||
decipher(url?: string, signature_cipher?: string, cipher?: string): string {
|
||||
decipher(url?: string, signature_cipher?: string, cipher?: string, this_response_nsig_cache?: Map<string, string>): string {
|
||||
url = url || signature_cipher || cipher;
|
||||
|
||||
if (!url)
|
||||
@@ -76,10 +80,12 @@ export default class Player {
|
||||
const url_components = new URL(args.get('url') || url);
|
||||
|
||||
if (signature_cipher || cipher) {
|
||||
const signature = Platform.shim.eval(this.#sig_sc, {
|
||||
const signature = Platform.shim.eval(this.sig_sc, {
|
||||
sig: args.get('s')
|
||||
});
|
||||
|
||||
Log.info(TAG, `Transformed signature from ${args.get('s')} to ${signature}.`);
|
||||
|
||||
if (typeof signature !== 'string')
|
||||
throw new PlayerError('Failed to decipher signature');
|
||||
|
||||
@@ -93,15 +99,25 @@ export default class Player {
|
||||
const n = url_components.searchParams.get('n');
|
||||
|
||||
if (n) {
|
||||
const nsig = Platform.shim.eval(this.#nsig_sc, {
|
||||
nsig: n
|
||||
});
|
||||
let nsig;
|
||||
|
||||
if (typeof nsig !== 'string')
|
||||
throw new PlayerError('Failed to decipher nsig');
|
||||
if (this_response_nsig_cache && this_response_nsig_cache.has(n)) {
|
||||
nsig = this_response_nsig_cache.get(n) as string;
|
||||
} else {
|
||||
nsig = Platform.shim.eval(this.nsig_sc, {
|
||||
nsig: n
|
||||
});
|
||||
|
||||
if (nsig.startsWith('enhanced_except_')) {
|
||||
console.warn('Warning:\nCould not transform nsig, download may be throttled.\nChanging the InnerTube client to "ANDROID" might help!');
|
||||
Log.info(TAG, `Transformed n signature from ${n} to ${nsig}.`);
|
||||
|
||||
if (typeof nsig !== 'string')
|
||||
throw new PlayerError('Failed to decipher nsig');
|
||||
|
||||
if (nsig.startsWith('enhanced_except_')) {
|
||||
Log.warn(TAG, 'Could not transform nsig, download may be throttled.');
|
||||
} else if (this_response_nsig_cache) {
|
||||
this_response_nsig_cache.set(n, nsig);
|
||||
}
|
||||
}
|
||||
|
||||
url_components.searchParams.set('n', nsig);
|
||||
@@ -130,6 +146,10 @@ export default class Player {
|
||||
break;
|
||||
}
|
||||
|
||||
const result = url_components.toString();
|
||||
|
||||
Log.info(TAG, `Deciphered URL: ${result}`);
|
||||
|
||||
return url_components.toString();
|
||||
}
|
||||
|
||||
@@ -151,10 +171,8 @@ export default class Player {
|
||||
const sig_buf = buffer.slice(12, 12 + sig_len);
|
||||
const nsig_buf = buffer.slice(12 + sig_len);
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
const sig_sc = decoder.decode(sig_buf);
|
||||
const nsig_sc = decoder.decode(nsig_buf);
|
||||
const sig_sc = LZW.decompress(new TextDecoder().decode(sig_buf));
|
||||
const nsig_sc = LZW.decompress(new TextDecoder().decode(nsig_buf));
|
||||
|
||||
return new Player(sig_timestamp, sig_sc, nsig_sc, player_id);
|
||||
}
|
||||
@@ -170,20 +188,20 @@ export default class Player {
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const sig_buf = encoder.encode(this.#sig_sc);
|
||||
const nsig_buf = encoder.encode(this.#nsig_sc);
|
||||
const sig_buf = encoder.encode(LZW.compress(this.sig_sc));
|
||||
const nsig_buf = encoder.encode(LZW.compress(this.nsig_sc));
|
||||
|
||||
const buffer = new ArrayBuffer(12 + sig_buf.byteLength + nsig_buf.byteLength);
|
||||
const view = new DataView(buffer);
|
||||
|
||||
view.setUint32(0, Player.LIBRARY_VERSION, true);
|
||||
view.setUint32(4, this.#sig_sc_timestamp, true);
|
||||
view.setUint32(4, this.sts, true);
|
||||
view.setUint32(8, sig_buf.byteLength, true);
|
||||
|
||||
new Uint8Array(buffer).set(sig_buf, 12);
|
||||
new Uint8Array(buffer).set(nsig_buf, 12 + sig_buf.byteLength);
|
||||
|
||||
await cache.set(this.#player_id, new Uint8Array(buffer));
|
||||
await cache.set(this.player_id, new Uint8Array(buffer));
|
||||
}
|
||||
|
||||
static extractSigTimestamp(data: string): number {
|
||||
@@ -196,37 +214,26 @@ export default class Player {
|
||||
const functions = getStringBetweenStrings(data, `var ${obj_name}={`, '};');
|
||||
|
||||
if (!functions || !calls)
|
||||
console.warn(new PlayerError('Failed to extract signature decipher algorithm'));
|
||||
Log.warn(TAG, 'Failed to extract signature decipher algorithm.');
|
||||
|
||||
return `function descramble_sig(a) { a = a.split(""); let ${obj_name}={${functions}}${calls} return a.join("") } descramble_sig(sig);`;
|
||||
}
|
||||
|
||||
static extractNSigSourceCode(data: string): string {
|
||||
const sc = `function descramble_nsig(a) { let b=a.split("")${getStringBetweenStrings(data, 'b=a.split("")', '}return b.join("")}')}} return b.join(""); } descramble_nsig(nsig)`;
|
||||
const match = data.match(/b=(?:a\.split\(|String\.prototype\.split\.call\(a,)""\).*?\}return (?:b\.join\(|Array\.prototype\.join\.call\(b,)""\)\}/s);
|
||||
|
||||
if (!sc)
|
||||
console.warn(new PlayerError('Failed to extract n-token decipher algorithm'));
|
||||
if (!match) {
|
||||
throw new PlayerError('Failed to extract n-token decipher algorithm');
|
||||
}
|
||||
|
||||
return sc;
|
||||
return `function descramble_nsig(a) { let ${match[0]} descramble_nsig(nsig)`;
|
||||
}
|
||||
|
||||
get url(): string {
|
||||
return new URL(`/s/player/${this.#player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE).toString();
|
||||
}
|
||||
|
||||
get sts(): number {
|
||||
return this.#sig_sc_timestamp;
|
||||
}
|
||||
|
||||
get nsig_sc(): string {
|
||||
return this.#nsig_sc;
|
||||
}
|
||||
|
||||
get sig_sc(): string {
|
||||
return this.#sig_sc;
|
||||
return new URL(`/s/player/${this.player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE).toString();
|
||||
}
|
||||
|
||||
static get LIBRARY_VERSION(): number {
|
||||
return 2;
|
||||
return 11;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
import OAuth2 from './OAuth2.ts';
|
||||
import { Log, EventEmitter, HTTPClient, LZW } from '../utils/index.ts';
|
||||
import * as Constants from '../utils/Constants.ts';
|
||||
import EventEmitterLike from '../utils/EventEmitterLike.ts';
|
||||
import * as Proto from '../proto/index.ts';
|
||||
import Actions from './Actions.ts';
|
||||
import Player from './Player.ts';
|
||||
|
||||
import * as Proto from '../proto/index.ts';
|
||||
import type { ICache } from '../types/Cache.ts';
|
||||
import type { FetchFunction } from '../types/PlatformShim.ts';
|
||||
import HTTPClient from '../utils/HTTPClient.ts';
|
||||
import {
|
||||
generateRandomString, getRandomUserAgent,
|
||||
InnertubeError, Platform, SessionError
|
||||
} from '../utils/Utils.ts';
|
||||
|
||||
import type { DeviceCategory } from '../utils/Utils.ts';
|
||||
import { generateRandomString, getRandomUserAgent, InnertubeError, Platform, SessionError } from '../utils/Utils.ts';
|
||||
import type { Credentials, OAuthAuthErrorEventHandler, OAuthAuthEventHandler, OAuthAuthPendingEventHandler } from './OAuth.ts';
|
||||
import OAuth from './OAuth.ts';
|
||||
import type { FetchFunction, ICache } from '../types/index.ts';
|
||||
import type { OAuth2Tokens, OAuth2AuthErrorEventHandler, OAuth2AuthPendingEventHandler, OAuth2AuthEventHandler } from './OAuth2.ts';
|
||||
|
||||
export enum ClientType {
|
||||
WEB = 'WEB',
|
||||
@@ -23,33 +25,43 @@ export enum ClientType {
|
||||
TV_EMBEDDED = 'TVHTML5_SIMPLY_EMBEDDED_PLAYER'
|
||||
}
|
||||
|
||||
export interface Context {
|
||||
export type Context = {
|
||||
client: {
|
||||
hl: string;
|
||||
gl: string;
|
||||
remoteHost?: string;
|
||||
screenDensityFloat: number;
|
||||
screenHeightPoints: number;
|
||||
screenPixelDensity: number;
|
||||
screenWidthPoints: number;
|
||||
visitorData: string;
|
||||
screenDensityFloat?: number;
|
||||
screenHeightPoints?: number;
|
||||
screenPixelDensity?: number;
|
||||
screenWidthPoints?: number;
|
||||
visitorData?: string;
|
||||
clientName: string;
|
||||
clientVersion: string;
|
||||
clientScreen?: string,
|
||||
androidSdkVersion?: string;
|
||||
androidSdkVersion?: number;
|
||||
osName: string;
|
||||
osVersion: string;
|
||||
platform: string;
|
||||
clientFormFactor: string;
|
||||
userInterfaceTheme: string;
|
||||
userInterfaceTheme?: string;
|
||||
timeZone: string;
|
||||
userAgent?: string;
|
||||
browserName?: string;
|
||||
browserVersion?: string;
|
||||
originalUrl: string;
|
||||
originalUrl?: string;
|
||||
deviceMake: string;
|
||||
deviceModel: string;
|
||||
utcOffsetMinutes: number;
|
||||
mainAppWebInfo?: {
|
||||
graftUrl: string;
|
||||
pwaInstallabilityStatus: string;
|
||||
webDisplayMode: string;
|
||||
isWebNativeShareAvailable: boolean;
|
||||
};
|
||||
memoryTotalKbytes?: string;
|
||||
configInfo?: {
|
||||
appInstallData: string;
|
||||
},
|
||||
kidsAppInfo?: {
|
||||
categorySettings: {
|
||||
enabledCategories: string[];
|
||||
@@ -63,13 +75,38 @@ export interface Context {
|
||||
user: {
|
||||
enableSafetyMode: boolean;
|
||||
lockedSafetyMode: boolean;
|
||||
onBehalfOfUser?: string;
|
||||
};
|
||||
thirdParty?: {
|
||||
embedUrl: string;
|
||||
};
|
||||
request?: {
|
||||
useSsl: boolean;
|
||||
internalExperimentFlags: any[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface SessionOptions {
|
||||
type ContextData = {
|
||||
hl: string;
|
||||
gl: string;
|
||||
remote_host?: string;
|
||||
visitor_data: string;
|
||||
client_name: string;
|
||||
client_version: string;
|
||||
os_name: string;
|
||||
os_version: string;
|
||||
device_category: string;
|
||||
time_zone: string;
|
||||
enable_safety_mode: boolean;
|
||||
browser_name?: string;
|
||||
browser_version?: string;
|
||||
app_install_data?: string;
|
||||
device_make: string;
|
||||
device_model: string;
|
||||
on_behalf_of_user?: string;
|
||||
}
|
||||
|
||||
export type SessionOptions = {
|
||||
/**
|
||||
* Language.
|
||||
*/
|
||||
@@ -80,12 +117,17 @@ export interface SessionOptions {
|
||||
location?: string;
|
||||
/**
|
||||
* The account index to use. This is useful if you have multiple accounts logged in.
|
||||
* **NOTE:**
|
||||
* Only works if you are signed in with cookies.
|
||||
*
|
||||
* **NOTE:** Only works if you are signed in with cookies.
|
||||
*/
|
||||
account_index?: number;
|
||||
/**
|
||||
* Specify the Page ID of the YouTube profile/channel to use, if the logged-in account has multiple profiles.
|
||||
*/
|
||||
on_behalf_of_user?: string;
|
||||
/**
|
||||
* Specifies whether to retrieve the JS player. Disabling this will make session creation faster.
|
||||
*
|
||||
* **NOTE:** Deciphering formats is not possible without the JS player.
|
||||
*/
|
||||
retrieve_player?: boolean;
|
||||
@@ -96,8 +138,15 @@ export interface SessionOptions {
|
||||
/**
|
||||
* Specifies whether to generate the session data locally or retrieve it from YouTube.
|
||||
* This can be useful if you need more performance.
|
||||
*
|
||||
* **NOTE:** If you are using the cache option and a session has already been generated, this will be ignored.
|
||||
* If you want to force a new session to be generated, you must clear the cache or disable session caching.
|
||||
*/
|
||||
generate_session_locally?: boolean;
|
||||
/**
|
||||
* Specifies whether the session data should be cached.
|
||||
*/
|
||||
enable_session_cache?: boolean;
|
||||
/**
|
||||
* Platform to use for the session.
|
||||
*/
|
||||
@@ -111,7 +160,7 @@ export interface SessionOptions {
|
||||
*/
|
||||
timezone?: string;
|
||||
/**
|
||||
* Used to cache the deciphering functions from the JS player.
|
||||
* Used to cache algorithms, session data, and OAuth2 tokens.
|
||||
*/
|
||||
cache?: ICache;
|
||||
/**
|
||||
@@ -129,54 +178,72 @@ export interface SessionOptions {
|
||||
fetch?: FetchFunction;
|
||||
}
|
||||
|
||||
export interface SessionData {
|
||||
export type SessionData = {
|
||||
context: Context;
|
||||
api_key: string;
|
||||
api_version: string;
|
||||
}
|
||||
|
||||
export type SWSessionData = {
|
||||
context_data: ContextData;
|
||||
api_key: string;
|
||||
api_version: string;
|
||||
}
|
||||
|
||||
export type SessionArgs = {
|
||||
lang: string;
|
||||
location: string;
|
||||
time_zone: string;
|
||||
device_category: DeviceCategory;
|
||||
client_name: ClientType;
|
||||
enable_safety_mode: boolean;
|
||||
visitor_data: string;
|
||||
on_behalf_of_user: string | undefined;
|
||||
}
|
||||
|
||||
const TAG = 'Session';
|
||||
|
||||
/**
|
||||
* Represents an InnerTube session. This holds all the data needed to make requests to YouTube.
|
||||
*/
|
||||
export default class Session extends EventEmitterLike {
|
||||
#api_version: string;
|
||||
#key: string;
|
||||
#context: Context;
|
||||
#account_index: number;
|
||||
#player?: Player;
|
||||
|
||||
oauth: OAuth;
|
||||
export default class Session extends EventEmitter {
|
||||
context: Context;
|
||||
player?: Player;
|
||||
oauth: OAuth2;
|
||||
http: HTTPClient;
|
||||
logged_in: boolean;
|
||||
actions: Actions;
|
||||
cache?: ICache;
|
||||
key: string;
|
||||
api_version: string;
|
||||
account_index: number;
|
||||
|
||||
constructor(context: Context, api_key: string, api_version: string, account_index: number, player?: Player, cookie?: string, fetch?: FetchFunction, cache?: ICache) {
|
||||
super();
|
||||
this.#context = context;
|
||||
this.#account_index = account_index;
|
||||
this.#key = api_key;
|
||||
this.#api_version = api_version;
|
||||
this.#player = player;
|
||||
this.http = new HTTPClient(this, cookie, fetch);
|
||||
this.actions = new Actions(this);
|
||||
this.oauth = new OAuth(this);
|
||||
this.oauth = new OAuth2(this);
|
||||
this.logged_in = !!cookie;
|
||||
this.cache = cache;
|
||||
this.account_index = account_index;
|
||||
this.key = api_key;
|
||||
this.api_version = api_version;
|
||||
this.context = context;
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
on(type: 'auth', listener: OAuthAuthEventHandler): void;
|
||||
on(type: 'auth-pending', listener: OAuthAuthPendingEventHandler): void;
|
||||
on(type: 'auth-error', listener: OAuthAuthErrorEventHandler): void;
|
||||
on(type: 'update-credentials', listener: OAuthAuthEventHandler): void;
|
||||
on(type: 'auth', listener: OAuth2AuthEventHandler): void;
|
||||
on(type: 'auth-pending', listener: OAuth2AuthPendingEventHandler): void;
|
||||
on(type: 'auth-error', listener: OAuth2AuthErrorEventHandler): void;
|
||||
on(type: 'update-credentials', listener: OAuth2AuthEventHandler): void;
|
||||
|
||||
on(type: string, listener: (...args: any[]) => void): void {
|
||||
super.on(type, listener);
|
||||
}
|
||||
|
||||
once(type: 'auth', listener: OAuthAuthEventHandler): void;
|
||||
once(type: 'auth-pending', listener: OAuthAuthPendingEventHandler): void;
|
||||
once(type: 'auth-error', listener: OAuthAuthErrorEventHandler): void;
|
||||
once(type: 'auth', listener: OAuth2AuthEventHandler): void;
|
||||
once(type: 'auth-pending', listener: OAuth2AuthPendingEventHandler): void;
|
||||
once(type: 'auth-error', listener: OAuth2AuthErrorEventHandler): void;
|
||||
|
||||
once(type: string, listener: (...args: any[]) => void): void {
|
||||
super.once(type, listener);
|
||||
@@ -193,7 +260,10 @@ export default class Session extends EventEmitterLike {
|
||||
options.device_category,
|
||||
options.client_type,
|
||||
options.timezone,
|
||||
options.fetch
|
||||
options.fetch,
|
||||
options.on_behalf_of_user,
|
||||
options.cache,
|
||||
options.enable_session_cache
|
||||
);
|
||||
|
||||
return new Session(
|
||||
@@ -203,6 +273,47 @@ export default class Session extends EventEmitterLike {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves session data from cache.
|
||||
* @param cache - A valid cache implementation.
|
||||
* @param session_args - User provided session arguments.
|
||||
*/
|
||||
static async fromCache(cache: ICache, session_args: SessionArgs): Promise<SessionData | null> {
|
||||
const buffer = await cache.get('innertube_session_data');
|
||||
|
||||
if (!buffer)
|
||||
return null;
|
||||
|
||||
const data = new TextDecoder().decode(buffer.slice(4));
|
||||
|
||||
try {
|
||||
const result = JSON.parse(LZW.decompress(data)) as SessionData;
|
||||
|
||||
if (session_args.visitor_data) {
|
||||
result.context.client.visitorData = session_args.visitor_data;
|
||||
}
|
||||
|
||||
if (session_args.lang)
|
||||
result.context.client.hl = session_args.lang;
|
||||
|
||||
if (session_args.location)
|
||||
result.context.client.gl = session_args.location;
|
||||
|
||||
if (session_args.on_behalf_of_user)
|
||||
result.context.user.onBehalfOfUser = session_args.on_behalf_of_user;
|
||||
|
||||
result.context.client.timeZone = session_args.time_zone;
|
||||
result.context.client.platform = session_args.device_category.toUpperCase();
|
||||
result.context.client.clientName = session_args.client_name;
|
||||
result.context.user.enableSafetyMode = session_args.enable_safety_mode;
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
Log.error(TAG, 'Failed to parse session data from cache.', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static async getSessionData(
|
||||
lang = '',
|
||||
location = '',
|
||||
@@ -213,51 +324,102 @@ export default class Session extends EventEmitterLike {
|
||||
device_category: DeviceCategory = 'desktop',
|
||||
client_name: ClientType = ClientType.WEB,
|
||||
tz: string = Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
fetch: FetchFunction = Platform.shim.fetch
|
||||
fetch: FetchFunction = Platform.shim.fetch,
|
||||
on_behalf_of_user?: string,
|
||||
cache?: ICache,
|
||||
enable_session_cache = true
|
||||
) {
|
||||
let session_data: SessionData;
|
||||
const session_args = { lang, location, time_zone: tz, device_category, client_name, enable_safety_mode, visitor_data, on_behalf_of_user };
|
||||
|
||||
const session_args = { lang, location, time_zone: tz, device_category, client_name, enable_safety_mode, visitor_data };
|
||||
let session_data: SessionData | undefined;
|
||||
|
||||
if (generate_session_locally) {
|
||||
session_data = this.#generateSessionData(session_args);
|
||||
} else {
|
||||
try {
|
||||
// This can fail if the data changes or the request is blocked for some reason.
|
||||
session_data = await this.#retrieveSessionData(session_args, fetch);
|
||||
} catch (err) {
|
||||
session_data = this.#generateSessionData(session_args);
|
||||
if (cache && enable_session_cache) {
|
||||
const cached_session_data = await this.fromCache(cache, session_args);
|
||||
if (cached_session_data) {
|
||||
Log.info(TAG, 'Found session data in cache.');
|
||||
session_data = cached_session_data;
|
||||
}
|
||||
}
|
||||
|
||||
if (!session_data) {
|
||||
Log.info(TAG, 'Generating session data.');
|
||||
|
||||
let api_key = Constants.CLIENTS.WEB.API_KEY;
|
||||
let api_version = Constants.CLIENTS.WEB.API_VERSION;
|
||||
|
||||
let context_data: ContextData = {
|
||||
hl: lang || 'en',
|
||||
gl: location || 'US',
|
||||
remote_host: '',
|
||||
visitor_data: visitor_data || Proto.encodeVisitorData(generateRandomString(11), Math.floor(Date.now() / 1000)),
|
||||
client_name: client_name,
|
||||
client_version: Constants.CLIENTS.WEB.VERSION,
|
||||
device_category: device_category.toUpperCase(),
|
||||
os_name: 'Windows',
|
||||
os_version: '10.0',
|
||||
time_zone: tz,
|
||||
browser_name: 'Chrome',
|
||||
browser_version: '125.0.0.0',
|
||||
device_make: '',
|
||||
device_model: '',
|
||||
enable_safety_mode: enable_safety_mode
|
||||
};
|
||||
|
||||
if (!generate_session_locally) {
|
||||
try {
|
||||
const sw_session_data = await this.#getSessionData(session_args, fetch);
|
||||
api_key = sw_session_data.api_key;
|
||||
api_version = sw_session_data.api_version;
|
||||
context_data = sw_session_data.context_data;
|
||||
} catch (error) {
|
||||
Log.error(TAG, 'Failed to retrieve session data from server. Session data generated locally will be used instead.', error);
|
||||
}
|
||||
}
|
||||
|
||||
session_data = {
|
||||
api_key,
|
||||
api_version,
|
||||
context: this.#buildContext(context_data)
|
||||
};
|
||||
|
||||
if (enable_session_cache)
|
||||
await this.#storeSession(session_data, cache);
|
||||
}
|
||||
|
||||
Log.debug(TAG, 'Session data:', session_data);
|
||||
|
||||
return { ...session_data, account_index };
|
||||
}
|
||||
|
||||
static async #retrieveSessionData(options: {
|
||||
lang: string;
|
||||
location: string;
|
||||
time_zone: string;
|
||||
device_category: string;
|
||||
client_name: string;
|
||||
enable_safety_mode: boolean;
|
||||
visitor_data: string;
|
||||
}, fetch: FetchFunction = Platform.shim.fetch): Promise<SessionData> {
|
||||
const url = new URL('/sw.js_data', Constants.URLS.YT_BASE);
|
||||
static async #storeSession(session_data: SessionData, cache?: ICache) {
|
||||
if (!cache) return;
|
||||
|
||||
Log.info(TAG, 'Compressing and caching session data.');
|
||||
|
||||
const compressed_session_data = new TextEncoder().encode(LZW.compress(JSON.stringify(session_data)));
|
||||
|
||||
const buffer = new ArrayBuffer(4 + compressed_session_data.byteLength);
|
||||
new DataView(buffer).setUint32(0, compressed_session_data.byteLength, true); // (Luan) XX: Leave this here for debugging purposes
|
||||
new Uint8Array(buffer).set(compressed_session_data, 4);
|
||||
|
||||
await cache.set('innertube_session_data', new Uint8Array(buffer));
|
||||
}
|
||||
|
||||
static async #getSessionData(options: SessionArgs, fetch: FetchFunction = Platform.shim.fetch): Promise<SWSessionData> {
|
||||
let visitor_id = generateRandomString(11);
|
||||
|
||||
if (options.visitor_data) {
|
||||
const decoded_visitor_data = Proto.decodeVisitorData(options.visitor_data);
|
||||
visitor_id = decoded_visitor_data.id;
|
||||
}
|
||||
if (options.visitor_data)
|
||||
visitor_id = this.#getVisitorID(options.visitor_data);
|
||||
|
||||
const url = new URL('/sw.js_data', Constants.URLS.YT_BASE);
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
'accept-language': options.lang || 'en-US',
|
||||
'user-agent': getRandomUserAgent('desktop'),
|
||||
'accept': '*/*',
|
||||
'referer': 'https://www.youtube.com/sw.js',
|
||||
'cookie': `PREF=tz=${options.time_zone.replace('/', '.')};VISITOR_INFO1_LIVE=${visitor_id};`
|
||||
'Accept-Language': options.lang || 'en-US',
|
||||
'User-Agent': getRandomUserAgent('desktop'),
|
||||
'Accept': '*/*',
|
||||
'Referer': `${Constants.URLS.YT_BASE}/sw.js`,
|
||||
'Cookie': `PREF=tz=${options.time_zone.replace('/', '.')};VISITOR_INFO1_LIVE=${visitor_id};`
|
||||
}
|
||||
});
|
||||
|
||||
@@ -265,120 +427,114 @@ export default class Session extends EventEmitterLike {
|
||||
throw new SessionError(`Failed to retrieve session data: ${res.status}`);
|
||||
|
||||
const text = await res.text();
|
||||
|
||||
if (!text.startsWith(')]}\''))
|
||||
throw new SessionError('Invalid JSPB response');
|
||||
|
||||
const data = JSON.parse(text.replace(/^\)\]\}'/, ''));
|
||||
|
||||
const ytcfg = data[0][2];
|
||||
|
||||
const api_version = `v${ytcfg[0][0][6]}`;
|
||||
const api_version = Constants.CLIENTS.WEB.API_VERSION;
|
||||
|
||||
const [ [ device_info ], api_key ] = ytcfg;
|
||||
|
||||
const context: Context = {
|
||||
client: {
|
||||
hl: device_info[0],
|
||||
gl: options.location || device_info[2],
|
||||
remoteHost: device_info[3],
|
||||
screenDensityFloat: 1,
|
||||
screenHeightPoints: 1080,
|
||||
screenPixelDensity: 1,
|
||||
screenWidthPoints: 1920,
|
||||
visitorData: device_info[13],
|
||||
clientName: options.client_name,
|
||||
clientVersion: device_info[16],
|
||||
osName: device_info[17],
|
||||
osVersion: device_info[18],
|
||||
platform: options.device_category.toUpperCase(),
|
||||
clientFormFactor: 'UNKNOWN_FORM_FACTOR',
|
||||
userInterfaceTheme: 'USER_INTERFACE_THEME_LIGHT',
|
||||
timeZone: device_info[79] || options.time_zone,
|
||||
browserName: device_info[86],
|
||||
browserVersion: device_info[87],
|
||||
originalUrl: Constants.URLS.YT_BASE,
|
||||
deviceMake: device_info[11],
|
||||
deviceModel: device_info[12],
|
||||
utcOffsetMinutes: -new Date().getTimezoneOffset()
|
||||
},
|
||||
user: {
|
||||
enableSafetyMode: options.enable_safety_mode,
|
||||
lockedSafetyMode: false
|
||||
}
|
||||
const config_info = device_info[61];
|
||||
const app_install_data = config_info[config_info.length - 1];
|
||||
|
||||
const context_info = {
|
||||
hl: options.lang || device_info[0],
|
||||
gl: options.location || device_info[2],
|
||||
remote_host: device_info[3],
|
||||
visitor_data: device_info[13],
|
||||
client_name: options.client_name,
|
||||
client_version: device_info[16],
|
||||
os_name: device_info[17],
|
||||
os_version: device_info[18],
|
||||
time_zone: device_info[79] || options.time_zone,
|
||||
device_category: options.device_category,
|
||||
browser_name: device_info[86],
|
||||
browser_version: device_info[87],
|
||||
device_make: device_info[11],
|
||||
device_model: device_info[12],
|
||||
app_install_data: app_install_data,
|
||||
enable_safety_mode: options.enable_safety_mode
|
||||
};
|
||||
|
||||
return { context, api_key, api_version };
|
||||
return { context_data: context_info, api_key, api_version };
|
||||
}
|
||||
|
||||
static #generateSessionData(options: {
|
||||
lang: string;
|
||||
location: string;
|
||||
time_zone: string;
|
||||
device_category: DeviceCategory;
|
||||
client_name: string;
|
||||
enable_safety_mode: boolean;
|
||||
visitor_data: string;
|
||||
}): SessionData {
|
||||
let visitor_id = generateRandomString(11);
|
||||
|
||||
if (options.visitor_data) {
|
||||
const decoded_visitor_data = Proto.decodeVisitorData(options.visitor_data);
|
||||
visitor_id = decoded_visitor_data.id;
|
||||
}
|
||||
|
||||
static #buildContext(args: ContextData) {
|
||||
const context: Context = {
|
||||
client: {
|
||||
hl: options.lang || 'en',
|
||||
gl: options.location || 'US',
|
||||
hl: args.hl,
|
||||
gl: args.gl,
|
||||
remoteHost: args.remote_host,
|
||||
screenDensityFloat: 1,
|
||||
screenHeightPoints: 1080,
|
||||
screenHeightPoints: 1440,
|
||||
screenPixelDensity: 1,
|
||||
screenWidthPoints: 1920,
|
||||
visitorData: Proto.encodeVisitorData(visitor_id, Math.floor(Date.now() / 1000)),
|
||||
clientName: options.client_name,
|
||||
clientVersion: Constants.CLIENTS.WEB.VERSION,
|
||||
osName: 'Windows',
|
||||
osVersion: '10.0',
|
||||
platform: options.device_category.toUpperCase(),
|
||||
screenWidthPoints: 2560,
|
||||
visitorData: args.visitor_data,
|
||||
clientName: args.client_name,
|
||||
clientVersion: args.client_version,
|
||||
osName: args.os_name,
|
||||
osVersion: args.os_version,
|
||||
platform: args.device_category.toUpperCase(),
|
||||
clientFormFactor: 'UNKNOWN_FORM_FACTOR',
|
||||
userInterfaceTheme: 'USER_INTERFACE_THEME_LIGHT',
|
||||
timeZone: options.time_zone,
|
||||
timeZone: args.time_zone,
|
||||
originalUrl: Constants.URLS.YT_BASE,
|
||||
deviceMake: '',
|
||||
deviceModel: '',
|
||||
utcOffsetMinutes: -new Date().getTimezoneOffset()
|
||||
},
|
||||
user: {
|
||||
enableSafetyMode: options.enable_safety_mode,
|
||||
lockedSafetyMode: false
|
||||
}
|
||||
};
|
||||
|
||||
return { context, api_key: Constants.CLIENTS.WEB.API_KEY, api_version: Constants.CLIENTS.WEB.API_VERSION };
|
||||
}
|
||||
|
||||
async signIn(credentials?: Credentials): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const error_handler: OAuthAuthErrorEventHandler = (err) => reject(err);
|
||||
|
||||
this.once('auth', (data) => {
|
||||
this.off('auth-error', error_handler);
|
||||
|
||||
if (data.status === 'SUCCESS') {
|
||||
this.logged_in = true;
|
||||
resolve();
|
||||
deviceMake: args.device_make,
|
||||
deviceModel: args.device_model,
|
||||
browserName: args.browser_name,
|
||||
browserVersion: args.browser_version,
|
||||
utcOffsetMinutes: -Math.floor((new Date()).getTimezoneOffset()),
|
||||
memoryTotalKbytes: '8000000',
|
||||
mainAppWebInfo: {
|
||||
graftUrl: Constants.URLS.YT_BASE,
|
||||
pwaInstallabilityStatus: 'PWA_INSTALLABILITY_STATUS_UNKNOWN',
|
||||
webDisplayMode: 'WEB_DISPLAY_MODE_BROWSER',
|
||||
isWebNativeShareAvailable: true
|
||||
}
|
||||
},
|
||||
user: {
|
||||
enableSafetyMode: args.enable_safety_mode,
|
||||
lockedSafetyMode: false
|
||||
},
|
||||
request: {
|
||||
useSsl: true,
|
||||
internalExperimentFlags: []
|
||||
}
|
||||
};
|
||||
|
||||
reject(data);
|
||||
});
|
||||
if (args.app_install_data)
|
||||
context.client.configInfo = { appInstallData: args.app_install_data };
|
||||
|
||||
if (args.on_behalf_of_user)
|
||||
context.user.onBehalfOfUser = args.on_behalf_of_user;
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
static #getVisitorID(visitor_data: string) {
|
||||
const decoded_visitor_data = Proto.decodeVisitorData(visitor_data);
|
||||
return decoded_visitor_data.id;
|
||||
}
|
||||
|
||||
async signIn(credentials?: OAuth2Tokens): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const error_handler: OAuth2AuthErrorEventHandler = (err) => reject(err);
|
||||
|
||||
this.once('auth-error', error_handler);
|
||||
|
||||
this.once('auth', () => {
|
||||
this.off('auth-error', error_handler);
|
||||
this.logged_in = true;
|
||||
resolve();
|
||||
});
|
||||
|
||||
try {
|
||||
await this.oauth.init(credentials);
|
||||
|
||||
if (this.oauth.validateCredentials()) {
|
||||
await this.oauth.refreshIfRequired();
|
||||
this.logged_in = true;
|
||||
resolve();
|
||||
}
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
@@ -398,41 +554,15 @@ export default class Session extends EventEmitterLike {
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* InnerTube API key.
|
||||
*/
|
||||
get key(): string {
|
||||
return this.#key;
|
||||
}
|
||||
|
||||
/**
|
||||
* InnerTube API version.
|
||||
*/
|
||||
get api_version(): string {
|
||||
return this.#api_version;
|
||||
}
|
||||
|
||||
get client_version(): string {
|
||||
return this.#context.client.clientVersion;
|
||||
return this.context.client.clientVersion;
|
||||
}
|
||||
|
||||
get client_name(): string {
|
||||
return this.#context.client.clientName;
|
||||
}
|
||||
|
||||
get account_index(): number {
|
||||
return this.#account_index;
|
||||
}
|
||||
|
||||
get context(): Context {
|
||||
return this.#context;
|
||||
}
|
||||
|
||||
get player(): Player | undefined {
|
||||
return this.#player;
|
||||
return this.context.client.clientName;
|
||||
}
|
||||
|
||||
get lang(): string {
|
||||
return this.#context.client.hl;
|
||||
return this.context.client.hl;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import Channel from '../../parser/ytkids/Channel.ts';
|
||||
import HomeFeed from '../../parser/ytkids/HomeFeed.ts';
|
||||
import Search from '../../parser/ytkids/Search.ts';
|
||||
import VideoInfo from '../../parser/ytkids/VideoInfo.ts';
|
||||
import type Session from '../Session.ts';
|
||||
|
||||
import { generateRandomString } from '../../utils/Utils.ts';
|
||||
import { Parser } from '../../parser/index.ts';
|
||||
import { Channel, HomeFeed, Search, VideoInfo } from '../../parser/ytkids/index.ts';
|
||||
import { InnertubeError, generateRandomString } from '../../utils/Utils.ts';
|
||||
import KidsBlocklistPickerItem from '../../parser/classes/ytkids/KidsBlocklistPickerItem.ts';
|
||||
|
||||
import {
|
||||
BrowseEndpoint, NextEndpoint,
|
||||
PlayerEndpoint, SearchEndpoint
|
||||
} from '../endpoints/index.ts';
|
||||
|
||||
import { BlocklistPickerEndpoint } from '../endpoints/kids/index.ts';
|
||||
|
||||
import type { Session, ApiResponse } from '../index.ts';
|
||||
|
||||
export default class Kids {
|
||||
#session: Session;
|
||||
|
||||
@@ -80,4 +81,38 @@ export default class Kids {
|
||||
);
|
||||
return new HomeFeed(this.#session.actions, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the list of supervised accounts that the signed-in user has
|
||||
* access to, and blocks the given channel for each of them.
|
||||
* @param channel_id - The channel id to block.
|
||||
* @returns A list of API responses.
|
||||
*/
|
||||
async blockChannel(channel_id: string): Promise<ApiResponse[]> {
|
||||
if (!this.#session.logged_in)
|
||||
throw new InnertubeError('You must be signed in to perform this operation.');
|
||||
|
||||
const blocklist_payload = BlocklistPickerEndpoint.build({ channel_id: channel_id });
|
||||
const response = await this.#session.actions.execute(BlocklistPickerEndpoint.PATH, blocklist_payload );
|
||||
const popup = response.data.command.confirmDialogEndpoint;
|
||||
const popup_fragment = { contents: popup.content, engagementPanels: [] };
|
||||
const kid_picker = Parser.parseResponse(popup_fragment);
|
||||
const kids = kid_picker.contents_memo?.getType(KidsBlocklistPickerItem);
|
||||
|
||||
if (!kids)
|
||||
throw new InnertubeError('Could not find any kids profiles or supervised accounts.');
|
||||
|
||||
// Iterate through the kids and block the channel if not already blocked.
|
||||
const responses: ApiResponse[] = [];
|
||||
|
||||
for (const kid of kids) {
|
||||
if (!kid.block_button?.is_toggled) {
|
||||
kid.setActions(this.#session.actions);
|
||||
// Block channel and add to the response list.
|
||||
responses.push(await kid.blockChannel());
|
||||
}
|
||||
}
|
||||
|
||||
return responses;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
import Album from '../../parser/ytmusic/Album.ts';
|
||||
import Artist from '../../parser/ytmusic/Artist.ts';
|
||||
import Explore from '../../parser/ytmusic/Explore.ts';
|
||||
import HomeFeed from '../../parser/ytmusic/HomeFeed.ts';
|
||||
import Library from '../../parser/ytmusic/Library.ts';
|
||||
import Playlist from '../../parser/ytmusic/Playlist.ts';
|
||||
import Recap from '../../parser/ytmusic/Recap.ts';
|
||||
import Search from '../../parser/ytmusic/Search.ts';
|
||||
import TrackInfo from '../../parser/ytmusic/TrackInfo.ts';
|
||||
import * as Proto from '../../proto/index.ts';
|
||||
import { InnertubeError, generateRandomString, throwIfMissing } from '../../utils/Utils.ts';
|
||||
|
||||
import {
|
||||
Album, Artist, Explore,
|
||||
HomeFeed, Library, Playlist,
|
||||
Recap, Search, TrackInfo
|
||||
} from '../../parser/ytmusic/index.ts';
|
||||
|
||||
import AutomixPreviewVideo from '../../parser/classes/AutomixPreviewVideo.ts';
|
||||
import Message from '../../parser/classes/Message.ts';
|
||||
import MusicCarouselShelf from '../../parser/classes/MusicCarouselShelf.ts';
|
||||
import MusicDescriptionShelf from '../../parser/classes/MusicDescriptionShelf.ts';
|
||||
import MusicQueue from '../../parser/classes/MusicQueue.ts';
|
||||
import MusicTwoRowItem from '../../parser/classes/MusicTwoRowItem.ts';
|
||||
@@ -18,13 +16,6 @@ import PlaylistPanel from '../../parser/classes/PlaylistPanel.ts';
|
||||
import SearchSuggestionsSection from '../../parser/classes/SearchSuggestionsSection.ts';
|
||||
import SectionList from '../../parser/classes/SectionList.ts';
|
||||
import Tab from '../../parser/classes/Tab.ts';
|
||||
import * as Proto from '../../proto/index.ts';
|
||||
|
||||
import type { ObservedArray, YTNode } from '../../parser/helpers.ts';
|
||||
import type { MusicSearchFilters } from '../../types/index.ts';
|
||||
import { InnertubeError, generateRandomString, throwIfMissing } from '../../utils/Utils.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
import type Session from '../Session.ts';
|
||||
|
||||
import {
|
||||
BrowseEndpoint,
|
||||
@@ -35,6 +26,10 @@ import {
|
||||
|
||||
import { GetSearchSuggestionsEndpoint } from '../endpoints/music/index.ts';
|
||||
|
||||
import type { ObservedArray } from '../../parser/helpers.ts';
|
||||
import type { MusicSearchFilters } from '../../types/index.ts';
|
||||
import type { Actions, Session } from '../index.ts';
|
||||
|
||||
export default class Music {
|
||||
#session: Session;
|
||||
#actions: Actions;
|
||||
@@ -282,7 +277,7 @@ export default class Music {
|
||||
* Retrieves related content.
|
||||
* @param video_id - The video id.
|
||||
*/
|
||||
async getRelated(video_id: string): Promise<ObservedArray<MusicCarouselShelf | MusicDescriptionShelf>> {
|
||||
async getRelated(video_id: string): Promise<SectionList | Message> {
|
||||
throwIfMissing({ video_id });
|
||||
|
||||
const response = await this.#actions.execute(
|
||||
@@ -301,9 +296,9 @@ export default class Music {
|
||||
if (!page.contents)
|
||||
throw new InnertubeError('Unexpected response', page);
|
||||
|
||||
const shelves = page.contents.item().as(SectionList).contents.as(MusicCarouselShelf, MusicDescriptionShelf);
|
||||
const contents = page.contents.item().as(SectionList, Message);
|
||||
|
||||
return shelves;
|
||||
return contents;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -355,17 +350,17 @@ export default class Music {
|
||||
* Retrieves search suggestions for the given query.
|
||||
* @param query - The query.
|
||||
*/
|
||||
async getSearchSuggestions(query: string): Promise<ObservedArray<YTNode>> {
|
||||
async getSearchSuggestions(query: string): Promise<ObservedArray<SearchSuggestionsSection>> {
|
||||
const response = await this.#actions.execute(
|
||||
GetSearchSuggestionsEndpoint.PATH,
|
||||
{ ...GetSearchSuggestionsEndpoint.build({ input: query }), parse: true }
|
||||
);
|
||||
|
||||
if (!response.contents_memo)
|
||||
throw new InnertubeError('Unexpected response', response);
|
||||
return [] as unknown as ObservedArray<SearchSuggestionsSection>;
|
||||
|
||||
const search_suggestions_section = response.contents_memo.getType(SearchSuggestionsSection).first();
|
||||
const search_suggestions_sections = response.contents_memo.getType(SearchSuggestionsSection);
|
||||
|
||||
return search_suggestions_section.contents;
|
||||
return search_suggestions_sections;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import * as Proto from '../../proto/index.ts';
|
||||
import * as Constants from '../../utils/Constants.ts';
|
||||
import { Constants } from '../../utils/index.ts';
|
||||
import { InnertubeError, MissingParamError, Platform } from '../../utils/Utils.ts';
|
||||
import { CreateVideoEndpoint } from '../endpoints/upload/index.ts';
|
||||
|
||||
import type { UpdateVideoMetadataOptions, UploadedVideoMetadataOptions } from '../../types/Clients.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
import type Session from '../Session.ts';
|
||||
|
||||
import { CreateVideoEndpoint } from '../endpoints/upload/index.ts';
|
||||
import type { ApiResponse, Session } from '../index.ts';
|
||||
|
||||
interface UploadResult {
|
||||
status: string;
|
||||
|
||||
@@ -8,11 +8,6 @@ export const PATH = '/player';
|
||||
* @returns The payload.
|
||||
*/
|
||||
export function build(opts: PlayerEndpointOptions): IPlayerRequest {
|
||||
const is_android =
|
||||
opts.client === 'ANDROID' ||
|
||||
opts.client === 'YTMUSIC_ANDROID' ||
|
||||
opts.client === 'YTSTUDIO_ANDROID';
|
||||
|
||||
return {
|
||||
playbackContext: {
|
||||
contentPlaybackContext: {
|
||||
@@ -42,8 +37,7 @@ export function build(opts: PlayerEndpointOptions): IPlayerRequest {
|
||||
...{
|
||||
client: opts.client,
|
||||
playlistId: opts.playlist_id,
|
||||
// Workaround streaming URLs returning 403 or getting throttled when using Android based clients.
|
||||
params: is_android ? '2AMBCgIQBg' : opts.params
|
||||
params: opts.params
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -15,7 +15,9 @@ export function build(opts: EditPlaylistEndpointOptions): IEditPlaylistRequest {
|
||||
...{
|
||||
addedVideoId: action.added_video_id,
|
||||
setVideoId: action.set_video_id,
|
||||
movedSetVideoIdPredecessor: action.moved_set_video_id_predecessor
|
||||
movedSetVideoIdPredecessor: action.moved_set_video_id_predecessor,
|
||||
playlistDescription: action.playlist_description,
|
||||
playlistName: action.playlist_name
|
||||
}
|
||||
}))
|
||||
};
|
||||
|
||||
@@ -15,4 +15,6 @@ export * as Music from './music/index.ts';
|
||||
export * as Notification from './notification/index.ts';
|
||||
export * as Playlist from './playlist/index.ts';
|
||||
export * as Subscription from './subscription/index.ts';
|
||||
export * as Upload from './upload/index.ts';
|
||||
export * as Reel from './reel/index.ts';
|
||||
export * as Upload from './upload/index.ts';
|
||||
export * as Kids from './kids/index.ts';
|
||||
12
deno/src/core/endpoints/kids/BlocklistPickerEndpoint.ts
Normal file
12
deno/src/core/endpoints/kids/BlocklistPickerEndpoint.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { IBlocklistPickerRequest, BlocklistPickerRequestEndpointOptions } from '../../../types/index.ts';
|
||||
|
||||
export const PATH = '/kids/get_kids_blocklist_picker';
|
||||
|
||||
/**
|
||||
* Builds a `/kids/get_kids_blocklist_picker` request payload.
|
||||
* @param options - The options to use.
|
||||
* @returns The payload.
|
||||
*/
|
||||
export function build(options: BlocklistPickerRequestEndpointOptions): IBlocklistPickerRequest {
|
||||
return { blockedForKidsContent: { external_channel_id: options.channel_id } };
|
||||
}
|
||||
1
deno/src/core/endpoints/kids/index.ts
Normal file
1
deno/src/core/endpoints/kids/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * as BlocklistPickerEndpoint from './BlocklistPickerEndpoint.ts';
|
||||
18
deno/src/core/endpoints/reel/WatchEndpoint.ts
Normal file
18
deno/src/core/endpoints/reel/WatchEndpoint.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { IReelWatchRequest, ReelWatchEndpointOptions } from '../../../types/index.ts';
|
||||
|
||||
export const PATH = '/reel/reel_item_watch';
|
||||
|
||||
/**
|
||||
* Builds a `/reel/reel_watch_sequence` request payload.
|
||||
* @param opts - The options to use.
|
||||
* @returns The payload.
|
||||
*/
|
||||
export function build(opts: ReelWatchEndpointOptions): IReelWatchRequest {
|
||||
return {
|
||||
playerRequest: {
|
||||
videoId: opts.short_id,
|
||||
params: opts.params ?? 'CAUwAg%3D%3D'
|
||||
},
|
||||
params: opts.params ?? 'CAUwAg%3D%3D'
|
||||
};
|
||||
}
|
||||
14
deno/src/core/endpoints/reel/WatchSequenceEndpoint.ts
Normal file
14
deno/src/core/endpoints/reel/WatchSequenceEndpoint.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { IReelSequenceRequest, ReelWatchSequenceEndpointOptions } from '../../../types/index.ts';
|
||||
|
||||
export const PATH = '/reel/reel_watch_sequence';
|
||||
|
||||
/**
|
||||
* Builds a `/reel/reel_watch_sequence` request payload.
|
||||
* @param opts - The options to use.
|
||||
* @returns The payload.
|
||||
*/
|
||||
export function build(opts: ReelWatchSequenceEndpointOptions): IReelSequenceRequest {
|
||||
return {
|
||||
sequenceParams: opts.sequenceParams
|
||||
};
|
||||
}
|
||||
2
deno/src/core/endpoints/reel/index.ts
Normal file
2
deno/src/core/endpoints/reel/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * as WatchEndpoint from './WatchEndpoint.ts';
|
||||
export * as WatchSequenceEndpoint from './WatchSequenceEndpoint.ts';
|
||||
@@ -7,8 +7,8 @@ export * from './Actions.ts';
|
||||
export { default as Player } from './Player.ts';
|
||||
export * from './Player.ts';
|
||||
|
||||
export { default as OAuth } from './OAuth.ts';
|
||||
export * from './OAuth.ts';
|
||||
export { default as OAuth2 } from './OAuth2.ts';
|
||||
export * from './OAuth2.ts';
|
||||
|
||||
export * as Clients from './clients/index.ts';
|
||||
export * as Endpoints from './endpoints/index.ts';
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { Actions, ApiResponse } from '../index.ts';
|
||||
|
||||
import AccountInfo from '../../parser/youtube/AccountInfo.ts';
|
||||
import Analytics from '../../parser/youtube/Analytics.ts';
|
||||
import Settings from '../../parser/youtube/Settings.ts';
|
||||
@@ -7,9 +9,6 @@ import * as Proto from '../../proto/index.ts';
|
||||
import { InnertubeError } from '../../utils/Utils.ts';
|
||||
import { Account, BrowseEndpoint, Channel } from '../endpoints/index.ts';
|
||||
|
||||
import type Actions from '../Actions.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
|
||||
export default class AccountManager {
|
||||
#actions: Actions;
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import * as Proto from '../../proto/index.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
|
||||
import { throwIfMissing } from '../../utils/Utils.ts';
|
||||
import { LikeEndpoint, DislikeEndpoint, RemoveLikeEndpoint } from '../endpoints/like/index.ts';
|
||||
@@ -8,6 +6,8 @@ import { SubscribeEndpoint, UnsubscribeEndpoint } from '../endpoints/subscriptio
|
||||
import { CreateCommentEndpoint, PerformCommentActionEndpoint } from '../endpoints/comment/index.ts';
|
||||
import { ModifyChannelPreferenceEndpoint } from '../endpoints/notification/index.ts';
|
||||
|
||||
import type { Actions, ApiResponse } from '../index.ts';
|
||||
|
||||
export default class InteractionManager {
|
||||
#actions: Actions;
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import Playlist from '../../parser/youtube/Playlist.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
import type Feed from '../mixins/Feed.ts';
|
||||
|
||||
import type { EditPlaylistEndpointOptions } from '../../types/index.ts';
|
||||
import { InnertubeError, throwIfMissing } from '../../utils/Utils.ts';
|
||||
import { EditPlaylistEndpoint } from '../endpoints/browse/index.ts';
|
||||
import { BrowseEndpoint } from '../endpoints/index.ts';
|
||||
import { CreateEndpoint, DeleteEndpoint } from '../endpoints/playlist/index.ts';
|
||||
import Playlist from '../../parser/youtube/Playlist.ts';
|
||||
|
||||
import type { Actions } from '../index.ts';
|
||||
import type { Feed } from '../mixins/index.ts';
|
||||
import type { EditPlaylistEndpointOptions } from '../../types/index.ts';
|
||||
|
||||
export default class PlaylistManager {
|
||||
#actions: Actions;
|
||||
@@ -200,4 +200,60 @@ export default class PlaylistManager {
|
||||
action_result: response.data.actions // TODO: implement actions in the parser
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name (title) for the given playlist.
|
||||
* @param playlist_id - The playlist ID.
|
||||
* @param name - The name / title to use for the playlist.
|
||||
*/
|
||||
async setName(playlist_id: string, name: string): Promise<{ playlist_id: string; action_result: any; }> {
|
||||
throwIfMissing({ playlist_id, name });
|
||||
|
||||
if (!this.#actions.session.logged_in)
|
||||
throw new InnertubeError('You must be signed in to perform this operation.');
|
||||
|
||||
const payload: EditPlaylistEndpointOptions = { playlist_id, actions: [] };
|
||||
|
||||
payload.actions.push({
|
||||
action: 'ACTION_SET_PLAYLIST_NAME',
|
||||
playlist_name: name
|
||||
});
|
||||
|
||||
const response = await this.#actions.execute(
|
||||
EditPlaylistEndpoint.PATH, EditPlaylistEndpoint.build(payload)
|
||||
);
|
||||
|
||||
return {
|
||||
playlist_id,
|
||||
action_result: response.data.actions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the description for the given playlist.
|
||||
* @param playlist_id - The playlist ID.
|
||||
* @param description - The description to use for the playlist.
|
||||
*/
|
||||
async setDescription(playlist_id: string, description: string): Promise<{ playlist_id: string; action_result: any; }> {
|
||||
throwIfMissing({ playlist_id, description });
|
||||
|
||||
if (!this.#actions.session.logged_in)
|
||||
throw new InnertubeError('You must be signed in to perform this operation.');
|
||||
|
||||
const payload: EditPlaylistEndpointOptions = { playlist_id, actions: [] };
|
||||
|
||||
payload.actions.push({
|
||||
action: 'ACTION_SET_PLAYLIST_DESCRIPTION',
|
||||
playlist_description: description
|
||||
});
|
||||
|
||||
const response = await this.#actions.execute(
|
||||
EditPlaylistEndpoint.PATH, EditPlaylistEndpoint.build(payload)
|
||||
);
|
||||
|
||||
return {
|
||||
playlist_id,
|
||||
action_result: response.data.actions
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { Memo, ObservedArray, SuperParsedResult, YTNode } from '../../parser/helpers.ts';
|
||||
import Parser, { ReloadContinuationItemsCommand } from '../../parser/index.ts';
|
||||
import { Parser, ReloadContinuationItemsCommand } from '../../parser/index.ts';
|
||||
import { concatMemos, InnertubeError } from '../../utils/Utils.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
|
||||
import BackstagePost from '../../parser/classes/BackstagePost.ts';
|
||||
import SharedPost from '../../parser/classes/SharedPost.ts';
|
||||
@@ -10,6 +8,7 @@ import CompactVideo from '../../parser/classes/CompactVideo.ts';
|
||||
import GridChannel from '../../parser/classes/GridChannel.ts';
|
||||
import GridPlaylist from '../../parser/classes/GridPlaylist.ts';
|
||||
import GridVideo from '../../parser/classes/GridVideo.ts';
|
||||
import LockupView from '../../parser/classes/LockupView.ts';
|
||||
import Playlist from '../../parser/classes/Playlist.ts';
|
||||
import PlaylistPanelVideo from '../../parser/classes/PlaylistPanelVideo.ts';
|
||||
import PlaylistVideo from '../../parser/classes/PlaylistVideo.ts';
|
||||
@@ -27,12 +26,15 @@ import TwoColumnBrowseResults from '../../parser/classes/TwoColumnBrowseResults.
|
||||
import TwoColumnSearchResults from '../../parser/classes/TwoColumnSearchResults.ts';
|
||||
import WatchCardCompactVideo from '../../parser/classes/WatchCardCompactVideo.ts';
|
||||
|
||||
import type { ApiResponse, Actions } from '../index.ts';
|
||||
import type {
|
||||
Memo, ObservedArray,
|
||||
SuperParsedResult, YTNode
|
||||
} from '../../parser/helpers.ts';
|
||||
import type MusicQueue from '../../parser/classes/MusicQueue.ts';
|
||||
import type RichGrid from '../../parser/classes/RichGrid.ts';
|
||||
import type SectionList from '../../parser/classes/SectionList.ts';
|
||||
|
||||
import type { IParsedResponse } from '../../parser/types/index.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
|
||||
export default class Feed<T extends IParsedResponse = IParsedResponse> {
|
||||
#page: T;
|
||||
@@ -87,7 +89,18 @@ export default class Feed<T extends IParsedResponse = IParsedResponse> {
|
||||
* Get all playlists on a given page via memo
|
||||
*/
|
||||
static getPlaylistsFromMemo(memo: Memo) {
|
||||
return memo.getType(Playlist, GridPlaylist);
|
||||
const playlists: ObservedArray<Playlist | GridPlaylist | LockupView> = memo.getType(Playlist, GridPlaylist);
|
||||
|
||||
const lockup_views = memo.getType(LockupView)
|
||||
.filter((lockup) => {
|
||||
return [ 'PLAYLIST', 'ALBUM', 'PODCAST' ].includes(lockup.content_type);
|
||||
});
|
||||
|
||||
if (lockup_views.length > 0) {
|
||||
playlists.push(...lockup_views);
|
||||
}
|
||||
|
||||
return playlists;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,7 +190,7 @@ export default class Feed<T extends IParsedResponse = IParsedResponse> {
|
||||
* Checks if the feed has continuation.
|
||||
*/
|
||||
get has_continuation(): boolean {
|
||||
return (this.#memo.get('ContinuationItem') || []).length > 0;
|
||||
return this.#getBodyContinuations().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,17 +198,15 @@ export default class Feed<T extends IParsedResponse = IParsedResponse> {
|
||||
*/
|
||||
async getContinuationData(): Promise<T | undefined> {
|
||||
if (this.#continuation) {
|
||||
if (this.#continuation.length > 1)
|
||||
throw new InnertubeError('There are too many continuations, you\'ll need to find the correct one yourself in this.page');
|
||||
if (this.#continuation.length === 0)
|
||||
throw new InnertubeError('There are no continuations');
|
||||
throw new InnertubeError('There are no continuations.');
|
||||
|
||||
const response = await this.#continuation[0].endpoint.call<T>(this.#actions, { parse: true });
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
this.#continuation = this.#memo.getType(ContinuationItem);
|
||||
this.#continuation = this.#getBodyContinuations();
|
||||
|
||||
if (this.#continuation)
|
||||
return this.getContinuationData();
|
||||
@@ -210,4 +221,14 @@ export default class Feed<T extends IParsedResponse = IParsedResponse> {
|
||||
throw new InnertubeError('Could not get continuation data');
|
||||
return new Feed<T>(this.actions, continuation_data, true);
|
||||
}
|
||||
|
||||
#getBodyContinuations(): ObservedArray<ContinuationItem> {
|
||||
if (this.#page.header_memo) {
|
||||
const header_continuations = this.#page.header_memo.getType(ContinuationItem);
|
||||
return this.#memo.getType(ContinuationItem).filter(
|
||||
(continuation) => !header_continuations.includes(continuation)
|
||||
) as ObservedArray<ContinuationItem>;
|
||||
}
|
||||
return this.#memo.getType(ContinuationItem);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import Feed from './Feed.ts';
|
||||
import ChipCloudChip from '../../parser/classes/ChipCloudChip.ts';
|
||||
import FeedFilterChipBar from '../../parser/classes/FeedFilterChipBar.ts';
|
||||
import { InnertubeError } from '../../utils/Utils.ts';
|
||||
import Feed from './Feed.ts';
|
||||
|
||||
import type { ObservedArray } from '../../parser/helpers.ts';
|
||||
import type { IParsedResponse } from '../../parser/types/ParsedResponse.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
import type { IParsedResponse } from '../../parser/types/index.ts';
|
||||
import type { ApiResponse, Actions } from '../index.ts';
|
||||
|
||||
export default class FilterableFeed<T extends IParsedResponse> extends Feed<T> {
|
||||
#chips?: ObservedArray<ChipCloudChip>;
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
import type Actions from '../Actions.ts';
|
||||
import * as Constants from '../../utils/Constants.ts';
|
||||
import type { DownloadOptions, FormatFilter, FormatOptions, URLTransformer } from '../../types/FormatUtils.ts';
|
||||
import * as FormatUtils from '../../utils/FormatUtils.ts';
|
||||
import { Constants, FormatUtils } from '../../utils/index.ts';
|
||||
import { InnertubeError } from '../../utils/Utils.ts';
|
||||
import type Format from '../../parser/classes/misc/Format.ts';
|
||||
import type { INextResponse, IPlayerResponse } from '../../parser/index.ts';
|
||||
import Parser from '../../parser/index.ts';
|
||||
import type { DashOptions } from '../../types/DashOptions.ts';
|
||||
import PlayerStoryboardSpec from '../../parser/classes/PlayerStoryboardSpec.ts';
|
||||
import { getStreamingInfo } from '../../utils/StreamingInfo.ts';
|
||||
|
||||
import { Parser } from '../../parser/index.ts';
|
||||
import { TranscriptInfo } from '../../parser/youtube/index.ts';
|
||||
import ContinuationItem from '../../parser/classes/ContinuationItem.ts';
|
||||
|
||||
import type { ApiResponse, Actions } from '../index.ts';
|
||||
import type { INextResponse, IPlayerConfig, IPlayerResponse } from '../../parser/index.ts';
|
||||
import type { DownloadOptions, FormatFilter, FormatOptions, URLTransformer } from '../../types/FormatUtils.ts';
|
||||
import type Format from '../../parser/classes/misc/Format.ts';
|
||||
import type { DashOptions } from '../../types/DashOptions.ts';
|
||||
|
||||
export default class MediaInfo {
|
||||
#page: [IPlayerResponse, INextResponse?];
|
||||
#actions: Actions;
|
||||
@@ -18,6 +19,7 @@ export default class MediaInfo {
|
||||
#playback_tracking;
|
||||
streaming_data;
|
||||
playability_status;
|
||||
player_config: IPlayerConfig;
|
||||
|
||||
constructor(data: [ApiResponse, ApiResponse?], actions: Actions, cpn: string) {
|
||||
this.#actions = actions;
|
||||
@@ -33,6 +35,7 @@ export default class MediaInfo {
|
||||
|
||||
this.streaming_data = info.streaming_data;
|
||||
this.playability_status = info.playability_status;
|
||||
this.player_config = info.player_config;
|
||||
this.#playback_tracking = info.playback_tracking;
|
||||
}
|
||||
|
||||
@@ -44,13 +47,35 @@ export default class MediaInfo {
|
||||
* @returns DASH manifest
|
||||
*/
|
||||
async toDash(url_transformer?: URLTransformer, format_filter?: FormatFilter, options: DashOptions = { include_thumbnails: false }): Promise<string> {
|
||||
let storyboards;
|
||||
const player_response = this.#page[0];
|
||||
|
||||
if (options.include_thumbnails && this.#page[0].storyboards?.is(PlayerStoryboardSpec)) {
|
||||
storyboards = this.#page[0].storyboards;
|
||||
if (player_response.video_details && (player_response.video_details.is_live)) {
|
||||
throw new InnertubeError('Generating DASH manifests for live videos is not supported. Please use the DASH and HLS manifests provided by YouTube in `streaming_data.dash_manifest_url` and `streaming_data.hls_manifest_url` instead.');
|
||||
}
|
||||
|
||||
return FormatUtils.toDash(this.streaming_data, url_transformer, format_filter, this.#cpn, this.#actions.session.player, this.#actions, storyboards);
|
||||
let storyboards;
|
||||
let captions;
|
||||
|
||||
if (options.include_thumbnails && player_response.storyboards) {
|
||||
storyboards = player_response.storyboards;
|
||||
}
|
||||
|
||||
if (typeof options.captions_format === 'string' && player_response.captions?.caption_tracks) {
|
||||
captions = player_response.captions.caption_tracks;
|
||||
}
|
||||
|
||||
return FormatUtils.toDash(
|
||||
this.streaming_data,
|
||||
this.page[0].video_details?.is_post_live_dvr,
|
||||
url_transformer,
|
||||
format_filter,
|
||||
this.#cpn,
|
||||
this.#actions.session.player,
|
||||
this.#actions,
|
||||
storyboards,
|
||||
captions,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,12 +84,13 @@ export default class MediaInfo {
|
||||
getStreamingInfo(url_transformer?: URLTransformer, format_filter?: FormatFilter) {
|
||||
return getStreamingInfo(
|
||||
this.streaming_data,
|
||||
this.page[0].video_details?.is_post_live_dvr,
|
||||
url_transformer,
|
||||
format_filter,
|
||||
this.cpn,
|
||||
this.#actions.session.player,
|
||||
this.#actions,
|
||||
this.#page[0].storyboards?.is(PlayerStoryboardSpec) ? this.#page[0].storyboards : undefined
|
||||
this.#page[0].storyboards ? this.#page[0].storyboards : undefined
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,9 +107,45 @@ export default class MediaInfo {
|
||||
* @param options - Download options.
|
||||
*/
|
||||
async download(options: DownloadOptions = {}): Promise<ReadableStream<Uint8Array>> {
|
||||
const player_response = this.#page[0];
|
||||
|
||||
if (player_response.video_details && (player_response.video_details.is_live || player_response.video_details.is_post_live_dvr)) {
|
||||
throw new InnertubeError('Downloading is not supported for live and Post-Live-DVR videos, as they are split up into 5 second segments that are individual files, which require using a tool such as ffmpeg to stitch them together, so they cannot be returned in a single stream.');
|
||||
}
|
||||
|
||||
return FormatUtils.download(options, this.#actions, this.playability_status, this.streaming_data, this.#actions.session.player, this.cpn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the video's transcript.
|
||||
* @param video_id - The video id.
|
||||
*/
|
||||
async getTranscript(): Promise<TranscriptInfo> {
|
||||
const next_response = this.page[1];
|
||||
|
||||
if (!next_response)
|
||||
throw new InnertubeError('Cannot get transcript from basic video info.');
|
||||
|
||||
if (!next_response.engagement_panels)
|
||||
throw new InnertubeError('Engagement panels not found. Video likely has no transcript.');
|
||||
|
||||
const transcript_panel = next_response.engagement_panels.get({
|
||||
panel_identifier: 'engagement-panel-searchable-transcript'
|
||||
});
|
||||
|
||||
if (!transcript_panel)
|
||||
throw new InnertubeError('Transcript panel not found. Video likely has no transcript.');
|
||||
|
||||
const transcript_continuation = transcript_panel.content?.as(ContinuationItem);
|
||||
|
||||
if (!transcript_continuation)
|
||||
throw new InnertubeError('Transcript continuation not found.');
|
||||
|
||||
const response = await transcript_continuation.endpoint.call(this.actions);
|
||||
|
||||
return new TranscriptInfo(this.actions, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds video to the watch history.
|
||||
*/
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import Tab from '../../parser/classes/Tab.ts';
|
||||
import Feed from './Feed.ts';
|
||||
import { Feed } from './index.ts';
|
||||
import { InnertubeError } from '../../utils/Utils.ts';
|
||||
import Tab from '../../parser/classes/Tab.ts';
|
||||
|
||||
import type Actions from '../Actions.ts';
|
||||
import type { Actions, ApiResponse } from '../index.ts';
|
||||
import type { ObservedArray } from '../../parser/helpers.ts';
|
||||
import type { IParsedResponse } from '../../parser/types/ParsedResponse.ts';
|
||||
import type { ApiResponse } from '../Actions.ts';
|
||||
|
||||
export default class TabbedFeed<T extends IParsedResponse> extends Feed<T> {
|
||||
#tabs?: ObservedArray<Tab>;
|
||||
|
||||
18
deno/src/parser/classes/AboutChannel.ts
Normal file
18
deno/src/parser/classes/AboutChannel.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import AboutChannelView from './AboutChannelView.ts';
|
||||
import Button from './Button.ts';
|
||||
|
||||
export default class AboutChannel extends YTNode {
|
||||
static type = 'AboutChannel';
|
||||
|
||||
metadata: AboutChannelView | null;
|
||||
share_channel: Button | null;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.metadata = Parser.parseItem(data.metadata, AboutChannelView);
|
||||
this.share_channel = Parser.parseItem(data.shareChannel, Button);
|
||||
}
|
||||
}
|
||||
87
deno/src/parser/classes/AboutChannelView.ts
Normal file
87
deno/src/parser/classes/AboutChannelView.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import type { ObservedArray } from '../helpers.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ChannelExternalLinkView from './ChannelExternalLinkView.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class AboutChannelView extends YTNode {
|
||||
static type = 'AboutChannelView';
|
||||
|
||||
description?: string;
|
||||
description_label?: Text;
|
||||
country?: string;
|
||||
custom_links_label?: Text;
|
||||
subscriber_count?: string;
|
||||
view_count?: string;
|
||||
joined_date?: Text;
|
||||
canonical_channel_url?: string;
|
||||
channel_id?: string;
|
||||
additional_info_label?: Text;
|
||||
custom_url_on_tap?: NavigationEndpoint;
|
||||
video_count?: string;
|
||||
sign_in_for_business_email?: Text;
|
||||
links: ObservedArray<ChannelExternalLinkView>;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
if (Reflect.has(data, 'description')) {
|
||||
this.description = data.description;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'descriptionLabel')) {
|
||||
this.description_label = Text.fromAttributed(data.descriptionLabel);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'country')) {
|
||||
this.country = data.country;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'customLinksLabel')) {
|
||||
this.custom_links_label = Text.fromAttributed(data.customLinksLabel);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'subscriberCountText')) {
|
||||
this.subscriber_count = data.subscriberCountText;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'viewCountText')) {
|
||||
this.view_count = data.viewCountText;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'joinedDateText')) {
|
||||
this.joined_date = Text.fromAttributed(data.joinedDateText);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'canonicalChannelUrl')) {
|
||||
this.canonical_channel_url = data.canonicalChannelUrl;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'channelId')) {
|
||||
this.channel_id = data.channelId;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'additionalInfoLabel')) {
|
||||
this.additional_info_label = Text.fromAttributed(data.additionalInfoLabel);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'customUrlOnTap')) {
|
||||
this.custom_url_on_tap = new NavigationEndpoint(data.customUrlOnTap);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'videoCountText')) {
|
||||
this.video_count = data.videoCountText;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'signInForBusinessEmail')) {
|
||||
this.sign_in_for_business_email = Text.fromAttributed(data.signInForBusinessEmail);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'links')) {
|
||||
this.links = Parser.parseArray(data.links, ChannelExternalLinkView);
|
||||
} else {
|
||||
this.links = [] as unknown as ObservedArray<ChannelExternalLinkView>;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser from '../index.ts';
|
||||
import { Parser } from '../index.ts';
|
||||
import AccountItemSectionHeader from './AccountItemSectionHeader.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser from '../index.ts';
|
||||
import { Parser } from '../index.ts';
|
||||
import AccountChannel from './AccountChannel.ts';
|
||||
import AccountItemSection from './AccountItemSection.ts';
|
||||
|
||||
|
||||
17
deno/src/parser/classes/AttributionView.ts
Normal file
17
deno/src/parser/classes/AttributionView.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class AttributionView extends YTNode {
|
||||
static type = 'AttributionView';
|
||||
|
||||
text: Text;
|
||||
suffix: Text;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.text = Text.fromAttributed(data.text);
|
||||
this.suffix = Text.fromAttributed(data.suffix);
|
||||
}
|
||||
}
|
||||
26
deno/src/parser/classes/AvatarView.ts
Normal file
26
deno/src/parser/classes/AvatarView.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { type RawNode } from '../index.ts';
|
||||
import { Thumbnail } from '../misc.ts';
|
||||
|
||||
export default class AvatarView extends YTNode {
|
||||
static type = 'AvatarView';
|
||||
|
||||
image: Thumbnail[];
|
||||
image_processor: {
|
||||
border_image_processor: {
|
||||
circular: boolean
|
||||
}
|
||||
};
|
||||
avatar_image_size: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.image = Thumbnail.fromResponse(data.image);
|
||||
this.image_processor = {
|
||||
border_image_processor: {
|
||||
circular: data.image.processor.borderImageProcessor.circular
|
||||
}
|
||||
};
|
||||
this.avatar_image_size = data.avatarImageSize;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import CommentActionButtons from './comments/CommentActionButtons.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
@@ -18,7 +19,7 @@ export default class BackstagePost extends YTNode {
|
||||
vote_count?: Text;
|
||||
menu?: Menu | null;
|
||||
action_buttons?: CommentActionButtons | null;
|
||||
vote_button?: CommentActionButtons | null;
|
||||
vote_button?: Button | null;
|
||||
surface: string;
|
||||
endpoint?: NavigationEndpoint;
|
||||
attachment;
|
||||
@@ -56,7 +57,7 @@ export default class BackstagePost extends YTNode {
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'voteButton')) {
|
||||
this.vote_button = Parser.parseItem(data.voteButton, CommentActionButtons);
|
||||
this.vote_button = Parser.parseItem(data.voteButton, Button);
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'navigationEndpoint')) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
|
||||
export default class BackstagePostThread extends YTNode {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
|
||||
export default class BrowseFeedActions extends YTNode {
|
||||
|
||||
28
deno/src/parser/classes/ButtonView.ts
Normal file
28
deno/src/parser/classes/ButtonView.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
export default class ButtonView extends YTNode {
|
||||
static type = 'ButtonView';
|
||||
|
||||
icon_name: string;
|
||||
title: string;
|
||||
accessibility_text: string;
|
||||
style: string;
|
||||
is_full_width: boolean;
|
||||
button_type: string;
|
||||
button_size: string;
|
||||
on_tap: NavigationEndpoint;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.icon_name = data.iconName;
|
||||
this.title = data.title;
|
||||
this.accessibility_text = data.accessibilityText;
|
||||
this.style = data.style;
|
||||
this.is_full_width = data.isFullWidth;
|
||||
this.button_type = data.type;
|
||||
this.button_size = data.buttonSize;
|
||||
this.on_tap = new NavigationEndpoint(data.onTap);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import ChannelHeaderLinks from './ChannelHeaderLinks.ts';
|
||||
import ChannelHeaderLinksView from './ChannelHeaderLinksView.ts';
|
||||
import ChannelTagline from './ChannelTagline.ts';
|
||||
import SubscribeButton from './SubscribeButton.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
@@ -22,6 +23,7 @@ export default class C4TabbedHeader extends YTNode {
|
||||
header_links?: ChannelHeaderLinks | ChannelHeaderLinksView | null;
|
||||
channel_handle?: Text;
|
||||
channel_id?: string;
|
||||
tagline?: ChannelTagline | null;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
@@ -69,5 +71,9 @@ export default class C4TabbedHeader extends YTNode {
|
||||
if (Reflect.has(data, 'channelId')) {
|
||||
this.channel_id = data.channelId;
|
||||
}
|
||||
|
||||
if (Reflect.has(data, 'tagline')) {
|
||||
this.tagline = Parser.parseItem(data.tagline, ChannelTagline);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
|
||||
export default class Card extends YTNode {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class CardCollection extends YTNode {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
|
||||
export default class CarouselHeader extends YTNode {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
import InfoRow from './InfoRow.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import CompactVideo from './CompactVideo.ts';
|
||||
|
||||
export default class CarouselLockup extends YTNode {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Log } from '../../utils/index.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import SubscribeButton from './SubscribeButton.ts';
|
||||
@@ -44,6 +45,7 @@ export default class Channel extends YTNode {
|
||||
* Please use {@link Channel.subscriber_count} instead.
|
||||
*/
|
||||
get subscribers(): Text {
|
||||
Log.warnOnce(Channel.type, 'Channel#subscribers is deprecated. Please use Channel#subscriber_count instead.');
|
||||
return this.subscriber_count;
|
||||
}
|
||||
|
||||
@@ -53,6 +55,7 @@ export default class Channel extends YTNode {
|
||||
* Please use {@link Channel.video_count} instead.
|
||||
*/
|
||||
get videos(): Text {
|
||||
Log.warnOnce(Channel.type, 'Channel#videos is deprecated. Please use Channel#video_count instead.');
|
||||
return this.video_count;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Log } from '../../utils/index.ts';
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
@@ -55,6 +56,7 @@ export default class ChannelAboutFullMetadata extends YTNode {
|
||||
* Please use {@link Channel.view_count} instead.
|
||||
*/
|
||||
get views() {
|
||||
Log.warnOnce(ChannelAboutFullMetadata.type, 'ChannelAboutFullMetadata#views is deprecated. Please use ChannelAboutFullMetadata#view_count instead.');
|
||||
return this.view_count;
|
||||
}
|
||||
|
||||
@@ -64,6 +66,7 @@ export default class ChannelAboutFullMetadata extends YTNode {
|
||||
* Please use {@link Channel.joined_date} instead.
|
||||
*/
|
||||
get joined(): Text {
|
||||
Log.warnOnce(ChannelAboutFullMetadata.type, 'ChannelAboutFullMetadata#joined is deprecated. Please use ChannelAboutFullMetadata#joined_date instead.');
|
||||
return this.joined_date;
|
||||
}
|
||||
}
|
||||
20
deno/src/parser/classes/ChannelExternalLinkView.ts
Normal file
20
deno/src/parser/classes/ChannelExternalLinkView.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
export default class ChannelExternalLinkView extends YTNode {
|
||||
static type = 'ChannelExternalLinkView';
|
||||
|
||||
title: Text;
|
||||
link: Text;
|
||||
favicon: Thumbnail[];
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.title = Text.fromAttributed(data.title);
|
||||
this.link = Text.fromAttributed(data.link);
|
||||
this.favicon = Thumbnail.fromResponse(data.favicon);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class ChannelFeaturedContent extends YTNode {
|
||||
|
||||
@@ -14,6 +14,7 @@ export default class ChannelMetadata extends YTNode {
|
||||
is_family_safe: boolean;
|
||||
keywords: string[];
|
||||
avatar: Thumbnail[];
|
||||
music_artist_name?: string;
|
||||
available_countries: string[];
|
||||
android_deep_link: string;
|
||||
android_appindexing_link: string;
|
||||
@@ -30,6 +31,8 @@ export default class ChannelMetadata extends YTNode {
|
||||
this.is_family_safe = data.isFamilySafe;
|
||||
this.keywords = data.keywords;
|
||||
this.avatar = Thumbnail.fromResponse(data.avatar);
|
||||
// Can be an empty string sometimes, so we need the extra length check
|
||||
this.music_artist_name = typeof data.musicArtistName === 'string' && data.musicArtistName.length > 0 ? data.musicArtistName : undefined;
|
||||
this.available_countries = data.availableCountryCodes;
|
||||
this.android_deep_link = data.androidDeepLink;
|
||||
this.android_appindexing_link = data.androidAppindexingLink;
|
||||
|
||||
17
deno/src/parser/classes/ChannelOwnerEmptyState.ts
Normal file
17
deno/src/parser/classes/ChannelOwnerEmptyState.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
export default class ChannelOwnerEmptyState extends YTNode {
|
||||
static type = 'ChannelOwnerEmptyState';
|
||||
|
||||
illustration: Thumbnail[];
|
||||
description: Text;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.illustration = Thumbnail.fromResponse(data.illustration);
|
||||
this.description = new Text(data.description);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
export default class ChannelSubMenu extends YTNode {
|
||||
|
||||
44
deno/src/parser/classes/ChannelTagline.ts
Normal file
44
deno/src/parser/classes/ChannelTagline.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import EngagementPanelSectionList from './EngagementPanelSectionList.ts';
|
||||
|
||||
export default class ChannelTagline extends YTNode {
|
||||
static type = 'ChannelTagline';
|
||||
|
||||
content: string;
|
||||
max_lines: number;
|
||||
more_endpoint: {
|
||||
show_engagement_panel_endpoint: {
|
||||
engagement_panel: EngagementPanelSectionList | null,
|
||||
engagement_panel_popup_type: string;
|
||||
identifier: {
|
||||
surface: string,
|
||||
tag: string
|
||||
}
|
||||
}
|
||||
} | NavigationEndpoint;
|
||||
more_icon_type: string;
|
||||
more_label: string;
|
||||
target_id: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.content = data.content;
|
||||
this.max_lines = data.maxLines;
|
||||
this.more_endpoint = data.moreEndpoint.showEngagementPanelEndpoint ? {
|
||||
show_engagement_panel_endpoint: {
|
||||
engagement_panel: Parser.parseItem(data.moreEndpoint.showEngagementPanelEndpoint.engagementPanel, EngagementPanelSectionList),
|
||||
engagement_panel_popup_type: data.moreEndpoint.showEngagementPanelEndpoint.engagementPanelPresentationConfigs.engagementPanelPopupPresentationConfig.popupType,
|
||||
identifier: {
|
||||
surface: data.moreEndpoint.showEngagementPanelEndpoint.identifier.surface,
|
||||
tag: data.moreEndpoint.showEngagementPanelEndpoint.identifier.tag
|
||||
}
|
||||
}
|
||||
} : new NavigationEndpoint(data.moreEndpoint);
|
||||
this.more_icon_type = data.moreIcon.iconType;
|
||||
this.more_label = data.moreLabel;
|
||||
this.target_id = data.targetId;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import Text from './misc/Text.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import { Log } from '../../utils/index.ts';
|
||||
|
||||
export default class ChannelVideoPlayer extends YTNode {
|
||||
static type = 'ChannelVideoPlayer';
|
||||
@@ -26,6 +27,7 @@ export default class ChannelVideoPlayer extends YTNode {
|
||||
* Please use {@link ChannelVideoPlayer.view_count} instead.
|
||||
*/
|
||||
get views(): Text {
|
||||
Log.warnOnce(ChannelVideoPlayer.type, 'ChannelVideoPlayer#views is deprecated. Please use ChannelVideoPlayer#view_count instead.');
|
||||
return this.view_count;
|
||||
}
|
||||
|
||||
@@ -35,6 +37,7 @@ export default class ChannelVideoPlayer extends YTNode {
|
||||
* Please use {@link ChannelVideoPlayer.published_time} instead.
|
||||
*/
|
||||
get published(): Text {
|
||||
Log.warnOnce(ChannelVideoPlayer.type, 'ChannelVideoPlayer#published is deprecated. Please use ChannelVideoPlayer#published_time instead.');
|
||||
return this.published_time;
|
||||
}
|
||||
}
|
||||
14
deno/src/parser/classes/ChipBarView.ts
Normal file
14
deno/src/parser/classes/ChipBarView.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ChipView from './ChipView.ts';
|
||||
|
||||
export default class ChipBarView extends YTNode {
|
||||
static type = 'ChipBarView';
|
||||
|
||||
chips: ObservedArray<ChipView> | null;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.chips = Parser.parseArray(data.chips, ChipView);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import ChipCloudChip from './ChipCloudChip.ts';
|
||||
|
||||
|
||||
20
deno/src/parser/classes/ChipView.ts
Normal file
20
deno/src/parser/classes/ChipView.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
export default class ChipView extends YTNode {
|
||||
static type = 'ChipView';
|
||||
|
||||
text: string;
|
||||
display_type: string;
|
||||
endpoint: NavigationEndpoint;
|
||||
chip_entity_key: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.text = data.text;
|
||||
this.display_type = data.displayType;
|
||||
this.endpoint = new NavigationEndpoint(data.tapCommand);
|
||||
this.chip_entity_key = data.chipEntityKey;
|
||||
}
|
||||
}
|
||||
17
deno/src/parser/classes/ClipAdState.ts
Normal file
17
deno/src/parser/classes/ClipAdState.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class ClipAdState extends YTNode {
|
||||
static type = 'ClipAdState';
|
||||
|
||||
title: Text;
|
||||
body: Text;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.title = new Text(data.title);
|
||||
this.body = new Text(data.body);
|
||||
}
|
||||
}
|
||||
40
deno/src/parser/classes/ClipCreation.ts
Normal file
40
deno/src/parser/classes/ClipCreation.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
import Button from './Button.ts';
|
||||
import ClipCreationTextInput from './ClipCreationTextInput.ts';
|
||||
import ClipCreationScrubber from './ClipCreationScrubber.ts';
|
||||
import ClipAdState from './ClipAdState.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
import { Parser } from '../index.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class ClipCreation extends YTNode {
|
||||
static type = 'ClipCreation';
|
||||
|
||||
user_avatar: Thumbnail[];
|
||||
title_input: ClipCreationTextInput | null;
|
||||
scrubber: ClipCreationScrubber | null;
|
||||
save_button: Button | null;
|
||||
display_name: Text;
|
||||
publicity_label: string;
|
||||
cancel_button: Button | null;
|
||||
ad_state_overlay: ClipAdState | null;
|
||||
external_video_id: string;
|
||||
publicity_label_icon: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.user_avatar = Thumbnail.fromResponse(data.userAvatar);
|
||||
this.title_input = Parser.parseItem(data.titleInput, [ ClipCreationTextInput ]);
|
||||
this.scrubber = Parser.parseItem(data.scrubber, [ ClipCreationScrubber ]);
|
||||
this.save_button = Parser.parseItem(data.saveButton, [ Button ]);
|
||||
this.display_name = new Text(data.displayName);
|
||||
this.publicity_label = data.publicityLabel;
|
||||
this.cancel_button = Parser.parseItem(data.cancelButton, [ Button ]);
|
||||
this.ad_state_overlay = Parser.parseItem(data.adStateOverlay, [ ClipAdState ]);
|
||||
this.external_video_id = data.externalVideoId;
|
||||
this.publicity_label_icon = data.publicityLabelIcon;
|
||||
}
|
||||
}
|
||||
28
deno/src/parser/classes/ClipCreationScrubber.ts
Normal file
28
deno/src/parser/classes/ClipCreationScrubber.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class ClipCreationScrubber extends YTNode {
|
||||
static type = 'ClipCreationScrubber';
|
||||
|
||||
length_template: string;
|
||||
max_length_ms: number;
|
||||
min_length_ms: number;
|
||||
default_length_ms: number;
|
||||
window_size_ms: number;
|
||||
start_label?: string;
|
||||
end_label?: string;
|
||||
duration_label?: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.length_template = data.lengthTemplate;
|
||||
this.max_length_ms = data.maxLengthMs;
|
||||
this.min_length_ms = data.minLengthMs;
|
||||
this.default_length_ms = data.defaultLengthMs;
|
||||
this.window_size_ms = data.windowSizeMs;
|
||||
this.start_label = data.startAccessibility?.accessibilityData?.label;
|
||||
this.end_label = data.endAccessibility?.accessibilityData?.label;
|
||||
this.duration_label = data.durationAccessibility?.accessibilityData?.label;
|
||||
}
|
||||
}
|
||||
17
deno/src/parser/classes/ClipCreationTextInput.ts
Normal file
17
deno/src/parser/classes/ClipCreationTextInput.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class ClipCreationTextInput extends YTNode {
|
||||
static type = 'ClipCreationTextInput';
|
||||
|
||||
placeholder_text: Text;
|
||||
max_character_limit: number;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.placeholder_text = new Text(data.placeholderText);
|
||||
this.max_character_limit = data.maxCharacterLimit;
|
||||
}
|
||||
}
|
||||
19
deno/src/parser/classes/ClipSection.ts
Normal file
19
deno/src/parser/classes/ClipSection.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { ObservedArray } from '../helpers.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
|
||||
import ClipCreation from './ClipCreation.ts';
|
||||
|
||||
import { Parser } from '../index.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class ClipSection extends YTNode {
|
||||
static type = 'ClipSection';
|
||||
|
||||
contents: ObservedArray<ClipCreation> | null;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.contents = Parser.parse(data.contents, true, [ ClipCreation ]);
|
||||
}
|
||||
}
|
||||
25
deno/src/parser/classes/CollectionThumbnailView.ts
Normal file
25
deno/src/parser/classes/CollectionThumbnailView.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ThumbnailView from './ThumbnailView.ts';
|
||||
|
||||
export default class CollectionThumbnailView extends YTNode {
|
||||
static type = 'CollectionThumbnailView';
|
||||
|
||||
primary_thumbnail: ThumbnailView | null;
|
||||
stack_color?: {
|
||||
light_theme: number;
|
||||
dark_theme: number;
|
||||
};
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.primary_thumbnail = Parser.parseItem(data.primaryThumbnail, ThumbnailView);
|
||||
if (data.stackColor) {
|
||||
this.stack_color = {
|
||||
light_theme: data.stackColor.lightTheme,
|
||||
dark_theme: data.stackColor.darkTheme
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
14
deno/src/parser/classes/Command.ts
Normal file
14
deno/src/parser/classes/Command.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
export default class Command extends YTNode {
|
||||
static type = 'Command';
|
||||
|
||||
endpoint: NavigationEndpoint;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.endpoint = new NavigationEndpoint(data);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Parser from '../index.ts';
|
||||
import { Parser } from '../index.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
import { timeToSeconds } from '../../utils/Utils.ts';
|
||||
@@ -29,7 +30,6 @@ export default class CompactMovie extends YTNode {
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
console.log(data);
|
||||
const overlay_time_status = data.thumbnailOverlays
|
||||
.find((overlay: RawNode) => overlay.thumbnailOverlayTimeStatusRenderer)
|
||||
?.thumbnailOverlayTimeStatusRenderer.text || 'N/A';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { timeToSeconds } from '../../utils/Utils.ts';
|
||||
import { YTNode, type ObservedArray, type SuperParsedResult } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
import MetadataBadge from './MetadataBadge.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Button from './Button.ts';
|
||||
import { YTNode } from '../helpers.ts';
|
||||
|
||||
26
deno/src/parser/classes/ContentMetadataView.ts
Normal file
26
deno/src/parser/classes/ContentMetadataView.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import { Text } from '../misc.ts';
|
||||
|
||||
export type MetadataRow = {
|
||||
metadata_parts?: {
|
||||
text: Text;
|
||||
}[];
|
||||
};
|
||||
|
||||
export default class ContentMetadataView extends YTNode {
|
||||
static type = 'ContentMetadataView';
|
||||
|
||||
metadata_rows: MetadataRow[];
|
||||
delimiter: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.metadata_rows = data.metadataRows.map((row: RawNode) => ({
|
||||
metadata_parts: row.metadataParts?.map((part: RawNode) => ({
|
||||
text: Text.fromAttributed(part.text)
|
||||
}))
|
||||
}));
|
||||
this.delimiter = data.delimiter;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ export default class ContentPreviewImageView extends YTNode {
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.image = data.image.sources.map((x: any) => new Thumbnail(x)).sort((a: Thumbnail, b: Thumbnail) => b.width - a.width);
|
||||
this.image = Thumbnail.fromResponse(data.image);
|
||||
this.style = data.style;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Message from './Message.ts';
|
||||
|
||||
export default class ConversationBar extends YTNode {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
|
||||
export default class CopyLink extends YTNode {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import Dropdown from './Dropdown.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
21
deno/src/parser/classes/DecoratedAvatarView.ts
Normal file
21
deno/src/parser/classes/DecoratedAvatarView.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import AvatarView from './AvatarView.ts';
|
||||
|
||||
export default class DecoratedAvatarView extends YTNode {
|
||||
static type = 'DecoratedAvatarView';
|
||||
|
||||
avatar: AvatarView | null;
|
||||
a11y_label: string;
|
||||
on_tap_endpoint?: NavigationEndpoint;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.avatar = Parser.parseItem(data.avatar, AvatarView);
|
||||
this.a11y_label = data.a11yLabel;
|
||||
if (data.rendererContext?.commandContext?.onTap) {
|
||||
this.on_tap_endpoint = new NavigationEndpoint(data.rendererContext.commandContext.onTap);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Parser from '../index.ts';
|
||||
import { Parser } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import MultiMarkersPlayerBar from './MultiMarkersPlayerBar.ts';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
|
||||
47
deno/src/parser/classes/DescriptionPreviewView.ts
Normal file
47
deno/src/parser/classes/DescriptionPreviewView.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import EngagementPanelSectionList from './EngagementPanelSectionList.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class DescriptionPreviewView extends YTNode {
|
||||
static type = 'DescriptionPreviewView';
|
||||
|
||||
description: Text;
|
||||
max_lines: number;
|
||||
truncation_text: Text;
|
||||
always_show_truncation_text: boolean;
|
||||
more_endpoint?: {
|
||||
show_engagement_panel_endpoint: {
|
||||
engagement_panel: EngagementPanelSectionList | null,
|
||||
engagement_panel_popup_type: string;
|
||||
identifier: {
|
||||
surface: string,
|
||||
tag: string
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
|
||||
this.description = Text.fromAttributed(data.description);
|
||||
this.max_lines = parseInt(data.maxLines);
|
||||
this.truncation_text = Text.fromAttributed(data.truncationText);
|
||||
this.always_show_truncation_text = !!data.alwaysShowTruncationText;
|
||||
|
||||
if (data.rendererContext.commandContext?.onTap?.innertubeCommand?.showEngagementPanelEndpoint) {
|
||||
const endpoint = data.rendererContext.commandContext?.onTap?.innertubeCommand?.showEngagementPanelEndpoint;
|
||||
|
||||
this.more_endpoint = {
|
||||
show_engagement_panel_endpoint: {
|
||||
engagement_panel: Parser.parseItem(endpoint.engagementPanel, EngagementPanelSectionList),
|
||||
engagement_panel_popup_type: endpoint.engagementPanelPresentationConfigs.engagementPanelPopupPresentationConfig.popupType,
|
||||
identifier: {
|
||||
surface: endpoint.identifier.surface,
|
||||
tag: endpoint.identifier.tag
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
16
deno/src/parser/classes/DislikeButtonView.ts
Normal file
16
deno/src/parser/classes/DislikeButtonView.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ToggleButtonView from './ToggleButtonView.ts';
|
||||
|
||||
export default class DislikeButtonView extends YTNode {
|
||||
static type = 'DislikeButtonView';
|
||||
|
||||
toggle_button: ToggleButtonView | null;
|
||||
dislike_entity_key: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.toggle_button = Parser.parseItem(data.toggleButtonViewModel, ToggleButtonView);
|
||||
this.dislike_entity_key = data.dislikeEntityKey;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import DropdownItem from './DropdownItem.ts';
|
||||
|
||||
export default class Dropdown extends YTNode {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
export default class DynamicTextView extends YTNode {
|
||||
static type = 'DynamicTextView';
|
||||
|
||||
text: string;
|
||||
text: Text;
|
||||
max_lines: number;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.text = data.text.content;
|
||||
this.text = Text.fromAttributed(data.text);
|
||||
this.max_lines = parseInt(data.maxLines);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ChildElement from './misc/ChildElement.ts';
|
||||
import { type ObservedArray, YTNode, observe } from '../helpers.ts';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser from '../index.ts';
|
||||
import { Parser } from '../index.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
|
||||
export default class Endscreen extends YTNode {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
@@ -1,26 +1,37 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ClipSection from './ClipSection.ts';
|
||||
import ContinuationItem from './ContinuationItem.ts';
|
||||
import EngagementPanelTitleHeader from './EngagementPanelTitleHeader.ts';
|
||||
import MacroMarkersList from './MacroMarkersList.ts';
|
||||
import ProductList from './ProductList.ts';
|
||||
import SectionList from './SectionList.ts';
|
||||
import StructuredDescriptionContent from './StructuredDescriptionContent.ts';
|
||||
import VideoAttributeView from './VideoAttributeView.ts';
|
||||
|
||||
export default class EngagementPanelSectionList extends YTNode {
|
||||
static type = 'EngagementPanelSectionList';
|
||||
|
||||
header: EngagementPanelTitleHeader | null;
|
||||
content: SectionList | ContinuationItem | StructuredDescriptionContent | MacroMarkersList | null;
|
||||
content: VideoAttributeView | SectionList | ContinuationItem | ClipSection | StructuredDescriptionContent | MacroMarkersList | ProductList | null;
|
||||
target_id?: string;
|
||||
panel_identifier?: string;
|
||||
identifier?: {
|
||||
surface: string,
|
||||
tag: string
|
||||
};
|
||||
visibility?: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.header = Parser.parseItem(data.header, EngagementPanelTitleHeader);
|
||||
this.content = Parser.parseItem(data.content, [ SectionList, ContinuationItem, StructuredDescriptionContent, MacroMarkersList ]);
|
||||
this.content = Parser.parseItem(data.content, [ VideoAttributeView, SectionList, ContinuationItem, ClipSection, StructuredDescriptionContent, MacroMarkersList, ProductList ]);
|
||||
this.panel_identifier = data.panelIdentifier;
|
||||
this.identifier = data.identifier ? {
|
||||
surface: data.identifier.surface,
|
||||
tag: data.identifier.tag
|
||||
} : undefined;
|
||||
this.target_id = data.targetId;
|
||||
this.visibility = data.visibility;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Button from './Button.ts';
|
||||
import HorizontalCardList from './HorizontalCardList.ts';
|
||||
import HorizontalList from './HorizontalList.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
@@ -15,7 +16,7 @@ export default class ExpandableMetadata extends YTNode {
|
||||
expanded_title: Text;
|
||||
};
|
||||
|
||||
expanded_content: HorizontalCardList | null;
|
||||
expanded_content: HorizontalCardList | HorizontalList | null;
|
||||
expand_button: Button | null;
|
||||
collapse_button: Button | null;
|
||||
|
||||
@@ -31,7 +32,7 @@ export default class ExpandableMetadata extends YTNode {
|
||||
};
|
||||
}
|
||||
|
||||
this.expanded_content = Parser.parseItem(data.expandedContent, HorizontalCardList);
|
||||
this.expanded_content = Parser.parseItem(data.expandedContent, [ HorizontalCardList, HorizontalList ]);
|
||||
this.expand_button = Parser.parseItem(data.expandButton, Button);
|
||||
this.collapse_button = Parser.parseItem(data.collapseButton, Button);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
export default class ExpandableTab extends YTNode {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
|
||||
export default class ExpandedShelfContents extends YTNode {
|
||||
|
||||
16
deno/src/parser/classes/FancyDismissibleDialog.ts
Normal file
16
deno/src/parser/classes/FancyDismissibleDialog.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import type { RawNode } from '../index.ts';
|
||||
import { Text } from '../misc.ts';
|
||||
|
||||
export default class FancyDismissibleDialog extends YTNode {
|
||||
static type = 'FancyDismissibleDialog';
|
||||
|
||||
dialog_message: Text;
|
||||
confirm_label: Text;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.dialog_message = new Text(data.dialogMessage);
|
||||
this.confirm_label = new Text(data.confirmLabel);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ChipCloudChip from './ChipCloudChip.ts';
|
||||
|
||||
export default class FeedFilterChipBar extends YTNode {
|
||||
|
||||
26
deno/src/parser/classes/FeedNudge.ts
Normal file
26
deno/src/parser/classes/FeedNudge.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
import type { RawNode } from '../types/index.ts';
|
||||
|
||||
export default class FeedNudge extends YTNode {
|
||||
static type = 'FeedNudge';
|
||||
|
||||
title: Text;
|
||||
subtitle: Text;
|
||||
endpoint: NavigationEndpoint;
|
||||
apply_modernized_style: boolean;
|
||||
trim_style: string;
|
||||
background_style: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.title = new Text(data.title);
|
||||
this.subtitle = new Text(data.subtitle);
|
||||
this.endpoint = new NavigationEndpoint(data.impressionEndpoint);
|
||||
this.apply_modernized_style = data.applyModernizedStyle;
|
||||
this.trim_style = data.trimStyle;
|
||||
this.background_style = data.backgroundStyle;
|
||||
}
|
||||
}
|
||||
23
deno/src/parser/classes/FlexibleActionsView.ts
Normal file
23
deno/src/parser/classes/FlexibleActionsView.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import ButtonView from './ButtonView.ts';
|
||||
import ToggleButtonView from './ToggleButtonView.ts';
|
||||
|
||||
export type ActionRow = {
|
||||
actions: ObservedArray<ButtonView | ToggleButtonView>;
|
||||
};
|
||||
|
||||
export default class FlexibleActionsView extends YTNode {
|
||||
static type = 'FlexibleActionsView';
|
||||
|
||||
actions_rows: ActionRow[];
|
||||
style: string;
|
||||
|
||||
constructor(data: RawNode) {
|
||||
super();
|
||||
this.actions_rows = data.actionsRows.map((row: RawNode) => ({
|
||||
actions: Parser.parseArray(row.actions, [ ButtonView, ToggleButtonView ])
|
||||
}));
|
||||
this.style = data.style;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
|
||||
export default class GameCard extends YTNode {
|
||||
static type = 'GameCard';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
|
||||
export default class Grid extends YTNode {
|
||||
static type = 'Grid';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import MetadataBadge from './MetadataBadge.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
import Text from './misc/Text.ts';
|
||||
import Thumbnail from './misc/Thumbnail.ts';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { YTNode, type ObservedArray } from '../helpers.ts';
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import NavigationEndpoint from './NavigationEndpoint.ts';
|
||||
import Menu from './menus/Menu.ts';
|
||||
import Author from './misc/Author.ts';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Parser, { type RawNode } from '../index.ts';
|
||||
import { Parser, type RawNode } from '../index.ts';
|
||||
import HeatMarker from './HeatMarker.ts';
|
||||
import { type ObservedArray, YTNode } from '../helpers.ts';
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user