Compare commits

..

42 Commits

Author SHA1 Message Date
github-actions[bot]
4fb9dff0f2 chore(main): release 9.0.1 (#588)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-25 21:32:45 -03:00
LuanRT
81dd5d3288 fix(build): Circular imports causing issues with webpack 2024-01-25 21:30:14 -03:00
LuanRT
c7f42220db chore: revert unneeded import type changes & lint
Yes. Again.
2024-01-25 21:17:59 -03:00
LuanRT
5204b29e81 chore: Lint 2024-01-25 20:47:19 -03:00
LuanRT
cbaa838cee chore: Revert some unneeded import changes 2024-01-25 20:43:19 -03:00
github-actions[bot]
379e63d2f6 chore(main): release 9.0.0 (#572)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-25 19:04:29 -03:00
Luan
e86a0daf45 refactor(general): Clean up and add a logger (#587)
* feat(utils): Add logger

* chore: Clean up some classes and add more logging

* chore: Fix conflicts
2024-01-25 19:01:28 -03:00
absidue
7fbc37f9d1 fix(PlayerCaptionTracklist): Fix captions_tracks[].kind type (#586) 2024-01-20 01:44:54 -03:00
absidue
2e710dc9f7 feat(Channel): Support getting about with PageHeader (#581) 2024-01-18 14:58:58 -03:00
absidue
fed3512461 fix(DecoratedAvatarView): Fix parsing and optional properties (#584) 2024-01-18 14:55:10 -03:00
absidue
6dd03e1658 feat(toDash)!: Add support for generating manifests for Post Live DVR videos (#580)
BREAKING CHANGES: The `duration` property in `StreamingInfo` has been
replaced by the asynchronous `getDuration()` function, as getting the duration
of Post Live DVR videos requires making a fetch request.
2024-01-18 14:51:42 -03:00
absidue
2073aa910a feat(parser): Add ImageBannerView (#583) 2024-01-18 14:41:08 -03:00
absidue
f7b7bbd47a chore(Constants): Update web client version (#582) 2024-01-18 14:40:15 -03:00
Luan
04d55d04c7 refactor(Playlist): Ignore ContinuationItem nodes from SectionList#contents (#579)
* feat(PlaylistVideo): Add `style`

* refactor(Playlist): Ignore `ContinuationItem` nodes in `SectionList#contents`

This should fix some issues regarding the library fetching the wrong continuation or empty continuations (NOTE: This means the solution in 987f506 no longer applies as empty continuations were all in `SectionList#contents`).
2024-01-18 14:39:25 -03:00
absidue
6082b4a52e feat(Channel): Support PageHeader being used on user channels (#577) 2024-01-12 21:52:02 -03:00
absidue
3980f97b8f fix(proto): Fix visitor data base64url decoding (#576) 2024-01-12 14:42:50 -03:00
absidue
59f4cfb4db fix(toDash): Add missing transfer characteristics for h264 streams (#573) 2024-01-10 20:17:21 -03:00
absidue
254f77944f feat(VideoDetails): Add is_live_dvr_enabled, is_low_latency_live_stream and live_chunk_readahead (#569) 2024-01-10 11:49:14 -03:00
absidue
586bb5f139 feat(Format): Add max_dvr_duration_sec and target_duration_dec (#570) 2024-01-10 11:40:08 -03:00
absidue
562e6a20f0 feat(VideoInfo): Add live stream end_timestamp (#571) 2024-01-10 11:39:47 -03:00
github-actions[bot]
b7cacc34f3 chore(main): release 8.2.0 (#567)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-08 20:46:30 -03:00
Brahim Hadriche
8f07e49512 fix(Parser): Add SortFilterHeader (#563)
* Fix for SortFilterHeader

* fix(Settings): Use `YTNode#is` to identify headers with a title

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2024-01-08 20:37:06 -03:00
Luan
abd8a82cd0 chore(docs): Update auth documentation and examples (#568)
* chore(docs): Update auth documentation and examples

* chore(docs): Minor rewording

* chore(docs): Fix library version in the OAuth2 example
2024-01-08 20:16:16 -03:00
Luan
7ffd0fc25e feat(OAuth): Allow passing custom client identity (#566) 2024-01-08 20:03:01 -03:00
github-actions[bot]
b50408fc1c chore(main): release 8.1.0 (#548)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-12-26 23:24:27 -03:00
Brahim Hadriche
9618f38fe1 fear(parser): Add DecoratedAvatarView (#544)
* Add DecoratedAvatarView

* Export the class

* Update PageHeaderView

* Adjust thumbnails

* Add avatar view

* Apply suggestions from code review

---------

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
2023-12-26 23:21:37 -03:00
LuanRT
e7efec2cf4 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-12-26 23:17:19 -03:00
LuanRT
82d5d1e3e1 chore: Fix import formatting in multiple files 2023-12-26 23:16:45 -03:00
LuanRT
9c503f4fa8 fix(VideoInfo): Restore like, dislike & removeRating methods 2023-12-26 23:15:31 -03:00
RenautMestdagh
4dd977e375 Update interaction-manager.md (#562) 2023-12-26 21:36:55 -03:00
Daniel Wykerd
e4f2a00c84 feat(generator): add support for arrays (#556)
* feat(generator): add support for arrays

* fix(parser): add overload for non array validTypes

Add Parser#parse overload to support non array validTypes.

Fixes issue in generator generating invalid Parser#parse calls
introduced in #551.
2023-12-21 19:02:44 -03:00
absidue
fcd3044982 feat(parser): Support new like and dislike nodes (#557) 2023-12-21 19:02:19 -03:00
Brahim Hadriche
14578ac96a feat(YouTube): Add FEchannels feed (#560) 2023-12-21 19:00:31 -03:00
absidue
5c83e999df fix(Format): Extract correct audio language from captions (#553) 2023-12-07 08:46:05 -03:00
LuanRT
4e67240ff9 chore(FeedNudge): Add Text import 2023-12-04 15:51:09 -03:00
absidue
f938c34ee8 feat(generator): Add support for generating view models (#550) 2023-12-04 15:46:09 -03:00
absidue
bd487f8bef fix(generator): Output Parser.parseItem() calls with one valid type, without the array (#551) 2023-12-04 15:45:38 -03:00
absidue
48a5d4e7c3 feat(Thumbnail): Support sources in Thumbnail.fromResponse (#552) 2023-12-04 13:50:08 -03:00
absidue
37ae55a7c3 chore(protobuf): Commit generated files missing from #512 (#549)
Co-authored-by: Konstantin <duell10111@t-online.de>
2023-12-02 11:35:05 -03:00
LuanRT
923232de07 chore(PlayerConfig): Add default value to some fields 2023-12-01 17:56:25 -03:00
LuanRT
a1c3ef8fbb Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-12-01 17:15:07 -03:00
LuanRT
5c9c231cc2 feat(MediaInfo): Parse player config 2023-12-01 17:14:36 -03:00
116 changed files with 2070 additions and 552 deletions

View File

@@ -1,5 +1,68 @@
# Changelog
## [9.0.1](https://github.com/LuanRT/YouTube.js/compare/v9.0.0...v9.0.1) (2024-01-26)
### Bug Fixes
* **build:** Circular imports causing issues with webpack ([81dd5d3](https://github.com/LuanRT/YouTube.js/commit/81dd5d3288771132e7fb904b620e58277f639ccc))
## [9.0.0](https://github.com/LuanRT/YouTube.js/compare/v8.2.0...v9.0.0) (2024-01-25)
### ⚠ BREAKING CHANGES
* **toDash:** Add support for generating manifests for Post Live DVR videos ([#580](https://github.com/LuanRT/YouTube.js/issues/580))
### Features
* **Channel:** Support getting about with PageHeader ([#581](https://github.com/LuanRT/YouTube.js/issues/581)) ([2e710dc](https://github.com/LuanRT/YouTube.js/commit/2e710dc9f7e206627f189df19be17009b270bc8b))
* **Channel:** Support PageHeader being used on user channels ([#577](https://github.com/LuanRT/YouTube.js/issues/577)) ([6082b4a](https://github.com/LuanRT/YouTube.js/commit/6082b4a52ee07a622735e6e9128a0531a5ae3bfb))
* **Format:** Add `max_dvr_duration_sec` and `target_duration_dec` ([#570](https://github.com/LuanRT/YouTube.js/issues/570)) ([586bb5f](https://github.com/LuanRT/YouTube.js/commit/586bb5f1398d68bfabfb9449f527e53c398c3767))
* **parser:** Add `ImageBannerView` ([#583](https://github.com/LuanRT/YouTube.js/issues/583)) ([2073aa9](https://github.com/LuanRT/YouTube.js/commit/2073aa910a0e441a8ec1a9ba0434051ec0e2e6a9))
* **toDash:** Add support for generating manifests for Post Live DVR videos ([#580](https://github.com/LuanRT/YouTube.js/issues/580)) ([6dd03e1](https://github.com/LuanRT/YouTube.js/commit/6dd03e1658036c2fba0696de81033b5e16abb379))
* **VideoDetails:** Add `is_live_dvr_enabled`, `is_low_latency_live_stream` and `live_chunk_readahead` ([#569](https://github.com/LuanRT/YouTube.js/issues/569)) ([254f779](https://github.com/LuanRT/YouTube.js/commit/254f77944fcd398cc19cb62b82b0fdfbe6ed70ed))
* **VideoInfo:** Add live stream `end_timestamp` ([#571](https://github.com/LuanRT/YouTube.js/issues/571)) ([562e6a2](https://github.com/LuanRT/YouTube.js/commit/562e6a20f06ef5302af427861355215630d91edc))
### Bug Fixes
* **DecoratedAvatarView:** Fix parsing and optional properties ([#584](https://github.com/LuanRT/YouTube.js/issues/584)) ([fed3512](https://github.com/LuanRT/YouTube.js/commit/fed3512461277b7fc41e26c770e2bd3d4a7d5eb5))
* **PlayerCaptionTracklist:** Fix `captions_tracks[].kind` type ([#586](https://github.com/LuanRT/YouTube.js/issues/586)) ([7fbc37f](https://github.com/LuanRT/YouTube.js/commit/7fbc37f9d1c109e448085d5736326dce82ca2c9a))
* **proto:** Fix visitor data base64url decoding ([#576](https://github.com/LuanRT/YouTube.js/issues/576)) ([3980f97](https://github.com/LuanRT/YouTube.js/commit/3980f97b8fca05f95cda1ab347db9402c55b8b3c))
* **toDash:** Add missing transfer characteristics for h264 streams ([#573](https://github.com/LuanRT/YouTube.js/issues/573)) ([59f4cfb](https://github.com/LuanRT/YouTube.js/commit/59f4cfb4db6184d47f0a6634832055e9ce71f644))
## [8.2.0](https://github.com/LuanRT/YouTube.js/compare/v8.1.0...v8.2.0) (2024-01-08)
### Features
* **OAuth:** Allow passing custom client identity ([#566](https://github.com/LuanRT/YouTube.js/issues/566)) ([7ffd0fc](https://github.com/LuanRT/YouTube.js/commit/7ffd0fc25edef99a938e7986b1c74af05b8f954e))
### Bug Fixes
* **Parser:** Add `SortFilterHeader` ([#563](https://github.com/LuanRT/YouTube.js/issues/563)) ([8f07e49](https://github.com/LuanRT/YouTube.js/commit/8f07e49512c59eb72debc80a9d9623ca62330858))
## [8.1.0](https://github.com/LuanRT/YouTube.js/compare/v8.0.0...v8.1.0) (2023-12-27)
### Features
* **generator:** add support for arrays ([#556](https://github.com/LuanRT/YouTube.js/issues/556)) ([e4f2a00](https://github.com/LuanRT/YouTube.js/commit/e4f2a00c843fe453cc7904f79e35597cc6e2e619))
* **generator:** Add support for generating view models ([#550](https://github.com/LuanRT/YouTube.js/issues/550)) ([f938c34](https://github.com/LuanRT/YouTube.js/commit/f938c34ee81186774096b3d24d06250211ce2851))
* **MediaInfo:** Parse player config ([5c9c231](https://github.com/LuanRT/YouTube.js/commit/5c9c231cc2f17c49da03daa8262043b985320e9a))
* **parser:** Support new like and dislike nodes ([#557](https://github.com/LuanRT/YouTube.js/issues/557)) ([fcd3044](https://github.com/LuanRT/YouTube.js/commit/fcd30449821763e9b5b57718dd02eff15d964d2b))
* **Thumbnail:** Support `sources` in `Thumbnail.fromResponse` ([#552](https://github.com/LuanRT/YouTube.js/issues/552)) ([48a5d4e](https://github.com/LuanRT/YouTube.js/commit/48a5d4e7c37b76f8980f9b68e8815aef7a6d91ab))
* **YouTube:** Add FEchannels feed ([#560](https://github.com/LuanRT/YouTube.js/issues/560)) ([14578ac](https://github.com/LuanRT/YouTube.js/commit/14578ac96af4b8bee652cce87d043173de964113))
### Bug Fixes
* **Format:** Extract correct audio language from captions ([#553](https://github.com/LuanRT/YouTube.js/issues/553)) ([5c83e99](https://github.com/LuanRT/YouTube.js/commit/5c83e999dfa00386d18369f42aa9aa10123ba578))
* **generator:** Output Parser.parseItem() calls with one valid type, without the array ([#551](https://github.com/LuanRT/YouTube.js/issues/551)) ([bd487f8](https://github.com/LuanRT/YouTube.js/commit/bd487f8befe7f62022c61ff3aae7f487104e81eb))
* **VideoInfo:** Restore `like`, `dislike` & `removeRating` methods ([9c503f4](https://github.com/LuanRT/YouTube.js/commit/9c503f4fa8a750558cedbeca974faf36e304147e))
## [8.0.0](https://github.com/LuanRT/YouTube.js/compare/v7.0.0...v8.0.0) (2023-12-01)

View File

@@ -37,7 +37,7 @@ Dislikes given video.
| video_id | `string` | Video id |
<a name="removerating"></a>
### removeLike(video_id)
### removeRating(video_id)
Remover like/dislike.
@@ -105,4 +105,4 @@ Only works with channels you are subscribed to.
| Param | Type | Description |
| --- | --- | --- |
| channel_id | `string` | Channel id |
| type | `string` | `PERSONALIZED`, `ALL` or `NONE` |
| type | `string` | `PERSONALIZED`, `ALL` or `NONE` |

View File

@@ -1,8 +1,11 @@
# Authentication via OAuth
# OAuth2
## Usage
## Custom OAuth2 Credentials
Just like the official Data API, YouTube.js supports using your own OAuth2 credentials. A working example can be found [here](https://github.com/LuanRT/YouTube.js/blob/main/examples/auth/custom-oauth2-creds).
Before using any methods which require authentication, you have to authenticate the session:
## YouTube TV OAuth2
The library supports signing in using YouTube TV's client id. This is the recommended way to sign in as it doesn't require you to create your own OAuth2 credentials.
```js
// 'auth-pending' is fired with the info needed to sign in via OAuth.
@@ -25,9 +28,11 @@ yt.session.on('update-credentials', ({ credentials }) => {
await yt.session.signIn(/* credentials */);
```
### Cache Credentials
A working example can be found [here](https://github.com/LuanRT/YouTube.js/blob/main/examples/auth/yttv-oauth2.js).
If you don't wish to sign in every time you start the session, you can cache the credentials. Note that this SHOULD NOT be used in production, save your credentials in a database/file instead and pass them to `Session#signIn(creds?)` when signing in.
## Cache Credentials
If you don't want to start the sign in flow every time you initialize the session, you can cache the credentials. Note that this SHOULD NOT be used in production, save your credentials in a database/file instead and pass them to `Session#signIn(creds?)` when signing in.
```js
// If you use this, the next call to signIn won't fire 'auth-pending' instead just 'auth'
@@ -36,9 +41,9 @@ await yt.session.oauth.cacheCredentials();
**Note:** When using cached credentials, you are still required to make a call to `Session#signIn()`.
### Sign Out
## Sign Out
The sign out method may be used to sign out of the current session. This should also remove the cached credentials.
The sign out method may be used to sign out of the current session. This removes and revokes the credentials.
```js
await yt.session.signOut();
@@ -47,3 +52,14 @@ await yt.session.signOut();
// and only want to delete the cached credentials, use:
await yt.session.oauth.removeCache();
```
# Cookies
> **Note**
> This is not as reliable as OAuth2 as cookies expire and can be completely revoked at any time.
```js
const yt = await Innertube.create({
cookie: '...'
});
```

View File

@@ -0,0 +1,141 @@
import express from 'express';
import { Innertube, UniversalCache, YTNodes } from 'youtubei.js';
import { OAuth2Client } from 'google-auth-library';
const app = express();
let innertube: Innertube | undefined;
let oAuth2Client: OAuth2Client | undefined;
/**
* To get your own client id and secret, visit https://console.developers.google.com/, create a new project,
* and create an OAuth 2.0 Client ID (Web application) under the Credentials tab.
*
* Don't forget to add http://localhost:3000/login as an authorized redirect URI.
*/
const clientId = 'YOUR_OAUTH2_CLIENT_ID';
const clientSecret = 'YOUR_OAUTH2_CLIENT_SECRET';
const redirectUri = 'http://localhost:3000/login';
const port = 3000;
let authorizationUrl: string | undefined;
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true, limit: '3mb' }))
const cache = new UniversalCache(true);
console.info("Cache dir:", cache.cache_dir);
app.get('/', async (_req, res) => {
if (!innertube) {
console.info('Creating innertube instance.');
innertube = await Innertube.create({ cache });
innertube.session.on("update-credentials", async (_credentials) => {
console.info('Credentials updated.');
await innertube?.session.oauth.cacheCredentials();
});
}
if (await cache.get('youtubei_oauth_credentials')) {
await innertube.session.signIn();
}
if (innertube.session.logged_in) {
console.info('Innertube instance is logged in.');
const userInfo = await innertube.account.getInfo();
const library = await innertube.getLibrary();
const html = `
<p>Hello ${userInfo.contents?.contents.first().account_name.text}! You have ${userInfo.contents?.contents.first().account_byline.text} on your YouTube channel.</p>
<p>Email: ${userInfo.contents?.contents.first().endpoint.payload.directSigninUserProfile.email}</p>
<p>Obfuscated Gaia ID: ${userInfo.contents?.contents.first().endpoint.payload.directSigninIdentity.effectiveObfuscatedGaiaId}</p>
<p>Channel URL: <a href="https://www.youtube.com/channel/${userInfo.footers?.endpoint.payload.browseId}">https://www.youtube.com/channel/${userInfo.footers?.endpoint.payload.browseId}</a></p>
<p>Profile Picture:</p>
<img src="${userInfo.contents?.contents.first().account_photo[0].url}" />
<p>Recently watched videos:</p>
<ul>
${library.videos.map((video) => `<li><a href="${video.as(YTNodes.GridVideo).endpoint.toURL()}">${video.title.toString()}</a> by ${video.as(YTNodes.GridVideo).author.name.toString()} - ${video.as(YTNodes.GridVideo).duration?.text}</li>`).join('')}
</ul>
<button onclick="window.location.href = '/logout'">Logout</button>
`;
return res.send(html);
}
if (!oAuth2Client) {
console.info('Creating OAuth2 client.');
oAuth2Client = new OAuth2Client(
clientId,
clientSecret,
redirectUri
);
authorizationUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: [
"http://gdata.youtube.com",
"https://www.googleapis.com/auth/youtube-paid-content"
],
include_granted_scopes: true,
prompt: 'consent',
});
console.info('Redirecting to authorization URL...');
res.redirect(authorizationUrl);
} else if (authorizationUrl) {
console.info('OAuth2 client already exists. Redirecting to authorization URL...');
res.redirect(authorizationUrl);
}
});
app.get('/login', async (req, res) => {
const { code } = req.query;
if (!code) {
return res.send('No code provided.');
}
if (!oAuth2Client || !innertube) {
return res.send('OAuth2 client or innertube instance is not initialized.');
}
const { tokens } = await oAuth2Client.getToken(code as string);
if (tokens.access_token && tokens.refresh_token && tokens.expiry_date) {
await innertube.session.signIn({
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires: new Date(tokens.expiry_date),
client_id: clientId,
client_secret: clientSecret,
});
await innertube.session.oauth.cacheCredentials();
console.log('Logged in successfully. Redirecting to home page...');
res.redirect('/');
}
});
app.get('/logout', async (_req, res) => {
if (!innertube) {
return res.send('Innertube instance is not initialized.');
}
await innertube.session.signOut();
console.log('Logged out successfully. Redirecting to home page...');
res.redirect('/');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

View File

@@ -0,0 +1,20 @@
{
"name": "yt-oauth-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"google-auth-library": "^9.4.1",
"youtubei.js": "^8.1.0"
},
"devDependencies": {
"@types/express": "^4.17.21"
}
}

View File

@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "youtubei.js",
"version": "8.0.0",
"version": "9.0.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "youtubei.js",
"version": "8.0.0",
"version": "9.0.1",
"funding": [
"https://github.com/sponsors/LuanRT"
],

View File

@@ -1,6 +1,6 @@
{
"name": "youtubei.js",
"version": "8.0.0",
"version": "9.0.1",
"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",

View File

@@ -1,29 +1,8 @@
import type { SessionOptions } from './core/Session.js';
import Session from './core/Session.js';
import NavigationEndpoint from './parser/classes/NavigationEndpoint.js';
import type Format from './parser/classes/misc/Format.js';
import Channel from './parser/youtube/Channel.js';
import Comments from './parser/youtube/Comments.js';
import Guide from './parser/youtube/Guide.js';
import HashtagFeed from './parser/youtube/HashtagFeed.js';
import History from './parser/youtube/History.js';
import HomeFeed from './parser/youtube/HomeFeed.js';
import Library from './parser/youtube/Library.js';
import NotificationsMenu from './parser/youtube/NotificationsMenu.js';
import Playlist from './parser/youtube/Playlist.js';
import Search from './parser/youtube/Search.js';
import VideoInfo from './parser/youtube/VideoInfo.js';
import ShortsVideoInfo from './parser/ytshorts/VideoInfo.js';
import { Kids, Music, Studio } from './core/clients/index.js';
import { AccountManager, InteractionManager, PlaylistManager } from './core/managers/index.js';
import { Feed, TabbedFeed } from './core/mixins/index.js';
import * as Proto from './proto/index.js';
import * as Constants from './utils/Constants.js';
import { InnertubeError, generateRandomString, throwIfMissing } from './utils/Utils.js';
import {
BrowseEndpoint,
GetNotificationMenuEndpoint,
@@ -32,16 +11,39 @@ import {
PlayerEndpoint,
ResolveURLEndpoint,
SearchEndpoint,
Reel
Reel,
Notification
} from './core/endpoints/index.js';
import { GetUnseenCountEndpoint } from './core/endpoints/notification/index.js';
import {
Channel,
Comments,
Guide,
HashtagFeed,
History,
HomeFeed,
Library,
NotificationsMenu,
Playlist,
Search,
VideoInfo
} from './parser/youtube/index.js';
import { VideoInfo as ShortsVideoInfo } from './parser/ytshorts/index.js';
import NavigationEndpoint from './parser/classes/NavigationEndpoint.js';
import * as Proto from './proto/index.js';
import * as Constants from './utils/Constants.js';
import { InnertubeError, generateRandomString, throwIfMissing } from './utils/Utils.js';
import type { ApiResponse } from './core/Actions.js';
import { type IBrowseResponse, type IParsedResponse } from './parser/types/index.js';
import type { INextRequest } from './types/index.js';
import type { IBrowseResponse, IParsedResponse } from './parser/types/index.js';
import type { DownloadOptions, FormatOptions } from './types/FormatUtils.js';
import { encodeReelSequence } from './proto/index.js';
import type { SessionOptions } from './core/Session.js';
import type Format from './parser/classes/misc/Format.js';
export type InnertubeConfig = SessionOptions;
@@ -151,7 +153,7 @@ export default class Innertube {
const sequenceResponse = this.actions.execute(
Reel.WatchSequenceEndpoint.PATH, Reel.WatchSequenceEndpoint.build({
sequenceParams: encodeReelSequence(short_id)
sequenceParams: Proto.encodeReelSequence(short_id)
})
);
@@ -261,7 +263,7 @@ export default class Innertube {
}
/**
* Retrieves trending content.
* Retrieves Trending content.
*/
async getTrending(): Promise<TabbedFeed<IBrowseResponse>> {
const response = await this.actions.execute(
@@ -271,7 +273,7 @@ export default class Innertube {
}
/**
* Retrieves subscriptions feed.
* Retrieves Subscriptions feed.
*/
async getSubscriptionsFeed(): Promise<Feed<IBrowseResponse>> {
const response = await this.actions.execute(
@@ -280,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
@@ -308,7 +320,7 @@ 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;
}

View File

@@ -1,7 +1,7 @@
import { Parser, NavigateAction } from '../parser/index.js';
import { InnertubeError } from '../utils/Utils.js';
import type Session from './Session.js';
import type { Session } from './index.js';
import type {
IBrowseResponse, IGetNotificationsMenuResponse,
@@ -167,6 +167,7 @@ export default class Actions {
'FElibrary',
'FEhistory',
'FEsubscriptions',
'FEchannels',
'FEmusic_listening_review',
'FEmusic_library_landing',
'SPaccount_overview',

View File

@@ -1,7 +1,10 @@
import * as Constants from '../utils/Constants.js';
import { Log, Constants } from '../utils/index.js';
import { OAuthError, Platform } from '../utils/Utils.js';
import type Session from './Session.js';
/**
* Represents the credentials used for authentication.
*/
export interface Credentials {
/**
* Token used to sign in.
@@ -15,6 +18,14 @@ export interface Credentials {
* Access token's expiration date, which is usually 24hrs-ish.
*/
expires: Date;
/**
* Optional client ID.
*/
client_id?: string;
/**
* Optional client secret.
*/
client_secret?: string;
}
// TODO: actual type info for this.
@@ -28,7 +39,14 @@ export type OAuthAuthEventHandler = (data: {
export type OAuthAuthPendingEventHandler = (data: OAuthAuthPendingData) => any;
export type OAuthAuthErrorEventHandler = (err: OAuthError) => any;
export type OAuthClientIdentity = {
client_id: string;
client_secret: string;
};
export default class OAuth {
static TAG = 'OAuth';
#identity?: Record<string, string>;
#session: Session;
#credentials?: Credentials;
@@ -71,6 +89,8 @@ export default class OAuth {
this.#credentials = {
access_token: credentials.access_token,
refresh_token: credentials.refresh_token,
client_id: credentials.client_id,
client_secret: credentials.client_secret,
expires: new Date(credentials.expires)
};
@@ -157,6 +177,8 @@ export default class OAuth {
this.#credentials = {
access_token: response_data.access_token,
refresh_token: response_data.refresh_token,
client_id: this.#identity?.client_id,
client_secret: this.#identity?.client_secret,
expires: expiration_date
};
@@ -206,6 +228,8 @@ export default class OAuth {
this.#credentials = {
access_token: response_data.access_token,
refresh_token: response_data.refresh_token || this.#credentials.refresh_token,
client_id: this.#identity.client_id,
client_secret: this.#identity.client_secret,
expires: expiration_date
};
@@ -226,7 +250,15 @@ export default class OAuth {
/**
* Retrieves client identity from YouTube TV.
*/
async #getClientIdentity(): Promise<{ [key: string]: string; }> {
async #getClientIdentity(): Promise<OAuthClientIdentity> {
if (this.#credentials?.client_id && this.credentials?.client_secret) {
Log.info(OAuth.TAG, 'Using custom OAuth2 credentials.\n');
return {
client_id: this.#credentials.client_id,
client_secret: this.credentials.client_secret
};
}
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();
@@ -235,17 +267,21 @@ export default class OAuth {
if (!url_body)
throw new OAuthError('Could not obtain script url.', { status: 'FAILED' });
Log.info(OAuth.TAG, `Got YouTubeTV script URL (${url_body})`);
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;
const groups = client_identity?.groups as OAuthClientIdentity | null;
if (!groups)
throw new OAuthError('Could not obtain client identity.', { status: 'FAILED' });
Log.info(OAuth.TAG, 'OAuth2 credentials retrieved.\n', groups);
return groups;
}

View File

@@ -1,14 +1,13 @@
import { Log, Constants } from '../utils/index.js';
import { Platform, getRandomUserAgent, getStringBetweenStrings, PlayerError } from '../utils/Utils.js';
import * as Constants from '../utils/Constants.js';
import type { ICache } from '../types/Cache.js';
import type { FetchFunction } from '../types/PlatformShim.js';
import type { ICache, FetchFunction } from '../types/index.js';
/**
* Represents YouTube's player script. This is required to decipher signatures.
*/
export default class Player {
static TAG = 'Player';
#nsig_sc;
#sig_sc;
#sig_sc_timestamp;
@@ -17,9 +16,7 @@ export default class Player {
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;
}
@@ -34,11 +31,14 @@ export default class Player {
const player_id = getStringBetweenStrings(js, 'player\\/', '\\/');
Log.info(Player.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) {
Log.info(Player.TAG, 'Found a cached player.');
const cached_player = await Player.fromCache(cache, player_id);
if (cached_player)
return cached_player;
@@ -46,6 +46,8 @@ export default class Player {
const player_url = new URL(`/s/player/${player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE);
Log.info(Player.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,10 +61,11 @@ 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(Player.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);
}
@@ -80,6 +83,8 @@ export default class Player {
sig: args.get('s')
});
Log.info(Player.TAG, `Transformed signature ${args.get('s')} to ${signature}.`);
if (typeof signature !== 'string')
throw new PlayerError('Failed to decipher signature');
@@ -102,11 +107,13 @@ export default class Player {
nsig: n
});
Log.info(Player.TAG, `Transformed nsig ${n} to ${nsig}.`);
if (typeof nsig !== 'string')
throw new PlayerError('Failed to decipher nsig');
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.warn(Player.TAG, 'Could not transform nsig, download may be throttled.\nChanging the InnerTube client to "ANDROID" might help!');
} else if (this_response_nsig_cache) {
this_response_nsig_cache.set(n, nsig);
}
@@ -138,6 +145,10 @@ export default class Player {
break;
}
const result = url_components.toString();
Log.info(Player.TAG, `Full deciphered URL: ${result}`);
return url_components.toString();
}
@@ -204,7 +215,7 @@ 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(Player.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);`;
}
@@ -213,7 +224,7 @@ export default class Player {
const sc = `function descramble_nsig(a) { let b=a.split("")${getStringBetweenStrings(data, 'b=a.split("")', '}return b.join("")}')}} return b.join(""); } descramble_nsig(nsig)`;
if (!sc)
console.warn(new PlayerError('Failed to extract n-token decipher algorithm'));
Log.warn(Player.TAG, 'Failed to extract n-token decipher algorithm');
return sc;
}

View File

@@ -1,16 +1,21 @@
import OAuth from './OAuth.js';
import { Log, EventEmitter, HTTPClient } from '../utils/index.js';
import * as Constants from '../utils/Constants.js';
import EventEmitterLike from '../utils/EventEmitterLike.js';
import * as Proto from '../proto/index.js';
import Actions from './Actions.js';
import Player from './Player.js';
import * as Proto from '../proto/index.js';
import type { ICache } from '../types/Cache.js';
import type { FetchFunction } from '../types/PlatformShim.js';
import HTTPClient from '../utils/HTTPClient.js';
import {
generateRandomString, getRandomUserAgent,
InnertubeError, Platform, SessionError
} from '../utils/Utils.js';
import type { DeviceCategory } from '../utils/Utils.js';
import { generateRandomString, getRandomUserAgent, InnertubeError, Platform, SessionError } from '../utils/Utils.js';
import type { Credentials, OAuthAuthErrorEventHandler, OAuthAuthEventHandler, OAuthAuthPendingEventHandler } from './OAuth.js';
import OAuth from './OAuth.js';
import type { FetchFunction, ICache } from '../types/index.js';
import type {
Credentials, OAuthAuthErrorEventHandler,
OAuthAuthEventHandler, OAuthAuthPendingEventHandler
} from './OAuth.js';
export enum ClientType {
WEB = 'WEB',
@@ -140,10 +145,23 @@ export interface SessionData {
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;
}
/**
* Represents an InnerTube session. This holds all the data needed to make requests to YouTube.
*/
export default class Session extends EventEmitterLike {
export default class Session extends EventEmitter {
static TAG = 'Session';
#api_version: string;
#key: string;
#context: Context;
@@ -226,6 +244,8 @@ export default class Session extends EventEmitterLike {
const session_args = { lang, location, time_zone: tz, device_category, client_name, enable_safety_mode, visitor_data, on_behalf_of_user };
Log.info(Session.TAG, 'Retrieving InnerTube session.');
if (generate_session_locally) {
session_data = this.#generateSessionData(session_args);
} else {
@@ -233,30 +253,29 @@ export default class Session extends EventEmitterLike {
// 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) {
Log.error(Session.TAG, 'Failed to retrieve session data from server. Will try to generate it locally.');
session_data = this.#generateSessionData(session_args);
}
}
Log.info(Session.TAG, 'Got session data.\n', 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;
on_behalf_of_user?: string;
}, fetch: FetchFunction = Platform.shim.fetch): Promise<SessionData> {
static #getVisitorID(visitor_data: string) {
const decoded_visitor_data = Proto.decodeVisitorData(visitor_data);
Log.info(Session.TAG, 'Custom visitor data decoded successfully.\n', decoded_visitor_data);
return decoded_visitor_data.id;
}
static async #retrieveSessionData(options: SessionArgs, fetch: FetchFunction = Platform.shim.fetch): Promise<SessionData> {
const url = new URL('/sw.js_data', Constants.URLS.YT_BASE);
let visitor_id = generateRandomString(11);
if (options.visitor_data) {
const decoded_visitor_data = Proto.decodeVisitorData(options.visitor_data);
visitor_id = decoded_visitor_data.id;
visitor_id = this.#getVisitorID(options.visitor_data);
}
const res = await fetch(url, {
@@ -316,21 +335,11 @@ export default class Session extends EventEmitterLike {
return { context, 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;
on_behalf_of_user?: string;
}): SessionData {
static #generateSessionData(options: SessionArgs): 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;
visitor_id = this.#getVisitorID(options.visitor_data);
}
const context: Context = {

View File

@@ -1,12 +1,7 @@
import { Parser } from '../../parser/index.js';
import Channel from '../../parser/ytkids/Channel.js';
import HomeFeed from '../../parser/ytkids/HomeFeed.js';
import Search from '../../parser/ytkids/Search.js';
import VideoInfo from '../../parser/ytkids/VideoInfo.js';
import type Session from '../Session.js';
import { type ApiResponse } from '../Actions.js';
import { Channel, HomeFeed, Search, VideoInfo } from '../../parser/ytkids/index.js';
import { InnertubeError, generateRandomString } from '../../utils/Utils.js';
import KidsBlocklistPickerItem from '../../parser/classes/ytkids/KidsBlocklistPickerItem.js';
import {
BrowseEndpoint, NextEndpoint,
@@ -15,7 +10,7 @@ import {
import { BlocklistPickerEndpoint } from '../endpoints/kids/index.js';
import KidsBlocklistPickerItem from '../../parser/classes/ytkids/KidsBlocklistPickerItem.js';
import type { Session, ApiResponse } from '../index.js';
export default class Kids {
#session: Session;

View File

@@ -1,12 +1,11 @@
import Album from '../../parser/ytmusic/Album.js';
import Artist from '../../parser/ytmusic/Artist.js';
import Explore from '../../parser/ytmusic/Explore.js';
import HomeFeed from '../../parser/ytmusic/HomeFeed.js';
import Library from '../../parser/ytmusic/Library.js';
import Playlist from '../../parser/ytmusic/Playlist.js';
import Recap from '../../parser/ytmusic/Recap.js';
import Search from '../../parser/ytmusic/Search.js';
import TrackInfo from '../../parser/ytmusic/TrackInfo.js';
import * as Proto from '../../proto/index.js';
import { InnertubeError, generateRandomString, throwIfMissing } from '../../utils/Utils.js';
import {
Album, Artist, Explore,
HomeFeed, Library, Playlist,
Recap, Search, TrackInfo
} from '../../parser/ytmusic/index.js';
import AutomixPreviewVideo from '../../parser/classes/AutomixPreviewVideo.js';
import Message from '../../parser/classes/Message.js';
@@ -18,13 +17,6 @@ import PlaylistPanel from '../../parser/classes/PlaylistPanel.js';
import SearchSuggestionsSection from '../../parser/classes/SearchSuggestionsSection.js';
import SectionList from '../../parser/classes/SectionList.js';
import Tab from '../../parser/classes/Tab.js';
import * as Proto from '../../proto/index.js';
import type { ObservedArray } from '../../parser/helpers.js';
import type { MusicSearchFilters } from '../../types/index.js';
import { InnertubeError, generateRandomString, throwIfMissing } from '../../utils/Utils.js';
import type Actions from '../Actions.js';
import type Session from '../Session.js';
import {
BrowseEndpoint,
@@ -35,6 +27,10 @@ import {
import { GetSearchSuggestionsEndpoint } from '../endpoints/music/index.js';
import type { ObservedArray } from '../../parser/helpers.js';
import type { MusicSearchFilters } from '../../types/index.js';
import type { Actions, Session } from '../index.js';
export default class Music {
#session: Session;
#actions: Actions;

View File

@@ -1,12 +1,10 @@
import * as Proto from '../../proto/index.js';
import * as Constants from '../../utils/Constants.js';
import { Constants } from '../../utils/index.js';
import { InnertubeError, MissingParamError, Platform } from '../../utils/Utils.js';
import { CreateVideoEndpoint } from '../endpoints/upload/index.js';
import type { UpdateVideoMetadataOptions, UploadedVideoMetadataOptions } from '../../types/Clients.js';
import type { ApiResponse } from '../Actions.js';
import type Session from '../Session.js';
import { CreateVideoEndpoint } from '../endpoints/upload/index.js';
import type { ApiResponse, Session } from '../index.js';
interface UploadResult {
status: string;

View File

@@ -1,3 +1,5 @@
import type { Actions, ApiResponse } from '../index.js';
import AccountInfo from '../../parser/youtube/AccountInfo.js';
import Analytics from '../../parser/youtube/Analytics.js';
import Settings from '../../parser/youtube/Settings.js';
@@ -7,9 +9,6 @@ import * as Proto from '../../proto/index.js';
import { InnertubeError } from '../../utils/Utils.js';
import { Account, BrowseEndpoint, Channel } from '../endpoints/index.js';
import type Actions from '../Actions.js';
import type { ApiResponse } from '../Actions.js';
export default class AccountManager {
#actions: Actions;

View File

@@ -1,6 +1,4 @@
import * as Proto from '../../proto/index.js';
import type Actions from '../Actions.js';
import type { ApiResponse } from '../Actions.js';
import { throwIfMissing } from '../../utils/Utils.js';
import { LikeEndpoint, DislikeEndpoint, RemoveLikeEndpoint } from '../endpoints/like/index.js';
@@ -8,6 +6,8 @@ import { SubscribeEndpoint, UnsubscribeEndpoint } from '../endpoints/subscriptio
import { CreateCommentEndpoint, PerformCommentActionEndpoint } from '../endpoints/comment/index.js';
import { ModifyChannelPreferenceEndpoint } from '../endpoints/notification/index.js';
import type { Actions, ApiResponse } from '../index.js';
export default class InteractionManager {
#actions: Actions;

View File

@@ -1,12 +1,12 @@
import Playlist from '../../parser/youtube/Playlist.js';
import type Actions from '../Actions.js';
import type Feed from '../mixins/Feed.js';
import type { EditPlaylistEndpointOptions } from '../../types/index.js';
import { InnertubeError, throwIfMissing } from '../../utils/Utils.js';
import { EditPlaylistEndpoint } from '../endpoints/browse/index.js';
import { BrowseEndpoint } from '../endpoints/index.js';
import { CreateEndpoint, DeleteEndpoint } from '../endpoints/playlist/index.js';
import Playlist from '../../parser/youtube/Playlist.js';
import type { Actions } from '../index.js';
import type { Feed } from '../mixins/index.js';
import type { EditPlaylistEndpointOptions } from '../../types/index.js';
export default class PlaylistManager {
#actions: Actions;

View File

@@ -1,7 +1,5 @@
import type { Memo, ObservedArray, SuperParsedResult, YTNode } from '../../parser/helpers.js';
import { Parser, ReloadContinuationItemsCommand } from '../../parser/index.js';
import { concatMemos, InnertubeError } from '../../utils/Utils.js';
import type Actions from '../Actions.js';
import BackstagePost from '../../parser/classes/BackstagePost.js';
import SharedPost from '../../parser/classes/SharedPost.js';
@@ -27,12 +25,15 @@ import TwoColumnBrowseResults from '../../parser/classes/TwoColumnBrowseResults.
import TwoColumnSearchResults from '../../parser/classes/TwoColumnSearchResults.js';
import WatchCardCompactVideo from '../../parser/classes/WatchCardCompactVideo.js';
import type { ApiResponse, Actions } from '../index.js';
import type {
Memo, ObservedArray,
SuperParsedResult, YTNode
} from '../../parser/helpers.js';
import type MusicQueue from '../../parser/classes/MusicQueue.js';
import type RichGrid from '../../parser/classes/RichGrid.js';
import type SectionList from '../../parser/classes/SectionList.js';
import type { IParsedResponse } from '../../parser/types/index.js';
import type { ApiResponse } from '../Actions.js';
export default class Feed<T extends IParsedResponse = IParsedResponse> {
#page: T;
@@ -212,10 +213,10 @@ export default class Feed<T extends IParsedResponse = IParsedResponse> {
#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).filter(
(continuation) => !header_continuations.includes(continuation)
) as ObservedArray<ContinuationItem>;
}
return this.#memo.getType(ContinuationItem);
}
}

View File

@@ -1,12 +1,11 @@
import Feed from './Feed.js';
import ChipCloudChip from '../../parser/classes/ChipCloudChip.js';
import FeedFilterChipBar from '../../parser/classes/FeedFilterChipBar.js';
import { InnertubeError } from '../../utils/Utils.js';
import Feed from './Feed.js';
import type { ObservedArray } from '../../parser/helpers.js';
import type { IParsedResponse } from '../../parser/types/ParsedResponse.js';
import type Actions from '../Actions.js';
import type { ApiResponse } from '../Actions.js';
import type { IParsedResponse } from '../../parser/types/index.js';
import type { ApiResponse, Actions } from '../index.js';
export default class FilterableFeed<T extends IParsedResponse> extends Feed<T> {
#chips?: ObservedArray<ChipCloudChip>;

View File

@@ -1,17 +1,16 @@
import type { ApiResponse } from '../Actions.js';
import type Actions from '../Actions.js';
import * as Constants from '../../utils/Constants.js';
import type { DownloadOptions, FormatFilter, FormatOptions, URLTransformer } from '../../types/FormatUtils.js';
import * as FormatUtils from '../../utils/FormatUtils.js';
import { Constants, FormatUtils } from '../../utils/index.js';
import { InnertubeError } from '../../utils/Utils.js';
import type Format from '../../parser/classes/misc/Format.js';
import type { INextResponse, IPlayerResponse } from '../../parser/index.js';
import { Parser } from '../../parser/index.js';
import type { DashOptions } from '../../types/DashOptions.js';
import PlayerStoryboardSpec from '../../parser/classes/PlayerStoryboardSpec.js';
import { getStreamingInfo } from '../../utils/StreamingInfo.js';
import { Parser } from '../../parser/index.js';
import { TranscriptInfo } from '../../parser/youtube/index.js';
import ContinuationItem from '../../parser/classes/ContinuationItem.js';
import TranscriptInfo from '../../parser/youtube/TranscriptInfo.js';
import type { ApiResponse, Actions } from '../index.js';
import type { INextResponse, IPlayerConfig, IPlayerResponse } from '../../parser/index.js';
import type { DownloadOptions, FormatFilter, FormatOptions, URLTransformer } from '../../types/FormatUtils.js';
import type Format from '../../parser/classes/misc/Format.js';
import type { DashOptions } from '../../types/DashOptions.js';
export default class MediaInfo {
#page: [IPlayerResponse, INextResponse?];
@@ -20,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;
@@ -35,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;
}
@@ -48,17 +49,17 @@ export default class MediaInfo {
async toDash(url_transformer?: URLTransformer, format_filter?: FormatFilter, options: DashOptions = { include_thumbnails: false }): Promise<string> {
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('Generating DASH manifests for live and Post-Live-DVR 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.');
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.');
}
let storyboards;
if (options.include_thumbnails && player_response.storyboards?.is(PlayerStoryboardSpec)) {
if (options.include_thumbnails && player_response.storyboards) {
storyboards = player_response.storyboards;
}
return FormatUtils.toDash(this.streaming_data, url_transformer, format_filter, this.#cpn, this.#actions.session.player, this.#actions, storyboards);
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);
}
/**
@@ -67,12 +68,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
);
}

View File

@@ -1,11 +1,10 @@
import Tab from '../../parser/classes/Tab.js';
import Feed from './Feed.js';
import { Feed } from './index.js';
import { InnertubeError } from '../../utils/Utils.js';
import Tab from '../../parser/classes/Tab.js';
import type Actions from '../Actions.js';
import type { Actions, ApiResponse } from '../index.js';
import type { ObservedArray } from '../../parser/helpers.js';
import type { IParsedResponse } from '../../parser/types/ParsedResponse.js';
import type { ApiResponse } from '../Actions.js';
export default class TabbedFeed<T extends IParsedResponse> extends Feed<T> {
#tabs?: ObservedArray<Tab>;

View File

@@ -0,0 +1,17 @@
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import Text from './misc/Text.js';
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);
}
}

View File

@@ -0,0 +1,26 @@
import { YTNode } from '../helpers.js';
import { type RawNode } from '../index.js';
import { Thumbnail } from '../misc.js';
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;
}
}

View File

@@ -1,3 +1,4 @@
import { Log } from '../../utils/index.js';
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import Button from './Button.js';
@@ -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;
}
}

View File

@@ -1,3 +1,4 @@
import { Log } from '../../utils/index.js';
import { YTNode, type ObservedArray } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import Button from './Button.js';
@@ -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;
}
}

View File

@@ -15,6 +15,6 @@ export default class ChannelExternalLinkView extends YTNode {
this.title = Text.fromAttributed(data.title);
this.link = Text.fromAttributed(data.link);
this.favicon = data.favicon.sources.map((x: any) => new Thumbnail(x)).sort((a: Thumbnail, b: Thumbnail) => b.width - a.width);
this.favicon = Thumbnail.fromResponse(data.favicon);
}
}

View File

@@ -1,6 +1,7 @@
import Text from './misc/Text.js';
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import { Log } from '../../utils/index.js';
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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,21 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import NavigationEndpoint from './NavigationEndpoint.js';
import AvatarView from './AvatarView.js';
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);
}
}
}

View File

@@ -0,0 +1,47 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import EngagementPanelSectionList from './EngagementPanelSectionList.js';
import Text from './misc/Text.js';
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
}
}
};
}
}
}

View File

@@ -0,0 +1,16 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import ToggleButtonView from './ToggleButtonView.js';
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;
}
}

View File

@@ -1,13 +1,16 @@
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import Text from './misc/Text.js';
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);
}
}

View File

@@ -1,5 +1,6 @@
import { YTNode } from '../helpers.js';
import { NavigationEndpoint } from '../nodes.js';
import NavigationEndpoint from './NavigationEndpoint.js';
import Text from './misc/Text.js';
import type { RawNode } from '../types/index.js';

View File

@@ -1,4 +1,5 @@
import NavigationEndpoint from './NavigationEndpoint.js';
import Thumbnail from './misc/Thumbnail.js';
import { YTNode, observe } from '../helpers.js';
import { type RawNode } from '../index.js';
@@ -6,11 +7,7 @@ export class Panel extends YTNode {
static type = 'Panel';
thumbnail?: {
image: {
url: string;
width: number;
height: number;
}[];
image: Thumbnail[];
endpoint: NavigationEndpoint;
on_long_press_endpoint: NavigationEndpoint;
content_mode: string;
@@ -18,16 +15,8 @@ export class Panel extends YTNode {
};
background_image: {
image: {
url: string;
width: number;
height: number;
}[];
gradient_image: {
url: string;
width: number;
height: number;
}[];
image: Thumbnail[];
gradient_image: Thumbnail[];
};
strapline: string;
@@ -48,7 +37,7 @@ export class Panel extends YTNode {
if (data.thumbnail) {
this.thumbnail = {
image: data.thumbnail.image.sources,
image: Thumbnail.fromResponse(data.thumbnail.image),
endpoint: new NavigationEndpoint(data.thumbnail.onTap),
on_long_press_endpoint: new NavigationEndpoint(data.thumbnail.onLongPress),
content_mode: data.thumbnail.contentMode,
@@ -57,8 +46,8 @@ export class Panel extends YTNode {
}
this.background_image = {
image: data.backgroundImage.image.sources,
gradient_image: data.backgroundImage.gradientImage.sources
image: Thumbnail.fromResponse(data.backgroundImage.image),
gradient_image: Thumbnail.fromResponse(data.backgroundImage.gradientImage)
};
this.strapline = data.strapline;

View File

@@ -0,0 +1,16 @@
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import Thumbnail from './misc/Thumbnail.js';
export default class ImageBannerView extends YTNode {
static type = 'ImageBannerView';
image: Thumbnail[];
style: string;
constructor(data: RawNode) {
super();
this.image = Thumbnail.fromResponse(data.image);
this.style = data.style;
}
}

View File

@@ -3,18 +3,19 @@ import { Parser, type RawNode } from '../index.js';
import ItemSectionHeader from './ItemSectionHeader.js';
import ItemSectionTabbedHeader from './ItemSectionTabbedHeader.js';
import CommentsHeader from './comments/CommentsHeader.js';
import SortFilterHeader from './SortFilterHeader.js';
export default class ItemSection extends YTNode {
static type = 'ItemSection';
header: CommentsHeader | ItemSectionHeader | ItemSectionTabbedHeader | null;
header: CommentsHeader | ItemSectionHeader | ItemSectionTabbedHeader | SortFilterHeader | null;
contents: ObservedArray<YTNode>;
target_id?: string;
continuation?: string;
constructor(data: RawNode) {
super();
this.header = Parser.parseItem(data.header, [ CommentsHeader, ItemSectionHeader, ItemSectionTabbedHeader ]);
this.header = Parser.parseItem(data.header, [ CommentsHeader, ItemSectionHeader, ItemSectionTabbedHeader, SortFilterHeader ]);
this.contents = Parser.parseArray(data.contents);
if (data.targetId || data.sectionIdentifier) {

View File

@@ -0,0 +1,24 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import ToggleButtonView from './ToggleButtonView.js';
export default class LikeButtonView extends YTNode {
static type = 'LikeButtonView';
toggle_button: ToggleButtonView | null;
like_status_entity_key: string;
like_status_entity: {
key: string,
like_status: string
};
constructor(data: RawNode) {
super();
this.toggle_button = Parser.parseItem(data.toggleButtonViewModel, ToggleButtonView);
this.like_status_entity_key = data.likeStatusEntityKey;
this.like_status_entity = {
key: data.likeStatusEntity.key,
like_status: data.likeStatusEntity.likeStatus
};
}
}

View File

@@ -0,0 +1,19 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import Button from './Button.js';
import Text from './misc/Text.js';
export default class ModalWithTitleAndButton extends YTNode {
static type = 'ModalWithTitleAndButton';
title: Text;
content: Text;
button: Button | null;
constructor(data: RawNode) {
super();
this.title = new Text(data.title);
this.content = new Text(data.content);
this.button = Parser.parseItem(data.button, Button);
}
}

View File

@@ -1,4 +1,5 @@
import NavigationEndpoint from './NavigationEndpoint.js';
import Thumbnail from './misc/Thumbnail.js';
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
@@ -21,11 +22,7 @@ class ActionButton {
class Panel {
static type = 'Panel';
image: {
url: string;
width: number;
height: number;
}[];
image: Thumbnail[];
content_mode: string;
crop_options: string;
@@ -34,7 +31,7 @@ class Panel {
action_buttons: ActionButton[];
constructor (data: RawNode) {
this.image = data.image.image.sources;
this.image = Thumbnail.fromResponse(data.image.image);
this.content_mode = data.image.contentMode;
this.crop_options = data.image.cropOptions;
this.image_aspect_ratio = data.imageAspectRatio;

View File

@@ -4,6 +4,7 @@ import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import type { IParsedResponse } from '../types/ParsedResponse.js';
import CreatePlaylistDialog from './CreatePlaylistDialog.js';
import type ModalWithTitleAndButton from './ModalWithTitleAndButton.js';
import OpenPopupAction from './actions/OpenPopupAction.js';
export default class NavigationEndpoint extends YTNode {
@@ -11,8 +12,11 @@ export default class NavigationEndpoint extends YTNode {
payload;
dialog?: CreatePlaylistDialog | YTNode | null;
modal?: ModalWithTitleAndButton | YTNode | null;
open_popup?: OpenPopupAction | null;
next_endpoint?: NavigationEndpoint;
metadata: {
url?: string;
api_url?: string;
@@ -41,6 +45,13 @@ export default class NavigationEndpoint extends YTNode {
this.dialog = Parser.parseItem(this.payload.dialog || this.payload.content);
}
if (Reflect.has(this.payload, 'modal')) {
this.modal = Parser.parseItem(this.payload.modal);
}
if (Reflect.has(this.payload, 'nextEndpoint')) {
this.next_endpoint = new NavigationEndpoint(this.payload.nextEndpoint);
}
if (data?.serviceEndpoint) {
data = data.serviceEndpoint;

View File

@@ -2,22 +2,32 @@ import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import ContentMetadataView from './ContentMetadataView.js';
import ContentPreviewImageView from './ContentPreviewImageView.js';
import DecoratedAvatarView from './DecoratedAvatarView.js';
import DynamicTextView from './DynamicTextView.js';
import FlexibleActionsView from './FlexibleActionsView.js';
import DescriptionPreviewView from './DescriptionPreviewView.js';
import AttributionView from './AttributionView.js';
import ImageBannerView from './ImageBannerView.js';
export default class PageHeaderView extends YTNode {
static type = 'PageHeaderView';
title: DynamicTextView | null;
image: ContentPreviewImageView | null;
image: ContentPreviewImageView | DecoratedAvatarView | null;
metadata: ContentMetadataView | null;
actions: FlexibleActionsView | null;
description: DescriptionPreviewView | null;
attributation: AttributionView | null;
banner: ImageBannerView | null;
constructor(data: RawNode) {
super();
this.title = Parser.parseItem(data.title, DynamicTextView);
this.image = Parser.parseItem(data.image, ContentPreviewImageView);
this.image = Parser.parseItem(data.image, [ ContentPreviewImageView, DecoratedAvatarView ]);
this.metadata = Parser.parseItem(data.metadata, ContentMetadataView);
this.actions = Parser.parseItem(data.actions, FlexibleActionsView);
this.description = Parser.parseItem(data.description, DescriptionPreviewView);
this.attributation = Parser.parseItem(data.attributation, AttributionView);
this.banner = Parser.parseItem(data.banner, ImageBannerView);
}
}

View File

@@ -10,7 +10,7 @@ export default class PlayerCaptionsTracklist extends YTNode {
name: Text;
vss_id: string;
language_code: string;
kind: string;
kind?: 'asr' | 'frc';
is_translatable: boolean;
}[];

View File

@@ -1,11 +1,32 @@
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
export interface LiveStoryboardData {
type: 'live',
template_url: string,
thumbnail_width: number,
thumbnail_height: number,
columns: number,
rows: number
}
export default class PlayerLiveStoryboardSpec extends YTNode {
static type = 'PlayerLiveStoryboardSpec';
constructor() {
board: LiveStoryboardData;
constructor(data: RawNode) {
super();
// TODO: A little bit different from PlayerLiveStoryboardSpec
// https://i.ytimg.com/sb/5qap5aO4i9A/storyboard_live_90_2x2_b2/M$M.jpg?rs=AOn4CLC9s6IeOsw_gKvEbsbU9y-e2FVRTw#159#90#2#2
const [ template_url, thumbnail_width, thumbnail_height, columns, rows ] = data.spec.split('#');
this.board = {
type: 'live',
template_url,
thumbnail_width: parseInt(thumbnail_width, 10),
thumbnail_height: parseInt(thumbnail_height, 10),
columns: parseInt(columns, 10),
rows: parseInt(rows, 10)
};
}
}

View File

@@ -36,6 +36,7 @@ export default class PlayerMicroformat extends YTNode {
upload_date: string;
available_countries: string[];
start_timestamp: Date | null;
end_timestamp: Date | null;
constructor(data: RawNode) {
super();
@@ -70,5 +71,6 @@ export default class PlayerMicroformat extends YTNode {
this.upload_date = data.uploadDate;
this.available_countries = data.availableCountries;
this.start_timestamp = data.liveBroadcastDetails?.startTimestamp ? new Date(data.liveBroadcastDetails.startTimestamp) : null;
this.end_timestamp = data.liveBroadcastDetails?.endTimestamp ? new Date(data.liveBroadcastDetails.endTimestamp) : null;
}
}

View File

@@ -2,6 +2,7 @@ import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
export interface StoryboardData {
type: 'vod'
template_url: string;
thumbnail_width: number;
thumbnail_height: number;
@@ -31,6 +32,7 @@ export default class PlayerStoryboardSpec extends YTNode {
const storyboard_count = Math.ceil(parseInt(thumbnail_count, 10) / (parseInt(columns, 10) * parseInt(rows, 10)));
return {
type: 'vod',
template_url: url.toString().replace('$L', i).replace('$N', name),
thumbnail_width: parseInt(thumbnail_width, 10),
thumbnail_height: parseInt(thumbnail_height, 10),

View File

@@ -23,6 +23,7 @@ export default class PlaylistVideo extends YTNode {
upcoming?: Date;
video_info: Text;
accessibility_label?: string;
style?: string;
duration: {
text: string;
@@ -44,6 +45,10 @@ export default class PlaylistVideo extends YTNode {
this.video_info = new Text(data.videoInfo);
this.accessibility_label = data.title.accessibility.accessibilityData.label;
if (Reflect.has(data, 'style')) {
this.style = data.style;
}
const upcoming = data.upcomingEventData && Number(`${data.upcomingEventData.startTime}000`);
if (upcoming) {
this.upcoming = new Date(upcoming);

View File

@@ -1,4 +1,4 @@
import type { ObservedArray} from '../helpers.js';
import type { ObservedArray } from '../helpers.js';
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import { Parser } from '../index.js';

View File

@@ -0,0 +1,56 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import LikeButtonView from './LikeButtonView.js';
import DislikeButtonView from './DislikeButtonView.js';
export default class SegmentedLikeDislikeButtonView extends YTNode {
static type = 'SegmentedLikeDislikeButtonView';
like_button: LikeButtonView | null;
dislike_button: DislikeButtonView | null;
icon_type: string;
like_count_entity: {
key: string
};
dynamic_like_count_update_data: {
update_status_key: string,
placeholder_like_count_values_key: string,
update_delay_loop_id: string,
update_delay_sec: number
};
like_count?: number;
short_like_count?: string;
constructor(data: RawNode) {
super();
this.like_button = Parser.parseItem(data.likeButtonViewModel, LikeButtonView);
this.dislike_button = Parser.parseItem(data.dislikeButtonViewModel, DislikeButtonView);
this.icon_type = data.iconType;
if (this.like_button && this.like_button.toggle_button) {
const toggle_button = this.like_button.toggle_button;
if (toggle_button.default_button) {
this.short_like_count = toggle_button.default_button.title;
this.like_count = parseInt(toggle_button.default_button.accessibility_text.replace(/\D/g, ''));
} else if (toggle_button.toggled_button) {
this.short_like_count = toggle_button.toggled_button.title;
this.like_count = parseInt(toggle_button.toggled_button.accessibility_text.replace(/\D/g, ''));
}
}
this.like_count_entity = {
key: data.likeCountEntity.key
};
this.dynamic_like_count_update_data = {
update_status_key: data.dynamicLikeCountUpdateData.updateStatusKey,
placeholder_like_count_values_key: data.dynamicLikeCountUpdateData.placeholderLikeCountValuesKey,
update_delay_loop_id: data.dynamicLikeCountUpdateData.updateDelayLoopId,
update_delay_sec: data.dynamicLikeCountUpdateData.updateDelaySec
};
}
}

View File

@@ -0,0 +1,13 @@
import { YTNode } from '../helpers.js';
import { Parser, YTNodes, type RawNode } from '../index.js';
export default class SortFilterHeader extends YTNode {
static type = 'SortFilterHeader';
filter_menu: YTNodes.SortFilterSubMenu | null;
constructor(data: RawNode) {
super();
this.filter_menu = Parser.parseItem(data.filterMenu, YTNodes.SortFilterSubMenu);
}
}

View File

@@ -0,0 +1,20 @@
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';
import ButtonView from './ButtonView.js';
export default class ToggleButtonView extends YTNode {
static type = 'ToggleButtonView';
default_button: ButtonView | null;
toggled_button: ButtonView | null;
identifier?: string;
is_toggling_disabled: boolean;
constructor(data: RawNode) {
super();
this.default_button = Parser.parseItem(data.defaultButtonViewModel, ButtonView);
this.toggled_button = Parser.parseItem(data.toggledButtonViewModel, ButtonView);
this.identifier = data.identifier;
this.is_toggling_disabled = data.isTogglingDisabled;
}
}

View File

@@ -10,9 +10,7 @@ import Thumbnail from './misc/Thumbnail.js';
export default class VideoAttributeView extends YTNode {
static type = 'VideoAttributeView';
image: ContentPreviewImageView | {
sources: Thumbnail[];
} | null;
image: ContentPreviewImageView | Thumbnail[] | null;
image_style: string;
title: string;
subtitle: string;
@@ -26,11 +24,9 @@ export default class VideoAttributeView extends YTNode {
constructor(data: RawNode) {
super();
// @NOTE: "image" is not a renderer so not sure why we're parsing it as one. Leaving this hack here for now to avoid breaking things.
if (data.image?.sources) {
this.image = {
sources: data.image.sources.map((x: any) => new Thumbnail(x)).sort((a: Thumbnail, b: Thumbnail) => b.width - a.width)
};
this.image = Thumbnail.fromResponse(data.image);
} else {
this.image = Parser.parseItem(data.image, ContentPreviewImageView);
}

View File

@@ -1,4 +1,4 @@
import type { ObservedArray} from '../helpers.js';
import type { ObservedArray } from '../helpers.js';
import { YTNode } from '../helpers.js';
import type { RawNode } from '../index.js';
import { Parser } from '../index.js';

View File

@@ -1,4 +1,4 @@
import type { ObservedArray} from '../helpers.js';
import type { ObservedArray } from '../helpers.js';
import { YTNode } from '../helpers.js';
import { Parser, type RawNode } from '../index.js';

View File

@@ -1,5 +1,5 @@
import { Parser } from '../../index.js';
import type { ObservedArray} from '../../helpers.js';
import type { ObservedArray } from '../../helpers.js';
import { YTNode } from '../../helpers.js';
import type { RawNode } from '../../index.js';

View File

@@ -1,4 +1,4 @@
import type { ObservedArray} from '../../helpers.js';
import type { ObservedArray } from '../../helpers.js';
import { YTNode } from '../../helpers.js';
import type { RawNode } from '../../index.js';
import { Parser } from '../../index.js';

View File

@@ -1,4 +1,4 @@
import type { ObservedArray} from '../../helpers.js';
import type { ObservedArray } from '../../helpers.js';
import { YTNode } from '../../helpers.js';
import type { RawNode } from '../../index.js';
import { Parser } from '../../index.js';

View File

@@ -1,4 +1,4 @@
import type { SuperParsedResult} from '../../helpers.js';
import type { SuperParsedResult } from '../../helpers.js';
import { YTNode } from '../../helpers.js';
import type { RawNode } from '../../index.js';
import { Parser } from '../../index.js';

View File

@@ -41,6 +41,8 @@ export default class Format {
audio_sample_rate?: number;
audio_channels?: number;
loudness_db?: number;
max_dvr_duration_sec?: number;
target_duration_dec?: number;
has_audio: boolean;
has_video: boolean;
language?: string | null;
@@ -90,6 +92,8 @@ export default class Format {
this.audio_sample_rate = parseInt(data.audioSampleRate);
this.audio_channels = data.audioChannels;
this.loudness_db = data.loudnessDb;
this.max_dvr_duration_sec = data.maxDvrDurationSec;
this.target_duration_dec = data.targetDurationSec;
this.has_audio = !!data.audioBitrate || !!data.audioQuality;
this.has_video = !!data.qualityLabel;

View File

@@ -15,7 +15,20 @@ export default class Thumbnail {
* Get thumbnails from response object.
*/
static fromResponse(data: any): Thumbnail[] {
if (!data || !data.thumbnails) return [];
return data.thumbnails.map((x: any) => new Thumbnail(x)).sort((a: Thumbnail, b: Thumbnail) => b.width - a.width);
if (!data) return [];
let thumbnail_data;
if (data.thumbnails) {
thumbnail_data = data.thumbnails;
} else if (data.sources) {
thumbnail_data = data.sources;
}
if (thumbnail_data) {
return thumbnail_data.map((x: any) => new Thumbnail(x)).sort((a: Thumbnail, b: Thumbnail) => b.width - a.width);
}
return [];
}
}

View File

@@ -16,9 +16,12 @@ export default class VideoDetails {
is_private: boolean;
is_live: boolean;
is_live_content: boolean;
is_live_dvr_enabled: boolean;
is_upcoming: boolean;
is_crawlable: boolean;
is_post_live_dvr: boolean;
is_low_latency_live_stream: boolean;
live_chunk_readahead?: number;
constructor(data: RawNode) {
this.id = data.videoId;
@@ -35,8 +38,11 @@ export default class VideoDetails {
this.is_private = !!data.isPrivate;
this.is_live = !!data.isLive;
this.is_live_content = !!data.isLiveContent;
this.is_live_dvr_enabled = !!data.isLiveDvrEnabled;
this.is_low_latency_live_stream = !!data.isLowLatencyLiveStream;
this.is_upcoming = !!data.isUpcoming;
this.is_post_live_dvr = !!data.isPostLiveDvr;
this.is_crawlable = !!data.isCrawlable;
this.live_chunk_readahead = data.liveChunkReadahead;
}
}

View File

@@ -1,10 +1,11 @@
import type { ObservedArray } from './helpers.js';
import { YTNode, observe } from './helpers.js';
import type { RawNode } from './index.js';
import { Thumbnail } from './misc.js';
import { NavigationEndpoint, LiveChatItemList, LiveChatHeader, LiveChatParticipantsList, Message } from './nodes.js';
import * as Parser from './parser.js';
import type { RawNode } from './index.js';
import type { ObservedArray } from './helpers.js';
export class ItemSectionContinuation extends YTNode {
static readonly type = 'itemSectionContinuation';

View File

@@ -1,12 +1,14 @@
/* eslint-disable no-cond-assign */
import { YTNode } from './helpers.js';
import * as Parser from './parser.js';
import { InnertubeError } from '../utils/Utils.js';
import Author from './classes/misc/Author.js';
import Text from './classes/misc/Text.js';
import Thumbnail from './classes/misc/Thumbnail.js';
import NavigationEndpoint from './classes/NavigationEndpoint.js';
import type { YTNodeConstructor } from './helpers.js';
import { YTNode } from './helpers.js';
import * as Parser from './parser.js';
export type MiscInferenceType = {
type: 'misc',
@@ -30,27 +32,43 @@ export type MiscInferenceType = {
params: [string, string?],
}
export type InferenceType = {
type: 'renderer',
renderers: string[],
optional: boolean,
} | {
type: 'renderer_list',
renderers: string[],
optional: boolean,
} | MiscInferenceType | {
export interface ObjectInferenceType {
type: 'object',
keys: KeyInfo,
optional: boolean,
} | {
}
export interface RendererInferenceType {
type: 'renderer',
renderers: string[],
optional: boolean
}
export interface PrimativeInferenceType {
type: 'primative',
typeof: ('string' | 'number' | 'boolean' | 'bigint' | 'symbol' | 'undefined' | 'function')[],
optional: boolean,
} | {
type: 'unknown',
typeof: ('string' | 'number' | 'boolean' | 'bigint' | 'symbol' | 'undefined' | 'function' | 'never' | 'unknown')[],
optional: boolean,
}
export type ArrayInferenceType = {
type: 'array',
array_type: 'primitive',
items: PrimativeInferenceType,
optional: boolean,
} | {
type: 'array',
array_type: 'object',
items: ObjectInferenceType,
optional: boolean,
} | {
type: 'array',
array_type: 'renderer',
renderers: string[],
optional: boolean,
};
export type InferenceType = RendererInferenceType | MiscInferenceType | ObjectInferenceType | PrimativeInferenceType | ArrayInferenceType;
export type KeyInfo = (readonly [string, InferenceType])[];
const IGNORED_KEYS = new Set([
@@ -70,7 +88,7 @@ export function camelToSnake(str: string) {
* @returns The inferred type
*/
export function inferType(key: string, value: unknown): InferenceType {
let return_value: string | Record<string, any> | boolean | MiscInferenceType = false;
let return_value: string | Record<string, any> | false | MiscInferenceType | ArrayInferenceType = false;
if (typeof value === 'object' && value != null) {
if (return_value = isRenderer(value)) {
RENDERER_EXAMPLES[return_value] = Reflect.get(value, Reflect.ownKeys(value)[0]);
@@ -85,7 +103,8 @@ export function inferType(key: string, value: unknown): InferenceType {
RENDERER_EXAMPLES[key] = value;
}
return {
type: 'renderer_list',
type: 'array',
array_type: 'renderer',
renderers: Object.keys(return_value),
optional: false
};
@@ -93,6 +112,9 @@ export function inferType(key: string, value: unknown): InferenceType {
if (return_value = isMiscType(key, value)) {
return return_value as MiscInferenceType;
}
if (return_value = isArrayType(value)) {
return return_value as ArrayInferenceType;
}
}
const primative_type = typeof value;
if (primative_type === 'object')
@@ -116,6 +138,9 @@ export function inferType(key: string, value: unknown): InferenceType {
*/
export function isRendererList(value: unknown) {
const arr = Array.isArray(value);
if (arr && value.length === 0)
return false;
const is_list = arr && value.every((item) => isRenderer(item));
return (
is_list ?
@@ -176,12 +201,89 @@ export function isRenderer(value: unknown) {
const is_object = typeof value === 'object';
if (!is_object) return false;
const keys = Reflect.ownKeys(value as object);
if (keys.length === 1 && keys[0].toString().includes('Renderer')) {
return Parser.sanitizeClassName(keys[0].toString());
if (keys.length === 1) {
const first_key = keys[0].toString();
if (first_key.endsWith('Renderer') || first_key.endsWith('Model')) {
return Parser.sanitizeClassName(first_key);
}
}
return false;
}
/**
* Checks if the given value is an array
* @param value - The value to check
* @returns If it is an array, return the InferenceType. Otherwise, return false.
*/
export function isArrayType(value: unknown): false | ArrayInferenceType {
if (!Array.isArray(value))
return false;
// If the array is empty, we can't infer anything
if (value.length === 0)
return {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ 'never' ],
optional: false
},
optional: false
};
// We'll infer the primative type of the array entries
const array_entry_types = value.map((item) => typeof item);
// We only support arrays that have the same primative type throughout
const all_same_type = array_entry_types.every((type) => type === array_entry_types[0]);
if (!all_same_type)
return {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ 'unknown' ],
optional: false
},
optional: false
};
const type = array_entry_types[0];
if (type !== 'object')
return {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ type ],
optional: false
},
optional: false
};
let key_type: KeyInfo = [];
for (let i = 0; i < value.length; i++) {
const current_keys = Object.entries(value[i] as object).map(([ key, value ]) => [ key, inferType(key, value) ] as const);
if (i === 0) {
key_type = current_keys;
continue;
}
key_type = mergeKeyInfo(key_type, current_keys).resolved_key_info;
}
return {
type: 'array',
array_type: 'object',
items: {
type: 'object',
keys: key_type,
optional: false
},
optional: false
};
}
function introspectKeysFirstPass(classdata: unknown): KeyInfo {
if (typeof classdata !== 'object' || classdata === null) {
throw new InnertubeError('Generator: Cannot introspect non-object', {
@@ -236,7 +338,7 @@ function introspectKeysSecondPass(key_info: KeyInfo) {
// Verify that its actually badges
const badge_key_info = key_info.find(([ key ]) => key === cannonical_badges);
const is_badges = badge_key_info ?
badge_key_info[1].type === 'renderer_list' && Reflect.has(badge_key_info[1].renderers, 'MetadataBadge') :
badge_key_info[1].type === 'array' && badge_key_info[1].array_type === 'renderer' && Reflect.has(badge_key_info[1].renderers, 'MetadataBadge') :
false;
if (is_badges && cannonical_badges) excluded_keys.add(cannonical_badges);
@@ -273,7 +375,7 @@ export function introspect(classdata: unknown) {
const key_info = introspect2(classdata);
const dependencies = new Map<string, any>();
for (const [ , value ] of key_info) {
if (value.type === 'renderer' || value.type === 'renderer_list')
if (value.type === 'renderer' || (value.type === 'array' && value.array_type === 'renderer'))
for (const renderer of value.renderers) {
const example = RENDERER_EXAMPLES[renderer];
if (example)
@@ -401,6 +503,10 @@ export function generateTypescriptClass(classname: string, key_info: KeyInfo) {
return `class ${classname} extends YTNode {\n static type = '${classname}';\n\n ${props.join('\n ')}\n\n constructor(data: RawNode) {\n ${constructor_lines.join('\n ')}\n }\n}\n`;
}
function toTypeDeclarationObject(indentation: number, keys: KeyInfo) {
return `{\n${keys.map(([ key, value ]) => `${' '.repeat((indentation + 2) * 2)}${camelToSnake(key)}${value.optional ? '?' : ''}: ${toTypeDeclaration(value, indentation + 1)}`).join(',\n')}\n${' '.repeat((indentation + 1) * 2)}}`;
}
/**
* For a given inference type, get the typescript type declaration
* @param inference_type - The inference type to get the declaration for
@@ -413,13 +519,33 @@ export function toTypeDeclaration(inference_type: InferenceType, indentation = 0
{
return `${inference_type.renderers.map((type) => `YTNodes.${type}`).join(' | ')} | null`;
}
case 'renderer_list':
case 'array':
{
return `ObservedArray<${inference_type.renderers.map((type) => `YTNodes.${type}`).join(' | ')}> | null`;
switch (inference_type.array_type) {
case 'renderer':
return `ObservedArray<${inference_type.renderers.map((type) => `YTNodes.${type}`).join(' | ')}> | null`;
case 'primitive':
{
const items_list = inference_type.items.typeof;
if (inference_type.items.optional && !items_list.includes('undefined'))
items_list.push('undefined');
const items =
items_list.length === 1 ?
`${items_list[0]}` : `(${items_list.join(' | ')})`;
return `${items}[]`;
}
case 'object':
return `${toTypeDeclarationObject(indentation, inference_type.items.keys)}[]`;
default:
throw new Error('Unreachable code reached! Switch missing case!');
}
}
case 'object':
{
return `{\n${inference_type.keys.map(([ key, value ]) => `${' '.repeat((indentation + 2) * 2)}${camelToSnake(key)}${value.optional ? '?' : ''}: ${toTypeDeclaration(value, indentation + 1)}`).join(',\n')}\n${' '.repeat((indentation + 1) * 2)}}`;
return toTypeDeclarationObject(indentation, inference_type.keys);
}
case 'misc':
switch (inference_type.misc_type) {
@@ -430,11 +556,14 @@ export function toTypeDeclaration(inference_type: InferenceType, indentation = 0
}
case 'primative':
return inference_type.typeof.join(' | ');
case 'unknown':
return '/* TODO: determine correct type */ unknown';
}
}
function toParserObject(indentation: number, keys: KeyInfo, key_path: string[], key: string) {
const new_keypath = [ ...key_path, key ];
return `{\n${keys.map(([ key, value ]) => `${' '.repeat((indentation + 2) * 2)}${camelToSnake(key)}: ${toParser(key, value, new_keypath, indentation + 1)}`).join(',\n')}\n${' '.repeat((indentation + 1) * 2)}}`;
}
/**
* Generate statements to parse a given inference type
* @param key - The key to parse
@@ -448,18 +577,32 @@ export function toParser(key: string, inference_type: InferenceType, key_path: s
switch (inference_type.type) {
case 'renderer':
{
parser = `Parser.parseItem(${key_path.join('.')}.${key}, [ ${inference_type.renderers.map((type) => `YTNodes.${type}`).join(', ')} ])`;
parser = `Parser.parseItem(${key_path.join('.')}.${key}, ${toParserValidTypes(inference_type.renderers)})`;
}
break;
case 'renderer_list':
case 'array':
{
parser = `Parser.parse(${key_path.join('.')}.${key}, true, [ ${inference_type.renderers.map((type) => `YTNodes.${type}`).join(', ')} ])`;
switch (inference_type.array_type) {
case 'renderer':
parser = `Parser.parse(${key_path.join('.')}.${key}, true, ${toParserValidTypes(inference_type.renderers)})`;
break;
case 'object':
parser = `${key_path.join('.')}.${key}.map((item: any) => (${toParserObject(indentation, inference_type.items.keys, [], 'item')}))`;
break;
case 'primitive':
parser = `${key_path.join('.')}.${key}`;
break;
default:
throw new Error('Unreachable code reached! Switch missing case!');
}
}
break;
case 'object':
{
const new_keypath = [ ...key_path, key ];
parser = `{\n${inference_type.keys.map(([ key, value ]) => `${' '.repeat((indentation + 2) * 2)}${camelToSnake(key)}: ${toParser(key, value, new_keypath, indentation + 1)}`).join(',\n')}\n${' '.repeat((indentation + 1) * 2)}}`;
parser = toParserObject(indentation, inference_type.keys, key_path, key);
}
break;
case 'misc':
@@ -482,7 +625,6 @@ export function toParser(key: string, inference_type: InferenceType, key_path: s
throw new Error('Unreachable code reached! Switch missing case!');
break;
case 'primative':
case 'unknown':
parser = `${key_path.join('.')}.${key}`;
break;
}
@@ -491,6 +633,14 @@ export function toParser(key: string, inference_type: InferenceType, key_path: s
return parser;
}
function toParserValidTypes(types: string[]) {
if (types.length === 1) {
return `YTNodes.${types[0]}`;
}
return `[ ${types.map((type) => `YTNodes.${type}`).join(', ')} ]`;
}
function accessDataFromKeyPath(root: any, key_path: string[]) {
let data = root;
for (const key of key_path)
@@ -508,6 +658,15 @@ function hasDataFromKeyPath(root: any, key_path: string[]) {
return true;
}
function parseObject(key: string, data: unknown, key_path: string[], keys: KeyInfo, should_optional: boolean) {
const obj: any = {};
const new_key_path = [ ...key_path, key ];
for (const [ key, value ] of keys) {
obj[key] = should_optional ? parse(key, value, data, new_key_path) : undefined;
}
return obj;
}
/**
* Parse a value from a given key path using the given inference type
* @param key - The key to parse
@@ -523,18 +682,26 @@ export function parse(key: string, inference_type: InferenceType, data: unknown,
{
return should_optional ? Parser.parseItem(accessDataFromKeyPath({ data }, [ ...key_path, key ]), inference_type.renderers.map((type) => Parser.getParserByName(type))) : undefined;
}
case 'renderer_list':
case 'array':
{
return should_optional ? Parser.parse(accessDataFromKeyPath({ data }, [ ...key_path, key ]), true, inference_type.renderers.map((type) => Parser.getParserByName(type))) : undefined;
switch (inference_type.array_type) {
case 'renderer':
return should_optional ? Parser.parse(accessDataFromKeyPath({ data }, [ ...key_path, key ]), true, inference_type.renderers.map((type) => Parser.getParserByName(type))) : undefined;
break;
case 'object':
return should_optional ? accessDataFromKeyPath({ data }, [ ...key_path, key ]).map((_: any, idx: number) => {
return parseObject(`${idx}`, data, [ ...key_path, key ], inference_type.items.keys, should_optional);
}) : undefined;
case 'primitive':
return should_optional ? accessDataFromKeyPath({ data }, [ ...key_path, key ]) : undefined;
}
throw new Error('Unreachable code reached! Switch missing case!');
}
case 'object':
{
const obj: any = {};
const new_key_path = [ ...key_path, key ];
for (const [ key, value ] of inference_type.keys) {
obj[key] = should_optional ? parse(key, value, data, new_key_path) : undefined;
}
return obj;
return parseObject(key, data, key_path, inference_type.keys, should_optional);
}
case 'misc':
switch (inference_type.misc_type) {
@@ -556,7 +723,6 @@ export function parse(key: string, inference_type: InferenceType, data: unknown,
}
throw new Error('Unreachable code reached! Switch missing case!');
case 'primative':
case 'unknown':
return accessDataFromKeyPath({ data }, [ ...key_path, key ]);
}
}
@@ -585,7 +751,8 @@ export function mergeKeyInfo(key_info: KeyInfo, new_key_info: KeyInfo) {
if (type.type !== new_type.type) {
// We've got a type mismatch, this is unknown, we do not resolve unions
changed_keys.set(key, {
type: 'unknown',
type: 'primative',
typeof: [ 'unknown' ],
optional: true
});
continue;
@@ -628,27 +795,128 @@ export function mergeKeyInfo(key_info: KeyInfo, new_key_info: KeyInfo) {
if (did_change) changed_keys.set(key, resolved_key);
}
break;
case 'renderer_list':
case 'array':
{
if (new_type.type !== 'renderer_list') continue;
const union_map = {
...type.renderers,
...new_type.renderers
};
const either_optional = type.optional || new_type.optional;
const resolved_key: InferenceType = {
type: 'renderer_list',
renderers: union_map,
optional: either_optional
};
const did_change = JSON.stringify({
...resolved_key,
renderers: Object.keys(resolved_key.renderers)
}) !== JSON.stringify({
...type,
renderers: Object.keys(type.renderers)
});
if (did_change) changed_keys.set(key, resolved_key);
if (new_type.type !== 'array') continue;
switch (type.array_type) {
case 'renderer':
{
if (new_type.array_type !== 'renderer') {
// Type mismatch
changed_keys.set(key, {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ 'unknown' ],
optional: true
},
optional: true
});
continue;
}
const union_map = {
...type.renderers,
...new_type.renderers
};
const either_optional = type.optional || new_type.optional;
const resolved_key: InferenceType = {
type: 'array',
array_type: 'renderer',
renderers: union_map,
optional: either_optional
};
const did_change = JSON.stringify({
...resolved_key,
renderers: Object.keys(resolved_key.renderers)
}) !== JSON.stringify({
...type,
renderers: Object.keys(type.renderers)
});
if (did_change) changed_keys.set(key, resolved_key);
}
break;
case 'object':
{
if (new_type.array_type === 'primitive' && new_type.items.typeof.length == 1 && new_type.items.typeof[0] === 'never') {
// It's an empty array. We assume the type is unchanged
continue;
}
if (new_type.array_type !== 'object') {
// Type mismatch
changed_keys.set(key, {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ 'unknown' ],
optional: true
},
optional: true
});
continue;
}
const { resolved_key_info } = mergeKeyInfo(type.items.keys, new_type.items.keys);
const resolved_key: InferenceType = {
type: 'array',
array_type: 'object',
items: {
type: 'object',
keys: resolved_key_info,
optional: type.items.optional || new_type.items.optional
},
optional: type.optional || new_type.optional
};
const did_change = JSON.stringify(resolved_key) !== JSON.stringify(type);
if (did_change) changed_keys.set(key, resolved_key);
}
break;
case 'primitive':
{
if (type.items.typeof.includes('never') && new_type.array_type === 'object') {
// Type is now known from previosly unknown
changed_keys.set(key, new_type);
continue;
}
if (new_type.array_type !== 'primitive') {
// Type mismatch
changed_keys.set(key, {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: [ 'unknown' ],
optional: true
},
optional: true
});
continue;
}
const key_types = new Set([ ...new_type.items.typeof, ...type.items.typeof ]);
if (key_types.size > 1 && key_types.has('never'))
key_types.delete('never');
const resolved_key: InferenceType = {
type: 'array',
array_type: 'primitive',
items: {
type: 'primative',
typeof: Array.from(key_types),
optional: type.items.optional || new_type.items.optional
},
optional: type.optional || new_type.optional
};
const did_change = JSON.stringify(resolved_key) !== JSON.stringify(type);
if (did_change) changed_keys.set(key, resolved_key);
}
break;
default:
throw new Error('Unreachable code reached! Switch missing case!');
}
}
break;
case 'misc':
@@ -657,7 +925,8 @@ export function mergeKeyInfo(key_info: KeyInfo, new_key_info: KeyInfo) {
if (type.misc_type !== new_type.misc_type) {
// We've got a type mismatch, this is unknown, we do not resolve unions
changed_keys.set(key, {
type: 'unknown',
type: 'primative',
typeof: [ 'unknown' ],
optional: true
});
}

View File

@@ -1,3 +1,4 @@
import Log from '../utils/Log.js';
import { deepCompare, ParsingError } from '../utils/Utils.js';
const isObserved = Symbol('ObservedArray.isObserved');
@@ -62,6 +63,7 @@ export class YTNode {
}
export class Maybe {
#TAG = 'Maybe';
#value;
constructor (value: any) {
@@ -275,10 +277,11 @@ export class Maybe {
}
/**
* @deprecated This call is not meant to be used outside of debugging. Please use the specific type getter instead.
* @deprecated
* This call is not meant to be used outside of debugging. Please use the specific type getter instead.
*/
any(): any {
console.warn('This call is not meant to be used outside of debugging. Please use the specific type getter instead.');
Log.warn(this.#TAG, 'This call is not meant to be used outside of debugging. Please use the specific type getter instead.');
return this.#value;
}

View File

@@ -20,8 +20,10 @@ export { default as AnalyticsVodCarouselCard } from './classes/analytics/Analyti
export { default as CtaGoToCreatorStudio } from './classes/analytics/CtaGoToCreatorStudio.js';
export { default as DataModelSection } from './classes/analytics/DataModelSection.js';
export { default as StatRow } from './classes/analytics/StatRow.js';
export { default as AttributionView } from './classes/AttributionView.js';
export { default as AudioOnlyPlayability } from './classes/AudioOnlyPlayability.js';
export { default as AutomixPreviewVideo } from './classes/AutomixPreviewVideo.js';
export { default as AvatarView } from './classes/AvatarView.js';
export { default as BackstageImage } from './classes/BackstageImage.js';
export { default as BackstagePost } from './classes/BackstagePost.js';
export { default as BackstagePostThread } from './classes/BackstagePostThread.js';
@@ -93,9 +95,12 @@ export { default as ContinuationItem } from './classes/ContinuationItem.js';
export { default as ConversationBar } from './classes/ConversationBar.js';
export { default as CopyLink } from './classes/CopyLink.js';
export { default as CreatePlaylistDialog } from './classes/CreatePlaylistDialog.js';
export { default as DecoratedAvatarView } from './classes/DecoratedAvatarView.js';
export { default as DecoratedPlayerBar } from './classes/DecoratedPlayerBar.js';
export { default as DefaultPromoPanel } from './classes/DefaultPromoPanel.js';
export { default as DescriptionPreviewView } from './classes/DescriptionPreviewView.js';
export { default as DidYouMean } from './classes/DidYouMean.js';
export { default as DislikeButtonView } from './classes/DislikeButtonView.js';
export { default as DownloadButton } from './classes/DownloadButton.js';
export { default as Dropdown } from './classes/Dropdown.js';
export { default as DropdownItem } from './classes/DropdownItem.js';
@@ -148,6 +153,7 @@ export { default as HorizontalCardList } from './classes/HorizontalCardList.js';
export { default as HorizontalList } from './classes/HorizontalList.js';
export { default as HorizontalMovieList } from './classes/HorizontalMovieList.js';
export { default as IconLink } from './classes/IconLink.js';
export { default as ImageBannerView } from './classes/ImageBannerView.js';
export { default as IncludingResultsFor } from './classes/IncludingResultsFor.js';
export { default as InfoPanelContainer } from './classes/InfoPanelContainer.js';
export { default as InfoPanelContent } from './classes/InfoPanelContent.js';
@@ -158,6 +164,7 @@ export { default as ItemSectionHeader } from './classes/ItemSectionHeader.js';
export { default as ItemSectionTab } from './classes/ItemSectionTab.js';
export { default as ItemSectionTabbedHeader } from './classes/ItemSectionTabbedHeader.js';
export { default as LikeButton } from './classes/LikeButton.js';
export { default as LikeButtonView } from './classes/LikeButtonView.js';
export { default as LiveChat } from './classes/LiveChat.js';
export { default as AddBannerToLiveChatCommand } from './classes/livechat/AddBannerToLiveChatCommand.js';
export { default as AddChatItemAction } from './classes/livechat/AddChatItemAction.js';
@@ -227,6 +234,7 @@ export { default as MetadataRowHeader } from './classes/MetadataRowHeader.js';
export { default as MetadataScreen } from './classes/MetadataScreen.js';
export { default as MicroformatData } from './classes/MicroformatData.js';
export { default as Mix } from './classes/Mix.js';
export { default as ModalWithTitleAndButton } from './classes/ModalWithTitleAndButton.js';
export { default as Movie } from './classes/Movie.js';
export { default as MovingThumbnail } from './classes/MovingThumbnail.js';
export { default as MultiMarkersPlayerBar } from './classes/MultiMarkersPlayerBar.js';
@@ -328,6 +336,7 @@ export { default as SearchSuggestionsSection } from './classes/SearchSuggestions
export { default as SecondarySearchContainer } from './classes/SecondarySearchContainer.js';
export { default as SectionList } from './classes/SectionList.js';
export { default as SegmentedLikeDislikeButton } from './classes/SegmentedLikeDislikeButton.js';
export { default as SegmentedLikeDislikeButtonView } from './classes/SegmentedLikeDislikeButtonView.js';
export { default as SettingBoolean } from './classes/SettingBoolean.js';
export { default as SettingsCheckbox } from './classes/SettingsCheckbox.js';
export { default as SettingsOptions } from './classes/SettingsOptions.js';
@@ -346,6 +355,7 @@ export { default as SingleColumnMusicWatchNextResults } from './classes/SingleCo
export { default as SingleHeroImage } from './classes/SingleHeroImage.js';
export { default as SlimOwner } from './classes/SlimOwner.js';
export { default as SlimVideoMetadata } from './classes/SlimVideoMetadata.js';
export { default as SortFilterHeader } from './classes/SortFilterHeader.js';
export { default as SortFilterSubMenu } from './classes/SortFilterSubMenu.js';
export { default as StructuredDescriptionContent } from './classes/StructuredDescriptionContent.js';
export { default as StructuredDescriptionPlaylistLockup } from './classes/StructuredDescriptionPlaylistLockup.js';
@@ -373,6 +383,7 @@ export { default as ThumbnailOverlayToggleButton } from './classes/ThumbnailOver
export { default as TimedMarkerDecoration } from './classes/TimedMarkerDecoration.js';
export { default as TitleAndButtonListHeader } from './classes/TitleAndButtonListHeader.js';
export { default as ToggleButton } from './classes/ToggleButton.js';
export { default as ToggleButtonView } from './classes/ToggleButtonView.js';
export { default as ToggleMenuServiceItem } from './classes/ToggleMenuServiceItem.js';
export { default as Tooltip } from './classes/Tooltip.js';
export { default as TopicChannelDetails } from './classes/TopicChannelDetails.js';

View File

@@ -1,3 +1,16 @@
import * as YTNodes from './nodes.js';
import { InnertubeError, ParsingError, Platform } from '../utils/Utils.js';
import { Memo, observe, SuperParsedResult } from './helpers.js';
import { camelToSnake, generateRuntimeClass, generateTypescriptClass } from './generator.js';
import { Log } from '../utils/index.js';
import {
Continuation, ItemSectionContinuation, SectionListContinuation,
LiveChatContinuation, MusicPlaylistShelfContinuation, MusicShelfContinuation,
GridContinuation, PlaylistPanelContinuation, NavigateAction, ShowMiniplayerCommand,
ReloadContinuationItemsCommand, ContinuationCommand
} from './continuations.js';
import AudioOnlyPlayability from './classes/AudioOnlyPlayability.js';
import CardCollection from './classes/CardCollection.js';
import Endscreen from './classes/Endscreen.js';
@@ -8,27 +21,16 @@ import PlayerStoryboardSpec from './classes/PlayerStoryboardSpec.js';
import Alert from './classes/Alert.js';
import AlertWithButton from './classes/AlertWithButton.js';
import EngagementPanelSectionList from './classes/EngagementPanelSectionList.js';
import type { IParsedResponse, IRawResponse, RawData, RawNode } from './types/index.js';
import MusicMultiSelectMenuItem from './classes/menus/MusicMultiSelectMenuItem.js';
import Format from './classes/misc/Format.js';
import VideoDetails from './classes/misc/VideoDetails.js';
import NavigationEndpoint from './classes/NavigationEndpoint.js';
import { InnertubeError, ParsingError, Platform } from '../utils/Utils.js';
import type { ObservedArray, YTNodeConstructor, YTNode } from './helpers.js';
import { Memo, observe, SuperParsedResult } from './helpers.js';
import * as YTNodes from './nodes.js';
import type { KeyInfo } from './generator.js';
import { camelToSnake, generateRuntimeClass, generateTypescriptClass } from './generator.js';
import type { ObservedArray, YTNodeConstructor, YTNode } from './helpers.js';
import type { IParsedResponse, IRawResponse, RawData, RawNode } from './types/index.js';
import {
Continuation, ItemSectionContinuation, SectionListContinuation,
LiveChatContinuation, MusicPlaylistShelfContinuation, MusicShelfContinuation,
GridContinuation, PlaylistPanelContinuation, NavigateAction, ShowMiniplayerCommand,
ReloadContinuationItemsCommand, ContinuationCommand
} from './continuations.js';
const TAG = 'Parser';
export type ParserError = {
classname: string,
@@ -85,7 +87,7 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
switch (context.error_type) {
case 'parse':
if (context.error instanceof Error) {
console.warn(
Log.warn(TAG,
new InnertubeError(
`Something went wrong at ${classname}!\n` +
`This is a bug, please report it at ${Platform.shim.info.bugs_url}`, {
@@ -96,7 +98,7 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
}
break;
case 'typecheck':
console.warn(
Log.warn(TAG,
new ParsingError(
`Type mismatch, got ${classname} expected ${Array.isArray(context.expected) ? context.expected.join(' | ') : context.expected}.`,
context.classdata
@@ -104,7 +106,7 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
);
break;
case 'mutation_data_missing':
console.warn(
Log.warn(TAG,
new InnertubeError(
'Mutation data required for processing MusicMultiSelectMenuItems, but none found.\n' +
`This is a bug, please report it at ${Platform.shim.info.bugs_url}`
@@ -112,7 +114,7 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
);
break;
case 'mutation_data_invalid':
console.warn(
Log.warn(TAG,
new InnertubeError(
`Mutation data missing or invalid for ${context.failed} out of ${context.total} MusicMultiSelectMenuItems. ` +
`The titles of the failed items are: ${context.titles.join(', ')}.\n` +
@@ -121,7 +123,7 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
);
break;
case 'class_not_found':
console.warn(
Log.warn(TAG,
new InnertubeError(
`${classname} not found!\n` +
`This is a bug, want to help us fix it? Follow the instructions at ${Platform.shim.info.repo_url}/blob/main/docs/updating-the-parser.md or report it at ${Platform.shim.info.bugs_url}!\n` +
@@ -130,14 +132,14 @@ let ERROR_HANDLER: ParserErrorHandler = ({ classname, ...context }: ParserError)
);
break;
case 'class_changed':
console.warn(
Log.warn(TAG,
`${classname} changed!\n` +
`The following keys where altered: ${context.changed_keys.map(([ key ]) => camelToSnake(key)).join(', ')}\n` +
`The class has changed to:\n${generateTypescriptClass(classname, context.key_info)}`
);
break;
default:
console.warn(
Log.warn(TAG,
'Unreachable code reached at ParserErrorHandler'
);
break;
@@ -319,9 +321,9 @@ export function parseResponse<T extends IParsedResponse = IParsedResponse>(data:
parsed_data.continuation = continuation;
}
const continuationEndpoint = data.continuationEndpoint ? parseLC(data.continuationEndpoint) : null;
if (continuationEndpoint) {
parsed_data.continuationEndpoint = continuationEndpoint;
const continuation_endpoint = data.continuationEndpoint ? parseLC(data.continuationEndpoint) : null;
if (continuation_endpoint) {
parsed_data.continuation_endpoint = continuation_endpoint;
}
const metadata = parse(data.metadata);
@@ -398,6 +400,28 @@ export function parseResponse<T extends IParsedResponse = IParsedResponse>(data:
parsed_data.streaming_data = streaming_data;
}
if (data.playerConfig) {
const player_config = {
audio_config: {
loudness_db: data.playerConfig.audioConfig?.loudnessDb,
perceptual_loudness_db: data.playerConfig.audioConfig?.perceptualLoudnessDb,
enable_per_format_loudness: data.playerConfig.audioConfig?.enablePerFormatLoudness
},
stream_selection_config: {
max_bitrate: data.playerConfig.streamSelectionConfig?.maxBitrate || '0'
},
media_common_config: {
dynamic_readahead_config: {
max_read_ahead_media_time_ms: data.playerConfig.mediaCommonConfig?.dynamicReadaheadConfig?.maxReadAheadMediaTimeMs || 0,
min_read_ahead_media_time_ms: data.playerConfig.mediaCommonConfig?.dynamicReadaheadConfig?.minReadAheadMediaTimeMs || 0,
read_ahead_growth_rate_ms: data.playerConfig.mediaCommonConfig?.dynamicReadaheadConfig?.readAheadGrowthRateMs || 0
}
}
};
parsed_data.player_config = player_config;
}
const current_video_endpoint = data.currentVideoEndpoint ? new NavigationEndpoint(data.currentVideoEndpoint) : null;
if (current_video_endpoint) {
parsed_data.current_video_endpoint = current_video_endpoint;
@@ -545,6 +569,7 @@ export function parseArray(data?: RawNode[], validTypes?: YTNodeConstructor | YT
* @param validTypes - YTNode types that are allowed to be parsed.
*/
export function parse<T extends YTNode, K extends YTNodeConstructor<T>[]>(data: RawData, requireArray: true, validTypes?: K): ObservedArray<InstanceType<K[number]>> | null;
export function parse<T extends YTNode, K extends YTNodeConstructor<T>>(data: RawData, requireArray: true, validTypes?: K): ObservedArray<InstanceType<K>> | null;
export function parse<T extends YTNode = YTNode>(data?: RawData, requireArray?: false | undefined, validTypes?: YTNodeConstructor<T> | YTNodeConstructor<T>[]): SuperParsedResult<T>;
export function parse<T extends YTNode = YTNode>(data?: RawData, requireArray?: boolean, validTypes?: YTNodeConstructor<T> | YTNodeConstructor<T>[]) {
if (!data) return null;

View File

@@ -56,6 +56,7 @@ export interface IParsedResponse {
};
playability_status?: IPlayabilityStatus;
streaming_data?: IStreamingData;
player_config?: IPlayerConfig;
current_video_endpoint?: NavigationEndpoint;
endpoint?: NavigationEndpoint;
captions?: PlayerCaptionsTracklist;
@@ -68,7 +69,25 @@ export interface IParsedResponse {
items?: SuperParsedResult<YTNode>;
entries?: SuperParsedResult<YTNode>;
entries_memo?: Memo;
continuationEndpoint?: YTNode;
continuation_endpoint?: YTNode;
}
export interface IPlayerConfig {
audio_config: {
loudness_db?: number;
perceptual_loudness_db?: number;
enable_per_format_loudness: boolean;
};
stream_selection_config: {
max_bitrate: string;
};
media_common_config: {
dynamic_readahead_config: {
max_read_ahead_media_time_ms: number;
min_read_ahead_media_time_ms: number;
read_ahead_growth_rate_ms: number;
};
};
}
export interface IStreamingData {
@@ -87,6 +106,7 @@ export interface IPlayerResponse {
annotations?: ObservedArray<PlayerAnnotationsExpanded>;
playability_status: IPlayabilityStatus;
streaming_data?: IStreamingData;
player_config: IPlayerConfig;
playback_tracking?: {
videostats_watchtime_url: string;
videostats_playback_url: string;

View File

@@ -1,6 +1,24 @@
export type RawNode = Record<string, any>;
export type RawData = RawNode | RawNode[];
export interface IRawPlayerConfig {
audioConfig: {
loudnessDb?: number;
perceptualLoudnessDb?: number;
enablePerFormatLoudness: boolean;
};
streamSelectionConfig: {
maxBitrate: string;
};
mediaCommonConfig: {
dynamicReadaheadConfig: {
maxReadAheadMediaTimeMs: number;
minReadAheadMediaTimeMs: number;
readAheadGrowthRateMs: number;
};
};
}
export interface IRawResponse {
contents?: RawData;
onResponseReceivedActions?: RawNode[];
@@ -41,6 +59,7 @@ export interface IRawResponse {
dashManifestUrl?: string;
hlsManifestUrl?: string;
};
playerConfig?: IRawPlayerConfig;
currentVideoEndpoint?: RawNode;
unseenCount?: number;
playlistId?: string;

View File

@@ -1,13 +1,12 @@
import { Parser } from '../index.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IParsedResponse } from '../types/ParsedResponse.js';
import { InnertubeError } from '../../utils/Utils.js';
import AccountSectionList from '../classes/AccountSectionList.js';
import type { ApiResponse } from '../../core/index.js';
import type { IParsedResponse } from '../types/index.js';
import type AccountItemSection from '../classes/AccountItemSection.js';
import type AccountChannel from '../classes/AccountChannel.js';
import { InnertubeError } from '../../utils/Utils.js';
class AccountInfo {
#page: IParsedResponse;

View File

@@ -1,7 +1,7 @@
import { Parser } from '../index.js';
import Element from '../classes/Element.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { ApiResponse } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
class Analytics {
#page: IBrowseResponse;

View File

@@ -1,3 +1,7 @@
import Feed from '../../core/mixins/Feed.js';
import FilterableFeed from '../../core/mixins/FilterableFeed.js';
import { ChannelError, InnertubeError } from '../../utils/Utils.js';
import TabbedFeed from '../../core/mixins/TabbedFeed.js';
import C4TabbedHeader from '../classes/C4TabbedHeader.js';
import CarouselHeader from '../classes/CarouselHeader.js';
@@ -12,9 +16,6 @@ import SectionList from '../classes/SectionList.js';
import Tab from '../classes/Tab.js';
import PageHeader from '../classes/PageHeader.js';
import TwoColumnBrowseResults from '../classes/TwoColumnBrowseResults.js';
import Feed from '../../core/mixins/Feed.js';
import FilterableFeed from '../../core/mixins/FilterableFeed.js';
import ChipCloudChip from '../classes/ChipCloudChip.js';
import FeedFilterChipBar from '../classes/FeedFilterChipBar.js';
import ChannelSubMenu from '../classes/ChannelSubMenu.js';
@@ -22,11 +23,8 @@ import SortFilterSubMenu from '../classes/SortFilterSubMenu.js';
import ContinuationItem from '../classes/ContinuationItem.js';
import NavigationEndpoint from '../classes/NavigationEndpoint.js';
import { ChannelError, InnertubeError } from '../../utils/Utils.js';
import type { AppendContinuationItemsAction, ReloadContinuationItemsCommand } from '../index.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
export default class Channel extends TabbedFeed<IBrowseResponse> {
@@ -196,10 +194,13 @@ export default class Channel extends TabbedFeed<IBrowseResponse> {
if (this.hasTabWithURL('about')) {
const tab = await this.getTabByURL('about');
return tab.memo.getType(ChannelAboutFullMetadata)[0];
} else if (this.header?.is(C4TabbedHeader) && this.header.tagline) {
}
if (this.header.tagline.more_endpoint instanceof NavigationEndpoint) {
const response = await this.header.tagline.more_endpoint.call(this.actions);
const tagline = this.header?.is(C4TabbedHeader) && this.header.tagline;
if (tagline || this.header?.is(PageHeader) && this.header.content?.description) {
if (tagline && tagline.more_endpoint instanceof NavigationEndpoint) {
const response = await tagline.more_endpoint.call(this.actions);
const tab = new TabbedFeed<IBrowseResponse>(this.actions, response, false);
return tab.memo.getType(ChannelAboutFullMetadata)[0];
@@ -271,7 +272,9 @@ export default class Channel extends TabbedFeed<IBrowseResponse> {
get has_about(): boolean {
// Game topic channels still have an about tab, user channels have switched to the popup
return this.hasTabWithURL('about') || !!(this.header?.is(C4TabbedHeader) && this.header.tagline?.more_endpoint);
return this.hasTabWithURL('about') ||
!!(this.header?.is(C4TabbedHeader) && this.header.tagline?.more_endpoint) ||
!!(this.header?.is(PageHeader) && this.header.content?.description?.more_endpoint);
}
get has_search(): boolean {

View File

@@ -1,16 +1,16 @@
import { Parser } from '../index.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray } from '../helpers.js';
import { observe } from '../helpers.js';
import type { INextResponse } from '../types/ParsedResponse.js';
import CommentsHeader from '../classes/comments/CommentsHeader.js';
import CommentSimplebox from '../classes/comments/CommentSimplebox.js';
import CommentThread from '../classes/comments/CommentThread.js';
import ContinuationItem from '../classes/ContinuationItem.js';
import type { Actions, ApiResponse } from '../../core/index.js';
import type { ObservedArray } from '../helpers.js';
import type { INextResponse } from '../types/index.js';
class Comments {
#page: INextResponse;
#actions: Actions;

View File

@@ -1,10 +1,11 @@
import type { IGuideResponse } from '../types/ParsedResponse.js';
import type { IRawResponse} from '../index.js';
import { Parser } from '../index.js';
import type { ObservedArray } from '../helpers.js';
import GuideSection from '../classes/GuideSection.js';
import GuideSubscriptionsSection from '../classes/GuideSubscriptionsSection.js';
import type { ObservedArray } from '../helpers.js';
import type { IGuideResponse } from '../types/index.js';
import type { IRawResponse } from '../index.js';
export default class Guide {
#page: IGuideResponse;

View File

@@ -1,14 +1,13 @@
import FilterableFeed from '../../core/mixins/FilterableFeed.js';
import { InnertubeError } from '../../utils/Utils.js';
import FilterableFeed from '../../core/mixins/FilterableFeed.js';
import HashtagHeader from '../classes/HashtagHeader.js';
import RichGrid from '../classes/RichGrid.js';
import PageHeader from '../classes/PageHeader.js';
import Tab from '../classes/Tab.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type ChipCloudChip from '../classes/ChipCloudChip.js';
import type { Actions, ApiResponse } from '../../core/index.js';
import type { IBrowseResponse } from '../index.js';
import { PageHeader } from '../nodes.js';
import type ChipCloudChip from '../classes/ChipCloudChip.js';
export default class HashtagFeed extends FilterableFeed<IBrowseResponse> {
header?: HashtagHeader | PageHeader;

View File

@@ -1,9 +1,9 @@
import type Actions from '../../core/Actions.js';
import Feed from '../../core/mixins/Feed.js';
import ItemSection from '../classes/ItemSection.js';
import BrowseFeedActions from '../classes/BrowseFeedActions.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { Actions, ApiResponse } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
// TODO: make feed actions usable
class History extends Feed<IBrowseResponse> {

View File

@@ -1,12 +1,11 @@
import type Actions from '../../core/Actions.js';
import FilterableFeed from '../../core/mixins/FilterableFeed.js';
import type ChipCloudChip from '../classes/ChipCloudChip.js';
import FeedTabbedHeader from '../classes/FeedTabbedHeader.js';
import RichGrid from '../classes/RichGrid.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { IBrowseResponse } from '../types/index.js';
import type { AppendContinuationItemsAction, ReloadContinuationItemsCommand } from '../index.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type ChipCloudChip from '../classes/ChipCloudChip.js';
export default class HomeFeed extends FilterableFeed<IBrowseResponse> {
contents: RichGrid | AppendContinuationItemsAction | ReloadContinuationItemsCommand;

View File

@@ -1,12 +1,12 @@
import Button from '../classes/Button.js';
import Menu from '../classes/menus/Menu.js';
import Button from '../classes/Button.js';
import MenuServiceItem from '../classes/menus/MenuServiceItem.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
import type Actions from '../../core/Actions.js';
import type { Actions } from '../../core/index.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type { IParsedResponse } from '../types/ParsedResponse.js';
import type { IParsedResponse } from '../types/index.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
class ItemMenu {
#page: IParsedResponse;

View File

@@ -1,6 +1,4 @@
import type Actions from '../../core/Actions.js';
import { InnertubeError } from '../../utils/Utils.js';
import Feed from '../../core/mixins/Feed.js';
import History from './History.js';
import Playlist from './Playlist.js';
@@ -9,8 +7,8 @@ import Shelf from '../classes/Shelf.js';
import Button from '../classes/Button.js';
import PageHeader from '../classes/PageHeader.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { Actions, ApiResponse } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
class Library extends Feed<IBrowseResponse> {
header: PageHeader | null;

View File

@@ -1,42 +1,40 @@
import EventEmitter from '../../utils/EventEmitterLike.js';
import * as Proto from '../../proto/index.js';
import { EventEmitter } from '../../utils/index.js';
import { InnertubeError, Platform } from '../../utils/Utils.js';
import { Parser, LiveChatContinuation } from '../index.js';
import type VideoInfo from './VideoInfo.js';
import SmoothedQueue from './SmoothedQueue.js';
import AddChatItemAction from '../classes/livechat/AddChatItemAction.js';
import type AddLiveChatTickerItemAction from '../classes/livechat/AddLiveChatTickerItemAction.js';
import type MarkChatItemAsDeletedAction from '../classes/livechat/MarkChatItemAsDeletedAction.js';
import type MarkChatItemsByAuthorAsDeletedAction from '../classes/livechat/MarkChatItemsByAuthorAsDeletedAction.js';
import type ReplaceChatItemAction from '../classes/livechat/ReplaceChatItemAction.js';
import type ReplayChatItemAction from '../classes/livechat/ReplayChatItemAction.js';
import type ShowLiveChatActionPanelAction from '../classes/livechat/ShowLiveChatActionPanelAction.js';
import UpdateDateTextAction from '../classes/livechat/UpdateDateTextAction.js';
import UpdateDescriptionAction from '../classes/livechat/UpdateDescriptionAction.js';
import UpdateTitleAction from '../classes/livechat/UpdateTitleAction.js';
import UpdateToggleButtonTextAction from '../classes/livechat/UpdateToggleButtonTextAction.js';
import UpdateViewershipAction from '../classes/livechat/UpdateViewershipAction.js';
import NavigationEndpoint from '../classes/NavigationEndpoint.js';
import ItemMenu from './ItemMenu.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type VideoInfo from './VideoInfo.js';
import type AddBannerToLiveChatCommand from '../classes/livechat/AddBannerToLiveChatCommand.js';
import type RemoveBannerForLiveChatCommand from '../classes/livechat/RemoveBannerForLiveChatCommand.js';
import type ShowLiveChatTooltipCommand from '../classes/livechat/ShowLiveChatTooltipCommand.js';
import * as Proto from '../../proto/index.js';
import { InnertubeError, Platform } from '../../utils/Utils.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type Button from '../classes/Button.js';
import type LiveChatAutoModMessage from '../classes/livechat/items/LiveChatAutoModMessage.js';
import type LiveChatMembershipItem from '../classes/livechat/items/LiveChatMembershipItem.js';
import type LiveChatPaidMessage from '../classes/livechat/items/LiveChatPaidMessage.js';
import type LiveChatPaidSticker from '../classes/livechat/items/LiveChatPaidSticker.js';
import type LiveChatTextMessage from '../classes/livechat/items/LiveChatTextMessage.js';
import type LiveChatViewerEngagementMessage from '../classes/livechat/items/LiveChatViewerEngagementMessage.js';
import ItemMenu from './ItemMenu.js';
import type AddLiveChatTickerItemAction from '../classes/livechat/AddLiveChatTickerItemAction.js';
import type MarkChatItemAsDeletedAction from '../classes/livechat/MarkChatItemAsDeletedAction.js';
import type MarkChatItemsByAuthorAsDeletedAction from '../classes/livechat/MarkChatItemsByAuthorAsDeletedAction.js';
import type ReplaceChatItemAction from '../classes/livechat/ReplaceChatItemAction.js';
import type ReplayChatItemAction from '../classes/livechat/ReplayChatItemAction.js';
import type ShowLiveChatActionPanelAction from '../classes/livechat/ShowLiveChatActionPanelAction.js';
import type Button from '../classes/Button.js';
import type Actions from '../../core/Actions.js';
import type { IParsedResponse, IUpdatedMetadataResponse } from '../types/ParsedResponse.js';
import { NavigationEndpoint } from '../nodes.js';
import type { Actions } from '../../core/index.js';
import type { IParsedResponse, IUpdatedMetadataResponse } from '../types/index.js';
export type ChatAction =
AddChatItemAction | AddBannerToLiveChatCommand | AddLiveChatTickerItemAction |

View File

@@ -1,13 +1,12 @@
import { Parser } from '../index.js';
import { InnertubeError } from '../../utils/Utils.js';
import ContinuationItem from '../classes/ContinuationItem.js';
import SimpleMenuHeader from '../classes/menus/SimpleMenuHeader.js';
import Notification from '../classes/Notification.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IGetNotificationsMenuResponse } from '../types/ParsedResponse.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IGetNotificationsMenuResponse } from '../types/index.js';
class NotificationsMenu {
#page: IGetNotificationsMenuResponse;

View File

@@ -1,7 +1,7 @@
import { InnertubeError } from '../../utils/Utils.js';
import Feed from '../../core/mixins/Feed.js';
import Message from '../classes/Message.js';
import type Thumbnail from '../classes/misc/Thumbnail.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
import PlaylistCustomThumbnail from '../classes/PlaylistCustomThumbnail.js';
import PlaylistHeader from '../classes/PlaylistHeader.js';
import PlaylistMetadata from '../classes/PlaylistMetadata.js';
@@ -10,13 +10,15 @@ import PlaylistSidebarSecondaryInfo from '../classes/PlaylistSidebarSecondaryInf
import PlaylistVideoThumbnail from '../classes/PlaylistVideoThumbnail.js';
import VideoOwner from '../classes/VideoOwner.js';
import Alert from '../classes/Alert.js';
import ContinuationItem from '../classes/ContinuationItem.js';
import PlaylistVideo from '../classes/PlaylistVideo.js';
import SectionList from '../classes/SectionList.js';
import { observe, type ObservedArray } from '../helpers.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray } from '../helpers.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type Thumbnail from '../classes/misc/Thumbnail.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
export default class Playlist extends Feed<IBrowseResponse> {
info;
@@ -64,8 +66,38 @@ export default class Playlist extends Feed<IBrowseResponse> {
return primary_info.stats[index]?.toString() || 'N/A';
}
get items() {
return this.videos;
get items(): ObservedArray<PlaylistVideo> {
return observe(this.videos.as(PlaylistVideo).filter((video) => video.style !== 'PLAYLIST_VIDEO_RENDERER_STYLE_RECOMMENDED_VIDEO'));
}
get has_continuation() {
const section_list = this.memo.getType(SectionList).first();
if (!section_list)
return super.has_continuation;
return !!this.memo.getType(ContinuationItem).find((node) => !section_list.contents.includes(node));
}
async getContinuationData(): Promise<IBrowseResponse | undefined> {
const section_list = this.memo.getType(SectionList).first();
/**
* No section list means there can't be additional continuation nodes here,
* so no need to check.
*/
if (!section_list)
return await super.getContinuationData();
const playlist_contents_continuation = this.memo.getType(ContinuationItem)
.find((node) => !section_list.contents.includes(node));
if (!playlist_contents_continuation)
throw new InnertubeError('There are no continuations.');
const response = await playlist_contents_continuation.endpoint.call<IBrowseResponse>(this.actions, { parse: true });
return response;
}
async getContinuation(): Promise<Playlist> {

View File

@@ -8,10 +8,10 @@ import SearchSubMenu from '../classes/SearchSubMenu.js';
import SectionList from '../classes/SectionList.js';
import UniversalWatchCard from '../classes/UniversalWatchCard.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type { ISearchResponse } from '../types/ParsedResponse.js';
import type { ISearchResponse } from '../types/index.js';
class Search extends Feed<ISearchResponse> {
header?: SearchHeader;
results?: ObservedArray<YTNode> | null;

View File

@@ -8,12 +8,14 @@ import SectionList from '../classes/SectionList.js';
import SettingsOptions from '../classes/SettingsOptions.js';
import SettingsSidebar from '../classes/SettingsSidebar.js';
import SettingsSwitch from '../classes/SettingsSwitch.js';
import CommentsHeader from '../classes/comments/CommentsHeader.js';
import ItemSectionHeader from '../classes/ItemSectionHeader.js';
import ItemSectionTabbedHeader from '../classes/ItemSectionTabbedHeader.js';
import Tab from '../classes/Tab.js';
import TwoColumnBrowseResults from '../classes/TwoColumnBrowseResults.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
class Settings {
#page: IBrowseResponse;
@@ -42,7 +44,7 @@ class Settings {
this.introduction = contents?.shift()?.contents?.firstOfType(PageIntroduction);
this.sections = contents?.map((el: ItemSection) => ({
title: el.header?.title.toString() || null,
title: el.header?.is(CommentsHeader, ItemSectionHeader, ItemSectionTabbedHeader) ? el.header.title.toString() : null,
contents: el.contents
}));
}

View File

@@ -4,9 +4,9 @@ import SectionList from '../classes/SectionList.js';
import SingleColumnBrowseResults from '../classes/SingleColumnBrowseResults.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse } from '../../core/index.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { IBrowseResponse } from '../types/index.js';
class TimeWatched {
#page: IBrowseResponse;

View File

@@ -1,9 +1,9 @@
import type Actions from '../../core/Actions.js';
import { type ApiResponse } from '../../core/Actions.js';
import type { IGetTranscriptResponse } from '../index.js';
import { Parser } from '../index.js';
import Transcript from '../classes/Transcript.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IGetTranscriptResponse } from '../index.js';
export default class TranscriptInfo {
#page: IGetTranscriptResponse;
#actions: Actions;

View File

@@ -1,3 +1,6 @@
import { InnertubeError } from '../../utils/Utils.js';
import { MediaInfo } from '../../core/mixins/index.js';
import ChipCloud from '../classes/ChipCloud.js';
import ChipCloudChip from '../classes/ChipCloudChip.js';
import CommentsEntryPointHeader from '../classes/comments/CommentsEntryPointHeader.js';
@@ -12,14 +15,18 @@ import RelatedChipCloud from '../classes/RelatedChipCloud.js';
import RichMetadata from '../classes/RichMetadata.js';
import RichMetadataRow from '../classes/RichMetadataRow.js';
import SegmentedLikeDislikeButton from '../classes/SegmentedLikeDislikeButton.js';
import SegmentedLikeDislikeButtonView from '../classes/SegmentedLikeDislikeButtonView.js';
import ToggleButton from '../classes/ToggleButton.js';
import TwoColumnWatchNextResults from '../classes/TwoColumnWatchNextResults.js';
import VideoPrimaryInfo from '../classes/VideoPrimaryInfo.js';
import VideoSecondaryInfo from '../classes/VideoSecondaryInfo.js';
import LiveChatWrap from './LiveChat.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
import NavigationEndpoint from '../classes/NavigationEndpoint.js';
import PlayerLegacyDesktopYpcTrailer from '../classes/PlayerLegacyDesktopYpcTrailer.js';
import StructuredDescriptionContent from '../classes/StructuredDescriptionContent.js';
import VideoDescriptionMusicSection from '../classes/VideoDescriptionMusicSection.js';
import LiveChatWrap from './LiveChat.js';
import type { RawNode } from '../index.js';
import type CardCollection from '../classes/CardCollection.js';
import type Endscreen from '../classes/Endscreen.js';
import type PlayerAnnotationsExpanded from '../classes/PlayerAnnotationsExpanded.js';
@@ -27,15 +34,9 @@ import type PlayerCaptionsTracklist from '../classes/PlayerCaptionsTracklist.js'
import type PlayerLiveStoryboardSpec from '../classes/PlayerLiveStoryboardSpec.js';
import type PlayerStoryboardSpec from '../classes/PlayerStoryboardSpec.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import { InnertubeError } from '../../utils/Utils.js';
import { MediaInfo } from '../../core/mixins/index.js';
import StructuredDescriptionContent from '../classes/StructuredDescriptionContent.js';
import { VideoDescriptionMusicSection } from '../nodes.js';
class VideoInfo extends MediaInfo {
#watch_next_continuation?: ContinuationItem;
@@ -86,6 +87,7 @@ class VideoInfo extends MediaInfo {
category: info.microformat?.is(PlayerMicroformat) ? info.microformat?.category : null,
has_ypc_metadata: info.microformat?.is(PlayerMicroformat) ? info.microformat?.has_ypc_metadata : null,
start_timestamp: info.microformat?.is(PlayerMicroformat) ? info.microformat.start_timestamp : null,
end_timestamp: info.microformat?.is(PlayerMicroformat) ? info.microformat.end_timestamp : null,
view_count: info.microformat?.is(PlayerMicroformat) && isNaN(info.video_details?.view_count as number) ? info.microformat.view_count : info.video_details?.view_count
},
like_count: undefined as number | undefined,
@@ -105,11 +107,10 @@ class VideoInfo extends MediaInfo {
// The combined formats only exist for the default language, even for videos with multiple audio tracks
// So we can copy the language from the default audio track to the combined formats
this.streaming_data.formats.forEach((format) => format.language = default_audio_track.language);
} else if (typeof this.captions?.default_audio_track_index !== 'undefined' && this.captions?.audio_tracks && this.captions.caption_tracks) {
} else if (this.captions?.caption_tracks && this.captions?.caption_tracks.length > 0) {
// For videos with a single audio track and captions, we can use the captions to figure out the language of the audio and combined formats
const audioTrack = this.captions.audio_tracks[this.captions.default_audio_track_index];
const index = audioTrack.default_caption_track_index || 0;
const language_code = this.captions.caption_tracks[index].language_code;
const auto_generated_caption_track = this.captions.caption_tracks.find((caption) => caption.kind === 'asr');
const language_code = auto_generated_caption_track?.language_code;
this.streaming_data.adaptive_formats.forEach((format) => {
if (format.has_audio) {
@@ -164,6 +165,17 @@ class VideoInfo extends MediaInfo {
this.basic_info.is_disliked = segmented_like_dislike_button?.dislike_button?.is_toggled;
}
const segmented_like_dislike_button_view = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButtonView);
if (segmented_like_dislike_button_view) {
this.basic_info.like_count = segmented_like_dislike_button_view.like_count;
if (segmented_like_dislike_button_view.like_button) {
const like_status = segmented_like_dislike_button_view.like_button.like_status_entity.like_status;
this.basic_info.is_liked = like_status === 'LIKE';
this.basic_info.is_disliked = like_status === 'DISLIKE';
}
}
const comments_entry_point = results.get({ target_id: 'comments-entry-point' })?.as(ItemSection);
this.comments_entry_point_header = comments_entry_point?.contents?.firstOfType(CommentsEntryPointHeader);
@@ -211,7 +223,6 @@ class VideoInfo extends MediaInfo {
return super.addToWatchHistory();
}
/**
* Retrieves watch next feed continuation.
*/
@@ -239,6 +250,26 @@ class VideoInfo extends MediaInfo {
* Likes the video.
*/
async like(): Promise<ApiResponse> {
const segmented_like_dislike_button_view = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButtonView);
if (segmented_like_dislike_button_view) {
const button = segmented_like_dislike_button_view?.like_button?.toggle_button;
if (!button || !button.default_button || !segmented_like_dislike_button_view.like_button)
throw new InnertubeError('Like button not found', { video_id: this.basic_info.id });
const like_status = segmented_like_dislike_button_view.like_button.like_status_entity.like_status;
if (like_status === 'LIKE')
throw new InnertubeError('This video is already liked', { video_id: this.basic_info.id });
const endpoint = new NavigationEndpoint(button.default_button.on_tap.payload.commands.find((cmd: RawNode) => cmd.innertubeCommand));
const response = await endpoint.call(this.actions);
return response;
}
const segmented_like_dislike_button = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButton);
const button = segmented_like_dislike_button?.like_button;
@@ -260,6 +291,26 @@ class VideoInfo extends MediaInfo {
* Dislikes the video.
*/
async dislike(): Promise<ApiResponse> {
const segmented_like_dislike_button_view = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButtonView);
if (segmented_like_dislike_button_view) {
const button = segmented_like_dislike_button_view?.dislike_button?.toggle_button;
if (!button || !button.default_button || !segmented_like_dislike_button_view.dislike_button || !segmented_like_dislike_button_view.like_button)
throw new InnertubeError('Dislike button not found', { video_id: this.basic_info.id });
const like_status = segmented_like_dislike_button_view.like_button.like_status_entity.like_status;
if (like_status === 'DISLIKE')
throw new InnertubeError('This video is already disliked', { video_id: this.basic_info.id });
const endpoint = new NavigationEndpoint(button.default_button.on_tap.payload.commands.find((cmd: RawNode) => cmd.innertubeCommand));
const response = await endpoint.call(this.actions);
return response;
}
const segmented_like_dislike_button = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButton);
const button = segmented_like_dislike_button?.dislike_button;
@@ -283,6 +334,34 @@ class VideoInfo extends MediaInfo {
async removeRating(): Promise<ApiResponse> {
let button;
const segmented_like_dislike_button_view = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButtonView);
if (segmented_like_dislike_button_view) {
const toggle_button = segmented_like_dislike_button_view?.like_button?.toggle_button;
if (!toggle_button || !toggle_button.default_button || !segmented_like_dislike_button_view.like_button)
throw new InnertubeError('Like button not found', { video_id: this.basic_info.id });
const like_status = segmented_like_dislike_button_view.like_button.like_status_entity.like_status;
if (like_status === 'LIKE') {
button = segmented_like_dislike_button_view?.like_button?.toggle_button;
} else if (like_status === 'DISLIKE') {
button = segmented_like_dislike_button_view?.dislike_button?.toggle_button;
} else {
throw new InnertubeError('This video is not liked/disliked', { video_id: this.basic_info.id });
}
if (!button || !button.toggled_button)
throw new InnertubeError('Like/Dislike button not found', { video_id: this.basic_info.id });
const endpoint = new NavigationEndpoint(button.toggled_button.on_tap.payload.commands.find((cmd: RawNode) => cmd.innertubeCommand));
const response = await endpoint.call(this.actions);
return response;
}
const segmented_like_dislike_button = this.primary_info?.menu?.top_level_buttons.firstOfType(SegmentedLikeDislikeButton);
const like_button = segmented_like_dislike_button?.like_button;

View File

@@ -17,3 +17,4 @@ export { default as Settings } from './Settings.js';
export { default as SmoothedQueue } from './SmoothedQueue.js';
export { default as TimeWatched } from './TimeWatched.js';
export { default as VideoInfo } from './VideoInfo.js';
export { default as TranscriptInfo } from './TranscriptInfo.js';

View File

@@ -2,9 +2,9 @@ import Feed from '../../core/mixins/Feed.js';
import C4TabbedHeader from '../classes/C4TabbedHeader.js';
import ItemSection from '../classes/ItemSection.js';
import { ItemSectionContinuation } from '../index.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IBrowseResponse } from '../types/index.js';
import type { ApiResponse, Actions } from '../../core/index.js';
class Channel extends Feed<IBrowseResponse> {
header?: C4TabbedHeader;

View File

@@ -1,11 +1,11 @@
import { InnertubeError } from '../../utils/Utils.js';
import Feed from '../../core/mixins/Feed.js';
import KidsCategoriesHeader from '../classes/ytkids/KidsCategoriesHeader.js';
import KidsCategoryTab from '../classes/ytkids/KidsCategoryTab.js';
import KidsHomeScreen from '../classes/ytkids/KidsHomeScreen.js';
import { InnertubeError } from '../../utils/Utils.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
class HomeFeed extends Feed<IBrowseResponse> {

View File

@@ -1,10 +1,10 @@
import Feed from '../../core/mixins/Feed.js';
import ItemSection from '../classes/ItemSection.js';
import { InnertubeError } from '../../utils/Utils.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type { ISearchResponse } from '../types/ParsedResponse.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ISearchResponse } from '../types/index.js';
class Search extends Feed<ISearchResponse> {
estimated_results: number;

View File

@@ -1,13 +1,12 @@
import { MediaInfo } from '../../core/mixins/index.js';
import ItemSection from '../classes/ItemSection.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
import PlayerOverlay from '../classes/PlayerOverlay.js';
import SlimVideoMetadata from '../classes/SlimVideoMetadata.js';
import TwoColumnWatchNextResults from '../classes/TwoColumnWatchNextResults.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import { MediaInfo } from '../../core/mixins/index.js';
import type NavigationEndpoint from '../classes/NavigationEndpoint.js';
class VideoInfo extends MediaInfo {
basic_info;

View File

@@ -1,5 +1,3 @@
import type { ApiResponse } from '../../core/Actions.js';
import type { ObservedArray } from '../helpers.js';
import { Parser } from '../index.js';
import MicroformatData from '../classes/MicroformatData.js';
@@ -7,8 +5,10 @@ import MusicCarouselShelf from '../classes/MusicCarouselShelf.js';
import MusicDetailHeader from '../classes/MusicDetailHeader.js';
import MusicShelf from '../classes/MusicShelf.js';
import type { ApiResponse } from '../../core/index.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/index.js';
import type MusicResponsiveListItem from '../classes/MusicResponsiveListItem.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
class Album {
#page: IBrowseResponse;

View File

@@ -1,6 +1,4 @@
import { Parser } from '../index.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import { InnertubeError } from '../../utils/Utils.js';
import MusicShelf from '../classes/MusicShelf.js';
@@ -9,6 +7,8 @@ import MusicPlaylistShelf from '../classes/MusicPlaylistShelf.js';
import MusicImmersiveHeader from '../classes/MusicImmersiveHeader.js';
import MusicVisualHeader from '../classes/MusicVisualHeader.js';
import MusicHeader from '../classes/MusicHeader.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
class Artist {

View File

@@ -1,4 +1,5 @@
import { Parser } from '../index.js';
import { InnertubeError } from '../../utils/Utils.js';
import Grid from '../classes/Grid.js';
import MusicCarouselShelf from '../classes/MusicCarouselShelf.js';
@@ -6,10 +7,9 @@ import MusicNavigationButton from '../classes/MusicNavigationButton.js';
import SectionList from '../classes/SectionList.js';
import SingleColumnBrowseResults from '../classes/SingleColumnBrowseResults.js';
import type { ApiResponse } from '../../core/Actions.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ApiResponse } from '../../core/index.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { IBrowseResponse } from '../types/index.js';
class Explore {
#page: IBrowseResponse;

View File

@@ -1,17 +1,16 @@
import { InnertubeError } from '../../utils/Utils.js';
import { Parser, SectionListContinuation } from '../index.js';
import MusicCarouselShelf from '../classes/MusicCarouselShelf.js';
import SectionList from '../classes/SectionList.js';
import SingleColumnBrowseResults from '../classes/SingleColumnBrowseResults.js';
import MusicTastebuilderShelf from '../classes/MusicTastebuilderShelf.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import { InnertubeError } from '../../utils/Utils.js';
import ChipCloud from '../classes/ChipCloud.js';
import ChipCloudChip from '../classes/ChipCloudChip.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/index.js';
class HomeFeed {
#page: IBrowseResponse;
#actions: Actions;

View File

@@ -1,6 +1,4 @@
import { Parser, GridContinuation, MusicShelfContinuation, SectionListContinuation } from '../index.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import Grid from '../classes/Grid.js';
import MusicShelf from '../classes/MusicShelf.js';
@@ -12,11 +10,12 @@ import ChipCloud from '../classes/ChipCloud.js';
import ChipCloudChip from '../classes/ChipCloudChip.js';
import MusicMultiSelectMenuItem from '../classes/menus/MusicMultiSelectMenuItem.js';
import MusicSortFilterButton from '../classes/MusicSortFilterButton.js';
import type MusicMenuItemDivider from '../classes/menus/MusicMenuItemDivider.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { IBrowseResponse } from '../types/index.js';
import type MusicMenuItemDivider from '../classes/menus/MusicMenuItemDivider.js';
import type { ApiResponse, Actions } from '../../core/index.js';
class Library {
#page: IBrowseResponse;

View File

@@ -4,15 +4,14 @@ import MusicCarouselShelf from '../classes/MusicCarouselShelf.js';
import MusicDetailHeader from '../classes/MusicDetailHeader.js';
import MusicEditablePlaylistDetailHeader from '../classes/MusicEditablePlaylistDetailHeader.js';
import MusicPlaylistShelf from '../classes/MusicPlaylistShelf.js';
import type MusicResponsiveListItem from '../classes/MusicResponsiveListItem.js';
import MusicShelf from '../classes/MusicShelf.js';
import SectionList from '../classes/SectionList.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray, YTNode } from '../helpers.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { ApiResponse, Actions } from '../../core/index.js';
import type { IBrowseResponse } from '../types/index.js';
import type MusicResponsiveListItem from '../classes/MusicResponsiveListItem.js';
class Playlist {
#page: IBrowseResponse;

View File

@@ -1,22 +1,20 @@
import { Parser } from '../index.js';
import type Actions from '../../core/Actions.js';
import type { ApiResponse } from '../../core/Actions.js';
import { InnertubeError } from '../../utils/Utils.js';
import Playlist from './Playlist.js';
import HighlightsCarousel from '../classes/HighlightsCarousel.js';
import MusicCarouselShelf from '../classes/MusicCarouselShelf.js';
import MusicElementHeader from '../classes/MusicElementHeader.js';
import MusicHeader from '../classes/MusicHeader.js';
import SingleColumnBrowseResults from '../classes/SingleColumnBrowseResults.js';
import Playlist from './Playlist.js';
import ItemSection from '../classes/ItemSection.js';
import Message from '../classes/Message.js';
import SectionList from '../classes/SectionList.js';
import Tab from '../classes/Tab.js';
import { InnertubeError } from '../../utils/Utils.js';
import type { ObservedArray } from '../helpers.js';
import type { IBrowseResponse } from '../types/ParsedResponse.js';
import type { IBrowseResponse } from '../types/index.js';
import type { ApiResponse, Actions } from '../../core/index.js';
class Recap {
#page: IBrowseResponse;

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