Compare commits

...

405 Commits

Author SHA1 Message Date
github-actions[bot]
1e29019a07 chore(main): release 10.2.0 (#688)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-07-25 10:52:50 -03:00
Luan
6765f4e0d7 fix(Player): Bump cache version (#702)
We should always do this after updating the sig/nsig code, it's so that the old cache gets ignored : ).
2024-07-25 10:48:24 -03:00
absidue
3048f70f60 fix(Player): Fix extracting the n-token decipher algorithm again (#701) 2024-07-25 10:07:00 -03:00
Brahim Hadriche
090539b28f feat(parser): add classdata to unhandled parse errors (#691) 2024-07-24 15:55:20 -03:00
Brahim Hadriche
6d0bc89be1 fix(parser): ignore MiniGameCardView node (#692) 2024-07-24 15:54:37 -03:00
GurumNyang
a5f62093a1 feature(proto): Add comment_id to commentSectionParams (#693) 2024-07-24 15:54:14 -03:00
absidue
a352ddeb9d feat(Format): Add is_secondary for detecting secondary audio tracks (#697) 2024-07-24 15:53:27 -03:00
Brahim Hadriche
0f8f92a28a fix(parser): ThumbnailView background color (#686) 2024-07-11 14:31:27 -03:00
github-actions[bot]
7d03469e64 chore(main): release 10.1.0 (#669)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-07-10 03:44:43 -03:00
Luan
62ac2f6f32 fix(proto): Update Context message
Closes #681
2024-07-10 03:41:16 -03:00
absidue
142a7d0428 fix(Player): Fix extracting the n-token decipher algorithm (#682)
* fix(Player): Fix extracting the n-token decipher algorithm

* fix: bump Jinter to v2

---------

Co-authored-by: Luan <luan.lrt4@gmail.com>
2024-07-10 02:21:39 -03:00
Luan
efa7205723 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2024-07-01 08:53:45 -03:00
Luan
84f90aaf29 fix(Session): Round UTC offset minutes 2024-07-01 08:53:08 -03:00
absidue
858cdd197c feat(toDash): Add the "dub" role to translated captions (#677) 2024-06-30 23:05:08 -03:00
Luan
5a8fd3ad37 feat(Session): Add configInfo to InnerTube context
Minor addition. It's needed for certain UMP requests.
2024-06-30 22:51:02 -03:00
슈리튬
a19511de24 fix(FormatUtils): Throw an error if download requests fails 2024-06-28 16:45:39 -03:00
absidue
bd9f6ac64c feat(toDash): Add option to include WebVTT or TTML captions (#673) 2024-06-25 01:22:11 -03:00
absidue
e5aab9a9b3 fix(toDash): Fix image representations not being spec compliant (#672) 2024-06-24 15:48:38 -03:00
Luan
d6fa134c3d chore(Playlist): Add MusicResponsiveHeader to header types
Oops! I forgot this one also existed : ).
2024-06-21 21:12:54 -03:00
Luan
fe953072a2 chore: fix tests 2024-06-21 20:57:38 -03:00
Luan
055fa33403 chore: lint 2024-06-21 19:32:50 -03:00
Luan
14c3a06d40 fix(YTMusic): Add support for new header layouts
This is due to a minor page redesign by YouTube Music. See https://9to5google.com/2024/06/20/youtube-music-web-album-playlist-redesign/.
2024-06-21 19:31:40 -03:00
Luan
67376afae6 chore(Format): Clean up and add some extra fields 2024-06-16 16:22:33 -03:00
Luan
4cbaa7983f fix(InfoPanelContent): Update InfoPanelContent node to also support paragraphs
This would fail when `attributedParagraphs` was missing, so we still need `paragraphs` there.
2024-06-16 15:39:47 -03:00
github-actions[bot]
9802483233 chore(main): release 10.0.0 (#658)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-06-09 20:43:14 -03:00
Aidar Nugmanoff
2980a608b6 feat(Platform): Add support for react-native platform (#593) 2024-06-09 18:15:57 -03:00
Luan
b6cecb10f5 chore(docs): update readme 2024-06-09 18:02:46 -03:00
Luan
040a091639 fix(FlexibleActionsView): Update actions array type to include ToggleButtonView 2024-06-08 16:33:34 -03:00
Luan
3939405cc6 chore(Player): Rephrase nsig failure message 2024-06-07 14:26:27 -03:00
Luan
978ab1ed29 chore(docs): fix typo [skip ci] 2024-06-07 14:18:23 -03:00
Luan
5cdb9e1e2f fix(InfoPanelContainer): Use new attributed text prop
+ And update other related nodes.
2024-06-07 14:15:44 -03:00
Luan
15f3b5fdba fix(ButtonView): Rename type property to button_type
It was overriding the static property "type".
2024-06-05 16:00:16 -03:00
Luan
384b80ee41 fix(Cache): Use TextEncoder to encode compressed data 2024-06-05 12:30:12 -03:00
Luan
b588554ce1 chore: update docs [skip ci] 2024-06-03 19:16:41 -03:00
Luan
583fd9f8d7 fix(MusicResponsiveHeader): Add Text import
Looks like I forgot to add it.
2024-06-03 19:08:33 -03:00
Luan
7953296580 feat(Session): Add enable_session_cache option (#664)
See https://github.com/LuanRT/YouTube.js/pull/663#issuecomment-2146161637
2024-06-03 19:04:30 -03:00
Luan
cf29664d37 perf(general): Add session cache and LZW compression (#663)
* feat(utils): Implement LZW compression module

* feat(Session): Implement cache for sessions
This should improve performance quite a bit for those who are not using the `generate_session_locally` option (like me :P).

* refactor(Player): Add LZW compression
This considerably reduces the size of the cache.
2024-06-03 18:21:48 -03:00
Luan
4015a5e560 chore(JsRuntime): Change log levels in evaluate function 2024-06-03 17:42:18 -03:00
Luan
184df79b3a refactor(HTTPClient): Use getCookie fn to get SAPISID token 2024-06-03 17:41:09 -03:00
Luan
000f3f0915 refactor(Artist.ts): Change sections type to ObservedArray<MusicCarouselShelf | MusicShelf> 2024-06-03 17:39:42 -03:00
Luan
8372b3d22f Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2024-06-03 17:33:04 -03:00
Luan
b9d50daa57 chore: clean up
Updated deps, fixed some ts issues, renamed "scripts" to "dev-scripts", and added a script to delete build output.
2024-06-03 17:29:11 -03:00
absidue
031ffb696e feat(toDash): Add support for stable volume/DRC (#662) 2024-05-28 02:43:10 -03:00
Luan
8e942ada3b chore(docs): fix some markdown issues 2024-05-24 04:33:03 -03:00
LuanRT
aa3f34c428 chore: Fix browser example 2024-05-23 21:00:47 -03:00
LuanRT
c82bb70180 chore(HTTPClient): Remove env check when setting Android headers
These requests are supposed to be proxied, so there's no need to worry about browsers not liking it.
2024-05-23 20:58:37 -03:00
LuanRT
766045049d refactor(Innertube#getPlaylists)!: Return a Feed instance instead of items 2024-05-21 20:50:41 -03:00
Luan
b6ce5f903f refactor(OAuth2)!: Rewrite auth module (#661)
This is a rewrite of the OAuth2 module to address some bugs and inconsistencies. And since it changes the structure of the credentials, I'm marking this as a breaking change.

Note that you will have to update your existing credentials, that is if you wish to continue using them. Otherwise, simply delete them and sign in again.
2024-05-21 18:47:31 -03:00
absidue
6bb2086875 feat(Format): Add is_drc (#656) 2024-05-06 11:55:58 -03:00
Brahim Hadriche
810665407e Item section target_id fix (#655) 2024-04-29 14:22:28 -03:00
github-actions[bot]
1b00e2c6ce chore(main): release 9.4.0 (#644)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-04-29 09:14:43 -03:00
LuanRT
ea82beaa10 feat(Parser): Add MusicResponsiveHeader node 2024-04-29 08:24:13 -03:00
absidue
0ba8c54257 feat(Format): Add spatial_audio_type (#647) 2024-04-29 08:10:08 -03:00
Brahim Hadriche
7315fca1b4 Add getPlaylists function (#650) 2024-04-29 08:09:35 -03:00
Brahim Hadriche
0602dd2c3d Lint fix (#651) 2024-04-29 08:07:24 -03:00
LuanRT
13321888e8 chore(PlayerEndpoint): Remove outdated code 2024-04-29 08:05:59 -03:00
absidue
d48b9d0946 chore(HTTPClient): Add X-Youtube-Client-Name and remove X-Origin headers (#645) 2024-04-25 18:04:10 -03:00
LuanRT
592ddac30f chore: Fix tests
Oops :)
2024-04-19 16:37:38 -03:00
LuanRT
1ec2ea85e2 refactor(Music#getRelated): Return page contents directy 2024-04-19 16:22:21 -03:00
absidue
064436cef3 feat(Format): Add projection_type and stereo_layout (#643)
5930ebda46
2024-04-19 16:08:12 -03:00
ChunkyProgrammer
4022d7aa89 Remove test code (#636) 2024-04-11 23:29:46 -03:00
github-actions[bot]
cd69ce73c1 chore(main): release 9.3.0 (#635)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-04-11 18:19:12 -03:00
LuanRT
1c08bfe113 feat(CommentView): Implement comment interaction methods 2024-04-11 18:04:45 -03:00
LuanRT
a624963384 docs(Comments): Update API ref 2024-04-11 18:03:04 -03:00
LuanRT
66e34f9388 fix(CommentThread): Replies not being parsed correctly 2024-04-11 16:05:59 -03:00
github-actions[bot]
0c2cdc1599 chore(main): release 9.2.1 (#632)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-04-09 17:42:18 -03:00
absidue
010704929f fix(toDash): Add missing transfer characteristics for h264 streams (#631) 2024-04-09 17:41:08 -03:00
dependabot[bot]
d4a938771b chore(deps): bump undici from 5.28.3 to 5.28.4 (#627)
Bumps [undici](https://github.com/nodejs/undici) from 5.28.3 to 5.28.4.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.28.3...v5.28.4)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-04 15:02:28 -03:00
github-actions[bot]
5ecfb08772 chore(main): release 9.2.0 (#611)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-03-31 11:39:15 -03:00
Ayoub
2029aec90d feat: add support of cloudflare workers (#596) 2024-03-31 11:37:06 -03:00
Luan
d589365ea2 fix(PlayerEndpoint): Workaround for "The following content is not available on this app" (Android) (#624)
* chore: Update Android client version and UA

* refactor: Update shorts parameter protobuf

* chore: Update auto generated files

* chore: Add test

* chore: Update comments test id (unrelated)

* chore: Update comments test again (unrelated)
2024-03-31 11:35:12 -03:00
LuanRT
45f33d8c04 refactor(MusicResponsiveListItem): Improve podcast and video/song parsing 2024-03-25 11:55:06 -03:00
LuanRT
92117eaaa0 chore(tests): use test instead of describe 2024-03-25 08:26:29 -03:00
LuanRT
39725374e3 chore(tests): remove beforeAll for the home feed test 2024-03-25 08:23:59 -03:00
LuanRT
213d78b1ab chore: remove home feed continuation test
Home feed now requires a visitor id with reputation or an account.

Removing this for now until I find a way around it for the tests at least.
2024-03-25 08:19:14 -03:00
LuanRT
28f53a698d chore: remove API key parameter
No longer needed.
2024-03-25 08:07:49 -03:00
Adam Learns
776a156f65 Fix broken README links (#618)
There were apostrophes in the links.
2024-03-25 07:25:17 -03:00
absidue
4a9bd32fd7 chore(LockupView): Remove debug logging (#617) 2024-03-25 07:24:24 -03:00
WhiteMind
3170659880 fix(Cache): handle the value read from the db correctly according to its type (#620) 2024-03-25 07:23:56 -03:00
absidue
e6f1f078a8 feat(Text): Support formatting and emojis in fromAttributed (#615) 2024-03-25 07:22:24 -03:00
absidue
900f557202 feat(parser): Support CommentView nodes (#614) 2024-03-25 07:20:29 -03:00
absidue
7ca2a0c3e4 feat(parser): Support LockupView and it's child nodes (#609) 2024-02-29 13:29:53 -03:00
LuanRT
f95283b236 chore: add any-of-issue-labels option to stale workflow 2024-02-22 23:04:46 -03:00
LuanRT
f6a7bcc44a Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2024-02-22 22:47:36 -03:00
LuanRT
c444843799 chore: update workflows 2024-02-22 22:47:17 -03:00
github-actions[bot]
5fe91d6642 chore(main): release 9.1.0 (#600)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-02-22 22:29:37 -03:00
absidue
bff65f8889 feat(Format): Support caption tracks in adaptive formats (#598) 2024-02-22 22:28:16 -03:00
dependabot[bot]
dac5eb712d chore(deps): bump undici from 5.27.0 to 5.28.3 (#599)
Bumps [undici](https://github.com/nodejs/undici) from 5.27.0 to 5.28.3.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.27.0...v5.28.3)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-22 22:27:47 -03:00
LuanRT
2068dfb73e fix(Session): Don't try to extract api version from service worker
It doesn't make sense to do this anyway because if it ever changed, we'd probably have to refactor the entire library.

Closes #602, #603, #604
2024-02-22 22:25:30 -03:00
LuanRT
3e84775fd3 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2024-02-18 23:37:13 -03:00
LuanRT
89fa3b27a8 fix(Playlist): items getter failing if a playlist contains Shorts 2024-02-18 23:36:01 -03:00
github-actions[bot]
ab7201f0cc chore(main): release 9.0.2 (#591)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-31 19:50:59 -03:00
absidue
b21eb9f33d fix(VideoInfo): Fix error because of typo in getWatchNextContinuation (#590) 2024-01-31 19:34:46 -03:00
LuanRT
0751793380 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2024-01-29 22:19:35 -03:00
LuanRT
5c91c2af4a chore: merge main 2024-01-29 22:14:22 -03:00
LuanRT
47cad4c6e1 chore: lint build scripts [skip ci] 2024-01-29 22:11:20 -03:00
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
github-actions[bot]
572e16c541 chore(main): release 8.0.0 (#530)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-12-01 00:54:29 -03:00
LuanRT
ed2cbf8a13 chore: lint 2023-12-01 00:50:26 -03:00
LuanRT
4261915fd4 fix(Library)!: Add support for the new layout and remove profile & stats info 2023-12-01 00:49:22 -03:00
LuanRT
f74ed5a1cf fix(StructuredDescriptionContent): Add ReelShelf to list of possible nodes 2023-11-30 23:36:32 -03:00
LuanRT
5ae15be63d fix(VideoAttributeView): Fix image and overflow_menu_on_tap props 2023-11-30 23:34:31 -03:00
Konstantin
a32aa8c633 feat: Add Shorts endpoint (#512)
* chore: first try for shorts endpoints

* chore: add shorts to index

* fix: fix code style

* chore: fix suggestions

* fix: fix code style with spaces on curly brackets

* chore: add curly rule to eslint

* chore: run request in parallel

* chore: remove console.logs and add other expect tests

* chore: apply eslint suggestions

* Update ReelPlayerOverlay.ts

* Update VideoInfo.ts

* chore: remove console.log from tests

---------

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-11-30 22:58:11 -03:00
absidue
4806fc6c11 feat(toDash): Add contentType to audio and video adaption sets (#539) 2023-11-30 22:33:13 -03:00
absidue
95ed60207a perf: Use named Parser import, to allow bundlers to create direct function references (#535)
Co-authored-by: Luan <luan.lrt4@gmail.com>
2023-11-30 22:31:59 -03:00
absidue
b50e2001aa chore: Clean up so unneeded private properties (#540) 2023-11-30 22:21:14 -03:00
absidue
b60930a0c1 feat(parser): Add ChannelOwnerEmptyState (#541) 2023-11-30 22:12:11 -03:00
absidue
c66eb1fecf feat(Channel): Support new about popup (#537)
* feat(Channel): Support new about popup

* chore: Minor cleanup

* fix(concatMemos): Merge duplicate nodes instead of overwriting

* fix(Feed): `has_continuation` and `getContinuation()` avoid header continuations

* chore(Channel): Remove unused import

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-11-30 22:06:25 -03:00
absidue
6a5a579e39 fix(Channel)!: Remove getChannels() and has_channels, as YouTube removed the tab (#542)
BREAKING CHANGE: YouTube removed the "Channels" tab on channels, so this
pull request removes the `getChannels()` method and `has_channels`
getter from the `YT.Channel` class, as they are no longer useful. The
featured channels are now shown on the channel home tab. To get them
you can use the `channels` getter on the home tab of the channel.
Please note that some channel owners might not have added that section
to their home page yet, so you won't be able to get the featured
channels for those channels. The home tab is the default tab that is
returned when you call `InnerTube#getChannel()`, you can also access
that tab by calling `getHome()` on a `YT.Channel` object.
2023-11-30 22:03:36 -03:00
JellyBrick
ff4ab1680e feat: add VideoAttributeView (#531)
* feat: add `VideoAttributeView`

* fix: remove `logging_directives`

See https://github.com/LuanRT/YouTube.js/pull/531#discussion_r1375315550

* fix: Update src/parser/classes/VideoAttributeView.ts

---------

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
Co-authored-by: Luan <luan.lrt4@gmail.com>
2023-11-30 21:38:51 -03:00
JellyBrick
9007b65237 feat(Parser): Add ClipSection (#532)
* feat: add `ClipSection`

* fix: Update src/parser/classes/ClipCreation.ts

---------

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
2023-11-30 21:29:18 -03:00
JellyBrick
e02139532b feat: add FeedNudge (#533)
* feat: add `FeedNudge`

see https://github.com/LuanRT/YouTube.js/actions/runs/6679090140/job/18150827068?pr=532

* fix: lint

* fix: update parser-map
2023-10-29 09:51:25 -03:00
JellyBrick
db7f6209b2 feat: Use overrides instead of --legacy-peer-deps (#529) 2023-10-28 16:32:39 -03:00
github-actions[bot]
312c636ec4 chore(main): release 7.0.0 (#528)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-10-28 15:21:53 -03:00
Azarattum
4c0de199e8 fix(build): Inline package.json import to avoid runtime erros (#509)
* chore(main): Inline package.json import

* chore: add `--legacy-peer-deps` flag to ci

* chore: update lock file

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-10-28 15:19:37 -03:00
Ryan Sandbach
9ab528ec82 feat(Kids): Add blockChannel command to easily block channels (#503)
* Add blockChannel command to support easily blocking content for supervised accounts.

* Moved blockChannel functionality to the Kids client and updated API docs.

* Fix whitepsace issues.

* Resolve remaining linting errors.

* Avoid changing interaction manager. Remove comment for ToggleButton change.

* chore: clean up

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-10-28 14:28:17 -03:00
LuanRT
24ffb01aef Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-10-28 13:31:10 -03:00
LuanRT
eaac38c919 chore: lint 2023-10-28 13:30:58 -03:00
absidue
e627887fe0 chore(MediaInfo): Throw helpful errors when calling toDash or download for live and Post-Live DVR videos (#526)
* Address pull request feedback

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-10-28 13:29:37 -03:00
LuanRT
beaa28f4c6 feat(music#getSearchSuggestions)!: Return array of SearchSuggestionsSection instead of a single node 2023-10-28 13:27:58 -03:00
LuanRT
a45273fec4 feat(parser): Add PlayerOverflow and PlayerControlsOverlay 2023-10-28 13:17:26 -03:00
absidue
bc97e07ac6 feat(UpdateViewerShipAction): Add original_view_count and unlabeled_view_count_value (#527) 2023-10-21 12:39:03 -03:00
LuanRT
f35b4c2c8c Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-10-18 23:32:01 -03:00
LuanRT
c934325648 chore: update readme [skip ci] 2023-10-18 23:31:03 -03:00
dependabot[bot]
cd27acd25b chore(deps-dev): bump @babel/traverse from 7.22.10 to 7.23.2 (#524)
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.22.10 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-16 22:55:44 -03:00
dependabot[bot]
83b42d2585 chore(deps): bump undici from 5.23.0 to 5.26.2 (#523)
Bumps [undici](https://github.com/nodejs/undici) from 5.23.0 to 5.26.2.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.23.0...v5.26.2)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-16 17:36:00 -03:00
github-actions[bot]
e54c0c4bf1 chore(main): release 6.4.1 (#507)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-10-02 00:04:10 -03:00
LuanRT
8e372d5c67 fix(Feed): Do not throw when multiple continuations are present 2023-10-01 23:39:54 -03:00
LuanRT
987f50604a fix(Playlist): Throw a more helpful error when parsing empty responses 2023-10-01 23:31:05 -03:00
Luan
69702085c6 refactor: Move transcript logic to MediaInfo (#511)
* refactor: Move transcript logic to `MediaInfo`

+ Add support for retrieving different languages.

* docs: Update and add examples
2023-09-17 22:17:14 -03:00
absidue
d2959b3a55 perf: Cache deciphered n-params by info response (#505) 2023-09-17 18:52:32 -03:00
absidue
68df321858 perf(generator): Remove duplicate checks in isMiscType (#506) 2023-09-15 15:25:08 -03:00
Ryan Sandbach
f4bc8508d0 chore(docs): Minor update (#502)
* Updated documentation example to matche syntax of existing parsers.

* Changed from require since package is setup as module.
2023-09-12 03:49:36 -03:00
LuanRT
e216124bb0 chore: update docs 2023-09-10 02:14:14 -03:00
github-actions[bot]
6d98abbd53 chore(main): release 6.4.0 (#499)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-09-10 02:08:24 -03:00
LuanRT
fba3fc9714 fix(BackstagePost): vote_button type mismatch 2023-09-10 02:06:01 -03:00
Luan
f94ea6cf91 feat: Add support for retrieving transcripts (#500)
* feat: Add support for retrieving transcripts

* chore: lint

* chore: update docs

* chore: Do not include nodes in errors thrown

* chore: Improve error messages

* fix(ExpandableMetadata): `expanded_content` type mismatch

* chore: lint
2023-09-10 01:50:30 -03:00
Jeremy Banks
86fb33ed03 feat(PlaylistManager): add .setName() and .setDescription() functions for editing playlists (#498) 2023-09-01 17:40:25 -03:00
github-actions[bot]
bff4210349 chore(main): release 6.3.0 (#495)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-31 20:41:06 -03:00
absidue
91de6e5c0e feat(ChannelMetadata): Add music_artist_name (#497) 2023-08-31 20:29:58 -03:00
absidue
c26972c42a fix(CompactMovie): Add missing import and remove unnecessary console.log (#496) 2023-08-31 20:28:25 -03:00
Jeremy Banks
8bc2aaa358 feat(Session): Add on_behalf_of_user session option. (#494)
This specifies which channel to use if multiple are associated with the logged-in account.
2023-08-31 08:20:37 -03:00
github-actions[bot]
2e5f076fd7 chore(main): release 6.2.0 (#491)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-29 14:25:32 -03:00
absidue
0412fa05ff fix(Format): Fix is_original always being true (#492) 2023-08-29 14:23:08 -03:00
Luan
10c15bfb9f feat(Session): Add fallback for session data retrieval (#490)
* feat(Session): Add fallback for session data retrieval

Should have added this when we first implemented session data retrieval to be honest. It makes a request to YouTube's service worker and the data there can change or the request can just fail.

* chore: lint
2023-08-28 07:18:27 -03:00
github-actions[bot]
4862c35cee chore(main): release 6.1.0 (#489)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-27 16:43:10 -03:00
absidue
2eed1726d5 feat(parser): Add CompactMovie (#487) 2023-08-27 16:29:50 -03:00
absidue
8b69587787 feat(parser): Add AlertWithButton (#486) 2023-08-27 16:29:23 -03:00
absidue
ed7be2a675 feat(parser): Add ChannelHeaderLinksView (#484) 2023-08-27 16:28:49 -03:00
github-actions[bot]
361fb4a9f1 chore(main): release 6.0.2 (#481)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-24 17:06:07 -03:00
Daniel Wykerd
1c3ea2acd3 fix: invalid set ids in dash manifest (#480) 2023-08-24 15:59:10 -03:00
github-actions[bot]
859c4585d9 chore(main): release 6.0.1 (#476)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-22 09:07:49 -03:00
LuanRT
751f2b90fd Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-08-22 09:06:23 -03:00
LuanRT
90be877d28 fix(SearchSubMenu): Groups not being parsed due to a typo 2023-08-22 09:06:06 -03:00
github-actions[bot]
052632314b chore(main): release 6.0.0 (#461)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-08-18 08:39:05 -03:00
LuanRT
22a38c0762 feat(Session): Add IOS to ClientType enum 2023-08-18 08:36:17 -03:00
LuanRT
f7614634b6 chore: lint 2023-08-18 08:26:39 -03:00
LuanRT
bf1510b235 fix(parser): Logger logging classdata as [Object object] 2023-08-18 08:17:23 -03:00
LuanRT
815e54b854 feat(MusicResponsiveListItem): Detect non music tracks properly
This should make it easier to identify podcast episodes.
2023-08-18 08:15:04 -03:00
LuanRT
f7666051f6 chore(parser): update MusicCarouselShelf 2023-08-18 08:11:04 -03:00
LuanRT
494ee8776a feat(parser): add MusicMultiRowListItem
Used to display podcasts.
2023-08-18 08:09:04 -03:00
Daniel Wykerd
87ed3960ff refactor!: replace unnecessary classes with pure functions (#468)
* deps: update linkedom

* refactor!: remove YTNodeGenerator in favour of namespaced pure functions

BREAKING CHANGES:
- Removes `YTNodeGenerator` from `import('youtubei.js').Generator` and exposes its functions directly in `import('youtubei.js').Generator`

* refactor!: replace Parser class with pure functions

- Remove Parser class in favour of pure functions
- Merge duplicate classes `AppendContinuationItemsAction` into a single class
- Move continuation parsers into a seperate file
- Add better custom logging support to parser methods as per issue #460

* refactor!: replace Proto class with pure functions

* chore: update package-lock.json

* refactor!: replace FormatUtils with pure functions and JSX components

- Replace linkedom DASH manifest generation with a dependency free JSX implementation
- Remove FormatUtils class in favour of pure functions
- Remove DOMParser requirement
- Remove duplicate types

* refactor: implement changes from #462

* chore: lint

* fix: deno support

* fix: render valid xml document

* fix: wrong function call in DashUtils

* fix: typo in parser

Co-authored-by: LuanRT <luan.lrt4@gmail.com>

* refactor!: move streaming info logic into seperate function

This allows users to access the same data available in the dash manifest while also simplifying the manifest generation

* chore: lint

* refactor: readability improvements & fixes

Remove redundant getAudioTrackGroups
General readability improvements in StreamingInfo.ts
Share response object between `getBitrate` and `getMimeType` as to not make duplicate requests

* build: remove unnecessary step in deno build

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>

* refactor: move types to `types` directory

* docs: add back comments lost during refactor

* chore: lint

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
2023-08-18 06:49:58 -03:00
LuanRT
eb3cca1e2e chore(example/browser): fix ALR requests failing 2023-08-18 06:33:01 -03:00
LuanRT
9971ffe021 chore: update package.json [skip ci] 2023-08-12 23:52:16 -03:00
LuanRT
7949b3df66 chore(COLLABORATORS.md): add Absidue 2023-08-12 23:50:27 -03:00
LuanRT
aa385142e4 chore: update contact email [skip ci] 2023-08-12 23:45:28 -03:00
LuanRT
6c8a916f0f chore: migrate browser example to Shaka player [skip ci] (#471)
* chore: use Shaka for the browser example

* chore: lint

* fix(HashtagFeed): resolve type casting issue so tests pass
2023-08-12 23:21:20 -03:00
absidue
31d27b1bca fix(Format): Extracting audio language from captions (#470) 2023-08-12 16:01:32 -03:00
LuanRT
cb37c6a17b chore: use ESM for dev scripts [skip ci]
Just to keep things consistent.
2023-08-11 19:29:51 -03:00
absidue
1ff3e1a440 fix(toDash): Format grouping into AdaptationSets (#462) 2023-08-09 16:07:03 -03:00
Ronnie Vega
46fe18b763 feat(VideoInfo): support iOS client (#467) 2023-08-09 04:29:25 -03:00
absidue
0dda97e0b0 perf: Cleanup some unnecessary uses of YTNode#key and Maybe (#463) 2023-08-06 19:15:47 -03:00
absidue
e370116092 fix(Playlist): Only try extracting the subtitle for the first page (#465) 2023-08-06 19:14:21 -03:00
LuanRT
3bc53a8c12 fix(parser): Allow any property in the RawResponse interface 2023-08-01 20:38:15 -03:00
github-actions[bot]
74e1a5e068 chore(main): release 5.8.0 (#459)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-30 16:02:19 -03:00
absidue
0fa5a859ae feat(YouTube Playlist): Add subtitle and fix author optionality (#458) 2023-07-30 15:59:39 -03:00
LuanRT
02a111250a chore: update image links 2023-07-28 07:12:45 -03:00
github-actions[bot]
c1886f9a83 chore(main): release 5.7.1 (#455)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-25 02:46:12 -03:00
LuanRT
5f4cbdb904 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-07-25 02:45:00 -03:00
LuanRT
d91695a9ec fix(SearchHeader): remove console.log
Oopsie!
2023-07-25 02:44:43 -03:00
github-actions[bot]
137464ca66 chore(main): release 5.7.0 (#451)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-24 20:48:09 -03:00
LuanRT
6997982cf2 feat(parser): Add SearchHeader
We may want to remove the old SearchSubMenu node in the future but YouTube still uses it sometimes, so we will keep it for now.

Closes #452
2023-07-24 20:26:05 -03:00
absidue
18cbc8c038 feat(parser): Add PageHeader (#450) 2023-07-19 19:00:26 -03:00
github-actions[bot]
30ff087587 chore(main): release 5.6.0 (#448)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-18 15:34:48 -03:00
absidue
1a034733f6 feat(toDash): Add option to include thumbnails in the manifest (#446)
* feat(toDash): Add option to include thumbnails in the manifest

* refactor: Move toDash function back to MediaInfo class
2023-07-18 02:08:02 -03:00
ChunkyProgrammer
c477b824c0 feat(parser): Add IncludingResultsFor (#447) 2023-07-18 01:53:44 -03:00
github-actions[bot]
7e5c3648c1 chore(main): release 5.5.0 (#441)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-16 17:57:11 -03:00
absidue
bdd98a3b9b feat(Format): Populate audio language from captions when available (#445) 2023-07-16 17:54:26 -03:00
LuanRT
06750aaa74 chore: lint 2023-07-16 17:40:05 -03:00
LuanRT
708c5f7394 feat(parser): add MacroMarkersList (#444)
This should fix a few parsing issues that were happening after recent updates.
2023-07-16 17:38:16 -03:00
LuanRT
a9cdbf7010 feat(parser): Add ShowMiniplayerCommand (#443) 2023-07-16 17:34:42 -03:00
LuanRT
b50d1ef67d fix(StructuredDescriptionContent): items can also be a HorizontalCardList 2023-07-16 17:00:36 -03:00
LuanRT
555d257459 feat(parser): Add CommentsSimplebox parser (#442) 2023-07-16 16:46:46 -03:00
titong0
2aef67876e fix(package): Bump Jinter to fix bad export order (#439)
Version 1.0.0 has an export order which crashes some webpack environments (at least I came across it when using next.js 13). Updating to 1.1.0 fixes it. A bit more context here https://github.com/LuanRT/YouTube.js/issues/432

* chore(package): update lock file

* chore: lint

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-07-16 16:23:14 -03:00
ChunkyProgrammer
ae2557d15c feat(parser): Add HashtagTile (#440) 2023-07-16 15:35:55 -03:00
github-actions[bot]
8c688efb4a chore(main): release 5.4.0 (#438)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-14 00:00:43 -03:00
ChunkyProgrammer
cffa868c6e feat(parser): Add Quiz (#437) 2023-07-13 23:57:39 -03:00
ChunkyProgrammer
f267fcd8be Add getReleases and getPodcasts to Channel (#436)
* feat(Channel): Add `getReleases` method

* feat(Channel): Add `getPodcasts` method

* Fix(Playlist): Parse `PlaylistCustomThumbnail`
2023-07-13 15:25:20 -03:00
github-actions[bot]
23c22a93c4 chore(main): release 5.3.0 (#433)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-11 15:48:51 -03:00
absidue
1ca20836bf perf(Format): Cleanup the xtags parsing (#434) 2023-07-11 15:45:42 -03:00
absidue
5f058e69ae perf(toDash): Hoist duplicates from Representation to AdaptationSet (#431) 2023-07-11 15:22:02 -03:00
absidue
3500e92632 feat(toDash): Add color information (#430) 2023-07-10 21:25:48 -03:00
LuanRT
3f57c2fa5c refactor(PlayerEndpoint.ts): send specific params only if using Android based clients 2023-07-10 21:23:10 -03:00
LuanRT
7528ebdb60 chore: fix YouTube Music tests failing 2023-07-10 21:17:06 -03:00
github-actions[bot]
5e3846259f chore(main): release 5.2.1 (#429)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-03 22:30:29 -03:00
LuanRT
222dfce6bb fix: incorrect node parser implementations (#428)
These were causing some issues in v5.2.0.
2023-07-03 21:58:00 -03:00
github-actions[bot]
83cbfd631b chore(main): release 5.2.0 (#406)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-06-28 17:13:36 -03:00
RikThePixel
4f9427d752 fix(Playlist): Add thumbnail_renderer on Playlist when response includes it (#424) 2023-06-28 17:12:06 -03:00
Patrick Kan
07c1b3e0e5 fix(OAuth): client identity matching (#421) 2023-06-28 16:26:33 -03:00
absidue
89548ad48a chore(constants): Update web client version (#420) 2023-06-28 06:56:57 -03:00
absidue
519be72445 fix(PlayerEndpoint): Use different player params (#419)
* fix(PlayerEndpoint): Use different player params

* fix(PlayerEndpoint): Use new throttling bypass player params
2023-06-28 06:56:21 -03:00
Emma
e434bb2632 fix(VideoInfo.ts): reimplement get music_tracks (#409)
* fix(VideoInfo.ts): reimplement `get music_tracks`

- Add parser classes to parse needed data
  - Add `CarouselLockup`
  - Add `EngagementPanelSectionList`
  - Add `InfoRow`
  - Add `StructuredDescriptionContent`
  - Add `VideoDescriptionMusicSection`
  - Add `VideoDescriptionHeader`
  - Add `Factoid`
  - Add `ExpandableVideoDescriptionBody`
  - Add `AdsEngagementPanelContent`
- Add `engagement_panels` to raw and parsed next responses
- Add `engagement_panels` parsing code to `parser.ts`

* Check for song inside of video_lockup first before checking info_rows

* Add support for pulling artist ids out of music_tracks

- Add support for WRITERS InfoRow
- Check for video id inside of naviagation endpoint on info_row metadata

* Add `AdsEngagementPanelContent` to ignore list

* Switch `map => parseItem` to `parseArray`

* Use `Text` && `NavigationEndpoint`

* Replace `String` with `Text` in `ExpandableVideoDescriptionBody`
2023-06-28 06:54:55 -03:00
absidue
a11e5962c6 feat(VideoDetails): Add is_post_live_dvr property (#411) 2023-05-31 19:12:19 -03:00
Jake Reid Browning
77b39c79ee feat(ytmusic): Add support for YouTube Music mood filters (#404)
* add filters property to ytmusic HomeFeed

* remove implied type

* add applyFilter to HomeFeed

* add test

* remove section_list var
2023-05-23 15:00:05 -03:00
absidue
7c530d30ee chore(parser): Remove extra Array.from call (#407) 2023-05-20 18:00:15 -03:00
absidue
1e07a184ff perf(Search): Speed up results parsing (#408) 2023-05-20 17:57:48 -03:00
absidue
5de7b24dc5 perf(toDash): Speed up format filtering (#405) 2023-05-18 14:41:21 -03:00
github-actions[bot]
01fd1ee72a chore(main): release 5.1.0 (#403)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-14 01:12:16 -03:00
absidue
84b4f1efd1 feat(toDash): Add audio track labels to the manifest when available (#402) 2023-05-14 01:11:02 -03:00
absidue
046103a4d8 feat(ReelItem): Add accessibility label (#401) 2023-05-14 01:09:51 -03:00
github-actions[bot]
beb4733e84 chore(main): release 5.0.4 (#399)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-10 15:35:11 -03:00
absidue
66b026bf49 fix(Utils): Circular dependency introduced in 38a83c3c2a (#400) 2023-05-10 15:32:00 -03:00
absidue
26734194ab fix(bundles): Use ESM tslib build for the browser bundles (#397) 2023-05-06 15:54:18 -03:00
absidue
38a83c3c2a fix(Utils): Use instanceof in deepCompare instead of the constructor name (#398) 2023-05-06 15:47:51 -03:00
absidue
b1f19f16ac refactor(constants): Use namespace import internally (#396) 2023-05-06 15:46:20 -03:00
github-actions[bot]
891d889408 chore(main): release 5.0.3 (#395)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-03 19:47:01 -03:00
LuanRT
d4adb9eb6b chore(PlayerEndpoint.ts): add back attestationRequest field
This was accidentally removed in a recent PR. It tells InnerTube to omit the botguard program data.
2023-05-03 19:31:59 -03:00
LuanRT
3b0498b68b fix(Video): typo causing node parsing to fail 2023-05-02 03:21:02 -03:00
github-actions[bot]
154a5d2868 chore(main): release 5.0.2 (#394)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 17:24:14 -03:00
absidue
7c0abfccd7 fix(VideoInfo): Use microformat view_count when videoDetails view_count is NaN (#393) 2023-04-30 17:21:57 -03:00
github-actions[bot]
8f50c668aa chore(main): release 5.0.1 (#392)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 00:51:44 -03:00
LuanRT
4f7ec07c3f fix(web): slow downloads due to visitor data (#391)
* fix(web): slow downloads due to visitor data

It seems that YouTube will throttle clients if a shared visitor id is used.

* dev: include `params` for `/player` reqs
2023-04-30 00:50:08 -03:00
github-actions[bot]
ab3d5ab16c chore(main): release 5.0.0 (#389)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-29 02:14:26 -03:00
LuanRT
dd21f8c75a feat(NavigationEndpoint): parse content prop
This usually has dialog nodes.
2023-04-29 01:54:34 -03:00
LuanRT
3a7e58d2b9 chore(eslint): enforce the use of import type 2023-04-28 22:35:09 -03:00
LuanRT
75ea09dde8 fix(android): workaround streaming URLs returning 403 (#390) 2023-04-28 22:02:45 -03:00
LuanRT
95e0294eab refactor!: overhaul core classes and remove redundant code (#388)
* feat(Player.ts): append `cver` to deciphered URLs

* refactor(Actions.ts): remove redundant `getVideoInfo` function

This is leftover code from previous versions. It had many problems and it is no longer required.

* fix(Kids.ts): remove unneeded `await` keywords

* dev: add more endpoints

* chore: update deps

* refactor: separate endpoints into files

* dev: improve types

* dev: add more endpoints

* refactor: put clients in a separate directory inside `core`

* chore: lint

* refactor: move mixins and managers to separate folders

* chore: fix tests

* dev: add `CreateVideoEndpoint`

* chore: clean up

* chore: lint

* chore: add some comments

* chore: remove unnecessary test

* dev: add `playlist/CreateEndpoint`

* dev: add `playlist/DeleteEndpoint`

* dev: add `browse/EditPlaylistEndpoint`

* fix(parser): add a few checks to avoid parsing errors
2023-04-28 19:01:04 -03:00
LuanRT
22ae6c93ee chore(contributing.md): reword 2023-04-23 06:41:02 -03:00
LuanRT
257bd475a0 refactor: clean up parser and tests (#387)
* tests: improve coverage

* refactor: clean up nodes

* chore: lint

* feat(parser): ignore `BrandVideoShelf`

Seems to be used for ads.

* feat(parser): ignore `BrandVideoSingleton` too
2023-04-23 06:37:33 -03:00
github-actions[bot]
f66f0bd656 chore(main): release 4.3.0 (#384)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-13 07:52:42 -03:00
LuanRT
05de3ec97a feat(GridVideo): add upcoming, upcoming_text, is_reminder_set and buttons
Closes: #380
2023-04-13 07:50:18 -03:00
LuanRT
a0566969ba feat(ToggleMenuServiceItem): parse default nav endpoint 2023-04-13 06:10:17 -03:00
LuanRT
a9cad49333 feat(ytmusic): add taste builder nodes (#383)
Adds MusicTastebuilderShelf and MusicTastebuilderShelfThumbnail. These usually appear on new accounts.
2023-04-13 05:37:49 -03:00
LuanRT
096bf362c9 feat(MusicResponsiveListItem): make flex/fixed cols public (#382)
Plus refactor a few things.
2023-04-13 05:35:46 -03:00
LuanRT
ec9c0979f5 refactor: fix inconsistencies in the guide nodes (#379) 2023-04-11 05:52:47 -03:00
LuanRT
342d1d95e9 chore: fix readme formatting [skip ci] 2023-04-11 05:06:03 -03:00
github-actions[bot]
dbfc569602 chore(main): release 4.2.0 (#377)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-09 03:40:01 -03:00
LuanRT
c16a967987 chore(docs): minor improvements 2023-04-09 03:38:09 -03:00
LuanRT
a07375eb20 chore(docs): rewording [skip ci] 2023-04-09 03:02:23 -03:00
LuanRT
ce9d9c56b4 feat(parser): ignore PrimetimePromo node
This node is used to display advertisements.
2023-04-09 02:51:29 -03:00
LuanRT
f50ce1a06b chore: simplify Pull Request template 2023-04-09 02:43:19 -03:00
LuanRT
3b6ccfa3d8 chore: fix cjs build 2023-04-09 02:18:53 -03:00
LuanRT
878488d1b3 chore: clean up README.md 2023-04-09 01:20:27 -03:00
LuanRT
3c94c9da4b deps: bump Jinter to v1.0.0 2023-04-08 23:53:59 -03:00
absidue
0b301de6a1 feat: Enable importHelpers in tsconfig to reduce output size (#378) 2023-04-08 20:19:20 -03:00
absidue
c9135e66d3 feat(PlaylistVideo): Extract video_info and accessibility_label texts (#376) 2023-04-07 20:43:20 -03:00
github-actions[bot]
e82c843928 chore(main): release 4.1.1 (#374)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-28 22:29:08 -03:00
LuanRT
be71d7c937 chore: fix some inconsistencies 2023-03-28 21:22:12 -03:00
LuanRT
470d8d9406 fix(PlayerCaptionsTracklist): parse props only if they exist in the node
Fixes #372
2023-03-28 20:50:50 -03:00
absidue
2c5907f80f fix(Search): Return search results even if there are ads (#373) 2023-03-27 15:00:57 -03:00
github-actions[bot]
ade5feb31c chore(main): release 4.1.0 (#362)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-24 01:34:29 -03:00
LuanRT
13ebf0a039 feat(Session): allow setting a custom visitor data token (#371)
* feat(Session): allow setting a custom visitor data token

* docs: update init options

* chore: lint
2023-03-24 01:30:24 -03:00
Araxeus
cb8fafe94b fix(http): android tv http client missing clientName (#370) 2023-03-22 19:45:37 -03:00
absidue
bd35faa597 fix(parser): Make Video.is_live work on channel pages (#368) 2023-03-22 18:02:21 -03:00
absidue
a8b507ee65 fix(toDash): Generate unique Representation ids (#366) 2023-03-22 17:48:09 -03:00
Araxeus
e7eacd9742 fix(node) Electron apps crashing (#367)
Inside a `app.asar` file, the package.json might get trimmed and the `bugs_url` might be missing

`repo_url` conditional check was added for good measure

* fix(node) resolve `bugs_url` from repo_url
2023-03-22 17:13:40 -03:00
absidue
1c72a41675 fix(Utils): Properly parse timestamps with thousands separators (#363) 2023-03-22 03:48:01 -03:00
LuanRT
62a68b207c chore(docs): fix typo 2023-03-17 18:19:10 -03:00
LuanRT
1d9587e8c1 feat(ShowingResultsFor): parse all props 2023-03-17 07:27:00 -03:00
github-actions[bot]
a90e5e0d07 chore(main): release 4.0.1 (#360)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-16 04:55:10 -03:00
LuanRT
955c8010a6 chore: lint 2023-03-16 04:53:48 -03:00
LuanRT
b2269deb79 chore: add Button type
Oops :D
2023-03-16 04:52:07 -03:00
LuanRT
573c8643aa fix(Channel): type mismatch in subscribe_button prop
The `subscribe_button` property can also be of type `Button`.
2023-03-16 04:48:59 -03:00
github-actions[bot]
e21542c227 chore(main): release 4.0.0 (#353)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-15 21:08:37 -03:00
LuanRT
9d912e5938 refactor: use getters instead of props in the Innertube class 2023-03-15 20:34:58 -03:00
LuanRT
7ca0607004 refactor(ytmusic): rename SearchFilters interface to MusicSearchFilters
This allows us to expose the types from the InnerTube class as there is another interface there named `SearchFilters`
2023-03-15 19:24:17 -03:00
LuanRT
20d84265b5 chore(docs): minor improvements 2023-03-15 18:50:34 -03:00
Daniel Wykerd
b13bf6e992 refactor(Parser)!: general refactoring of parsers (#344)
* refactor: move common info into MediaInfo

* refactor: better inference on Memo

* refactor: improved typesafety in parser methods

* refactor: remove PlaylistAuthor in favor of Author

* refactor: cleanup live chat parsers

- Replace non standard author type with Author class
- Remove redundant code

* fix: new errors due to changes

* fix: pass actions to FormatUtils#toDash

* refactor!: merge NavigatableText and Text into single class
2023-03-15 18:25:12 -03:00
LuanRT
3d3436472f refactor(parser): fix many minor inconsistencies 2023-03-15 06:43:04 -03:00
LuanRT
1a2fc3abd7 chore(docs): add documentation for search filters 2023-03-15 05:35:00 -03:00
LuanRT
8ef4b42d44 feat(parser): add GridShow and ShowCustomThumbnail
Closes #459
2023-03-15 05:15:16 -03:00
LuanRT
b71f03caf2 chore(docs): oops, fix a typo 2023-03-15 04:15:35 -03:00
LuanRT
dae7d6e40c chore: update parser docs to reflect latest changes 2023-03-15 04:12:21 -03:00
Daniel Wykerd
2cee59024c feat(Parser): just-in-time YTNode generation (#310)
* refactor: merge NavigatableText into Text

* fix(Text): data might not be object

* refactor: remove GetParserByName from map

* feat(Parser): just-in-time YTNode generation

* refactor: cleanup YTNodeGenerator

* fix: YTNode map imports

* feat(YTNodeGenerator): primative types

Add support for inferring primatives types

* fix(YTNodeGenerator): NavigationEndpoint detection

* fix(YTNodeGenerator): fix generated typescript

Correct types and linting for generated typescript class

* chore: update parsers after merge

* feat: add support for object type inference

* fix: object type def

* docs: basic YTNodeGenerator explanation

* docs: tsdoc for YTNodeGenerator

* docs: update parser updating guide

* fix: apply suggested changes

* docs: accessing generated nodes
2023-03-15 03:39:36 -03:00
absidue
ffd7d79308 refactor(shim): Move node CustomEvent polyfill to Platform.shim (#357) 2023-03-15 00:49:33 -03:00
LuanRT
9b005d62d6 feat(parser): add MusicCardShelf (#358) 2023-03-14 20:16:31 -03:00
Patrick Kan
a8e7e644ec feat(parser): add GridMix (#356) 2023-03-14 06:19:22 -03:00
LuanRT
ad1d3dbf91 chore(docs): overhaul parser documentation
[skip ci]
2023-03-14 05:57:37 -03:00
LuanRT
3df3261488 chore(docs): improve contributing guidelines 2023-03-14 05:56:01 -03:00
LuanRT
1b1ce41c00 chore: overhaul documentation
Fix typos, add missing docs, rephrase some things and add a `COLLABORATORS.md`

[skip ci]
2023-03-13 07:08:26 -03:00
LuanRT
b82b720e4b docs: update browser example [skip ci] 2023-03-13 01:40:25 -03:00
LuanRT
4784dfa563 feat(parser): add InfoPanelContent and InfoPanelContainer nodes
These are usually used to add more context to videos that discuss misinformation.

Fixes: #326
2023-03-13 01:04:03 -03:00
absidue
3e4d41bf06 feat!: Add support for OTF format streams (#351) 2023-03-12 23:48:58 -03:00
Patrick Kan
9f1c31d7a0 feat(yt): add support for movie items and trailers (#349) 2023-03-12 18:15:21 -03:00
Patrick Kan
9cb4530299 feat(parser): add view_playlist to Playlist (#348) 2023-03-12 18:10:48 -03:00
Patrick Kan
cb9a0c5410 Add status to SearchFilter and fix endpoint (#347)
* feat(parser): add `status` to `SearchFilter`

* fix(parser): `SearchFilter` endpoint parsing
2023-03-12 18:07:59 -03:00
Patrick Kan
427db5bbc2 feat(parser): Add play_all_button to Shelf (#345) 2023-03-12 18:04:35 -03:00
github-actions[bot]
2b29244b41 chore(main): release 3.3.0 (#343)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-09 01:24:26 -03:00
LuanRT
f9754f5ac6 fix(ytmusic): use static visitor id to avoid empty API responses
Fixes #279
2023-03-09 01:21:13 -03:00
LuanRT
b2253df802 feat(parser): add ConversationBar node 2023-03-08 18:09:21 -03:00
LuanRT
f3517708ff fix(MultiMarkersPlayerBar): avoid observing undefined objects 2023-03-08 17:43:20 -03:00
Patrick Kan
0d35fe0ca5 feat(VideoInfo): support get by endpoint + more info (#342)
* feat(VideoInfo): get by endpoint + more info

* chore: fix param description for `getInfo()`
2023-03-08 16:42:41 -03:00
LuanRT
3e3dc351bb fix(SharedPost): import Menu node directly (oops) 2023-03-08 11:29:39 -03:00
github-actions[bot]
197bb759cd chore(main): release 3.2.0 (#334)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-08 07:20:21 -03:00
LuanRT
c76b24b3f4 chore(parser): import YTNodes directly to reduce web bundle size 2023-03-08 07:18:01 -03:00
absidue
574b67a1f7 feat: Add support for descriptive audio tracks (#338) 2023-03-08 05:36:01 -03:00
LuanRT
9b2738f128 fix(SegmentedLikeDislikeButton): like/dislike buttons can also be a simple Button 2023-03-07 05:43:32 -03:00
LuanRT
95f1d4077f fix(YouTube): fix warnings when retrieving members-only content (#341) 2023-03-07 05:15:46 -03:00
LuanRT
a511608f18 feat(YouTube/Search): add SearchSubMenu node (#340) 2023-03-07 04:17:58 -03:00
LuanRT
cf8a33c79f fix(ytmusic): export search filters type 2023-03-07 03:02:44 -03:00
Chinmay Kumar
cfc1a183e0 refactor(parser): type YTNodes' data arg as RawNode (wip) (#339)
* replaced YTNode's data arg as RawNode

* updated documentation

* removed unused import

---- Note that there are still many nodes that need to be updated, hence the WIP status.
2023-03-07 02:02:07 -03:00
Patrick Kan
95033e723e feat(parser): add banner to PlaylistHeader (#337) 2023-03-05 22:44:09 -03:00
Patrick Kan
2cc7b8bcd6 feat(yt): add getGuide() (#335)
* feat(yt): add `getGuide()`

* chore: lint

* fix(Guide): wrong prop

* fix(Guide): include subscription section

* fix(Guide): wrong import

* feat(Guide): add `page`
2023-03-04 06:23:17 -03:00
LuanRT
2d774e26aa feat: export FormatUtils' types 2023-03-04 04:06:19 -03:00
Nico K
214aa147ce feat(VideoInfo): add game_info and category (#333) 2023-03-03 03:47:20 -03:00
Daniel Wykerd
ce53ac1843 feat(parser): SharedPost (#332)
Add support for SharedPost in community tab.
Related to issue #331
2023-03-03 03:41:04 -03:00
github-actions[bot]
0ad26f28d9 chore(main): release 3.1.1 (#330)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-01 16:30:10 -03:00
ChunkyProgrammer
4c7b8a3403 fix(Channel): getting community continuations (#329) 2023-03-01 16:28:26 -03:00
github-actions[bot]
33a6e740d7 chore(main): release 3.1.0 (#318)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-02-26 20:35:20 -03:00
LuanRT
0b1840a62c chore(docs): update examples to reflect recent changes [skip ci] 2023-02-26 20:28:16 -03:00
LuanRT
f4e0f30e6e fix: send correct UA for Android requests
Related: #322
2023-02-26 19:21:41 -03:00
LuanRT
200632f374 fix(parser): export YTNodes individually so they can be used as types
Related: #321
2023-02-26 18:56:04 -03:00
LuanRT
f933cb45bc feat(VideoSecondaryInfo): add support for attributed descriptions (#325) 2023-02-26 16:47:47 -03:00
absidue
a0e6cef00f fix(PlayerMicroformat): Make the embed field optional (#320) 2023-02-25 12:11:03 -03:00
absidue
a0bfe16427 feat: Add upcoming and live info to playlist videos (#317) 2023-02-20 18:25:53 -03:00
Daniel Wykerd
9d352b58eb docs: update imports for platforms (#315)
* docs: fix browser import

* docs: add deno.land instructions

As mentioned in issue #314
2023-02-17 14:53:06 -03:00
github-actions[bot]
6b6c80ddf1 chore(main): release 3.0.0 (#309)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-02-17 01:22:53 -03:00
LuanRT
58a6c84121 style: lint and format 2023-02-16 23:10:23 -03:00
LuanRT
63b1261b7c deps: bump Jinter to 0.4.1 2023-02-16 23:09:40 -03:00
dependabot[bot]
d2eff3bfb8 build(deps): bump undici from 5.14.0 to 5.19.1 (#313)
Bumps [undici](https://github.com/nodejs/undici) from 5.14.0 to 5.19.1.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.14.0...v5.19.1)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-16 21:49:49 -03:00
LuanRT
b668ba8cfb style(docs): rephrase some things 2023-02-16 19:38:48 -03:00
LuanRT
0b88575614 docs(browser): add ytjsexample.pages.dev live example 2023-02-16 19:32:24 -03:00
LuanRT
bed0ff4154 docs(readme): fix formatting 2023-02-16 19:05:42 -03:00
LuanRT
27a50a2a7e docs: add documentation for Feed, FilterableFeed and TabbedFeed 2023-02-16 18:38:10 -03:00
LuanRT
d4f2d704bb build: update package description 2023-02-16 17:03:17 -03:00
LuanRT
97f181b212 docs: update browser example 2023-02-16 07:50:02 -03:00
LuanRT
251ed74bba chore(ChannelAgeGate): fix node type
channelAgeGate ---> ChannelAgeGate
2023-02-16 07:15:52 -03:00
LuanRT
1cdf701c84 feat(parser): add ChannelAgeGate node 2023-02-16 07:07:34 -03:00
LuanRT
bf12740333 feat: add support for hashtag feeds (#312)
* feat: add hashtag params proto

* feat: add support for hashtags

* chore: add test

* docs: update API ref

* fix(tests): remove unneeded `#` from param

* fix: do not throw when missing the header
2023-02-16 06:46:20 -03:00
LuanRT
0d77b59945 chore: make browser example more complete
See: https://ytjsexample.pages.dev/
2023-02-14 06:53:28 -03:00
LuanRT
6e30309f56 style: clean up and fix minor inconsistencies 2023-02-13 19:42:49 -03:00
ChunkyProgrammer
e37cf62732 fix: assign MetadataBadge's label (#311) 2023-02-13 03:15:06 -03:00
LuanRT
567fdbaf52 docs(parser): fix parser.ts link 2023-02-12 08:55:26 -03:00
LuanRT
0a22319d9e chore(docs): update test status badge 2023-02-12 08:47:36 -03:00
LuanRT
eb72c2f6ef refactor(parser): improve typings and do some refactoring (#305)
* dev: add response types

* dev: refactor `Parser#parseResponse()`

* dev: update YouTube parsers

* dev: update YouTube Music classes

* dev: update YouTube Kids classes

* dev: update core classes

* dev(Parser): fix some inconsistencies

* chore: update docs

* chore: update docs x2

* fix: export response types 

* chore(docs): update parser example
2023-02-12 07:04:17 -03:00
Daniel Wykerd
2ccbe2ce62 refactor!: cleanup platform support (#306)
* refactor!: cleanup platform support

* chore: lint

* fix: web platform

* feat: provide UniversalCache

Provide UniversalCache as a wrapper around Platform.shim.Cache.

* fix: invalid import

* refactor: remove isolated-vm support

* fix: type info

* refactor: cleanup exports

* fix: mark jintr as external dependency

In the bundled CJS node build, mark jintr as external.

* chore: add additional exports

web exports provide a way to select web implementation manually without
relying on the bundler to select it correctly from the "exports" field

web points to src/platform/web.js
web.bundle points to bundle/browser.js
web.bundle.browser points to bundle/browser.min.js

agnostic exports provide users of the library to provide their own
platform implementation without first importing the default one.

agnostic points to src/platform/lib.ts

* fix: toDash on web

* revert: eval is synchronous

* fix: use serializeDOM in FormatUtils

* ci: automate releases with `release-please`

* chore: clean up workflow files

* ci: fix NPM publish action

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-02-12 04:21:44 -03:00
absidue
a69e43bf3a feat(FormatUtils): support multiple audio tracks in the DASH manifest (#308) 2023-02-11 20:34:39 -03:00
absidue
b2900f48a7 feat(Channel): Add getters for all optional tabs (#303)
* feat(Channel): Add getters for all optional tabs

* Fix typo in test description

Co-authored-by: LuanRT <luan.lrt4@gmail.com>

---------

Co-authored-by: LuanRT <luan.lrt4@gmail.com>
2023-02-02 00:29:54 -03:00
absidue
d612590530 fix(TopicChannelDetails): avatar and subtitle parsing (#302) 2023-02-01 17:17:31 -03:00
Daniel Wykerd
e82e23dfbb feat(parser): Text#toHTML (#300)
Added support to render Text nodes as HTML for use in web applications.
2023-02-01 16:27:59 -03:00
absidue
f62c66db39 fix(ChannelAboutFullMetadata): fix error when there are no primary links (#299) 2023-01-29 21:28:19 -03:00
ChunkyProgrammer
de61782f1a feat: add parser support for MultiImage community posts (#298) 2023-01-29 14:39:46 -03:00
absidue
ceefbed98c feat: allow checking whether a channel has optional tabs (#296) 2023-01-29 14:37:09 -03:00
LuanRT
315d89f84a refactor(Player): remove unneeded parameters 2023-01-29 02:26:18 -03:00
LuanRT
2ea3602b61 Merge branch 'main' of https://github.com/LuanRT/YouTube.js 2023-01-29 01:55:17 -03:00
LuanRT
b7df3d6df4 refactor: clean up backstage post nodes 2023-01-29 01:54:24 -03:00
ChunkyProgrammer
2acb7da019 feat: parse isLive in CompactVideo (#294)
* Feat: parse isLive in CompactVideo

* Use 3 equal signs

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>

* use parse array for badges

add is_premiere, is_new, is_fundraiser

---------

Co-authored-by: absidue <48293849+absidue@users.noreply.github.com>
2023-01-27 14:44:32 -03:00
LuanRT
0b991800a5 feat: extract channel error alert 2023-01-27 07:15:17 -03:00
LuanRT
50ef71284d feat(Channel): add support for sorting the playlist tab (#295) 2023-01-27 06:37:35 -03:00
LuanRT
d6c5a9b971 feat: improve support for dubbed content (#293)
* feat(Format): add `language`, `is_dubbed` and `is_original`

* feat: add a format filtering option to the DASH function
> And a simple language option to VideoInfo's download method.

* chore: update docs

* feat: improve audio track info parsing

* feat(Format): parse `audioTrack` prop
2023-01-27 00:42:20 -03:00
LuanRT
0fc29f0bbf feat(ytkids): add getChannel() (#292) 2023-01-23 05:38:53 -03:00
LuanRT
2bbefefbb7 feat: add support for YouTube Kids (#291)
* dev: add `WEB_KIDS` innertube client

* refactor: move DASH manifest stuff out of `VideoInfo`
This makes it easier to use these functions elsewhere.

* feat(ytkids): add `Kids#getInfo()` & `Kids#search()`

* feat: add `Innertube#kids.getHomeFeed()`

* docs: add YouTube Kids API ref

* docs: fix typo

* docs: fix yet another typo

* docs: update YouTube Music API ref
Unrelated but required to reflect changes made to the DASH manifest generation functions

* chore: lint

* chore: add tests

* feat: include `captions` in `VideoInfo`

* chore: fix tests
2023-01-23 03:39:51 -03:00
absidue
13ad3774c9 fix(VideoInfo): Gracefully handle missing watch next continuation (#288) 2023-01-23 03:36:38 -03:00
LuanRT
8051a7dee6 refactor: improve live chat polling and error handling (#287) 2023-01-21 02:56:10 -03:00
760 changed files with 32630 additions and 17822 deletions

View File

@@ -5,4 +5,5 @@ cache/
src/proto/youtube.ts
coverage/
node_modules/
dist/
dist/
src/proto/generated/

View File

@@ -8,10 +8,13 @@ extends: [ eslint:recommended, 'plugin:@typescript-eslint/recommended' ]
parser: '@typescript-eslint/parser'
parserOptions:
ecmaVersion: latest
project:
- tsconfig.json
overrides:
-
files:
- '**/*.js'
- '**/*.mjs'
rules:
'tsdoc/syntax': 'off'
rules:
@@ -30,6 +33,8 @@ rules:
'@typescript-eslint/ban-types': 'off'
'tsdoc/syntax': 'warn'
'@typescript-eslint/no-explicit-any': 'off'
'@typescript-eslint/consistent-type-imports': 'error'
'@typescript-eslint/consistent-type-exports': 'error'
no-template-curly-in-string: error
no-unreachable-loop: error
@@ -75,6 +80,7 @@ rules:
prefer-template: error
keyword-spacing: ["error", { "before": true } ]
object-curly-spacing: ["warn", "always"]
array-bracket-spacing: ["error", "always"]
arrow-parens: ["error", "always"]
comma-dangle: ["error", "never"]

View File

@@ -2,13 +2,7 @@ version: 1
labels:
- label: "breaking-change"
title: "^refactor!:.*"
- label: "enhancement"
title: "^feat:.*"
- label: "bug"
title: "^fix:.*"
- label: "github"
files:
- ".github/.*"

View File

@@ -1,27 +1,6 @@
# Pull Request Template
## Description
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
Fixes # (issue)
## Type of change
Please delete options that are not relevant.
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update
## Checklist:
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] I have checked my code and corrected any misspellings
<!-- Thank you for submitting a Pull Request! Please:
* Read our contributing guidelines: https://github.com/LuanRT/YouTube.js/blob/main/CONTRIBUTING.md
* Add "Fixes #<issue_number>" to the PR description if you are fixing an issue.
* Ensure that the code is up-to-date with the `main` branch.
* Include a description of the proposed changes and how to test them.
-->

20
.github/release.yml vendored
View File

@@ -1,20 +0,0 @@
changelog:
exclude:
labels:
- ignore-for-release
authors:
- octocat
categories:
- title: Breaking Changes
labels:
- Semver-Major
- breaking-change
- title: New Features
labels:
- Semver-Minor
- enhancement
- title: Bug Fixes
- bug
- title: Other Changes
labels:
- "*"

View File

@@ -5,9 +5,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: srvaroa/labeler@master
with:

View File

@@ -1,17 +1,18 @@
name: Lint
name: lint
on: [push, pull_request]
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
eslint:
name: Lint
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- name: npm install and lint
run: |
npm install
npm run lint
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 20
- run: npm ci
- run: npm run lint

View File

@@ -1,26 +0,0 @@
name: Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [ 16.x, 18.x ]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm run test

62
.github/workflows/release-please.yml vendored Normal file
View File

@@ -0,0 +1,62 @@
name: release-please
on:
push:
branches:
- main
jobs:
release-please:
permissions:
contents: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
release-type: node
package-name: youtubei.js
token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: "16.x"
- name: Build for Deno
run: |
npm ci
npm run build:deno
if: ${{ steps.release.outputs.release_created }}
- name: Move Deno files
run: |
mkdir build
mv deno build/deno
cp deno.ts build/deno.ts
cp {LICENSE,README.md} build
if: ${{ steps.release.outputs.release_created }}
- name: Push to the Deno branch
uses: s0/git-publish-subdir-action@develop
env:
REPO: self
BRANCH: deno
FOLDER: ./build
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SKIP_EMPTY_COMMITS: true
MESSAGE: "chore: ${{ steps.release.outputs.tag_name }} release"
TAG: ${{ steps.release.outputs.tag_name }}-deno
if: ${{ steps.release.outputs.release_created }}
- name: Remove Deno folder
run: rm -rf build
if: ${{ steps.release.outputs.release_created }}
- uses: actions/setup-node@v3
with:
node-version: "16.x"
registry-url: "https://registry.npmjs.org"
if: ${{ steps.release.outputs.release_created }}
- name: Publish package to npmjs
run: |
npm ci
npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
if: ${{ steps.release.outputs.release_created }}

View File

@@ -11,9 +11,8 @@ jobs:
- uses: actions/stale@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.'
stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.'
stale-pr-message: 'This PR has been automatically marked as stale because it has not had recent activity. Remove the stale label or comment or this will be closed in 2 days'
any-of-issue-labels: 'needs-more-info,cannot-reproduce,question,help-wanted'
days-before-stale: 60
days-before-close: 4

18
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: test
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 20
- run: npm ci
- run: npm run test

6
.gitignore vendored
View File

@@ -66,6 +66,12 @@ tmp/
dist/
bundle/*.js.*
bundle/*.js
bundle/*.cjs
bundle/*.cjs.*
deno/
# VSCode files
.vscode/
# MacOS
.DS_Store

691
CHANGELOG.md Normal file
View File

@@ -0,0 +1,691 @@
# Changelog
## [10.2.0](https://github.com/LuanRT/YouTube.js/compare/v10.1.0...v10.2.0) (2024-07-25)
### Features
* **Format:** Add `is_secondary` for detecting secondary audio tracks ([#697](https://github.com/LuanRT/YouTube.js/issues/697)) ([a352dde](https://github.com/LuanRT/YouTube.js/commit/a352ddeb9db001e99f49025048ad0942d84f1b3e))
* **parser:** add classdata to unhandled parse errors ([#691](https://github.com/LuanRT/YouTube.js/issues/691)) ([090539b](https://github.com/LuanRT/YouTube.js/commit/090539b28f9bc3387d01e37325ba5741b33b1765))
* **proto:** Add `comment_id` to commentSectionParams ([#693](https://github.com/LuanRT/YouTube.js/issues/693)) ([a5f6209](https://github.com/LuanRT/YouTube.js/commit/a5f62093a18705fc822abd86beaa81788b6535ce))
### Bug Fixes
* **parser:** ignore MiniGameCardView node ([#692](https://github.com/LuanRT/YouTube.js/issues/692)) ([6d0bc89](https://github.com/LuanRT/YouTube.js/commit/6d0bc89be18f27a8ce74517f5cab5020d6790328))
* **parser:** ThumbnailView background color ([#686](https://github.com/LuanRT/YouTube.js/issues/686)) ([0f8f92a](https://github.com/LuanRT/YouTube.js/commit/0f8f92a28a5b6143e890626b22ce570730a0cf09))
* **Player:** Bump cache version ([#702](https://github.com/LuanRT/YouTube.js/issues/702)) ([6765f4e](https://github.com/LuanRT/YouTube.js/commit/6765f4e0d791c657fc7411e9cdd2c0f9284e9982))
* **Player:** Fix extracting the n-token decipher algorithm again ([#701](https://github.com/LuanRT/YouTube.js/issues/701)) ([3048f70](https://github.com/LuanRT/YouTube.js/commit/3048f70f60756884bd7b591d770f7b6343cfa259))
## [10.1.0](https://github.com/LuanRT/YouTube.js/compare/v10.0.0...v10.1.0) (2024-07-10)
### Features
* **Session:** Add `configInfo` to InnerTube context ([5a8fd3a](https://github.com/LuanRT/YouTube.js/commit/5a8fd3ad37bce1decad28ec3727453ddd430a561))
* **toDash:** Add option to include WebVTT or TTML captions ([#673](https://github.com/LuanRT/YouTube.js/issues/673)) ([bd9f6ac](https://github.com/LuanRT/YouTube.js/commit/bd9f6ac64ca9ba96e856aabe5fcc175fd9c294dc))
* **toDash:** Add the "dub" role to translated captions ([#677](https://github.com/LuanRT/YouTube.js/issues/677)) ([858cdd1](https://github.com/LuanRT/YouTube.js/commit/858cdd197cb2bb1e1d7a7285966cb56043ad8961))
### Bug Fixes
* **FormatUtils:** Throw an error if download requests fails ([a19511d](https://github.com/LuanRT/YouTube.js/commit/a19511de24bb82007aab072844efe64bbb8698da))
* **InfoPanelContent:** Update InfoPanelContent node to also support `paragraphs` ([4cbaa79](https://github.com/LuanRT/YouTube.js/commit/4cbaa7983f35a82b9907197769672ac3b300bfbe))
* **Player:** Fix extracting the n-token decipher algorithm ([#682](https://github.com/LuanRT/YouTube.js/issues/682)) ([142a7d0](https://github.com/LuanRT/YouTube.js/commit/142a7d042885188605bdc0655d3733502d1e20fa))
* **proto:** Update `Context` message ([62ac2f6](https://github.com/LuanRT/YouTube.js/commit/62ac2f6f32d35fec3c31b5f5d556bd4569fa49f9)), closes [#681](https://github.com/LuanRT/YouTube.js/issues/681)
* **Session:** Round UTC offset minutes ([84f90aa](https://github.com/LuanRT/YouTube.js/commit/84f90aaf2908ecacb9dfb6ce5497c4c4d14a72c3))
* **toDash:** Fix image representations not being spec compliant ([#672](https://github.com/LuanRT/YouTube.js/issues/672)) ([e5aab9a](https://github.com/LuanRT/YouTube.js/commit/e5aab9a9b35f0752cd5ca50bfa25936dce4718c6))
* **YTMusic:** Add support for new header layouts ([14c3a06](https://github.com/LuanRT/YouTube.js/commit/14c3a06d402989e98a9d32c79b2dc26f74fb0219))
## [10.0.0](https://github.com/LuanRT/YouTube.js/compare/v9.4.0...v10.0.0) (2024-06-09)
### ⚠ BREAKING CHANGES
* **Innertube#getPlaylists:** Return a `Feed` instance instead of items
* **OAuth2:** Rewrite auth module ([#661](https://github.com/LuanRT/YouTube.js/issues/661))
### Features
* **Format:** Add `is_drc` ([#656](https://github.com/LuanRT/YouTube.js/issues/656)) ([6bb2086](https://github.com/LuanRT/YouTube.js/commit/6bb2086875d089f47c5f86ce94db9e32cb051319))
* **Platform:** Add support for `react-native` platform ([#593](https://github.com/LuanRT/YouTube.js/issues/593)) ([2980a60](https://github.com/LuanRT/YouTube.js/commit/2980a608b67f18416d7f73f1bdbcf4b897307b26))
* **Session:** Add `enable_session_cache` option ([#664](https://github.com/LuanRT/YouTube.js/issues/664)) ([7953296](https://github.com/LuanRT/YouTube.js/commit/795329658033652625d2d61b275ccf703573a437))
* **toDash:** Add support for stable volume/DRC ([#662](https://github.com/LuanRT/YouTube.js/issues/662)) ([031ffb6](https://github.com/LuanRT/YouTube.js/commit/031ffb696e3b7e160779e8b55a49b0cfa9f95620))
### Bug Fixes
* **ButtonView:** Rename `type` property to `button_type` ([15f3b5f](https://github.com/LuanRT/YouTube.js/commit/15f3b5fdba17f11cddada168de268546875e48f9))
* **Cache:** Use `TextEncoder` to encode compressed data ([384b80e](https://github.com/LuanRT/YouTube.js/commit/384b80ee41d7547a00d8dc17c50c8542629264b5))
* **FlexibleActionsView:** Update actions array type to include `ToggleButtonView` ([040a091](https://github.com/LuanRT/YouTube.js/commit/040a09163903b914f546d5083dbfdeab7175b24c))
* **InfoPanelContainer:** Use new attributed text prop ([5cdb9e1](https://github.com/LuanRT/YouTube.js/commit/5cdb9e1e2fa4ad5abdb3659bb35d0b3edc60123c))
* **ItemSection:** Fix `target_id` not being set because of a typo. ([#655](https://github.com/LuanRT/YouTube.js/issues/655)) ([8106654](https://github.com/LuanRT/YouTube.js/commit/810665407e91b2890a8e555fd759d67ccd800379))
* **MusicResponsiveHeader:** Add `Text` import ([583fd9f](https://github.com/LuanRT/YouTube.js/commit/583fd9f8d70735d071b34bd1d68faa62eeac593a))
### Performance Improvements
* **general:** Add session cache and LZW compression ([#663](https://github.com/LuanRT/YouTube.js/issues/663)) ([cf29664](https://github.com/LuanRT/YouTube.js/commit/cf29664d376ff792602400ef9a4ac301c676735c))
### Code Refactoring
* **Innertube#getPlaylists:** Return a `Feed` instance instead of items ([7660450](https://github.com/LuanRT/YouTube.js/commit/766045049d7154866e6fe32f6d965025d736d77d))
* **OAuth2:** Rewrite auth module ([#661](https://github.com/LuanRT/YouTube.js/issues/661)) ([b6ce5f9](https://github.com/LuanRT/YouTube.js/commit/b6ce5f903fa2285cb381d73aedf02cc5e2712478))
## [9.4.0](https://github.com/LuanRT/YouTube.js/compare/v9.3.0...v9.4.0) (2024-04-29)
### Features
* **Format:** Add `projection_type` and `stereo_layout` ([#643](https://github.com/LuanRT/YouTube.js/issues/643)) ([064436c](https://github.com/LuanRT/YouTube.js/commit/064436cef30e892d8f569d4f7b146557fd72b09f))
* **Format:** Add `spatial_audio_type` ([#647](https://github.com/LuanRT/YouTube.js/issues/647)) ([0ba8c54](https://github.com/LuanRT/YouTube.js/commit/0ba8c54257b068d7e4518c982396acb42f1dd41d))
* **Parser:** Add `MusicResponsiveHeader` node ([ea82bea](https://github.com/LuanRT/YouTube.js/commit/ea82beaa10f6c877d6dd3102e10f6ae382560e0f))
## [9.3.0](https://github.com/LuanRT/YouTube.js/compare/v9.2.1...v9.3.0) (2024-04-11)
### Features
* **CommentView:** Implement comment interaction methods ([1c08bfe](https://github.com/LuanRT/YouTube.js/commit/1c08bfe113804c69fbc4e49b42442d9a63d73be6))
### Bug Fixes
* **CommentThread:** Replies not being parsed correctly ([66e34f9](https://github.com/LuanRT/YouTube.js/commit/66e34f9388429a2088d5c5835d19eebdc881c957))
## [9.2.1](https://github.com/LuanRT/YouTube.js/compare/v9.2.0...v9.2.1) (2024-04-09)
### Bug Fixes
* **toDash:** Add missing transfer characteristics for h264 streams ([#631](https://github.com/LuanRT/YouTube.js/issues/631)) ([0107049](https://github.com/LuanRT/YouTube.js/commit/010704929fa4b737f68a5a1f10bf0b166cfbf905))
## [9.2.0](https://github.com/LuanRT/YouTube.js/compare/v9.1.0...v9.2.0) (2024-03-31)
### Features
* add support of cloudflare workers ([#596](https://github.com/LuanRT/YouTube.js/issues/596)) ([2029aec](https://github.com/LuanRT/YouTube.js/commit/2029aec90de3c0fdb022094d7b704a2feed4133b))
* **parser:** Support CommentView nodes ([#614](https://github.com/LuanRT/YouTube.js/issues/614)) ([900f557](https://github.com/LuanRT/YouTube.js/commit/900f5572021d348e7012909f2080e52eac06adae))
* **parser:** Support LockupView and it's child nodes ([#609](https://github.com/LuanRT/YouTube.js/issues/609)) ([7ca2a0c](https://github.com/LuanRT/YouTube.js/commit/7ca2a0c3e43ebd4b9443e69b7432f302b09e9c7a))
* **Text:** Support formatting and emojis in `fromAttributed` ([#615](https://github.com/LuanRT/YouTube.js/issues/615)) ([e6f1f07](https://github.com/LuanRT/YouTube.js/commit/e6f1f078a828f8ea5db1fe7aec9f677bc53694e3))
### Bug Fixes
* **Cache:** handle the value read from the db correctly according to its type ([#620](https://github.com/LuanRT/YouTube.js/issues/620)) ([3170659](https://github.com/LuanRT/YouTube.js/commit/317065988007c860bf6173b0ac3c3d685ed81d20))
* **PlayerEndpoint:** Workaround for "The following content is not available on this app" (Android) ([#624](https://github.com/LuanRT/YouTube.js/issues/624)) ([d589365](https://github.com/LuanRT/YouTube.js/commit/d589365ea27f540ff36e33a65362c932cd28c274))
## [9.1.0](https://github.com/LuanRT/YouTube.js/compare/v9.0.2...v9.1.0) (2024-02-23)
### Features
* **Format:** Support caption tracks in adaptive formats ([#598](https://github.com/LuanRT/YouTube.js/issues/598)) ([bff65f8](https://github.com/LuanRT/YouTube.js/commit/bff65f8889c32813ec05bd187f3a4386fc6127c0))
### Bug Fixes
* **Playlist:** `items` getter failing if a playlist contains Shorts ([89fa3b2](https://github.com/LuanRT/YouTube.js/commit/89fa3b27a839d98aaf8bd70dd75220ee309c2bea))
* **Session:** Don't try to extract api version from service worker ([2068dfb](https://github.com/LuanRT/YouTube.js/commit/2068dfb73eefc0e40157421d4e5b4096c0c8429c))
## [9.0.2](https://github.com/LuanRT/YouTube.js/compare/v9.0.1...v9.0.2) (2024-01-31)
### Bug Fixes
* **VideoInfo:** Fix error because of typo in getWatchNextContinuation ([#590](https://github.com/LuanRT/YouTube.js/issues/590)) ([b21eb9f](https://github.com/LuanRT/YouTube.js/commit/b21eb9f33d956e130bac98712384125ae04ace47))
## [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)
### ⚠ BREAKING CHANGES
* **Library:** Add support for the new layout and remove profile & stats info
* **Channel:** YouTube removed the "Channels" tab on channels, so this pull request removes the `getChannels()` method and `has_channels` getter from the `YT.Channel` class, as they are no longer useful. The featured channels are now shown on the channel home tab. To get them you can use the `channels` getter on the home tab of the channel. Please note that some channel owners might not have added that section to their home page yet, so you won't be able to get the featured channels for those channels. The home tab is the default tab that is returned when you call `InnerTube#getChannel()`, you can also access that tab by calling `getHome()` on a `YT.Channel` object.
### Features
* add `FeedNudge` ([#533](https://github.com/LuanRT/YouTube.js/issues/533)) ([e021395](https://github.com/LuanRT/YouTube.js/commit/e02139532b2c07aaf72dd1bd8610f63b6780001d))
* add `VideoAttributeView` ([#531](https://github.com/LuanRT/YouTube.js/issues/531)) ([ff4ab16](https://github.com/LuanRT/YouTube.js/commit/ff4ab1680e110fc32e09d09215fd3e05dbde2c85))
* Add Shorts endpoint ([#512](https://github.com/LuanRT/YouTube.js/issues/512)) ([a32aa8c](https://github.com/LuanRT/YouTube.js/commit/a32aa8c633b6f3c3bb0695ad1878cbb313867346))
* **Channel:** Support new about popup ([#537](https://github.com/LuanRT/YouTube.js/issues/537)) ([c66eb1f](https://github.com/LuanRT/YouTube.js/commit/c66eb1fecf0e66d9eca841be0ca56b39ad4466eb))
* **parser:** Add `ChannelOwnerEmptyState` ([#541](https://github.com/LuanRT/YouTube.js/issues/541)) ([b60930a](https://github.com/LuanRT/YouTube.js/commit/b60930a0c1ce419dddb753846c84d4e46ddf04e1))
* **Parser:** Add `ClipSection` ([#532](https://github.com/LuanRT/YouTube.js/issues/532)) ([9007b65](https://github.com/LuanRT/YouTube.js/commit/9007b652375e1ca3c3844bdf091fe3670f98dc2c))
* **toDash:** Add `contentType` to audio and video adaption sets ([#539](https://github.com/LuanRT/YouTube.js/issues/539)) ([4806fc6](https://github.com/LuanRT/YouTube.js/commit/4806fc6c112cb3cf0584f7d253f3c4aeaffa9927))
* Use `overrides` instead of `--legacy-peer-deps` ([#529](https://github.com/LuanRT/YouTube.js/issues/529)) ([db7f620](https://github.com/LuanRT/YouTube.js/commit/db7f6209b2329bf18b8b35aababfdb9b750c3b0f))
### Bug Fixes
* **Channel:** Remove `getChannels()` and `has_channels`, as YouTube removed the tab ([#542](https://github.com/LuanRT/YouTube.js/issues/542)) ([6a5a579](https://github.com/LuanRT/YouTube.js/commit/6a5a579e3947109af0e7c2a318aef40edb8484f8))
* **Library:** Add support for the new layout and remove profile & stats info ([4261915](https://github.com/LuanRT/YouTube.js/commit/4261915fd4aa84f7619a45d678910be0ae30e13e))
* **StructuredDescriptionContent:** Add `ReelShelf` to list of possible nodes ([f74ed5a](https://github.com/LuanRT/YouTube.js/commit/f74ed5a1cf352a7b57fa84b9373f9ed9ba1911fc))
* **VideoAttributeView:** Fix `image` and `overflow_menu_on_tap` props ([5ae15be](https://github.com/LuanRT/YouTube.js/commit/5ae15be63dee2a2393a1aa2a308ca5378140760a))
### Performance Improvements
* Use named Parser import, to allow bundlers to create direct function references ([#535](https://github.com/LuanRT/YouTube.js/issues/535)) ([95ed602](https://github.com/LuanRT/YouTube.js/commit/95ed60207a1219f4891f28d2b2b90cf816f11831))
## [7.0.0](https://github.com/LuanRT/YouTube.js/compare/v6.4.1...v7.0.0) (2023-10-28)
### ⚠ BREAKING CHANGES
* **music#getSearchSuggestions:** Return array of `SearchSuggestionsSection` instead of a single node
### Features
* **Kids:** Add `blockChannel` command to easily block channels ([#503](https://github.com/LuanRT/YouTube.js/issues/503)) ([9ab528e](https://github.com/LuanRT/YouTube.js/commit/9ab528ec823dcd527a97150009eed632c6d3eb6a))
* **music#getSearchSuggestions:** Return array of `SearchSuggestionsSection` instead of a single node ([beaa28f](https://github.com/LuanRT/YouTube.js/commit/beaa28f4c68de8366caa84ce5a026bf9e12e1b9d))
* **parser:** Add `PlayerOverflow` and `PlayerControlsOverlay` ([a45273f](https://github.com/LuanRT/YouTube.js/commit/a45273fec498df87eecd364ffb708c9f787793d5))
* **UpdateViewerShipAction:** Add `original_view_count` and `unlabeled_view_count_value` ([#527](https://github.com/LuanRT/YouTube.js/issues/527)) ([bc97e07](https://github.com/LuanRT/YouTube.js/commit/bc97e07ac6d1cdc45194e214c6001cf92190e1d5))
### Bug Fixes
* **build:** Inline package.json import to avoid runtime erros ([#509](https://github.com/LuanRT/YouTube.js/issues/509)) ([4c0de19](https://github.com/LuanRT/YouTube.js/commit/4c0de199e85dd5cc8b3719920b24dec9613acaab))
## [6.4.1](https://github.com/LuanRT/YouTube.js/compare/v6.4.0...v6.4.1) (2023-10-02)
### Bug Fixes
* **Feed:** Do not throw when multiple continuations are present ([8e372d5](https://github.com/LuanRT/YouTube.js/commit/8e372d5c67f148be288bb0485f2c70ec43fbecd0))
* **Playlist:** Throw a more helpful error when parsing empty responses ([987f506](https://github.com/LuanRT/YouTube.js/commit/987f50604a0163f9a07091ce787995c6f6fddb75))
### Performance Improvements
* Cache deciphered n-params by info response ([#505](https://github.com/LuanRT/YouTube.js/issues/505)) ([d2959b3](https://github.com/LuanRT/YouTube.js/commit/d2959b3a55a5081295da4754627913933bbaf1e7))
* **generator:** Remove duplicate checks in `isMiscType` ([#506](https://github.com/LuanRT/YouTube.js/issues/506)) ([68df321](https://github.com/LuanRT/YouTube.js/commit/68df3218580db10c9a0932c93ff2ce487526ff1e))
## [6.4.0](https://github.com/LuanRT/YouTube.js/compare/v6.3.0...v6.4.0) (2023-09-10)
### Features
* Add support for retrieving transcripts ([#500](https://github.com/LuanRT/YouTube.js/issues/500)) ([f94ea6c](https://github.com/LuanRT/YouTube.js/commit/f94ea6cf917f63f30dd66514b22a4cf43b948f07))
* **PlaylistManager:** add .setName() and .setDescription() functions for editing playlists ([#498](https://github.com/LuanRT/YouTube.js/issues/498)) ([86fb33e](https://github.com/LuanRT/YouTube.js/commit/86fb33ed03a127d9fd4caa695ca97642bffe61bd))
### Bug Fixes
* **BackstagePost:** `vote_button` type mismatch ([fba3fc9](https://github.com/LuanRT/YouTube.js/commit/fba3fc971454d66d80d4920fbd60889a221de381))
## [6.3.0](https://github.com/LuanRT/YouTube.js/compare/v6.2.0...v6.3.0) (2023-08-31)
### Features
* **ChannelMetadata:** Add `music_artist_name` ([#497](https://github.com/LuanRT/YouTube.js/issues/497)) ([91de6e5](https://github.com/LuanRT/YouTube.js/commit/91de6e5c0e5b27e6d12ce5db2f500c5ff78b9830))
* **Session:** Add on_behalf_of_user session option. ([#494](https://github.com/LuanRT/YouTube.js/issues/494)) ([8bc2aaa](https://github.com/LuanRT/YouTube.js/commit/8bc2aaa3587fcf79f69eedbc2bf422a4c6fa7eb1))
### Bug Fixes
* **CompactMovie:** Add missing import and remove unnecessary console.log ([#496](https://github.com/LuanRT/YouTube.js/issues/496)) ([c26972c](https://github.com/LuanRT/YouTube.js/commit/c26972c42a6368822ac254c00f1bbee5a1542486))
## [6.2.0](https://github.com/LuanRT/YouTube.js/compare/v6.1.0...v6.2.0) (2023-08-29)
### Features
* **Session:** Add fallback for session data retrieval ([#490](https://github.com/LuanRT/YouTube.js/issues/490)) ([10c15bf](https://github.com/LuanRT/YouTube.js/commit/10c15bfb9f131a2acea2f26ff3328993d8d8f4aa))
### Bug Fixes
* **Format:** Fix `is_original` always being `true` ([#492](https://github.com/LuanRT/YouTube.js/issues/492)) ([0412fa0](https://github.com/LuanRT/YouTube.js/commit/0412fa05ff1f00960b398c2f18d5ce39ce0cb864))
## [6.1.0](https://github.com/LuanRT/YouTube.js/compare/v6.0.2...v6.1.0) (2023-08-27)
### Features
* **parser:** Add `AlertWithButton` ([#486](https://github.com/LuanRT/YouTube.js/issues/486)) ([8b69587](https://github.com/LuanRT/YouTube.js/commit/8b6958778721ba274283f641779fb60bc6f42cd2))
* **parser:** Add `ChannelHeaderLinksView` ([#484](https://github.com/LuanRT/YouTube.js/issues/484)) ([ed7be2a](https://github.com/LuanRT/YouTube.js/commit/ed7be2a675cf1ec663e743e90db6260c97546739))
* **parser:** Add `CompactMovie` ([#487](https://github.com/LuanRT/YouTube.js/issues/487)) ([2eed172](https://github.com/LuanRT/YouTube.js/commit/2eed1726d5bde7648af09273cc14ab4a315cb23e))
## [6.0.2](https://github.com/LuanRT/YouTube.js/compare/v6.0.1...v6.0.2) (2023-08-24)
### Bug Fixes
* invalid set ids in dash manifest ([#480](https://github.com/LuanRT/YouTube.js/issues/480)) ([1c3ea2a](https://github.com/LuanRT/YouTube.js/commit/1c3ea2acd38652c6b40a0817a7836c672a776c4e))
## [6.0.1](https://github.com/LuanRT/YouTube.js/compare/v6.0.0...v6.0.1) (2023-08-22)
### Bug Fixes
* **SearchSubMenu:** Groups not being parsed due to a typo ([90be877](https://github.com/LuanRT/YouTube.js/commit/90be877d28e0ef013056eaeaa4f2765c91addd61))
## [6.0.0](https://github.com/LuanRT/YouTube.js/compare/v5.8.0...v6.0.0) (2023-08-18)
### ⚠ BREAKING CHANGES
* replace unnecessary classes with pure functions ([#468](https://github.com/LuanRT/YouTube.js/issues/468))
### Features
* **MusicResponsiveListItem:** Detect non music tracks properly ([815e54b](https://github.com/LuanRT/YouTube.js/commit/815e54b854fcda3f5423231c8495ce1fb69d8237))
* **parser:** add `MusicMultiRowListItem` ([494ee87](https://github.com/LuanRT/YouTube.js/commit/494ee8776af0839d3ee2cca3d2fd836680cfdb9e))
* **Session:** Add `IOS` to `ClientType` enum ([22a38c0](https://github.com/LuanRT/YouTube.js/commit/22a38c0762499de74f0aeb3ef01332f893518b08))
* **VideoInfo:** support iOS client ([#467](https://github.com/LuanRT/YouTube.js/issues/467)) ([46fe18b](https://github.com/LuanRT/YouTube.js/commit/46fe18b763e0c943b24ea10fdf25456ab9ade709))
### Bug Fixes
* **Format:** Extracting audio language from captions ([#470](https://github.com/LuanRT/YouTube.js/issues/470)) ([31d27b1](https://github.com/LuanRT/YouTube.js/commit/31d27b1bca489ee0053d2783f1a956609845a901))
* **parser:** Allow any property in the `RawResponse` interface ([3bc53a8](https://github.com/LuanRT/YouTube.js/commit/3bc53a8c12e65b22f19a3e337641196b692a94db))
* **parser:** Logger logging `classdata` as `[Object object]` ([bf1510b](https://github.com/LuanRT/YouTube.js/commit/bf1510b235e3ee7d13d51f092babd1105c3d6b9f))
* **Playlist:** Only try extracting the subtitle for the first page ([#465](https://github.com/LuanRT/YouTube.js/issues/465)) ([e370116](https://github.com/LuanRT/YouTube.js/commit/e3701160928e9e959b88ca215c6b0a44c70ca6e6))
* **toDash:** Format grouping into AdaptationSets ([#462](https://github.com/LuanRT/YouTube.js/issues/462)) ([1ff3e1a](https://github.com/LuanRT/YouTube.js/commit/1ff3e1a440389e71055d4b201c29021ca5b39254))
### Performance Improvements
* Cleanup some unnecessary uses of `YTNode#key` and `Maybe` ([#463](https://github.com/LuanRT/YouTube.js/issues/463)) ([0dda97e](https://github.com/LuanRT/YouTube.js/commit/0dda97e0b03171de52d7f11a5abf78911e74cead))
### Code Refactoring
* replace unnecessary classes with pure functions ([#468](https://github.com/LuanRT/YouTube.js/issues/468)) ([87ed396](https://github.com/LuanRT/YouTube.js/commit/87ed3960ffa1c738b6f3b5acaf423647db4d367e))
## [5.8.0](https://github.com/LuanRT/YouTube.js/compare/v5.7.1...v5.8.0) (2023-07-30)
### Features
* **YouTube Playlist:** Add subtitle and fix author optionality ([#458](https://github.com/LuanRT/YouTube.js/issues/458)) ([0fa5a85](https://github.com/LuanRT/YouTube.js/commit/0fa5a859ae15a35266297079e3e34fd9f3a5ebf4))
## [5.7.1](https://github.com/LuanRT/YouTube.js/compare/v5.7.0...v5.7.1) (2023-07-25)
### Bug Fixes
* **SearchHeader:** remove console.log ([d91695a](https://github.com/LuanRT/YouTube.js/commit/d91695a9ec6c55445cbeedba4ace4ac1e0a72eee))
## [5.7.0](https://github.com/LuanRT/YouTube.js/compare/v5.6.0...v5.7.0) (2023-07-24)
### Features
* **parser:** Add `PageHeader` ([#450](https://github.com/LuanRT/YouTube.js/issues/450)) ([18cbc8c](https://github.com/LuanRT/YouTube.js/commit/18cbc8c038ddddffa1ba1519e56a8054b2996e42))
* **parser:** Add `SearchHeader` ([6997982](https://github.com/LuanRT/YouTube.js/commit/6997982cf2db87edf4929e9a77e2690e7b630d3d)), closes [#452](https://github.com/LuanRT/YouTube.js/issues/452)
## [5.6.0](https://github.com/LuanRT/YouTube.js/compare/v5.5.0...v5.6.0) (2023-07-18)
### Features
* **parser:** Add `IncludingResultsFor` ([#447](https://github.com/LuanRT/YouTube.js/issues/447)) ([c477b82](https://github.com/LuanRT/YouTube.js/commit/c477b824c084552169062f72cde8890e77b31f59))
* **toDash:** Add option to include thumbnails in the manifest ([#446](https://github.com/LuanRT/YouTube.js/issues/446)) ([1a03473](https://github.com/LuanRT/YouTube.js/commit/1a034733f6bb641e2d97df12de81ae3516c1f703))
## [5.5.0](https://github.com/LuanRT/YouTube.js/compare/v5.4.0...v5.5.0) (2023-07-16)
### Features
* **Format:** Populate audio language from captions when available ([#445](https://github.com/LuanRT/YouTube.js/issues/445)) ([bdd98a3](https://github.com/LuanRT/YouTube.js/commit/bdd98a3b9be39c11942043a300a6ebce9a15efc6))
* **parser:** Add `CommentsSimplebox` parser ([#442](https://github.com/LuanRT/YouTube.js/issues/442)) ([555d257](https://github.com/LuanRT/YouTube.js/commit/555d257459b76d7c0158e9c6b189a75a82b10faf))
* **parser:** Add `HashtagTile` ([#440](https://github.com/LuanRT/YouTube.js/issues/440)) ([ae2557d](https://github.com/LuanRT/YouTube.js/commit/ae2557d15c9df09bb92e0dc6191670d72b36631a))
* **parser:** add `MacroMarkersList` ([#444](https://github.com/LuanRT/YouTube.js/issues/444)) ([708c5f7](https://github.com/LuanRT/YouTube.js/commit/708c5f7394b4ea140836b9483848cb61b97ea1af))
* **parser:** Add `ShowMiniplayerCommand` ([#443](https://github.com/LuanRT/YouTube.js/issues/443)) ([a9cdbf7](https://github.com/LuanRT/YouTube.js/commit/a9cdbf7010e7b9b9cfde5db645d51bdad51006c5))
### Bug Fixes
* **package:** Bump Jinter to fix bad export order ([#439](https://github.com/LuanRT/YouTube.js/issues/439)) ([2aef678](https://github.com/LuanRT/YouTube.js/commit/2aef67876ec19118b37d3cecd429ccf8239989e0))
* **StructuredDescriptionContent:** `items` can also be a `HorizontalCardList` ([b50d1ef](https://github.com/LuanRT/YouTube.js/commit/b50d1ef67d81276864818de10c61b5a7980cbc1a))
## [5.4.0](https://github.com/LuanRT/YouTube.js/compare/v5.3.0...v5.4.0) (2023-07-14)
### Features
* **Channel:** Add `getPodcasts()` method ([f267fcd](https://github.com/LuanRT/YouTube.js/commit/f267fcd8beccf237b8d1924463990273887cae28))
* **Channel:** Add `getReleases()` method ([f267fcd](https://github.com/LuanRT/YouTube.js/commit/f267fcd8beccf237b8d1924463990273887cae28))
* **parser:** Add `Quiz` ([#437](https://github.com/LuanRT/YouTube.js/issues/437)) ([cffa868](https://github.com/LuanRT/YouTube.js/commit/cffa868c6eeb579047653fac65da8e913fb3c621))
### Bug Fixes
* **Playlist:** Parse `PlaylistCustomThumbnail` for `thumbnail_renderer` ([f267fcd](https://github.com/LuanRT/YouTube.js/commit/f267fcd8beccf237b8d1924463990273887cae28))
## [5.3.0](https://github.com/LuanRT/YouTube.js/compare/v5.2.1...v5.3.0) (2023-07-11)
### Features
* **toDash:** Add color information ([#430](https://github.com/LuanRT/YouTube.js/issues/430)) ([3500e92](https://github.com/LuanRT/YouTube.js/commit/3500e926327d560b1db036bfe503c276b91922ac))
### Performance Improvements
* **Format:** Cleanup the xtags parsing ([#434](https://github.com/LuanRT/YouTube.js/issues/434)) ([1ca2083](https://github.com/LuanRT/YouTube.js/commit/1ca20836bf343c78461fab7ad3b71db2b96e65c3))
* **toDash:** Hoist duplicates from Representation to AdaptationSet ([#431](https://github.com/LuanRT/YouTube.js/issues/431)) ([5f058e6](https://github.com/LuanRT/YouTube.js/commit/5f058e69ae8594491133f7f96287bea4137f7822))
## [5.2.1](https://github.com/LuanRT/YouTube.js/compare/v5.2.0...v5.2.1) (2023-07-04)
### Bug Fixes
* incorrect node parser implementations ([#428](https://github.com/LuanRT/YouTube.js/issues/428)) ([222dfce](https://github.com/LuanRT/YouTube.js/commit/222dfce6bbd13b2cd80ae11540cbc0edd9053fc5))
## [5.2.0](https://github.com/LuanRT/YouTube.js/compare/v5.1.0...v5.2.0) (2023-06-28)
### Features
* **VideoDetails:** Add is_post_live_dvr property ([#411](https://github.com/LuanRT/YouTube.js/issues/411)) ([a11e596](https://github.com/LuanRT/YouTube.js/commit/a11e5962c6eb73b14623a9de1e6c8c2534146b1e))
* **ytmusic:** Add support for YouTube Music mood filters ([#404](https://github.com/LuanRT/YouTube.js/issues/404)) ([77b39c7](https://github.com/LuanRT/YouTube.js/commit/77b39c79ee0768eb203b7d47ea81286d470c21f2))
### Bug Fixes
* **OAuth:** client identity matching ([#421](https://github.com/LuanRT/YouTube.js/issues/421)) ([07c1b3e](https://github.com/LuanRT/YouTube.js/commit/07c1b3e0e57cb1fa42e4772775bfd1437bbc731f))
* **PlayerEndpoint:** Use different player params ([#419](https://github.com/LuanRT/YouTube.js/issues/419)) ([519be72](https://github.com/LuanRT/YouTube.js/commit/519be72445b7ff392b396e16bcb1dc05c7df8976))
* **Playlist:** Add thumbnail_renderer on Playlist when response includes it ([#424](https://github.com/LuanRT/YouTube.js/issues/424)) ([4f9427d](https://github.com/LuanRT/YouTube.js/commit/4f9427d752e89faec8dd1c4fd7a9607dca998c7a))
* **VideoInfo.ts:** reimplement `get music_tracks` ([#409](https://github.com/LuanRT/YouTube.js/issues/409)) ([e434bb2](https://github.com/LuanRT/YouTube.js/commit/e434bb2632fe2b20aab6f1e707a93ca76f9d5c91))
### Performance Improvements
* **Search:** Speed up results parsing ([#408](https://github.com/LuanRT/YouTube.js/issues/408)) ([1e07a18](https://github.com/LuanRT/YouTube.js/commit/1e07a184ffaff508ad5ba869cb5e7dc9f095f744))
* **toDash:** Speed up format filtering ([#405](https://github.com/LuanRT/YouTube.js/issues/405)) ([5de7b24](https://github.com/LuanRT/YouTube.js/commit/5de7b24dc55fca3eb8fccc6fa30d3c2cd60b8184))
## [5.1.0](https://github.com/LuanRT/YouTube.js/compare/v5.0.4...v5.1.0) (2023-05-14)
### Features
* **ReelItem:** Add accessibility label ([#401](https://github.com/LuanRT/YouTube.js/issues/401)) ([046103a](https://github.com/LuanRT/YouTube.js/commit/046103a4d8af09fafefab6e9f971184eeca75c2e))
* **toDash:** Add audio track labels to the manifest when available ([#402](https://github.com/LuanRT/YouTube.js/issues/402)) ([84b4f1e](https://github.com/LuanRT/YouTube.js/commit/84b4f1efd111321e4f3e5a87844790c4ec9b0b52))
## [5.0.4](https://github.com/LuanRT/YouTube.js/compare/v5.0.3...v5.0.4) (2023-05-10)
### Bug Fixes
* **bundles:** Use ESM tslib build for the browser bundles ([#397](https://github.com/LuanRT/YouTube.js/issues/397)) ([2673419](https://github.com/LuanRT/YouTube.js/commit/26734194ab0bc5a9f57e1c509d7646ce8903d0c6))
* **Utils:** Circular dependency introduced in 38a83c3c2aa814150d1d9b8ed99fca915c1d67fe ([#400](https://github.com/LuanRT/YouTube.js/issues/400)) ([66b026b](https://github.com/LuanRT/YouTube.js/commit/66b026bf493d71a39e12825938fe54dc63aefd16))
* **Utils:** Use instanceof in deepCompare instead of the constructor name ([#398](https://github.com/LuanRT/YouTube.js/issues/398)) ([38a83c3](https://github.com/LuanRT/YouTube.js/commit/38a83c3c2aa814150d1d9b8ed99fca915c1d67fe))
## [5.0.3](https://github.com/LuanRT/YouTube.js/compare/v5.0.2...v5.0.3) (2023-05-03)
### Bug Fixes
* **Video:** typo causing node parsing to fail ([3b0498b](https://github.com/LuanRT/YouTube.js/commit/3b0498b68b5378e63283e792bd45571c0b919e0b))
## [5.0.2](https://github.com/LuanRT/YouTube.js/compare/v5.0.1...v5.0.2) (2023-04-30)
### Bug Fixes
* **VideoInfo:** Use microformat view_count when videoDetails view_count is NaN ([#393](https://github.com/LuanRT/YouTube.js/issues/393)) ([7c0abfc](https://github.com/LuanRT/YouTube.js/commit/7c0abfccd78a6c291d898f898d73a4f16170e2a9))
## [5.0.1](https://github.com/LuanRT/YouTube.js/compare/v5.0.0...v5.0.1) (2023-04-30)
### Bug Fixes
* **web:** slow downloads due to visitor data ([#391](https://github.com/LuanRT/YouTube.js/issues/391)) ([4f7ec07](https://github.com/LuanRT/YouTube.js/commit/4f7ec07c3f689219b07e8291877c23b6fbf45fb1))
## [5.0.0](https://github.com/LuanRT/YouTube.js/compare/v4.3.0...v5.0.0) (2023-04-29)
### ⚠ BREAKING CHANGES
* overhaul core classes and remove redundant code ([#388](https://github.com/LuanRT/YouTube.js/issues/388))
### Features
* **NavigationEndpoint:** parse `content` prop ([dd21f8c](https://github.com/LuanRT/YouTube.js/commit/dd21f8c75ae1d76180faab4f0ef9ee40920966e3))
### Bug Fixes
* **android:** workaround streaming URLs returning 403 ([#390](https://github.com/LuanRT/YouTube.js/issues/390)) ([75ea09d](https://github.com/LuanRT/YouTube.js/commit/75ea09dde86b1bdf13b197d6e02701899300a371))
### Code Refactoring
* overhaul core classes and remove redundant code ([#388](https://github.com/LuanRT/YouTube.js/issues/388)) ([95e0294](https://github.com/LuanRT/YouTube.js/commit/95e0294eabfdb20bbee2a4bfb751fd101402c5d6))
## [4.3.0](https://github.com/LuanRT/YouTube.js/compare/v4.2.0...v4.3.0) (2023-04-13)
### Features
* **GridVideo:** add `upcoming`, `upcoming_text`, `is_reminder_set` and `buttons` ([05de3ec](https://github.com/LuanRT/YouTube.js/commit/05de3ec97a1fea92543b5e5f84933b86a07ab830)), closes [#380](https://github.com/LuanRT/YouTube.js/issues/380)
* **MusicResponsiveListItem:** make flex/fixed cols public ([#382](https://github.com/LuanRT/YouTube.js/issues/382)) ([096bf36](https://github.com/LuanRT/YouTube.js/commit/096bf362c9bd46a510ecb0d01623c70841e26e26))
* **ToggleMenuServiceItem:** parse default nav endpoint ([a056696](https://github.com/LuanRT/YouTube.js/commit/a0566969ba436f31ca3722d09442a0c6302235d7))
* **ytmusic:** add taste builder nodes ([#383](https://github.com/LuanRT/YouTube.js/issues/383)) ([a9cad49](https://github.com/LuanRT/YouTube.js/commit/a9cad49333aa85c98bbb96e5f2d5b57d9beeb0c7))
## [4.2.0](https://github.com/LuanRT/YouTube.js/compare/v4.1.1...v4.2.0) (2023-04-09)
### Features
* Enable importHelpers in tsconfig to reduce output size ([#378](https://github.com/LuanRT/YouTube.js/issues/378)) ([0b301de](https://github.com/LuanRT/YouTube.js/commit/0b301de6a1e1352a64881c1751a84360922a77cd))
* **parser:** ignore PrimetimePromo node ([ce9d9c5](https://github.com/LuanRT/YouTube.js/commit/ce9d9c56b4f45c0139d74edc95c295ecfd1ee4b1))
* **PlaylistVideo:** Extract video_info and accessibility_label texts ([#376](https://github.com/LuanRT/YouTube.js/issues/376)) ([c9135e6](https://github.com/LuanRT/YouTube.js/commit/c9135e66d3c9c72b8d063eedcf3cc2123800946d))
## [4.1.1](https://github.com/LuanRT/YouTube.js/compare/v4.1.0...v4.1.1) (2023-03-29)
### Bug Fixes
* **PlayerCaptionsTracklist:** parse props only if they exist in the node ([470d8d9](https://github.com/LuanRT/YouTube.js/commit/470d8d94063f0159cd005c9eb15fd1a4a175bea0)), closes [#372](https://github.com/LuanRT/YouTube.js/issues/372)
* **Search:** Return search results even if there are ads ([#373](https://github.com/LuanRT/YouTube.js/issues/373)) ([2c5907f](https://github.com/LuanRT/YouTube.js/commit/2c5907f80fd76452afe87d1722fe35a4f45a22e0))
## [4.1.0](https://github.com/LuanRT/YouTube.js/compare/v4.0.1...v4.1.0) (2023-03-24)
### Features
* **Session:** allow setting a custom visitor data token ([#371](https://github.com/LuanRT/YouTube.js/issues/371)) ([13ebf0a](https://github.com/LuanRT/YouTube.js/commit/13ebf0a03973e7ba7b65e9f72c4333927e4254f6))
* **ShowingResultsFor:** parse all props ([1d9587e](https://github.com/LuanRT/YouTube.js/commit/1d9587e8c1ee0b11bb0e444c3d1e98162e9e1059))
### Bug Fixes
* **http:** android tv http client missing `clientName` ([#370](https://github.com/LuanRT/YouTube.js/issues/370)) ([cb8fafe](https://github.com/LuanRT/YouTube.js/commit/cb8fafe94b8ab330ae58211a892923321d65d890))
* **node:** Electron apps crashing ([#367](https://github.com/LuanRT/YouTube.js/issues/367)) ([e7eacd9](https://github.com/LuanRT/YouTube.js/commit/e7eacd974211c90e7fbddfbf8019388cda3dfa5a))
* **parser:** Make Video.is_live work on channel pages ([#368](https://github.com/LuanRT/YouTube.js/issues/368)) ([bd35faa](https://github.com/LuanRT/YouTube.js/commit/bd35faa5978f0b822e98d019523be1303374ddc0))
* **toDash:** Generate unique Representation ids ([#366](https://github.com/LuanRT/YouTube.js/issues/366)) ([a8b507e](https://github.com/LuanRT/YouTube.js/commit/a8b507ee65ccd8edc9aea2aef8a908fa272bb23c))
* **Utils:** Properly parse timestamps with thousands separators ([#363](https://github.com/LuanRT/YouTube.js/issues/363)) ([1c72a41](https://github.com/LuanRT/YouTube.js/commit/1c72a41675e47f711bd61ebb898bca5527406a79))
## [4.0.1](https://github.com/LuanRT/YouTube.js/compare/v4.0.0...v4.0.1) (2023-03-16)
### Bug Fixes
* **Channel:** type mismatch in `subscribe_button` prop ([573c864](https://github.com/LuanRT/YouTube.js/commit/573c8643aae16ec7b6be5b333619a5d8c91ca5c1))
## [4.0.0](https://github.com/LuanRT/YouTube.js/compare/v3.3.0...v4.0.0) (2023-03-15)
### ⚠ BREAKING CHANGES
* **Parser:** general refactoring of parsers ([#344](https://github.com/LuanRT/YouTube.js/issues/344))
* The `toDash` functions are now asynchronous, they now return a `Promise<string>` instead of a `string`, as we need to fetch the first sequence of the OTF format streams while building the manifest.
### Features
* Add support for OTF format streams ([3e4d41b](https://github.com/LuanRT/YouTube.js/commit/3e4d41bf06ba16232979977c705444f2032bcde6))
* **parser:** add `GridMix` ([#356](https://github.com/LuanRT/YouTube.js/issues/356)) ([a8e7e64](https://github.com/LuanRT/YouTube.js/commit/a8e7e644ec6df3b3c98a313f0321da27b4ca456e))
* **parser:** add `GridShow` and `ShowCustomThumbnail` ([8ef4b42](https://github.com/LuanRT/YouTube.js/commit/8ef4b42d444c4fbe5cd65a55c0e0e7aa31738755)), closes [#459](https://github.com/LuanRT/YouTube.js/issues/459)
* **parser:** add `MusicCardShelf` ([#358](https://github.com/LuanRT/YouTube.js/issues/358)) ([9b005d6](https://github.com/LuanRT/YouTube.js/commit/9b005d62d6590a2ddf6848dabfa33fce36e8df9c))
* **parser:** Add `play_all_button` to `Shelf` ([#345](https://github.com/LuanRT/YouTube.js/issues/345)) ([427db5b](https://github.com/LuanRT/YouTube.js/commit/427db5bbc2bf3e8ec60371d504c2ab1cdae6e918))
* **parser:** add `view_playlist` to `Playlist` ([#348](https://github.com/LuanRT/YouTube.js/issues/348)) ([9cb4530](https://github.com/LuanRT/YouTube.js/commit/9cb45302997771d909487b1ecba6f38655abef48))
* **parser:** add InfoPanelContent and InfoPanelContainer nodes ([4784dfa](https://github.com/LuanRT/YouTube.js/commit/4784dfa563a4dbeaee31811824d5aa37a67f5557)), closes [#326](https://github.com/LuanRT/YouTube.js/issues/326)
* **Parser:** just-in-time YTNode generation ([#310](https://github.com/LuanRT/YouTube.js/issues/310)) ([2cee590](https://github.com/LuanRT/YouTube.js/commit/2cee59024c730c34aa06052849ed6fb3f862ef33))
* **yt:** add support for movie items and trailers ([#349](https://github.com/LuanRT/YouTube.js/issues/349)) ([9f1c31d](https://github.com/LuanRT/YouTube.js/commit/9f1c31d7a09532e80a187b14acceff31c22579bf))
### Code Refactoring
* **Parser:** general refactoring of parsers ([#344](https://github.com/LuanRT/YouTube.js/issues/344)) ([b13bf6e](https://github.com/LuanRT/YouTube.js/commit/b13bf6e9926c19a1939e0f4b69cbd53d1af0f7c8))
## [3.3.0](https://github.com/LuanRT/YouTube.js/compare/v3.2.0...v3.3.0) (2023-03-09)
### Features
* **parser:** add `ConversationBar` node ([b2253df](https://github.com/LuanRT/YouTube.js/commit/b2253df8022217dc486155d8cacbf22db04dd9c2))
* **VideoInfo:** support get by endpoint + more info ([#342](https://github.com/LuanRT/YouTube.js/issues/342)) ([0d35fe0](https://github.com/LuanRT/YouTube.js/commit/0d35fe0ca5e87a877b76cbb6cf3c92843eac5a99))
### Bug Fixes
* **MultiMarkersPlayerBar:** avoid observing undefined objects ([f351770](https://github.com/LuanRT/YouTube.js/commit/f3517708ff34093a544c09d6f5f1ec806130d5cc))
* **SharedPost:** import `Menu` node directly (oops) ([3e3dc35](https://github.com/LuanRT/YouTube.js/commit/3e3dc351bb44faec87616d9b922924d14a95f29f))
* **ytmusic:** use static visitor id to avoid empty API responses ([f9754f5](https://github.com/LuanRT/YouTube.js/commit/f9754f5ac61d0f11b025f37f93783f971560268b)), closes [#279](https://github.com/LuanRT/YouTube.js/issues/279)
## [3.2.0](https://github.com/LuanRT/YouTube.js/compare/v3.1.1...v3.2.0) (2023-03-08)
### Features
* Add support for descriptive audio tracks ([#338](https://github.com/LuanRT/YouTube.js/issues/338)) ([574b67a](https://github.com/LuanRT/YouTube.js/commit/574b67a1f707a32378586dd2fe7b2f36f4ab6ddb))
* export `FormatUtils`' types ([2d774e2](https://github.com/LuanRT/YouTube.js/commit/2d774e26aae79f3d1b115e0e85c148ae80985529))
* **parser:** add `banner` to `PlaylistHeader` ([#337](https://github.com/LuanRT/YouTube.js/issues/337)) ([95033e7](https://github.com/LuanRT/YouTube.js/commit/95033e723ef912706e4d176de6b2760f017184e1))
* **parser:** SharedPost ([#332](https://github.com/LuanRT/YouTube.js/issues/332)) ([ce53ac1](https://github.com/LuanRT/YouTube.js/commit/ce53ac18435cbcb20d6d4c4ab52fd156091e7592))
* **VideoInfo:** add `game_info` and `category` ([#333](https://github.com/LuanRT/YouTube.js/issues/333)) ([214aa14](https://github.com/LuanRT/YouTube.js/commit/214aa147ce6306e37a6bf860a7bed5635db4797e))
* **YouTube/Search:** add `SearchSubMenu` node ([#340](https://github.com/LuanRT/YouTube.js/issues/340)) ([a511608](https://github.com/LuanRT/YouTube.js/commit/a511608f18b37b0d9f2c7958ed5128330fabcfa0))
* **yt:** add `getGuide()` ([#335](https://github.com/LuanRT/YouTube.js/issues/335)) ([2cc7b8b](https://github.com/LuanRT/YouTube.js/commit/2cc7b8bcd6938c7fb3af4f854a1d78b86d153873))
### Bug Fixes
* **SegmentedLikeDislikeButton:** like/dislike buttons can also be a simple `Button` ([9b2738f](https://github.com/LuanRT/YouTube.js/commit/9b2738f1285b278c3e83541857651be9a6248288))
* **YouTube:** fix warnings when retrieving members-only content ([#341](https://github.com/LuanRT/YouTube.js/issues/341)) ([95f1d40](https://github.com/LuanRT/YouTube.js/commit/95f1d4077ff3775f36967dca786139a09e2830a2))
* **ytmusic:** export search filters type ([cf8a33c](https://github.com/LuanRT/YouTube.js/commit/cf8a33c79f5432136b865d535fd0ecedc2393382))
## [3.1.1](https://github.com/LuanRT/YouTube.js/compare/v3.1.0...v3.1.1) (2023-03-01)
### Bug Fixes
* **Channel:** getting community continuations ([#329](https://github.com/LuanRT/YouTube.js/issues/329)) ([4c7b8a3](https://github.com/LuanRT/YouTube.js/commit/4c7b8a34030effa26c4ea186d3e9509128aec31c))
## [3.1.0](https://github.com/LuanRT/YouTube.js/compare/v3.0.0...v3.1.0) (2023-02-26)
### Features
* Add upcoming and live info to playlist videos ([#317](https://github.com/LuanRT/YouTube.js/issues/317)) ([a0bfe16](https://github.com/LuanRT/YouTube.js/commit/a0bfe164279ec27b0c49c6b0c32222c1a92df5c3))
* **VideoSecondaryInfo:** add support for attributed descriptions ([#325](https://github.com/LuanRT/YouTube.js/issues/325)) ([f933cb4](https://github.com/LuanRT/YouTube.js/commit/f933cb45bcb92c07b3bc063d63869a51cbff4eb0))
### Bug Fixes
* **parser:** export YTNodes individually so they can be used as types ([200632f](https://github.com/LuanRT/YouTube.js/commit/200632f374d5e0e105b600d579a2665a6fb36e38)), closes [#321](https://github.com/LuanRT/YouTube.js/issues/321)
* **PlayerMicroformat:** Make the embed field optional ([#320](https://github.com/LuanRT/YouTube.js/issues/320)) ([a0e6cef](https://github.com/LuanRT/YouTube.js/commit/a0e6cef00fb9e3f52593cec22704f7ddc1f7553e))
* send correct UA for Android requests ([f4e0f30](https://github.com/LuanRT/YouTube.js/commit/f4e0f30e6e94b347b28d67d9a86284ea2d23ee15)), closes [#322](https://github.com/LuanRT/YouTube.js/issues/322)
## [3.0.0](https://github.com/LuanRT/YouTube.js/compare/v2.9.0...v3.0.0) (2023-02-17)
### ⚠ BREAKING CHANGES
* cleanup platform support ([#306](https://github.com/LuanRT/YouTube.js/issues/306))
### Features
* add parser support for MultiImage community posts ([#298](https://github.com/LuanRT/YouTube.js/issues/298)) ([de61782](https://github.com/LuanRT/YouTube.js/commit/de61782f1a673cbe66ae9b410341e39b7501ba84))
* add support for hashtag feeds ([#312](https://github.com/LuanRT/YouTube.js/issues/312)) ([bf12740](https://github.com/LuanRT/YouTube.js/commit/bf12740333a82c26fe84e7c702c2fbb8859814fc))
* add support for YouTube Kids ([#291](https://github.com/LuanRT/YouTube.js/issues/291)) ([2bbefef](https://github.com/LuanRT/YouTube.js/commit/2bbefefbb7cb061f3e7b686158b7568c32f0da5d))
* allow checking whether a channel has optional tabs ([#296](https://github.com/LuanRT/YouTube.js/issues/296)) ([ceefbed](https://github.com/LuanRT/YouTube.js/commit/ceefbed98c70bb936e2d2df58c02834842acfdfc))
* **Channel:** Add getters for all optional tabs ([#303](https://github.com/LuanRT/YouTube.js/issues/303)) ([b2900f4](https://github.com/LuanRT/YouTube.js/commit/b2900f48a7aa4c22635e1819ba9f636e81964f2c))
* **Channel:** add support for sorting the playlist tab ([#295](https://github.com/LuanRT/YouTube.js/issues/295)) ([50ef712](https://github.com/LuanRT/YouTube.js/commit/50ef71284db41e5f94bb511892651d22a1d363a0))
* extract channel error alert ([0b99180](https://github.com/LuanRT/YouTube.js/commit/0b991800a5c67f0e702251982b52eb8531f36f19))
* **FormatUtils:** support multiple audio tracks in the DASH manifest ([#308](https://github.com/LuanRT/YouTube.js/issues/308)) ([a69e43b](https://github.com/LuanRT/YouTube.js/commit/a69e43bf3ae02f2428c4aa86f647e3e5e0db5ba6))
* improve support for dubbed content ([#293](https://github.com/LuanRT/YouTube.js/issues/293)) ([d6c5a9b](https://github.com/LuanRT/YouTube.js/commit/d6c5a9b971444d0cd746aaf5310d3389793680ea))
* parse isLive in CompactVideo ([#294](https://github.com/LuanRT/YouTube.js/issues/294)) ([2acb7da](https://github.com/LuanRT/YouTube.js/commit/2acb7da0198bfeca6ff911cf95cf06a220fccaa5))
* **parser:** add `ChannelAgeGate` node ([1cdf701](https://github.com/LuanRT/YouTube.js/commit/1cdf701c8403db6b681a26ecb1df2daa51add454))
* **parser:** Text#toHTML ([#300](https://github.com/LuanRT/YouTube.js/issues/300)) ([e82e23d](https://github.com/LuanRT/YouTube.js/commit/e82e23dfbb24dff3ddf45754c7319d783990e254))
* **ytkids:** add `getChannel()` ([#292](https://github.com/LuanRT/YouTube.js/issues/292)) ([0fc29f0](https://github.com/LuanRT/YouTube.js/commit/0fc29f0bbf965215146a6ae192494c74e6cefcbb))
### Bug Fixes
* assign MetadataBadge's label ([#311](https://github.com/LuanRT/YouTube.js/issues/311)) ([e37cf62](https://github.com/LuanRT/YouTube.js/commit/e37cf627322f688fcef18d41345f77cbccd58829))
* **ChannelAboutFullMetadata:** fix error when there are no primary links ([#299](https://github.com/LuanRT/YouTube.js/issues/299)) ([f62c66d](https://github.com/LuanRT/YouTube.js/commit/f62c66db396ba7d2f93007414101112b49d8375f))
* **TopicChannelDetails:** avatar and subtitle parsing ([#302](https://github.com/LuanRT/YouTube.js/issues/302)) ([d612590](https://github.com/LuanRT/YouTube.js/commit/d612590530f5fe590fee969810b1dd44c37f0457))
* **VideoInfo:** Gracefully handle missing watch next continuation ([#288](https://github.com/LuanRT/YouTube.js/issues/288)) ([13ad377](https://github.com/LuanRT/YouTube.js/commit/13ad3774c9783ed2a9f286aeee88110bd43b3a73))
### Code Refactoring
* cleanup platform support ([#306](https://github.com/LuanRT/YouTube.js/issues/306)) ([2ccbe2c](https://github.com/LuanRT/YouTube.js/commit/2ccbe2ce6260ace3bfac8b4b391e583fbcc4e286))

20
COLLABORATORS.md Normal file
View File

@@ -0,0 +1,20 @@
# Collaborators
This page lists the collaborators who have contributed to the development and success of the project.
## [LuanRT](https://github.com/LuanRT)
[![Github Sponsors](https://img.shields.io/badge/donate-30363D?style=flat-square&logo=GitHub-Sponsors&logoColor=#white)](https://github.com/sponsors/LuanRT)
Owner and maintainer.
## [Wykerd](https://github.com/wykerd/)
Initial parser implementation, several bug fixes, major refactorings and general maintenance.
## [MasterOfBob777](https://github.com/MasterOfBob777)
Bug fixes and TypeScript support.
## [patrickkfkan](https://github.com/patrickkfkan)
Major refactorings, improved YouTube Music support, and bug fixes.
## [Absidue](https://github.com/absidue)
Several bug fixes, new features & improved MPD support.

View File

@@ -1,81 +1,66 @@
# Contributing to YouTube.js
Welcome to YouTube.js! We're thrilled to have you interested in contributing to our project. As a community-driven project, we believe in the power of collaboration and look forward to working with you. To get started, please follow our guidelines:
Thank you for taking the time to contribute!
The following is a set of guidelines for contributing to YouTube.js.
___
* [Issues](#issues)
* [Create a new issue](#issue-1)
* [Solve an issue](#issue-2)
* [Make changes](#changes)
* [Commit your updates](#changes-1)
* [Create a PR](#changes-2)
* [Run tests](#test)
* [Lint your code](#lint)
* [Build](#build)
## Issues
<a id="issue-1"></a>
#### Create a new issue
If you find a problem, search if an issue already exists. If a related issue doesn't exist, you can open a new issue using a relevant issue form.
### Creating a new issue
Before creating a new issue, we recommend searching for similar or related issues to avoid duplication efforts. However, if you can't find one, you're more than welcome to create a new issue using a relevant issue form. Please make sure to describe the issue as clearly and concisely as possible.
<a id="issue-2"></a>
#### Solve an issue
Scan through the existing issues to find one that interests you. You can narrow down the search using labels as filters. If you find an issue to work on, you are welcome to open a PR with a fix. Documentation updates and grammar fixes are also appreciated!
### Solving an issue
If you want to lend a hand by solving an issue, it's always good to browse existing issues to find one that grabs your attention. You can narrow down the search using tags as filters. If you find an issue you'd like to help with, please feel free to open a Pull Request with a fix. We appreciate documentation updates and grammar fixes too!
<a id="changes"></a>
## Make changes
## Making Changes
1. Fork the repository
2. Install or update to **Node.js v16**
3. Create a working branch and start with your changes!
1. Fork the repository on GitHub.
2. Ensure that you have the latest Node.js v16 version installed.
3. Create a working branch and start making your changes and improvements!
<a id="changes-1"></a>
#### Commit your updates
### Committing updates
When you're done with the changes, make sure to commit them. Don't forget to write a clear, descriptive commit message. We recommend following the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
Commit the changes once you're happy with them.
### Creating a Pull Request
Once you're happy with your updates, create a pull request on GitHub. This is the most efficient way to get your contribution reviewed and eventually merged into our codebase.
<a id="changes-2"></a>
#### Pull Request
- Use the pull request template to fill in the necessary details.
- If you're solving an issue, link the pull request to that issue.
- Enable the checkbox to allow maintainers to edit the branch and update it for merging.
- Changes may be required before we can merge your changes, and we'll let you know what needs to be done.
When you think the code is ready for review a pull request should be created on Github. Owners of the repository will watch out for new PRs and review them in regular intervals.
### Testing, Linting, and Building
We have some automated processes set up for testing, linting, and building. Please run the following commands to test, lint, and build your code before submitting it:
- Fill the template.
- Link the PR to an issue, if you are solving one.
- Enable the checkbox to allow maintainer edits so the branch can be updated for a merge.
- Changes may be requested before a PR can be merged.
- As you update your PR and apply changes, mark each conversation as resolved.
<a id="test"></a>
#### Test
```bash
Testing:
```sh
npm run test
```
<a id="lint"></a>
#### Lint
```bash
Linting:
```sh
npm run lint
npm run lint:fix
```
<a id="build"></a>
#### Build
```bash
# Node
npm run build:node
# Browser
npm run build:browser
npm run build:browser:prod
Building:
```sh
# Build all
npm run build
# Protobuf
npm run build:proto
# Parser map
npm run build:parser-map
```
# Deno
npm run build:deno
# ES Module
npm run build:esm
# Node
npm run bundle:node
# Browser
npm run bundle:browser
npm run bundle:browser:prod
```
We appreciate your efforts and contributions to YouTube.js! Together, we can make this project even better.

425
README.md
View File

@@ -3,100 +3,62 @@
[versions]: https://www.npmjs.com/package/youtubei.js?activeTab=versions
[codefactor]: https://www.codefactor.io/repository/github/luanrt/youtube.js
[actions]: https://github.com/LuanRT/YouTube.js/actions
[say-thanks]: https://saythanks.io/to/LuanRT
[github-sponsors]:https://github.com/sponsors/LuanRT
[collaborators]: https://github.com/LuanRT/YouTube.js/blob/main/COLLABORATORS.md
<!-- OTHER LINKS -->
[project]: https://github.com/LuanRT/YouTube.js
[twitter]: https://twitter.com/thesciencephile
[discord]: https://discord.gg/syDu7Yks54
[nodejs]: https://nodejs.org
<h1 align=center>YouTube.js</h1>
<p align=center>A full-featured wrapper around the InnerTube API, which is what YouTube itself uses</p>
<div align="center">
<br/>
<p>
<a href="https://github.com/LuanRT/YouTube.js"><img src="https://luanrt.github.io/assets/img/ytjs.svg" title="youtube.js" alt="YouTube.js' Github Page" width="200" /></a>
</p>
<p align="center">A full-featured wrapper around the InnerTube API</p>
[![Tests](https://github.com/LuanRT/YouTube.js/actions/workflows/node.js.yml/badge.svg)][actions]
[![NPM Version](https://img.shields.io/npm/v/youtubei.js?color=%2335C757)][versions]
[![Codefactor](https://www.codefactor.io/repository/github/luanrt/youtube.js/badge)][codefactor]
[![Downloads](https://img.shields.io/npm/dt/youtubei.js)][npm]
[![Discord](https://img.shields.io/badge/discord-online-brightgreen.svg)][discord]
[![Say thanks](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)][say-thanks]
[![CI](https://github.com/LuanRT/YouTube.js/actions/workflows/test.yml/badge.svg)][actions]
[![NPM Version](https://img.shields.io/npm/v/youtubei.js?color=%2335C757)][versions]
[![Downloads](https://img.shields.io/npm/dt/youtubei.js)][npm]
[![Codefactor](https://www.codefactor.io/repository/github/luanrt/youtube.js/badge)][codefactor]
<h5>
Sponsored by&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://serpapi.com"><img src="https://luanrt.github.io/assets/img/serpapi.svg" alt="SerpApi - API to get search engine results with ease." height=35 valign="middle"></a>
</h5>
<br>
[![Donate](https://img.shields.io/badge/donate-30363D?style=for-the-badge&logo=GitHub-Sponsors&logoColor=#white)][github-sponsors]
</div>
<p align="center">
<a><sub>Special thanks to:<sub></a>
</p>
<table align="center">
<body>
<tr>
<td align="center">
<a href="https://serpapi.com/" target="_blank">
<img width="80" alt="SerpApi" src="https://luanrt.is-a.dev/assets/img/serpapi.svg" />
<br>
<b>
<sub>
Scrape Google and other search engines from a fast, easy and complete API.
</sub>
</b>
</a>
</td>
</tr>
</body>
</table>
___
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li>
<a href="#usage">Usage</a>
<ul>
<li><a href="#browser-usage">Browser Usage</a></li>
<li><a href="#caching">Caching</a></li>
<li><a href="#api">API</a></li>
</ul>
</li>
<li><a href="#extending-the-library">Extending the library</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#disclaimer">Disclaimer</a></li>
<li><a href="#license">License</a></li>
</ol>
</details>
## Description
InnerTube is an API used by all YouTube clients. It was created to simplify the deployment of new features and experiments across the platform[^1]. This library handles all the low-level communication with InnerTube, providing a simple, and efficient way to interact with YouTube programmatically. It is designed to emulate an actual client as closely as possible, including how API responses are [parsed](https://github.com/LuanRT/YouTube.js/tree/main/src/parser#how-it-works).
InnerTube is an API used by all YouTube clients. It was created to simplify the deployment of new features and experiments across the platform [^1]. This library manages all low-level communication with InnerTube, providing a simple and efficient way to interact with YouTube programmatically. Its design aims to closely emulate an actual client, including the parsing of API responses.
If you have any questions or need help, feel free to reach out to us on our [Discord server][discord] or open an issue [here](https://github.com/LuanRT/YouTube.js/issues).
## Getting Started
### Table of Contents
<ol>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
<li>
<a href="#usage">Usage</a>
<ul>
<li><a href="#browser-usage">Browser Usage</a></li>
<li><a href="#caching">Caching</a></li>
<li><a href="#api">API</a></li>
<li><a href="#extending-the-library">Extending the library</a></li>
</ul>
</li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#disclaimer">Disclaimer</a></li>
<li><a href="#license">License</a></li>
</ol>
### Prerequisites
YouTube.js runs on Node.js, Deno, and modern browsers.
It requires a runtime with the following features:
- [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- On Node we use [undici]()'s fetch implementation which requires Node.js 16.8+. You may provide your fetch implementation if you need to use an older version. See [providing your own fetch implementation](#custom-fetch) for more information.
- The `Response` object returned by fetch must thus be spec compliant and return a `ReadableStream` object if you want to use the `VideoInfo#download` method. (Implementations like `node-fetch` returns a non-standard `Readable` object.)
- On Node, we use [undici](https://github.com/nodejs/undici)'s fetch implementation, which requires Node.js 16.8+. If you need to use an older version, you may provide your own fetch implementation. See [providing your own fetch implementation](#custom-fetch) for more information.
- The `Response` object returned by fetch must thus be spec compliant and return a `ReadableStream` object if you want to use the `VideoInfo#download` method. (Implementations like `node-fetch` return a non-standard `Readable` object.)
- [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) and [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) are required.
### Installation
@@ -112,24 +74,55 @@ yarn add youtubei.js@latest
npm install github:LuanRT/YouTube.js
```
**TODO:** Deno install instructions (esm.sh possibly?)
When using Deno, you can import YouTube.js directly from deno.land:
```ts
import { Innertube } from 'https://deno.land/x/youtubei/deno.ts';
```
## Usage
Create an InnerTube instance:
```ts
// const { Innertube } = require('youtubei.js');
import { Innertube } from 'youtubei.js';
const youtube = await Innertube.create();
const youtube = await Innertube.create(/* options */);
```
## Browser Usage
To use YouTube.js in the browser you must proxy requests through your own server. You can see our simple reference implementation in Deno in [`examples/browser/proxy/deno.ts`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/proxy/deno.ts).
### Options
<details>
<summary>Click to expand</summary>
You may provide your own fetch implementation to be used by YouTube.js. Which we will use here to modify and send the requests through our proxy. See [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/web) for a simple example using [Vite](https://vitejs.dev/).
| Option | Type | Description | Default |
| --- | --- | --- | --- |
| `lang` | `string` | Language. | `en` |
| `location` | `string` | Geolocation. | `US` |
| `account_index` | `number` | The account index to use. This is useful if you have multiple accounts logged in. **NOTE:** Only works if you are signed in with cookies. | `0` |
| `visitor_data` | `string` | Setting this to a valid and persistent visitor data string will allow YouTube to give this session tailored content even when not logged in. A good way to get a valid one is by either grabbing it from a browser or calling InnerTube's `/visitor_id` endpoint. | `undefined` |
| `retrieve_player` | `boolean` | Specifies whether to retrieve the JS player. Disabling this will make session creation faster. **NOTE:** Deciphering formats is not possible without the JS player. | `true` |
| `enable_safety_mode` | `boolean` | Specifies whether to enable safety mode. This will prevent the session from loading any potentially unsafe content. | `false` |
| `generate_session_locally` | `boolean` | Specifies whether to generate the session data locally or retrieve it from YouTube. This can be useful if you need more performance. **NOTE:** If you are using the cache option and a session has already been generated, this will be ignored. If you want to force a new session to be generated, you must clear the cache or disable session caching. | `false` |
| `enable_session_cache` | `boolean` | Specifies whether to cache the session data. | `true` |
| `device_category` | `DeviceCategory` | Platform to use for the session. | `DESKTOP` |
| `client_type` | `ClientType` | InnerTube client type. | `WEB` |
| `timezone` | `string` | The time zone. | `*` |
| `cache` | `ICache` | Used to cache algorithms, session data, and OAuth2 tokens. | `undefined` |
| `cookie` | `string` | YouTube cookies. | `undefined` |
| `fetch` | `FetchFunction` | Fetch function to use. | `fetch` |
</details>
### Browser Usage
To use YouTube.js in the browser, you must proxy requests through your own server. You can see our simple reference implementation in Deno at [`examples/browser/proxy/deno.ts`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/proxy/deno.ts).
You may provide your own fetch implementation to be used by YouTube.js, which we will use to modify and send the requests through a proxy. See [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/tree/main/examples/browser/web) for a simple example using [Vite](https://vitejs.dev/).
```ts
// Pre-bundled version for the web
import { Innertube } from 'youtubei.js/bundle/browser';
// Multiple exports are available for the web.
// Unbundled ESM version
import { Innertube } from 'youtubei.js/web';
// Bundled ESM version
// import { Innertube } from 'youtubei.js/web.bundle';
// Production Bundled ESM version
// import { Innertube } from 'youtubei.js/web.bundle.min';
await Innertube.create({
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
// Modify the request
@@ -147,18 +140,18 @@ YouTube.js supports streaming of videos in the browser by converting YouTube's s
The example below uses [`dash.js`](https://github.com/Dash-Industry-Forum/dash.js) to play the video.
```ts
import { Innertube } from 'youtubei.js';
import { Innertube } from 'youtubei.js/web';
import dashjs from 'dashjs';
const youtube = await Innertube.create({ /* setup - see above */ });
// get the video info
// Get the video info
const videoInfo = await youtube.getInfo('videoId');
// now convert to a dash manifest
// again - to be able to stream the video in the browser - we must proxy the requests through our own server
// to do this, we provide a method to transform the URLs before writing them to the manifest
const manifest = videoInfo.toDash(url => {
const manifest = await videoInfo.toDash(url => {
// modify the url
// and return it
return url;
@@ -172,10 +165,11 @@ const player = dashjs.MediaPlayer().create();
player.initialize(videoElement, uri, true);
```
Our browser example in [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/blob/main/examples/browser/web) provides a fully working example.
A fully working example can be found in [`examples/browser/web`](https://github.com/LuanRT/YouTube.js/blob/main/examples/browser/web).
<a name="custom-fetch"></a>
## Providing your own fetch implementation
### Providing your own fetch implementation
You may provide your own fetch implementation to be used by YouTube.js. This can be useful in some cases to modify the requests before they are sent and transform the responses before they are returned (eg. for proxies).
```ts
// provide a fetch implementation
@@ -192,35 +186,37 @@ const yt = await Innertube.create({
<a name="caching"></a>
## Caching
To improve performance, you may wish to cache the transformed player instance which we use to decode the streaming urls.
### Caching
Caching the transformed player instance can greatly improve the performance. Our `UniversalCache` implementation uses different caching methods depending on the environment.
Our cache uses the `node:fs` module in Node-like environments, `Deno.writeFile` in Deno, and `indexedDB` in browsers.
In Node.js, we use the `node:fs` module, `Deno.writeFile()` in Deno, and `indexedDB` in browsers.
By default, the cache stores data in the operating system's temporary directory (or `indexedDB` in browsers). You can make this cache persistent by specifying the path to the cache directory, which will be created if it doesn't exist.
```ts
import { Innertube, UniversalCache } from 'youtubei.js';
// By default, cache stores files in the OS temp directory (or indexedDB in browsers).
// Create a cache that stores files in the OS temp directory (or indexedDB in browsers) by default.
const yt = await Innertube.create({
cache: new UniversalCache()
cache: new UniversalCache(false)
});
// You may wish to make the cache persistent (on Node and Deno)
// You may want to create a persistent cache instead (on Node and Deno).
const yt = await Innertube.create({
cache: new UniversalCache(
// Enables persistent caching
true,
// Path to the cache directory will create the directory if it doesn't exist
// Path to the cache directory. The directory will be created if it doesn't exist
'./.cache'
)
});
```
## API
### API
* `Innertube`
<details>
<summary>Objects</summary>
<summary>Properties</summary>
<p>
* [.session](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/session.md)
@@ -229,6 +225,7 @@ const yt = await Innertube.create({
* [.playlist](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/playlist.md)
* [.music](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/music.md)
* [.studio](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/studio.md)
* [.kids](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/kids.md)
</p>
</details>
@@ -238,12 +235,13 @@ const yt = await Innertube.create({
<summary>Methods</summary>
<p>
* [.getInfo(video_id, client?)](#getinfo)
* [.getInfo(target, client?)](#getinfo)
* [.getBasicInfo(video_id, client?)](#getbasicinfo)
* [.search(query, filters?)](#search)
* [.getSearchSuggestions(query)](#getsearchsuggestions)
* [.getComments(video_id, sort_by?)](#getcomments)
* [.getHomeFeed()](#gethomefeed)
* [.getGuide()](#getguide)
* [.getLibrary()](#getlibrary)
* [.getHistory()](#gethistory)
* [.getTrending()](#gettrending)
@@ -252,6 +250,7 @@ const yt = await Innertube.create({
* [.getNotifications()](#getnotifications)
* [.getUnseenNotificationsCount()](#getunseennotificationscount)
* [.getPlaylist(id)](#getplaylist)
* [.getHashtag(hashtag)](#gethashtag)
* [.getStreamingData(video_id, options)](#getstreamingdata)
* [.download(video_id, options?)](#download)
* [.resolveURL(url)](#resolveurl)
@@ -261,15 +260,15 @@ const yt = await Innertube.create({
</details>
<a name="getinfo"></a>
### getInfo(video_id, client?)
### `getInfo(target, client?)`
Retrieves video info, including playback data and even layout elements such as menus, buttons, etc — all nicely parsed.
Retrieves video info.
**Returns**: `Promise.<VideoInfo>`
**Returns**: `Promise<VideoInfo>`
| Param | Type | Description |
| --- | --- | --- |
| video_id | `string` | The id of the video |
| target | `string` \| `NavigationEndpoint` | If `string`, the id of the video. If `NavigationEndpoint`, the endpoint of watchable elements such as `Video`, `Mix` and `Playlist`. To clarify, valid endpoints have payloads containing at least `videoId` and optionally `playlistId`, `params` and `index`. |
| client? | `InnerTubeClient` | `WEB`, `ANDROID`, `YTMUSIC`, `YTMUSIC_ANDROID` or `TV_EMBEDDED` |
<details>
@@ -282,21 +281,27 @@ Retrieves video info, including playback data and even layout elements such as m
- `<info>#dislike()`
- Dislikes the video.
- `<info>#removeLike()`
- `<info>#removeRating()`
- Removes like/dislike.
- `<info>#getLiveChat()`
- Returns a LiveChat instance.
- `<info>#getTrailerInfo()`
- Returns trailer info in a new `VideoInfo` instance, or `null` if none. Typically available for non-purchased movies or films.
- `<info>#chooseFormat(options)`
- Used to choose streaming data formats.
- `<info>#toDash(url_transformer)`
- `<info>#toDash(url_transformer?, format_filter?)`
- Converts streaming data to an MPEG-DASH manifest.
- `<info>#download(options)`
- Downloads the video. See [download](#download).
- `<info>#getTranscript()`
- Retrieves the video's transcript.
- `<info>#filters`
- Returns filters that can be applied to the watch next feed.
@@ -309,6 +314,12 @@ Retrieves video info, including playback data and even layout elements such as m
- `<info>#addToWatchHistory()`
- Adds the video to the watch history.
- `<info>#autoplay_video_endpoint`
- Returns the endpoint of the video for Autoplay.
- `<info>#has_trailer`
- Checks if trailer is available.
- `<info>#page`
- Returns original InnerTube response (sanitized).
@@ -316,11 +327,11 @@ Retrieves video info, including playback data and even layout elements such as m
</details>
<a name="getbasicinfo"></a>
### getBasicInfo(video_id, client?)
### `getBasicInfo(video_id, client?)`
Suitable for cases where you only need basic video metadata. Also, it is faster than [`getInfo()`](#getinfo).
**Returns**: `Promise.<VideoInfo>`
**Returns**: `Promise<VideoInfo>`
| Param | Type | Description |
| --- | --- | --- |
@@ -328,17 +339,34 @@ Suitable for cases where you only need basic video metadata. Also, it is faster
| client? | `InnerTubeClient` | `WEB`, `ANDROID`, `YTMUSIC_ANDROID`, `YTMUSIC`, `TV_EMBEDDED` |
<a name="search"></a>
### search(query, filters?)
### `search(query, filters?)`
Searches the given query on YouTube.
**Returns**: `Promise.<Search>`
**Returns**: `Promise<Search>`
> **Note**
> `Search` extends the [`Feed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/feed.md) class.
| Param | Type | Description |
| --- | --- | --- |
| query | `string` | The search query |
| filters? | `SearchFilters` | Search filters |
<details>
<summary>Search Filters</summary>
| Filter | Type | Value | Description |
| --- | --- | --- | --- |
| upload_date | `string` | `all` \| `hour` \| `today` \| `week` \| `month` \| `year` | Filter by upload date |
| type | `string` | `all` \| `video` \| `channel` \| `playlist` \| `movie` | Filter by type |
| duration | `string` | `all` \| `short` \| `medium` \| `long` | Filter by duration |
| sort_by | `string` | `relevance` \| `rating` \| `upload_date` \| `view_count` | Sort by |
| features | `string[]` | `hd` \| `subtitles` \| `creative_commons` \| `3d` \| `live` \| `purchased` \| `4k` \| `360` \| `location` \| `hdr` \| `vr180` | Filter by features |
</details>
<details>
<summary>Methods & Getters</summary>
<p>
@@ -356,20 +384,20 @@ Searches the given query on YouTube.
</details>
<a name="getsearchsuggestions"></a>
### getSearchSuggestions(query)
### `getSearchSuggestions(query)`
Retrieves search suggestions for given query.
**Returns**: `Promise.<string[]>`
**Returns**: `Promise<string[]>`
| Param | Type | Description |
| --- | --- | --- |
| query | `string` | The search query |
<a name="getcomments"></a>
### getComments(video_id, sort_by?)
### `getComments(video_id, sort_by?)`
Retrieves comments for given video.
**Returns**: `Promise.<Comments>`
**Returns**: `Promise<Comments>`
| Param | Type | Description |
| --- | --- | --- |
@@ -379,10 +407,13 @@ Retrieves comments for given video.
See [`./examples/comments`](https://github.com/LuanRT/YouTube.js/blob/main/examples/comments) for examples.
<a name="gethomefeed"></a>
### getHomeFeed()
### `getHomeFeed()`
Retrieves YouTube's home feed.
**Returns**: `Promise.<HomeFeed>`
**Returns**: `Promise<HomeFeed>`
> **Note**
> `HomeFeed` extends the [`FilterableFeed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/filterable-feed.md) class.
<details>
<summary>Methods & Getters</summary>
@@ -409,11 +440,20 @@ Retrieves YouTube's home feed.
</p>
</details>
<a name="getguide"></a>
### `getGuide()`
Retrieves YouTube's content guide.
**Returns**: `Promise<Guide>`
<a name="getlibrary"></a>
### getLibrary()
### `getLibrary()`
Retrieves the account's library.
**Returns**: `Promise.<Library>`
**Returns**: `Promise<Library>`
> **Note**
> `Library` extends the [`Feed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/feed.md) class.
<details>
<summary>Methods & Getters</summary>
@@ -422,19 +462,20 @@ Retrieves the account's library.
- `<library>#history`
- `<library>#watch_later`
- `<library>#liked_videos`
- `<library>#playlists`
- `<library>#playlists_section`
- `<library>#clips`
- `<library>#page`
- Returns original InnerTube response (sanitized).
</p>
</details>
<a name="gethistory"></a>
### getHistory()
### `getHistory()`
Retrieves watch history.
**Returns**: `Promise.<History>`
**Returns**: `Promise<History>`
> **Note**
> `History` extends the [`Feed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/feed.md) class.
<details>
<summary>Methods & Getters</summary>
@@ -447,22 +488,25 @@ Retrieves watch history.
</details>
<a name="gettrending"></a>
### getTrending()
### `getTrending()`
Retrieves trending content.
**Returns**: `Promise.<TabbedFeed>`
**Returns**: `Promise<TabbedFeed<IBrowseResponse>>`
<a name="getsubscriptionsfeed"></a>
### getSubscriptionsFeed()
Retrieves subscriptions feed.
### `getSubscriptionsFeed()`
Retrieves the subscriptions feed.
**Returns**: `Promise.<Feed>`
**Returns**: `Promise<Feed<IBrowseResponse>>`
<a name="getchannel"></a>
### getChannel(id)
### `getChannel(id)`
Retrieves contents for a given channel.
**Returns**: `Promise.<Channel>`
**Returns**: `Promise<Channel>`
> **Note**
> `Channel` extends the [`TabbedFeed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/tabbed-feed.md) class.
| Param | Type | Description |
| --- | --- | --- |
@@ -475,14 +519,21 @@ Retrieves contents for a given channel.
- `<channel>#getVideos()`
- `<channel>#getShorts()`
- `<channel>#getLiveStreams()`
- `<channel>#getReleases()`
- `<channel>#getPodcasts()`
- `<channel>#getPlaylists()`
- `<channel>#getHome()`
- `<channel>#getCommunity()`
- `<channel>#getChannels()`
- `<channel>#getAbout()`
- `<channel>#search(query)`
- `<channel>#applyFilter(filter)`
- `<channel>#applyContentTypeFilter(content_type_filter)`
- `<channel>#applySort(sort)`
- `<channel>#getContinuation()`
- `<channel>#filters`
- `<channel>#content_type_filters`
- `<channel>#sort_filters`
- `<channel>#page`
</p>
@@ -491,10 +542,10 @@ Retrieves contents for a given channel.
See [`./examples/channel`](https://github.com/LuanRT/YouTube.js/blob/main/examples/channel) for examples.
<a name="getnotifications"></a>
### getNotifications()
### `getNotifications()`
Retrieves notifications.
**Returns**: `Promise.<NotificationsMenu>`
**Returns**: `Promise<NotificationsMenu>`
<details>
<summary>Methods & Getter</summary>
@@ -507,16 +558,19 @@ Retrieves notifications.
</details>
<a name="getunseennotificationscount"></a>
### getUnseenNotificationsCount()
### `getUnseenNotificationsCount()`
Retrieves unseen notifications count.
**Returns**: `Promise.<number>`
**Returns**: `Promise<number>`
<a name="getplaylist"></a>
### getPlaylist(id)
### `getPlaylist(id)`
Retrieves playlist contents.
**Returns**: `Promise.<Playlist>`
**Returns**: `Promise<Playlist>`
> **Note**
> `Playlist` extends the [`Feed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/feed.md) class.
| Param | Type | Description |
| --- | --- | --- |
@@ -532,19 +586,51 @@ Retrieves playlist contents.
</p>
</details>
<a name="gethashtag"></a>
### `getHashtag(hashtag)`
Retrieves a given hashtag's page.
**Returns**: `Promise<HashtagFeed>`
> **Note**
> `HashtagFeed` extends the [`FilterableFeed`](https://github.com/LuanRT/YouTube.js/blob/main/docs/API/filterable-feed.md) class.
| Param | Type | Description |
| --- | --- | --- |
| hashtag | `string` | The hashtag |
<details>
<summary>Methods & Getter</summary>
<p>
- `<hashtag>#applyFilter(filter)`
- Applies given filter and returns a new `HashtagFeed` instance.
- `<hashtag>#getContinuation()`
- Retrieves next batch of contents.
</p>
</details>
<a name="getstreamingdata"></a>
### getStreamingData(video_id, options)
### `getStreamingData(video_id, options)`
Returns deciphered streaming data.
**Note:**
It is recommended to retrieve streaming data from a `VideoInfo`/`TrackInfo` object instead if you want to select formats manually, example:
> **Note**
> This method will be deprecated in the future. We recommend retrieving streaming data from a `VideoInfo` or `TrackInfo` object instead if you want to select formats manually. Please refer to the following example:
```ts
const info = await yt.getBasicInfo('somevideoid');
const url = info.streaming_data?.formats[0].decipher(yt.session.player);
console.info('Playback url:', url);
// or:
const format = info.chooseFormat({ type: 'audio', quality: 'best' });
const url = format?.decipher(yt.session.player);
console.info('Playback url:', url);
```
**Returns**: `Promise.<object>`
**Returns**: `Promise<object>`
| Param | Type | Description |
| --- | --- | --- |
@@ -552,10 +638,10 @@ console.info('Playback url:', url);
| options | `FormatOptions` | Format options |
<a name="download"></a>
### download(video_id, options?)
### `download(video_id, options?)`
Downloads a given video.
**Returns**: `Promise.<ReadableStream<Uint8Array>>`
**Returns**: `Promise<ReadableStream<Uint8Array>>`
| Param | Type | Description |
| --- | --- | --- |
@@ -565,32 +651,31 @@ Downloads a given video.
See [`./examples/download`](https://github.com/LuanRT/YouTube.js/blob/main/examples/download) for examples.
<a name="resolveurl"></a>
### resolveURL(url)
### `resolveURL(url)`
Resolves a given url.
**Returns**: `Promise.<NavigationEndpoint>`
**Returns**: `Promise<NavigationEndpoint>`
| Param | Type | Description |
| --- | --- | --- |
| url | `string` | Url to resolve |
<a name="call"></a>
### call(endpoint, args?)
### `call(endpoint, args?)`
Utility to call navigation endpoints.
**Returns**: `Promise.<ActionsResponse | ParsedResponse>`
**Returns**: `Promise<T extends IParsedResponse | IParsedResponse | ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
| endpoint | `NavigationEndpoint` | The target endpoint |
| args? | `object` | Additional payload arguments |
## Extending the library
### Extending the library
YouTube.js is completely modular and easy to extend. Almost all methods, classes, and utilities used internally are exposed and can be used to implement your own extensions without having to modify the library's source code.
For example, let's say we want to implement a method to retrieve video info manually. We can do that by using an instance of the `Actions` class:
YouTube.js is modular and easy to extend. Most of the methods, classes, and utilities used internally are exposed and can be used to implement your own extensions without having to modify the library's source code.
For example, let's say we want to implement a method to retrieve video info. We can do that by using an instance of the `Actions` class:
```ts
import { Innertube } from 'youtubei.js';
@@ -599,10 +684,10 @@ import { Innertube } from 'youtubei.js';
async function getVideoInfo(videoId: string) {
const videoInfo = await yt.actions.execute('/player', {
// anything added here will be merged with the default payload and sent to InnerTube.
// You can add any additional payloads here, and they'll merge with the default payload sent to InnerTube.
videoId,
client: 'YTMUSIC', // InnerTube client, can be ANDROID, YTMUSIC, YTMUSIC_ANDROID, WEB or TV_EMBEDDED
parse: true // tells YouTube.js to parse the response, this is not sent to InnerTube.
client: 'YTMUSIC', // InnerTube client options: ANDROID, YTMUSIC, YTMUSIC_ANDROID, WEB, or TV_EMBEDDED.
parse: true // tells YouTube.js to parse the response (not sent to InnerTube).
});
return videoInfo;
@@ -613,8 +698,7 @@ import { Innertube } from 'youtubei.js';
})();
```
Or perhaps there's a `NavigationEndpoint` in a parsed response and we want to call it to see what happens:
Alternatively, suppose we locate a `NavigationEndpoint` in a parsed response and want to see what happens when we call it:
```ts
import { Innertube, YTNodes } from 'youtubei.js';
@@ -624,12 +708,12 @@ import { Innertube, YTNodes } from 'youtubei.js';
const artist = await yt.music.getArtist('UC52ZqHVQz5OoGhvbWiRal6g');
const albums = artist.sections[1].as(YTNodes.MusicCarouselShelf);
// Say we want to click the “More” button:
// Let's imagine that we wish to click on the “More” button:
const button = albums.as(YTNodes.MusicCarouselShelf).header?.more_content;
if (button) {
// After making sure it exists, we can call its navigation endpoint:
const page = await button.endpoint.call(yt.actions);
// Having ensured that it exists, we can then call its navigation endpoint using the following code:
const page = await button.endpoint.call(yt.actions, { parse: true });
console.info(page);
}
})();
@@ -637,16 +721,16 @@ import { Innertube, YTNodes } from 'youtubei.js';
### Parser
YouTube.js' parser allows you to parse InnerTube responses and turn their nodes into strongly typed objects that can be easily manipulated. It also provides a set of utility methods that make working with InnerTube much easier.
YouTube.js' parser enables you to parse InnerTube responses and convert their nodes into strongly-typed objects that are simple to manipulate. Additionally, it provides numerous utility methods that make working with InnerTube a breeze.
Example:
Here's an example of its usage:
```ts
// See ./examples/parser
import { Parser, YTNodes } from 'youtubei.js';
import { readFileSync } from 'fs';
// Artist page response from YouTube Music
// YouTube Music's artist page response
const data = readFileSync('./artist.json').toString();
const page = Parser.parseResponse(JSON.parse(data));
@@ -655,14 +739,8 @@ const header = page.header?.item().as(YTNodes.MusicImmersiveHeader, YTNodes.Musi
console.info('Header:', header);
/**
* The parser encapsulates all arrays in a proxy object.
* A proxy intercepts access to the actual data, allowing
* the parser to add type safety and many utility methods
* that make working with InnerTube much easier.
*/
const tab = page.contents.item().as(YTNodes.SingleColumnBrowseResults).tabs.firstOfType(YTNodes.Tab);
// The parser uses a proxy object to add type safety and utility methods for working with InnerTube's data arrays:
const tab = page.contents?.item().as(YTNodes.SingleColumnBrowseResults).tabs.firstOfType(YTNodes.Tab);
if (!tab)
throw new Error('Target tab not found');
@@ -670,40 +748,37 @@ if (!tab)
if (!tab.content)
throw new Error('Target tab appears to be empty');
const sections = tab.content?.as(YTNodes.SectionList).contents.array().as(YTNodes.MusicCarouselShelf, YTNodes.MusicDescriptionShelf, YTNodes.MusicShelf);
const sections = tab.content?.as(YTNodes.SectionList).contents.as(YTNodes.MusicCarouselShelf, YTNodes.MusicDescriptionShelf, YTNodes.MusicShelf);
console.info('Sections:', sections);
```
Documentation for the parser can be found [here](https://github.com/LuanRT/YouTube.js/blob/main/src/parser).
<!-- CONTRIBUTING -->
## Contributing
Contributions, issues, and feature requests are welcome.
Feel free to check the [issues page](https://github.com/LuanRT/YouTube.js/issues) and our [guidelines](https://github.com/LuanRT/YouTube.js/blob/main/CONTRIBUTING.md) if you want to contribute.
We welcome all contributions, issues and feature requests, whether small or large. If you want to contribute, feel free to check out our [issues page](https://github.com/LuanRT/YouTube.js/issues) and our [guidelines](https://github.com/LuanRT/YouTube.js/blob/main/CONTRIBUTING.md).
Thank you to all the wonderful people who have contributed to this project:
We are immensely grateful to all the wonderful people who have contributed to this project. A special shoutout to all our contributors! 🎉
<a href="https://github.com/LuanRT/YouTube.js/graphs/contributors">
<img src="https://contrib.rocks/image?repo=LuanRT/YouTube.js" />
</a>
## Contact
LuanRT - [@thesciencephile][twitter] - luan.lrt4@gmail.com
LuanRT - [@thesciencephile][twitter] - luanrt@thatsciencephile.com
Project Link: [https://github.com/LuanRT/YouTube.js][project]
## Disclaimer
This project is not affiliated with, endorsed, or sponsored by YouTube or any of its affiliates or subsidiaries.
All trademarks, logos, and brand names are the property of their respective owners and are used only to directly describe the services being provided, as such, any usage of trademarks to refer to such services is considered nominative use.
This project is not affiliated with, endorsed, or sponsored by YouTube or any of its affiliates or subsidiaries. All trademarks, logos, and brand names used in this project are the property of their respective owners and are used solely to describe the services provided.
Should you have any questions or concerns please contact me directly via email.
As such, any usage of trademarks to refer to such services is considered nominative use. If you have any questions or concerns, please contact me directly via email.
[^1]: https://gizmodo.com/how-project-innertube-helped-pull-youtube-out-of-the-gu-1704946491
## License
Distributed under the [MIT](https://choosealicense.com/licenses/mit/) License.
<p align=" right">
<p align="right">
(<a href="#top">back to top</a>)
</p>
</p>

View File

@@ -1,11 +0,0 @@
// Deno and browser runtimes
import Innertube from './src/Innertube';
export * from './src/utils';
export { YTNodes } from './src/parser/map';
export { default as Parser } from './src/parser';
export { default as Innertube } from './src/Innertube';
export { default as Session } from './src/core/Session';
export { default as Player } from './src/core/Player';
export default Innertube;

2
bundle/browser.d.ts vendored
View File

@@ -1 +1 @@
export * from '../dist/browser';
export * from '../dist/src/platform/lib.js';

1
bundle/node.d.cts Normal file
View File

@@ -0,0 +1 @@
export * from '../dist/src/platform/lib.js';

3
deno.ts Normal file
View File

@@ -0,0 +1,3 @@
export * from './deno/src/platform/deno.ts';
import Innertube from './deno/src/platform/deno.ts';
export default Innertube;

View File

@@ -0,0 +1,42 @@
import glob from 'glob';
import path from 'path';
import fs from 'fs';
import url from 'url';
const import_list = [];
const misc_imports = [];
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
glob.sync('../src/parser/classes/**/*.{js,ts}', { cwd: __dirname })
.forEach((file) => {
// Trim path
const is_misc = file.includes('/misc/');
file = file.replace('../src/parser/classes/', '').replace('.js', '').replace('.ts', '');
const import_name = file.split('/').pop();
if (is_misc) {
const class_name = file.split('/').pop().replace('.js', '').replace('.ts', '');
misc_imports.push(`export { default as ${class_name} } from './classes/${file}.js';`);
} else {
import_list.push(`export { default as ${import_name} } from './classes/${file}.js';`);
}
});
fs.writeFileSync(
path.resolve(__dirname, '../src/parser/nodes.ts'),
`// This file was auto generated, do not edit.
// See ./scripts/build-parser-map.js
${import_list.join('\n')}
`
);
fs.writeFileSync(
path.resolve(__dirname, '../src/parser/misc.ts'),
`// This file was auto generated, do not edit.
// See ./scripts/build-parser-map.js
${misc_imports.join('\n')}
`
);

View File

@@ -0,0 +1,48 @@
import { fetch } from 'undici';
import { gunzip } from 'zlib';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { writeFile } from 'fs/promises';
const __dirname = dirname(fileURLToPath(import.meta.url));
const buf = await (await fetch('https://github.com/intoli/user-agents/blob/master/src/user-agents.json.gz?raw=true')).arrayBuffer();
const bytes = new Uint8Array(buf);
// Only get desktop and mobile agents
const allowed_agents = new Set([
'desktop',
'mobile'
]);
const decompressed = await new Promise((resolve, reject) => {
gunzip(bytes, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result.buffer);
}
});
});
const contents = new TextDecoder().decode(decompressed);
const agents = JSON.parse(contents);
if (!Array.isArray(agents)) {
throw new Error('Invalid user-agents.json');
}
const agentsByDevice = agents.reduce((acc, agent) => {
const device = agent.deviceCategory;
if (!allowed_agents.has(device))
return acc;
if (!acc[device]) {
acc[device] = [];
}
// We dont want to massive of a list of agents for each device
if (acc[device].length <= 25) acc[device].push(agent.userAgent);
return acc;
}, {});
await writeFile(resolve(__dirname, '..', 'src', 'utils', 'user-agents.ts'), `/* eslint-disable */\n/* Generated file do not edit */\nexport default ${JSON.stringify(agentsByDevice, null, 2)} as { desktop: string[], mobile: string[] };`);

View File

@@ -46,7 +46,7 @@ Retrieves account information.
<p>
- `<accountinfo>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -63,7 +63,7 @@ Retrieves time watched statistics.
<p>
- `<timewatched>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -91,6 +91,9 @@ Retrieves YouTube settings.
- `<settings>#sidebar_items`
- Returns options available in the sidebar menu.
- `<settings>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -106,7 +109,7 @@ Retrieves basic channel analytics.
<p>
- `<analytics>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>

115
docs/API/feed.md Normal file
View File

@@ -0,0 +1,115 @@
# Feed
Represents a YouTube feed. This class provides a set of utility methods for parsing and interacting with feeds.
## API
* Feed
* [.videos](#videos)
* [.posts](#posts)
* [.channels](#channels)
* [.playlists](#playlists)
* [.shelves](#shelves)
* [.memo](#memo)
* [.page_contents](#page_contents)
* [.secondary_contents](#secondary_contents)
* [.page](#page)
* [.has_continuation](#has_continuation)
* [.getContinuationData()](#getcontinuationdata)
* [.getContinuation()](#getcontinuation)
* [.getShelf(title)](#getshelf)
<a name="videos"></a>
### videos
Returns all videos in the feed.
**Returns:** `ObservedArray<Video | GridVideo | ReelItem | CompactVideo | PlaylistVideo | PlaylistPanelVideo | WatchCardCompactVideo>`
<a name="posts"></a>
### posts
Returns all posts in the feed.
**Returns:** `ObservedArray<Post | BackstagePost>`
<a name="channels"></a>
### channels
Returns all channels in the feed.
**Returns:** `ObservedArray<Channel | GridChannel>`
<a name="playlists"></a>
### playlists
Returns all playlists in the feed.
**Returns:** `ObservedArray<Playlist | GridPlaylist>`
<a name="shelves"></a>
### shelves
Returns all shelves in the feed.
**Returns:** `ObservedArray<Shelf | RichShelf | ReelShelf>`
<a name="memo"></a>
### memo
Returns the memoized feed contents.
**Returns:** `Memo`
<a name="page_contents"></a>
### page_contents
Returns the page contents.
**Returns:** `SectionList | MusicQueue | RichGrid | ReloadContinuationItemsCommand`
<a name="secondary_contents"></a>
### secondary_contents
Returns the secondary contents node.
**Returns:** `SuperParsedResult<YTNode> | undefined `
<a name="page"></a>
### page
Returns the original InnerTube response, parsed and sanitized.
**Returns:** `T extends IParsedResponse = IParsedResponse`
<a name="has_continuation"></a>
### has_continuation
Returns whether the feed has a continuation.
**Returns:** `boolean`
<a name="getcontinuationdata"></a>
### getContinuationData()
Returns the continuation data.
**Returns:** `Promise<T | undefined>`
<a name="getcontinuation"></a>
### getContinuation()
Retrieves the feed's continuation.
**Returns:** `Promise<Feed<T>>`
<a name="getshelf"></a>
### getShelf(title)
Gets a shelf by its title.
**Returns:** `Shelf | RichShelf | ReelShelf | undefined`
| Param | Type | Description |
| --- | --- | --- |
| title | `string` | The title of the shelf to get |

View File

@@ -0,0 +1,38 @@
# FilterableFeed
Represents a feed that can be filtered.
> **Note**
> This class extends the [Feed](feed.md) class.
## API
* FilterableFeed
* [.filter_chips](#filter_chips)
* [.filters](#filters)
* [.getFilteredFeed(filter: string | ChipCloudChip)](#getfilteredfeed)
<a name="filter_chips"></a>
### filter_chips
Returns the feed's filter chips.
**Returns:** `ObservedArray<ChipCloudChip>`
<a name="filters"></a>
### filters
Returns the feed's filter chips as an array of strings.
**Returns:** `string[]`
<a name="getfilteredfeed"></a>
### getFilteredFeed(filter: string | ChipCloudChip)
Returns a new [Feed](feed.md) with the given filter applied.
**Returns:** `Promise<Feed<T>>`
| Param | Type | Description |
| --- | --- | --- |
| filter | `string` \| `ChipCloudChip` | The filter to apply |

View File

@@ -12,14 +12,14 @@ Handles direct interactions.
* [.unsubscribe(video_id)](#unsubscribe)
* [.comment(video_id, text)](#comment)
* [.translate(text, target_language, args?)](#translate)
* [.setNotificationPreferences(channel_id, type)](#setnotificationpreferences)
* [.setNotificationPreferences(channel_id, type)](#setnotificationpreferences)
<a name="like"></a>
### like(video_id)
Likes given video.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -30,18 +30,18 @@ Likes given video.
Dislikes given video.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
| video_id | `string` | Video id |
<a name="removerating"></a>
### removeLike(video_id)
### removeRating(video_id)
Remover like/dislike.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -52,7 +52,7 @@ Remover like/dislike.
Subscribes to given channel.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -63,7 +63,7 @@ Subscribes to given channel.
Unsubscribes from given channel.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -74,7 +74,7 @@ Unsubscribes from given channel.
Posts a comment on given video.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -86,7 +86,7 @@ Posts a comment on given video.
Translates given text using YouTube's comment translation feature.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -100,9 +100,9 @@ Translates given text using YouTube's comment translation feature.
Changes notification preferences for a given channel.
Only works with channels you are subscribed to.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
| channel_id | `string` | Channel id |
| type | `string` | `PERSONALIZED`, `ALL` or `NONE` |
| type | `string` | `PERSONALIZED`, `ALL` or `NONE` |

127
docs/API/kids.md Normal file
View File

@@ -0,0 +1,127 @@
# YouTube Kids
YouTube Kids is a modified version of the YouTube app, with a simplified interface and curated content. This class allows you to interact with its API.
## API
* Kids
* [.search(query)](#search)
* [.getInfo(video_id)](#getinfo)
* [.getChannel(channel_id)](#getchannel)
* [.getHomeFeed()](#gethomefeed)
* [.blockChannel(channel_id)](#blockchannel)
<a name="search"></a>
### search(query)
Searches the given query on YouTube Kids.
**Returns:** `Promise.<Search>`
| Param | Type | Description |
| --- | --- | --- |
| query | `string` | The query to search |
<details>
<summary>Methods & Getters</summary>
<p>
- `<search>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
<a name="getinfo"></a>
### getInfo(video_id)
Retrieves video info.
**Returns:** `Promise.<VideoInfo>`
| Param | Type | Description |
| --- | --- | --- |
| video_id | `string` | The video id |
<details>
<summary>Methods & Getters</summary>
<p>
- `<info>#toDash(url_transformer?, format_filter?)`
- Generates a DASH manifest from the streaming data.
- `<info>#chooseFormat(options)`
- Selects the format that best matches the given options. This method is used internally by `#download`.
- `<info>#download(options?)`
- Downloads the video.
- `<info>#addToWatchHistory()`
- Adds the video to the watch history.
- `<info>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
<a name="getchannel"></a>
### getChannel(channel_id)
Retrieves channel info.
**Returns:** `Promise.<Channel>`
| Param | Type | Description |
| --- | --- | --- |
| channel_id | `string` | The channel id |
<details>
<summary>Methods & Getters</summary>
<p>
- `<channel>#getContinuation()`
- Retrieves next batch of videos.
- `<channel>#has_continuation`
- Returns whether there are more videos to retrieve.
- `<channel>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
<a name="gethomefeed"></a>
### getHomeFeed()
Retrieves the home feed.
**Returns:** `Promise.<HomeFeed>`
<details>
<summary>Methods & Getters</summary>
<p>
- `<feed>#selectCategoryTab(tab: string | KidsCategoryTab)`
- Selects the given category tab.
- `<feed>#categories`
- Returns available categories.
- `<feed>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</details>
<a name="blockChannel"></a>
### blockChannel(channel_id)
Retrieves the list of supervised accounts that the signed-in user has access to and blocks the given channel for each of them.
**Returns:** `Promise.<ApiResponse[]>`
| Param | Type | Description |
| --- | --- | --- |
| channel_id | `string` | Channel id |

View File

@@ -1,6 +1,6 @@
# Music
# YouTube Music
YouTube Music class.
YouTube Music is a music streaming service developed by YouTube, a subsidiary of Google. It provides a tailored interface for the service oriented towards music streaming, with a greater emphasis on browsing and discovery compared to its main service. This class allows you to interact with its API.
## API
@@ -49,6 +49,21 @@ Retrieves track info.
- `<info>#available_tabs`
- Returns available tabs.
- `<info>#toDash(url_transformer?, format_filter?)`
- Generates a DASH manifest from the streaming data.
- `<info>#chooseFormat(options)`
- Selects the format that best matches the given options. This method is used internally by `#download`.
- `<info>#download(options?)`
- Downloads the track.
- `<info>#addToWatchHistory()`
- Adds the song to the watch history.
- `<info>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -62,7 +77,16 @@ Searches on YouTube Music.
| Param | Type | Description |
| --- | --- | --- |
| query | `string` | Search query |
| filters? | `object` | Search filters |
| filters? | `MusicSearchFilters` | Search filters |
<details>
<summary>Search Filters</summary>
| Filter | Type | Value | Description |
| --- | --- | --- | --- |
| type | `string` | `all`, `song`, `video`, `album`, `playlist`, `artist` | Search type |
</details>
<details>
<summary>Methods & Getters</summary>
@@ -99,7 +123,7 @@ Searches on YouTube Music.
- Returns songs shelf.
- `<search>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -124,6 +148,9 @@ Retrieves home feed.
- `<homefeed>#page`
- Returns original InnerTube response (sanitized).
- `<homefeed>#page`
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -139,7 +166,7 @@ Retrieves “Explore” feed.
<p>
- `<explore>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -174,7 +201,7 @@ Retrieves library.
- Returns available sort options.
- `<library>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -195,7 +222,7 @@ Retrieves artist's info & content.
<p>
- `<artist>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -216,7 +243,7 @@ Retrieves given album.
<p>
- `<album>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -249,7 +276,7 @@ Retrieves given playlist.
- Checks if continuation is available.
- `<playlist>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>
@@ -303,7 +330,7 @@ Retrieves your YouTube Music recap.
- Retrieves recap playlist.
- `<recap>#page`
- Returns original InnerTube response (sanitized).
- Returns the original InnerTube response(s), parsed and sanitized.
</p>
</details>

View File

@@ -10,13 +10,15 @@ Playlist management class.
* [.addVideos(playlist_id, video_ids)](#addvideos)
* [.removeVideos(playlist_id, video_ids)](#removevideos)
* [.moveVideo(playlist_id, moved_video_id, predecessor_video_id)](#movevideo)
* [.setName(playlist_id, name)](#setname)
* [.setDescription(playlist_id, description)](#setdescription)
<a name="create"></a>
### create(title, video_ids)
Creates a playlist.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -28,7 +30,7 @@ Creates a playlist.
Deletes given playlist.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -69,4 +71,29 @@ Moves a video to a new position within a given playlist.
| --- | --- | --- |
| playlist_id | `string` | Playlist id |
| moved_video_id | `string` | the video to be moved |
| predecessor_video_id | `string` | the video present in the target position |
| predecessor_video_id | `string` | the video present in the target position |
<a name="setname"></a>
### setName(playlist_id, name)
Sets the name / title for the given playlist.
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
| playlist_id | `string` | Playlist id |
| name | `string` | Name / title |
<a name="setdescription"></a>
### setDescription(playlist_id, description)
Sets the description for the given playlist.
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
| playlist_id | `string` | Playlist id |
| description | `string` | Description |

View File

@@ -14,7 +14,7 @@ YouTube Studio class (WIP).
Uploads a custom thumbnail and sets it for a video.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -26,7 +26,7 @@ Uploads a custom thumbnail and sets it for a video.
Updates given video's metadata.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |
@@ -38,7 +38,7 @@ Updates given video's metadata.
Uploads a video to YouTube.
**Returns:** `Promise.<ActionsResponse>`
**Returns:** `Promise.<ApiResponse>`
| Param | Type | Description |
| --- | --- | --- |

62
docs/API/tabbed-feed.md Normal file
View File

@@ -0,0 +1,62 @@
# TabbedFeed
Represents a feed with tabs.
> **Note**
> This class extends the [Feed](feed.md) class.
## API
* TabbedFeed
* [.tabs](#tabs)
* [.getTabByName(title: string)](#gettabbyname)
* [.getTabByURL(url: string)](#gettabbyurl)
* [.hasTabWithURL(url: string)](#hastabwithurl)
* [.title](#title)
<a name="tabs"></a>
### tabs
Returns the feed's tabs as an array of strings.
**Returns:** `string[]`
<a name="gettabbyname"></a>
### getTabByName(title: string)
Fetches a tab by its title.
**Returns:** `Promise<TabbedFeed<T>>`
| Param | Type | Description |
| --- | --- | --- |
| title | `string` | The title of the tab to get |
<a name="gettabbyurl"></a>
### getTabByURL(url: string)
Fetches a tab by its URL.
**Returns:** `Promise<TabbedFeed<T>>`
| Param | Type | Description |
| --- | --- | --- |
| url | `string` | The URL of the tab to get |
<a name="hastabwithurl"></a>
### hasTabWithURL(url: string)
Returns whether the feed has a tab with the given URL.
**Returns:** `boolean`
| Param | Type | Description |
| --- | --- | --- |
| url | `string` | The URL to check |
<a name="title"></a>
### title
Returns the currently selected tab's title.
**Returns:** `string | undefined`

View File

@@ -1,54 +1,60 @@
# Updating the parser
# Updating the Parser
YouTube is constantly changing, so it is not rare to see YouTube crawlers/scrapers breaking every now and then.
YouTube is constantly changing, so it is not uncommon to see YouTube crawlers/scrapers breaking every now and then.
Our parser, on the other hand, was written so that it behaves similarly to an official client, parsing and mapping renderers (also known as YTNodes) dynamically without hard-coding their path in the response. This way, whenever a new renderer pops up (e.g., when YouTube adds a new feature or makes a minor UI change), the library will print a warning similar to this:
Our parser, on the other hand, was written so that it behaves similarly to an official client, parsing and mapping renderers (a.k.a YTNodes) dynamically without hard-coding their path in the response. This way, whenever a new renderer pops up (e.g; YouTube adds a new feature / minor UI changes) the library will print a warning similar to this:
```
InnertubeError: SomeRenderer not found!
SomeRenderer not found!
This is a bug, want to help us fix it? Follow the instructions at https://github.com/LuanRT/YouTube.js/blob/main/docs/updating-the-parser.md or report it at https://github.com/LuanRT/YouTube.js/issues!
at Parser.printError (...)
at Parser.parseItem (...)
at Parser.parseArray (...) {
info: {
// renderer data, can be used as a reference to implement the renderer parser
},
date: 2022-05-22T22:16:06.831Z,
version: '2.2.3'
Introspected and JIT generated this class in the meantime:
class SomeRenderer extends YTNode {
static type = 'SomeRenderer';
// ...
constructor(data: RawNode) {
super();
// ...
}
}
```
This warning **does not** throw an error. The parser itself will continue working normally, even if a parsing error occurs in an existing renderer parser.
## Adding a new renderer parser
## Adding a New Renderer Parser
Thanks to the modularity of the parser, a renderer can be implemented by simply adding a new file anywhere in the [classes directory](../src/parser/classes)!
For example, say we found a new renderer named `verticalListRenderer`, to let the parser know it exists we would have to create a file with the following structure:
For example, suppose we have found a new renderer named `verticalListRenderer`. In that case, to let the parser know it exists at compile-time, we would have to create a file with the following structure:
> `../classes/VerticalList.ts`
```ts
import Parser from '..';
import { YTNode } from '../helpers';
class VerticalList extends YTNode {
```ts
import { Parser, RawNode } from '../index.js';
import { YTNode } from '../helpers.js';
export default class VerticalList extends YTNode {
static type = 'VerticalList';
header;
contents;
constructor(data: any) {
constructor(data: RawNode) {
super();
// parse the data here, ex;
this.header = Parser.parseItem(data.header);
this.contents = Parser.parseArray(data.contents);
}
}
export default VerticalList;
```
You may use the parser's generated class for the new renderer as a starting point for your own implementation.
Then update the parser map:
```bash
npm run build:parser-map
```
And that's it!
And that's it!

View File

@@ -1,33 +1,37 @@
# 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.
// Fired when waiting for the user to authorize the sign in attempt.
yt.session.on('auth-pending', (data) => {
// data.verification_url contains the URL to visit to authenticate.
// data.user_code contains the code to enter on the website.
// data.verification_url contains the authorization URL.
// data.user_code contains the code to enter on the website.
});
// 'auth' is fired once the authentication is complete
// Fired when authentication is successful.
yt.session.on('auth', ({ credentials }) => {
// do something with the credentials, eg; save them in a database.
// Do something with the credentials, eg; save them in a database.
console.log('Sign in successful');
});
// 'update-credentials' is fired when the access token expires, if you do not save the updated credentials any subsequent request will fail
yt.session.on('update-credentials', ({ credentials }) => {
// do something with the updated credentials
});
// Fired when the access token expires.
yt.session.on('update-credentials', ({ credentials }) => { /** do something with the updated 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 +40,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 +51,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. Cookies can expire and are not very secure.
```js
const yt = await Innertube.create({
cookie: '...'
});
```

View File

@@ -0,0 +1,143 @@
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,
expiry_date: new Date(tokens.expiry_date).toISOString(),
client: {
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. */
}
}

View File

@@ -1,24 +1,25 @@
const { Innertube, UniversalCache } = require('youtubei.js');
import { Innertube, UniversalCache } from 'youtubei.js';
(async () => {
const yt = await Innertube.create({
// required if you wish to use OAuth#cacheCredentials
cache: new UniversalCache()
cache: new UniversalCache(false)
});
// 'auth-pending' is fired with the info needed to sign in via OAuth.
// Fired when waiting for the user to authorize the sign in attempt.
yt.session.on('auth-pending', (data) => {
console.log(`Go to ${data.verification_url} in your browser and enter code ${data.user_code} to authenticate.`);
});
// 'auth' is fired once the authentication is complete
// Fired when authentication is successful.
yt.session.on('auth', ({ credentials }) => {
console.log('Sign in successful:', credentials);
});
// 'update-credentials' is fired when the access token expires, if you do not save the updated credentials any subsequent request will fail
yt.session.on('update-credentials', ({ credentials }) => {
// Fired when the access token expires.
yt.session.on('update-credentials', async ({ credentials }) => {
console.log('Credentials updated:', credentials);
await yt.session.oauth.cacheCredentials();
});
// Attempt to sign in

View File

@@ -0,0 +1,23 @@
import { Innertube, UniversalCache } from 'youtubei.js';
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache(true, './credcache') });
yt.session.on('auth-pending', (data) => {
console.log(`Go to ${data.verification_url} in your browser and enter code ${data.user_code} to authenticate.`);
});
yt.session.on('auth', async () => {
console.log('Sign in successful');
await yt.session.oauth.cacheCredentials();
});
yt.session.on('update-credentials', async () => {
await yt.session.oauth.cacheCredentials();
});
// Attempt to sign in
await yt.session.signIn();
// Block Channel for all kids / profiles on the signed-in account.
const resp = await yt.kids.blockChannel('UCpbpfcZfo-hoDAx2m1blFhg');
console.info('Blocked channel for ', resp.length, ' profiles.');
})();

View File

@@ -2,14 +2,14 @@
YouTube.js works in the browser!
## How to use
## Usage
To use YouTube.js in the browser you must proxy requests through your own server. You can see our simple reference implementation in Deno in `examples/browser/proxy/deno.ts`.
We'll use our own fetch implementation to proxy requests through our server. This is a simple example, but you can use any fetch implementation you want.
```ts
import { Innertube } from "youtubei.js/build/browser";
import { Innertube } from "youtubei.js/web.bundle.min";
const yt = await Innertube.create({
fetch: async (input, init) => {
@@ -54,8 +54,8 @@ const yt = await Innertube.create({
});
```
after that you can use the library as normal.
After that, you can use the library as normal.
## Example
We've got a full example in `examples/browser/web` using vite.
We've got a full example in `examples/browser/web` using vite.

View File

@@ -18,7 +18,7 @@ const handler = async (request: Request): Promise<Response> => {
'Access-Control-Allow-Origin': request.headers.get('origin') || '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers':
'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-goog-visitor-id, x-origin, x-youtube-client-version, Accept-Language, Range, Referer',
'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-goog-visitor-id, x-origin, x-youtube-client-version, x-youtube-client-name, x-goog-api-format-version, x-user-agent, Accept-Language, Range, Referer',
'Access-Control-Max-Age': '86400',
'Access-Control-Allow-Credentials': 'true',
}),
@@ -45,6 +45,7 @@ const handler = async (request: Request): Promise<Response> => {
JSON.parse(url.searchParams.get('__headers') || '{}'),
);
copyHeader('range', request_headers, request.headers);
!request_headers.has('user-agent') && copyHeader('user-agent', request_headers, request.headers);
url.searchParams.delete('__headers');

View File

@@ -1,20 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<form>
<input type="text" name="id" placeholder="Video ID" />
<input type="submit" value="Play" />
</form>
<span id="video_name">
Library is loading...
</span>
<video></video>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="stylesheet" href="/src/assets/style.css" />
<link rel="stylesheet" href="/src/assets/player.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>YouTube.js Example</title>
</head>
<body>
<form>
<input type="text" name="id" placeholder="Video ID or URL" />
<input type="submit" value="Play" />
</form>
<div class="loader" id="loader"></div>
<div id="video-container">
<div class="shaka-container" id="shaka-container" data-shaka-player-container>
<video class="videoel" id="videoel" data-shaka-player autoplay></video>
</div>
<h2 id="title"></h2>
<div id="metadata"></div>
<hr />
<div id="description"></div>
</div>
<footer>
<p>Powered by <a href="https://github.com/LuanRT/YouTube.js">YouTube.js</a></p>
</footer>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@@ -13,6 +13,6 @@
"vite": "^3.0.0"
},
"dependencies": {
"dashjs": "^4.4.0"
"shaka-player": "^4.3.8"
}
}

View File

@@ -0,0 +1,423 @@
@import url(https://fonts.googleapis.com/css?family=Material+Icons+Sharp);
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v27/KFOmCnqEu92Fr1Me5Q.ttf) format('truetype');
}
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v27/KFOlCnqEu92Fr1MmEU9vAw.ttf) format('truetype');
}
.shaka-container {
font-family: 'Roboto', sans-serif;
}
.shaka-container .shaka-bottom-controls {
width: 100%;
padding: 0;
padding-bottom: 0;
z-index: 1;
}
.shaka-container .shaka-bottom-controls {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
.shaka-container .shaka-ad-controls {
-webkit-box-ordinal-group: 2;
-ms-flex-order: 1;
order: 1;
}
.shaka-container .shaka-spinner .shaka-spinner-path {
stroke: #ffffff;
}
.shaka-container .shaka-scrim-container {
margin: 0;
width: 100%;
height: 100%;
flex-shrink: 1;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
opacity: 0;
transition: opacity cubic-bezier(.4, 0, .6, 1) .6s;
background: linear-gradient(to top, hsla(0, 0%, 0%, 0.61), transparent 15%);
}
.shaka-container .shaka-play-button {
width: 100px;
height: 100px;
border-radius: 0;
background-color: transparent;
filter: invert();
box-shadow: none;
-webkit-box-ordinal-group: -3;
-ms-flex-order: -4;
order: -4;
}
.shaka-container .shaka-small-play-button {
-webkit-box-ordinal-group: -2;
-ms-flex-order: -3;
order: -3;
}
.shaka-container .shaka-mute-button {
-webkit-box-ordinal-group: -1;
-ms-flex-order: -2;
order: -2;
}
.shaka-container .shaka-controls-button-panel>* {
margin: 0;
padding: 3px 8px;
color: #EEE;
height: 40px;
}
.shaka-container .shaka-controls-button-panel>*:hover {
color: #FFF;
}
.shaka-container .shaka-controls-button-panel .shaka-volume-bar-container {
position: relative;
z-index: 10;
left: -1px;
-webkit-box-ordinal-group: 0;
-ms-flex-order: -1;
order: -1;
opacity: 0;
width: 0px;
-webkit-transition: width 0.2s cubic-bezier(0.4, 0, 1, 1);
height: 3px;
transition: width 0.2s cubic-bezier(0.4, 0, 1, 1);
padding: 0;
}
.shaka-container .shaka-controls-button-panel .shaka-volume-bar-container:hover,
.shaka-container .shaka-controls-button-panel .shaka-volume-bar-container:focus {
display: block;
width: 50px;
opacity: 1;
padding: 0 6px;
}
.shaka-container .shaka-mute-button:hover+div {
opacity: 1;
width: 50px;
padding: 0 6px;
}
.shaka-container .shaka-current-time {
padding: 0 10px;
font-size: 12px;
}
.shaka-container .shaka-seek-bar-container {
height: 3px;
position: relative;
top: -1px;
border-radius: 0;
margin-bottom: 0;
}
.shaka-container .shaka-seek-bar-container .shaka-range-element {
opacity: 0;
transition: opacity 0.2s cubic-bezier(0.4, 0, 1, 1);
}
.shaka-container .shaka-seek-bar-container:hover {
height: 5px;
top: 0;
cursor: pointer;
}
.shaka-container .shaka-seek-bar-container:hover .shaka-range-element {
opacity: 1;
cursor: pointer;
}
.shaka-container .shaka-seek-bar-container input[type=range]::-webkit-slider-thumb {
background: #FF0000;
cursor: pointer;
}
.shaka-container .shaka-seek-bar-container input[type=range]::-moz-range-thumb {
background: #FF0000;
cursor: pointer;
}
.shaka-container .shaka-seek-bar-container input[type=range]::-ms-thumb {
background: #FF0000;
cursor: pointer;
}
.shaka-container .shaka-video-container * {
font-family: 'Roboto', sans-serif;
}
.shaka-container .shaka-video-container .material-icons-round {
font-family: 'Material Icons Sharp';
}
.shaka-container .shaka-overflow-menu,
.shaka-container .shaka-settings-menu {
border-radius: 2px;
background: rgba(37, 37, 37, 0.9);
text-shadow: 0 0 2px rgb(0 0 0%);
-webkit-transition: opacity 0.1s cubic-bezier(0, 0, 0.2, 1);
transition: opacity 0.1s cubic-bezier(0, 0, 0.2, 1);
-moz-user-select: none;
-ms-user-select: none;
animation: fade 0.3s;
-webkit-user-select: none;
right: 10px;
bottom: 50px;
padding: 0;
min-width: 200px;
}
@keyframes fade {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.shaka-container .shaka-settings-menu {
padding: 0 0 8px;
}
.shaka-container .shaka-settings-menu button {
font-size: 12px;
}
.shaka-container .shaka-settings-menu button span {
margin-left: 33px;
font-size: 13px;
}
.shaka-container .shaka-settings-menu button[aria-selected="true"] {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.shaka-container .shaka-settings-menu button[aria-selected="true"] span {
-webkit-box-ordinal-group: 3;
-ms-flex-order: 2;
order: 2;
margin-left: 0;
}
.shaka-container .shaka-settings-menu button[aria-selected="true"] i {
-webkit-box-ordinal-group: 2;
-ms-flex-order: 1;
order: 1;
font-size: 18px;
padding-left: 5px;
}
.shaka-container .shaka-overflow-menu button {
padding: 0;
}
.shaka-container .shaka-overflow-menu button i {
display: none;
}
.shaka-container .shaka-overflow-menu button .shaka-overflow-button-label {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
cursor: default;
outline: none;
height: 40px;
-webkit-box-flex: 0;
-ms-flex: 0 0 100%;
flex: 0 0 100%;
}
.shaka-container .shaka-overflow-menu button .shaka-overflow-button-label span {
-ms-flex-negative: initial;
flex-shrink: initial;
padding-left: 15px;
font-size: 13px;
font-weight: 500;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.shaka-container .shaka-overflow-menu span+span {
color: #FFF;
font-weight: 400 !important;
font-size: 12px !important;
padding-right: 8px;
padding-left: 0 !important;
}
.shaka-container .shaka-overflow-menu span+span:after {
content: "navigate_next";
font-family: 'Material Icons Sharp';
font-size: 20px;
}
.shaka-container .shaka-overflow-menu .shaka-pip-button span+span {
padding-right: 15px !important;
}
.shaka-container .shaka-overflow-menu .shaka-pip-button span+span:after {
content: "";
}
.shaka-container .shaka-back-to-overflow-button {
padding: 8px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
font-size: 12px;
color: #eee;
height: 40px;
}
.shaka-container .shaka-back-to-overflow-button .material-icons-round {
font-size: 15px;
padding-right: 10px;
}
.shaka-container .shaka-back-to-overflow-button span {
margin-left: 3px !important;
}
.shaka-container .shaka-overflow-menu button:hover,
.shaka-container .shaka-settings-menu button:hover {
background-color: rgba(255, 255, 255, 0.1);
cursor: pointer;
}
.shaka-container .shaka-overflow-menu button:hover label,
.shaka-container .shaka-settings-menu button:hover label {
cursor: pointer;
}
.shaka-container .shaka-overflow-menu button,
.shaka-container .shaka-settings-menu button {
color: #EEE;
}
.shaka-container .shaka-captions-off {
color: #BFBFBF;
}
.shaka-container .shaka-overflow-menu-button {
font-size: 18px;
margin-right: 5px;
}
.shaka-container .shaka-fullscreen-button:hover {
font-size: 25px;
-webkit-transition: font-size 0.1s cubic-bezier(0, 0, 0.2, 1);
transition: font-size 0.1s cubic-bezier(0, 0, 0.2, 1);
}
.shaka-container .shaka-overflow-menu,
.shaka-container .shaka-settings-menu {
border-radius: 10px;
}
@media (prefers-color-scheme: light) {
.shaka-container .shaka-overflow-menu,
.shaka-container .shaka-settings-menu {
background: rgba(255, 255, 255, 0.9);
}
.shaka-container .shaka-overflow-menu span+span,
.shaka-container .shaka-overflow-menu button,
.shaka-container .shaka-settings-menu button {
color: #000000;
}
}
@media (min-width: 800px) {
.shaka-container .shaka-controls-button-panel {
-webkit-box-ordinal-group: 3;
-ms-flex-order: 2;
order: 2;
height: 40px;
padding: 0 10px;
}
}
@media (max-width: 800px) {
.shaka-container .shaka-scrim-container {
background: rgba(0, 0, 0, 0.5);
}
.shaka-container .shaka-range-container {
margin: 0;
top: 0;
}
.shaka-container .shaka-mute-button {
display: none;
}
.shaka-container .shaka-overflow-menu,
.shaka-container .shaka-settings-menu {
bottom: 0;
top: 0;
left: 0;
right: 0;
width: 80%;
margin: 10px;
border-radius: 10px;
}
.shaka-container .shaka-overflow-menu button,
.shaka-container .shaka-settings-menu button {
width: 100%;
height: 40px;
padding: 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}
.shaka-container .shaka-overflow-menu button span,
.shaka-container .shaka-settings-menu button span {
margin-left: 0;
padding-left: 15px;
}
}

View File

@@ -0,0 +1,135 @@
body {
display: flex;
flex-direction: column;
align-items: center;
background-color: #202020;
color: rgb(255, 255, 255);
line-height: 1.6;
font-family: Roboto, Arial, sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-tap-highlight-color: transparent;
}
hr {
width: 100%;
border: 1px solid transparent;
background-color: rgb(68, 68, 68);
}
form {
margin: 0.5rem 0;
display: none;
border-radius: 0.3rem;
background-color: rgb(68, 68, 68);
}
form input {
padding: 0.5rem;
border: none;
color: rgb(255, 255, 255);
}
form input[type="text"] {
background: transparent;
}
form input[type="text"]:focus {
outline: none;
}
form input[type="submit"] {
color: rgb(255, 255, 255);
background-color: rgba(0, 0, 0, 0.244);
cursor: pointer;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-background-clip: text;
-webkit-text-fill-color: #ffffff;
transition: background-color 5000s ease-in-out 0s;
}
#loader {
display: block;
border: 10px solid rgb(68, 68, 68);
border-top: 10px solid rgb(255, 255, 255);
border-radius: 50%;
width: 50px;
height: 50px;
align-self: center;
animation: spin 1s linear infinite;
margin: 0.5rem 0;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
#shaka-container {
height: 40vw;
}
#video-container {
display: none;
flex-direction: column;
position: relative;
width: 70vw !important;
margin: 0.5rem 0;
}
#metadata {
display: flex;
flex-direction: row;
align-self: left;
margin: 0.5rem 0;
}
#metadata>#metadata-item {
margin: 0 0.3rem;
background-color: #ffffff;
color: rgba(0, 0, 0, 0.757);
font-weight: 600;
padding: 0.2rem 0.5rem;
border-radius: 0.3rem;
}
#video-container>#description {
align-self: left;
margin-left: 0.5rem;
font-size: medium;
}
video {
width: 100%;
height: 100%;
}
footer {
margin: 0.5rem 0;
}
@media screen and (max-width: 768px) {
video {
height: auto;
}
#shaka-container {
height: auto;
}
#video-container {
width: 100% !important;
}
}

View File

@@ -1,18 +1,27 @@
import './style.css';
import { Innertube, UniversalCache } from '../../../../bundle/browser';
import dashjs from 'dashjs';
// @ts-ignore - Shaka's TS support is not the best.
import shaka from 'shaka-player/dist/shaka-player.ui.js';
import "shaka-player/dist/controls.css";
const title = document.getElementById('title') as HTMLHeadingElement;
const description = document.getElementById('description') as HTMLDivElement;
const metadata = document.getElementById('metadata') as HTMLDivElement;
const loader = document.getElementById('loader') as HTMLDivElement;
const form = document.querySelector('form') as HTMLFormElement;
async function main() {
const yt = await Innertube.create({
generate_session_locally: true,
fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
// url
const url = typeof input === 'string'
? new URL(input)
: input instanceof URL
? input
: new URL(input.url);
? input
: new URL(input.url);
// transform the url for use with our proxy
// Transform the url for use with our proxy.
url.searchParams.set('__host', url.host);
url.host = 'localhost:8080';
url.protocol = 'http';
@@ -20,13 +29,18 @@ async function main() {
const headers = init?.headers
? new Headers(init.headers)
: input instanceof Request
? input.headers
: new Headers();
? input.headers
: new Headers();
// now serialize the headers
// Now serialize the headers.
url.searchParams.set('__headers', JSON.stringify([...headers]));
// copy over the request
if (input instanceof Request) {
// @ts-ignore
input.duplex = 'half';
}
// Copy over the request.
const request = new Request(
url,
input instanceof Request ? input : undefined,
@@ -34,7 +48,6 @@ async function main() {
headers.delete('user-agent');
// fetch the url
return fetch(request, init ? {
...init,
headers
@@ -42,58 +55,227 @@ async function main() {
headers
});
},
cache: new UniversalCache(),
cache: new UniversalCache(false),
});
const span = document.getElementById('video_name') as HTMLSpanElement;
const form = document.querySelector('form') as HTMLFormElement;
form.animate({ opacity: [0, 1] }, { duration: 300, easing: 'ease-in-out' });
form.style.display = 'block';
span.textContent = 'Library ready';
showUI({ hidePlayer: true });
let player: dashjs.MediaPlayerClass | undefined;
let player: shaka.Player | undefined;
let ui: shaka.ui.Overlay | undefined;
form.addEventListener('submit', async (e) => {
e.preventDefault();
span.textContent = 'Loading...';
if (player) {
player.destroy();
}
const video_id = document.querySelector<HTMLInputElement>(
'input[type=text]',
)?.value;
if (!video_id) {
span.textContent = 'No video id';
hideUI();
let videoId;
const videoIdOrURL = document.querySelector<HTMLInputElement>('input[type=text]')?.value;
if (!videoIdOrURL) {
title.textContent = 'No video id or URL provided';
showUI({ hidePlayer: true });
return;
}
try {
const video = await yt.getInfo(video_id);
if (videoIdOrURL.match(/(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/)) {
const endpoint = await yt.resolveURL(videoIdOrURL);
console.log(video);
span.textContent = video.basic_info.title || null;
if (!endpoint.payload.videoId) {
title.textContent = 'Could not resolve URL';
showUI({ hidePlayer: true });
return;
}
const dash = video.toDash((url) => {
url.searchParams.set('__host', url.host);
url.host = 'localhost:8080';
url.protocol = 'http';
return url;
});
const uri = 'data:application/dash+xml;charset=utf-8;base64,' +
btoa(dash);
// create and append video element
const video_element = document.querySelector('video') as HTMLVideoElement;
video_element.setAttribute('controls', 'true');
// use dash.js to parse the manifest
if (player) {
player.destroy();
videoId = endpoint.payload.videoId;
} else {
videoId = videoIdOrURL;
}
const info = await yt.getInfo(videoId);
title.textContent = info.basic_info.title || null;
description.innerHTML = info.secondary_info?.description.toHTML() || '';
title.textContent = info.basic_info.title || null;
document.title = info.basic_info.title || '';
metadata.innerHTML = '';
metadata.innerHTML += `<div id="metadata-item">${info.primary_info?.published.toHTML()}</div>`;
metadata.innerHTML += `<div id="metadata-item">${info.primary_info?.view_count.toHTML()}</div>`;
metadata.innerHTML += `<div id="metadata-item">${info.basic_info.like_count} likes</div>`;
showUI({ hidePlayer: false });
const dash = await info.toDash();
const uri = 'data:application/dash+xml;charset=utf-8;base64,' + btoa(dash);
if (player) {
await player.destroy();
player = undefined;
}
if (ui) {
ui.destroy();
ui = undefined;
}
const videoEl = document.getElementById('videoel') as HTMLVideoElement;
const shakaContainer = document.getElementById('shaka-container') as HTMLDivElement;
shakaContainer
.querySelectorAll("div")
.forEach(node => node.remove());
shaka.polyfill.installAll();
if (shaka.Player.isBrowserSupported()) {
videoEl.poster = info.basic_info.thumbnail![0].url;
player = new shaka.Player();
await player.attach(videoEl);
ui = new shaka.ui.Overlay(player, shakaContainer, videoEl);
const config = {
seekBarColors: {
base: 'rgba(255,255,255,.2)',
buffered: 'rgba(255,255,255,.4)',
played: 'rgb(255,0,0)',
},
fadeDelay: 0,
};
ui.configure(config);
const overflowMenuButton = document.querySelector('.shaka-overflow-menu-button');
if (overflowMenuButton) {
overflowMenuButton.innerHTML = 'settings';
}
const backToOverflowButton = document.querySelector('.shaka-back-to-overflow-button .material-icons-round');
if (backToOverflowButton) {
backToOverflowButton.innerHTML = 'arrow_back_ios_new';
}
player.configure({
streaming: {
bufferingGoal: 180,
rebufferingGoal: 0.02,
bufferBehind: 300
}
});
player.getNetworkingEngine()?.registerRequestFilter((_type: any, request: any) => {
const uri = request.uris[0];
const url = new URL(uri);
const headers = request.headers;
if (url.host.endsWith(".googlevideo.com") || headers.Range) {
url.searchParams.set('__host', url.host);
url.host = 'localhost:8080';
url.protocol = 'http';
}
request.method = 'POST';
// protobuf - { 15: 0 }
request.body = new Uint8Array([120, 0]);
if (url.pathname === "/videoplayback") {
if (headers.Range) {
request.headers = {};
url.searchParams.set("range", headers.Range.split("=")[1]);
url.searchParams.set("alr", "yes");
delete headers.Range;
}
}
request.uris[0] = url.toString();
});
// The UTF-8 characters "h", "t", "t", and "p".
const HTTP_IN_HEX = 0x68747470;
const RequestType = shaka.net.NetworkingEngine.RequestType;
player.getNetworkingEngine()?.registerResponseFilter(async (type: any, response: any) => {
const dataView = new DataView(response.data);
if (response.data.byteLength < 4 ||
dataView.getUint32(0) != HTTP_IN_HEX) {
return;
}
const response_as_string = shaka.util.StringUtils.fromUTF8(response.data);
let retry_parameters;
if (type == RequestType.MANIFEST) {
retry_parameters = player!.getConfiguration().manifest.retryParameters;
} else if (type == RequestType.SEGMENT) {
retry_parameters = player!.getConfiguration().streaming.retryParameters;
} else if (type == RequestType.LICENSE) {
retry_parameters = player!.getConfiguration().drm.retryParameters;
} else {
retry_parameters = shaka.net.NetworkingEngine.defaultRetryParameters();
}
// Make another request for the redirect URL.
const uris = [response_as_string];
const redirect_request = shaka.net.NetworkingEngine.makeRequest(uris, retry_parameters);
const request_operation = player!.getNetworkingEngine()!.request(type, redirect_request);
const redirect_response = await request_operation.promise;
// Modify the original response to contain the results of the redirect
// response.
response.data = redirect_response.data;
response.headers = redirect_response.headers;
response.uri = redirect_response.uri;
});
try {
await player.load(uri);
} catch (e) {
console.error('Could not load manifest', e);
}
} else {
console.error('Browser not supported!');
}
player = dashjs.MediaPlayer().create();
player.initialize(video_element, uri, true);
} catch (error) {
span.textContent = 'An error occurred (see console)';
title.textContent = 'An error occurred (see console)';
showUI({ hidePlayer: true });
console.error(error);
}
});
}
main();
function showUI(args: { hidePlayer?: boolean } = {
hidePlayer: true,
}) {
const ytplayer = document.getElementById('shaka-container') as HTMLDivElement;
ytplayer.style.display = args.hidePlayer ? 'none' : 'block';
const video_container = document.getElementById('video-container') as HTMLDivElement;
video_container.animate({ opacity: [0, 1] }, { duration: 300, easing: 'ease-in-out' });
video_container.style.display = 'block';
loader.style.display = 'none';
}
function hideUI() {
const video_container = document.getElementById('video-container') as HTMLDivElement;
video_container.style.display = 'none';
loader.style.display = 'block';
}
main();

View File

@@ -1,12 +0,0 @@
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
video {
max-width: calc(100vw - 1rem);
width: fit-content;
max-height: calc(90vh - 12rem);
}

View File

@@ -1,7 +1,7 @@
import { Innertube, UniversalCache, YTNodes } from 'youtubei.js';
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache() });
const yt = await Innertube.create({ cache: new UniversalCache(false), generate_session_locally: true });
const channel = await yt.getChannel('UCX6OQ3DkcsbYNE6H8uQQuVA');

View File

@@ -0,0 +1,18 @@
{
"name": "cf-worker",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240208.0",
"typescript": "^5.0.4",
"wrangler": "^3.0.0"
},
"dependencies": {
"youtubei.js": "latest"
}
}

View File

@@ -0,0 +1,19 @@
import { Innertube } from "youtubei.js/cf-worker";
export interface Env {}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
// cannot initialize Innertube in global scope as it makes fetch requests
const yt = await Innertube.create();
const video = await yt.getInfo("jNQXAC9IVRw");
console.log("Video title is", video.basic_info.title);
return new Response("Hello World!");
},
};

View File

@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "es2021",
"lib": ["es2021"],
"jsx": "react",
"module": "es2022",
"moduleResolution": "node",
"types": ["@cloudflare/workers-types/2023-07-01"],
"resolveJsonModule": true,
"allowJs": true,
"checkJs": false,
"noEmit": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}

View File

@@ -0,0 +1,3 @@
name = "cf-worker-youtubei"
main = "src/index.ts"
compatibility_date = "2024-02-08"

View File

@@ -5,8 +5,8 @@ A `CommentThread` represents a top-level comment and its replies.
## API
* CommentThread
* [.comment](#comment) ⇒ `Comment`
* [.replies](#replies) ⇒ `Comment[]`
* [.comment](#comment) ⇒ `Comment | CommentView`
* [.replies](#replies) ⇒ `(Comment | CommentView)[]`
* [.getReplies](#getreplies) ⇒ `function`
* [.getContinuation](#getcontinuation) ⇒ `function`
* [.has_continuation](#hascontinuation) ⇒ `boolean`
@@ -14,7 +14,7 @@ A `CommentThread` represents a top-level comment and its replies.
<a name="comment"></a>
### comment
The top-level comment. **Note:** More about `Comment` [here](./Comment.md).
The top-level comment. **Note:** More about the `Comment` node [here](./Comment.md) (OUTDATED! `Comment` has been replaced by [`CommentView`](./CommentView.md) nodes).
**Type:** [`Comment`](../../src/parser/classes/comments/Comment.ts)
@@ -22,7 +22,7 @@ The top-level comment. **Note:** More about `Comment` [here](./Comment.md).
### replies
An array of replies to the top-level comment. (not populated until [`getReplies()`](#getreplies) is called).
**Type:** [`Comment[]`](../../src/parser/classes/comments/Comment.ts)
**Type:** [`(Comment | CommentView)[]`](../../src/parser/classes/comments/Comment.ts)
<a name="getreplies"></a>
### getReplies()

View File

@@ -0,0 +1,48 @@
## CommentView
Contains information about a single comment. A [`CommentView`](../../src/parser/classes/comments/CommentView.ts) can be a top-level comment or a reply to a top-level comment.
## API
* Comment
* [.like](#like) ⇒ `function`
* [.unlike](#like) ⇒ `function`
* [.dislike](#dislike) ⇒ `function`
* [.undislike](#dislike) ⇒ `function`
* [.reply](#reply) ⇒ `function`
* [.translate](#translate) ⇒ `function`
<a name="like"></a>
### like()
Likes the comment.
**Returns:** `Promise.<ApiResponse>`
<a name="unlike"></a>
### unlike()
Unlikes the comment.
**Returns:** `Promise.<ApiResponse>`
<a name="dislike"></a>
### dislike()
Dislikes the comment.
**Returns:** `Promise.<ApiResponse>`
<a name="undislike"></a>
### undislike()
Undislikes the comment.
**Returns:** `Promise.<ApiResponse>`
<a name="reply"></a>
### reply(comment_text: string)
Replies to the comment.
**Returns:** `Promise.<ApiResponse>`
<a name="translate"></a>
### translate(target_language: string)
Translates the comment to the given language.
**Returns:** `Promise.<ApiResponse & { content?: string }>`

View File

@@ -59,7 +59,4 @@ Returns whether there are more comments to be fetched.
### page
Returns original InnerTube response (sanitized).
**Returns:** `ParsedResponse`
## Example
See [`index.ts`]('./index.ts').
**Returns:** `ParsedResponse`

View File

@@ -1,45 +0,0 @@
import { Innertube, UniversalCache } from 'youtubei.js';
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache() });
const comment_section = await yt.getComments('a-rqu-hjobc');
console.info(`This video has ${comment_section.header?.comments_count.toString() || 'N/A'} comments.\n`);
for (const thread of comment_section.contents) {
const comment = thread.comment;
if (comment) {
console.info(
`${comment.is_pinned ? '[Pinned]' : ''}`,
`${comment.is_member ? `${comment.sponsor_comment_badge?.tooltip}` : ''}`,
`${comment.author.name}${comment.published}\n`,
`${comment.content.toString()}`, '\n',
`Likes: ${comment.vote_count}`, '\n'
);
if (thread.has_replies) {
console.info('Replies:', '\n');
let comment_thread = await thread.getReplies();
while (true) {
for (const reply of comment_thread?.replies || []) {
console.info(
`> ${reply.author.name}${reply.published}\n`,
`${reply.content.toString()}`, '\n',
`Likes: ${reply.vote_count}`, '\n'
);
}
try {
comment_thread = await comment_thread.getContinuation();
} catch { break; };
}
}
}
console.log('\n');
}
})();

View File

@@ -1,4 +1,4 @@
import { Innertube } from '../../bundle/browser.js';
import { Innertube } from 'https://deno.land/x/youtubei/deno.ts';
const yt = await Innertube.create();

View File

@@ -1,9 +1,8 @@
import { Innertube, UniversalCache } from 'youtubei.js';
import { readFileSync, existsSync, mkdirSync, createWriteStream } from 'fs';
import { streamToIterable } from 'youtubei.js/dist/src/utils/Utils';
import { Innertube, UniversalCache, Utils } from 'youtubei.js';
import { existsSync, mkdirSync, createWriteStream } from 'fs';
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache() });
const yt = await Innertube.create({ cache: new UniversalCache(false), generate_session_locally: true });
const search = await yt.music.search('No Copyright Background Music', { type: 'album' });
@@ -19,7 +18,7 @@ import { streamToIterable } from 'youtubei.js/dist/src/utils/Utils';
for (const song of album.contents) {
const stream = await yt.download(song.id as string, {
type: 'audio', // audio, video or audio+video
type: 'audio', // audio, video or video+audio
quality: 'best', // best, bestefficiency, 144p, 240p, 480p, 720p and so on.
format: 'mp4' // media container format
});
@@ -34,7 +33,7 @@ import { streamToIterable } from 'youtubei.js/dist/src/utils/Utils';
const file = createWriteStream(`${dir}/${song.title?.replace(/\//g, '')}.m4a`);
for await (const chunk of streamToIterable(stream)) {
for await (const chunk of Utils.streamToIterable(stream)) {
file.write(chunk);
}

View File

@@ -109,4 +109,4 @@ Sends a message.
**Returns:** `Promise<ObservedArray<AddChatItemAction>>`
## Example
See [`index.ts`]('./index.ts').
See [`index.ts`](./index.ts).

View File

@@ -1,9 +1,8 @@
import { Innertube, UniversalCache, YTNodes } from 'youtubei.js';
import { LiveChatContinuation } from 'youtubei.js/dist/src/parser';
import { Innertube, UniversalCache, YTNodes, LiveChatContinuation } from 'youtubei.js';
import { ChatAction, LiveMetadata } from 'youtubei.js/dist/src/parser/youtube/LiveChat';
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache(), generate_session_locally: true });
const yt = await Innertube.create({ cache: new UniversalCache(false), generate_session_locally: true });
const search = await yt.search('lofi hip hop radio - beats to relax/study to');
const info = await yt.getInfo(search.videos[0].as(YTNodes.Video).id);

View File

@@ -13,7 +13,7 @@ console.info('Header:', header);
// A proxy intercepts access to the actual data, allowing
// the parser to add type safety and many utility methods
// that make working with InnerTube much easier.
const tab = page.contents.item().as(YTNodes.SingleColumnBrowseResults).tabs.firstOfType(YTNodes.Tab);
const tab = page.contents?.item().as(YTNodes.SingleColumnBrowseResults).tabs.firstOfType(YTNodes.Tab);
if (!tab)
throw new Error('Target tab not found');
@@ -21,6 +21,6 @@ if (!tab)
if (!tab.content)
throw new Error('Target tab appears to be empty');
const sections = tab.content?.as(YTNodes.SectionList).contents.array().as(YTNodes.MusicCarouselShelf, YTNodes.MusicDescriptionShelf, YTNodes.MusicShelf);
const sections = tab.content?.as(YTNodes.SectionList).contents.as(YTNodes.MusicCarouselShelf, YTNodes.MusicDescriptionShelf, YTNodes.MusicShelf);
console.info('Sections:', sections);

View File

@@ -0,0 +1,16 @@
import { Innertube } from 'youtubei.js';
(async () => {
const yt = await Innertube.create({ generate_session_locally: true });
const info = await yt.getInfo('hePb00CqvP0');
const defaultTranscriptInfo = await info.getTranscript();
console.log(`Got ${defaultTranscriptInfo.selectedLanguage} transcript with ${defaultTranscriptInfo.transcript.content.body.initial_segments.length} lines.`);
console.log("Fetching Hebrew transcript...");
const heTranscriptInfo = await defaultTranscriptInfo.selectLanguage('Hebrew');
console.log(`Got ${heTranscriptInfo.selectedLanguage} transcript with ${heTranscriptInfo.transcript.content.body.initial_segments.length} lines.`);
})();

View File

@@ -5,7 +5,7 @@ const creds_path = './my_yt_creds.json';
const creds = existsSync(creds_path) ? JSON.parse(readFileSync(creds_path).toString()) : undefined;
(async () => {
const yt = await Innertube.create({ cache: new UniversalCache() });
const yt = await Innertube.create({ cache: new UniversalCache(false) });
yt.session.on('auth-pending', (data: any) => {
console.info(`Hello!\nOn your phone or computer, go to ${data.verification_url} and enter the code ${data.user_code}`);
@@ -31,5 +31,5 @@ const creds = existsSync(creds_path) ? JSON.parse(readFileSync(creds_path).toStr
privacy: 'UNLISTED'
});
console.info('Done!');
console.info('Done!', upload);
})();

View File

@@ -1,28 +0,0 @@
import { getRuntime } from './src/utils/Utils';
// Polyfill fetch for node
if (getRuntime() === 'node') {
// eslint-disable-next-line
const undici = require('undici');
Reflect.set(globalThis, 'fetch', undici.fetch);
Reflect.set(globalThis, 'Headers', undici.Headers);
Reflect.set(globalThis, 'Request', undici.Request);
Reflect.set(globalThis, 'Response', undici.Response);
Reflect.set(globalThis, 'FormData', undici.FormData);
Reflect.set(globalThis, 'File', undici.File);
try {
// eslint-disable-next-line
const { ReadableStream } = require('node:stream/web');
Reflect.set(globalThis, 'ReadableStream', ReadableStream);
} catch { /* do nothing */ }
}
import Innertube from './src/Innertube';
export * from './src/utils';
export { YTNodes } from './src/parser/map';
export { default as Parser } from './src/parser';
export { default as Innertube } from './src/Innertube';
export { default as Session } from './src/core/Session';
export { default as Player } from './src/core/Player';
export default Innertube;

View File

@@ -1,17 +1,10 @@
module.exports = {
projects: [
{
displayName: 'node',
roots: [ '<rootDir>/test' ],
testTimeout: 10000,
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
moduleFileExtensions: ["ts", "tsx", "js"],
testMatch: [ '**/*.test.ts' ],
setupFiles: []
}
]
/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
preset: 'ts-jest',
testEnvironment: 'node',
transform: { '^.+\\.(ts|tsx)$': 'ts-jest' },
testTimeout: 30000,
moduleFileExtensions: [ 'ts', 'tsx', 'js' ],
testMatch: [ '**/*.test.ts' ],
setupFiles: []
};

8811
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,68 @@
{
"name": "youtubei.js",
"version": "2.9.0",
"description": "Full-featured wrapper around YouTube's private API. Supports YouTube, YouTube Music and YouTube Studio (WIP).",
"main": "./dist/index.js",
"browser": "./bundle/browser.js",
"types": "./dist",
"version": "10.2.0",
"description": "A wrapper around YouTube's private API. Supports YouTube, YouTube Music, YouTube Kids and YouTube Studio (WIP).",
"type": "module",
"types": "./dist/src/platform/lib.d.ts",
"typesVersions": {
"*": {
"agnostic": [
"./dist/src/platform/lib.d.ts"
],
"web": [
"./dist/src/platform/lib.d.ts"
],
"react-native": [
"./dist/src/platform/lib.d.ts"
],
"web.bundle": [
"./dist/src/platform/lib.d.ts"
],
"web.bundle.min": [
"./dist/src/platform/lib.d.ts"
],
"cf-worker": [
"./dist/src/platform/lib.d.ts"
]
}
},
"exports": {
".": {
"node": {
"import": "./dist/src/platform/node.js",
"require": "./bundle/node.cjs"
},
"deno": "./dist/src/platform/deno.js",
"types": "./dist/src/platform/lib.d.ts",
"browser": "./dist/src/platform/web.js",
"react-native": "./dist/src/platform/react-native.js",
"default": "./dist/src/platform/web.js"
},
"./agnostic": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./dist/src/platform/lib.js"
},
"./web": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./dist/src/platform/web.js"
},
"./react-native": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./dist/src/platform/react-native.js"
},
"./web.bundle": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./bundle/browser.js"
},
"./web.bundle.min": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./bundle/browser.min.js"
},
"./cf-worker": {
"types": "./dist/src/platform/lib.d.ts",
"default": "./dist/src/platform/cf-worker.js"
}
},
"author": "LuanRT <luan.lrt4@gmail.com> (https://github.com/LuanRT)",
"funding": [
"https://github.com/sponsors/LuanRT"
@@ -13,7 +71,8 @@
"Wykerd (https://github.com/wykerd/)",
"MasterOfBob777 (https://github.com/MasterOfBob777)",
"patrickkfkan (https://github.com/patrickkfkan)",
"akkadaska (https://github.com/akkadaska)"
"akkadaska (https://github.com/akkadaska)",
"Absidue (https://github.com/absidue)"
],
"directories": {
"test": "./test",
@@ -24,12 +83,17 @@
"test": "npx jest --verbose",
"lint": "npx eslint ./src",
"lint:fix": "npx eslint --fix ./src",
"build": "npm run build:parser-map && npm run build:proto && npm run bundle:browser && npm run bundle:browser:prod && npm run build:node",
"build:node": "npx tsc",
"bundle:browser": "npx tsc --module esnext && npx esbuild ./dist/browser.js --banner:js=\"/* eslint-disable */\" --bundle --target=chrome58 --keep-names --format=esm --sourcemap --define:global=globalThis --outfile=./bundle/browser.js --platform=browser",
"clean": "npx rimraf ./dist/src ./dist/package.json ./bundle/browser.js ./bundle/browser.js.map ./bundle/browser.min.js ./bundle/browser.min.js.map ./bundle/node.cjs ./bundle/node.cjs.map ./bundle/cf-worker.js ./bundle/cf-worker.js.map ./bundle/react-native.js ./bundle/react-native.js.map ./deno",
"build": "npm run clean && npm run build:parser-map && npm run build:proto && npm run build:esm && npm run bundle:node && npm run bundle:browser && npm run bundle:browser:prod && npm run bundle:cf-worker && npm run bundle:react-native",
"build:parser-map": "node ./dev-scripts/gen-parser-map.mjs",
"build:proto": "npx pb-gen-ts --entry-path=\"src/proto\" --out-dir=\"src/proto/generated\" --ext-in-import=\".js\"",
"build:esm": "npx tspc",
"build:deno": "npx cpy ./src ./deno && npx esbuild ./src/utils/DashManifest.tsx --keep-names --format=esm --platform=neutral --target=es2020 --outfile=./deno/src/utils/DashManifest.js && npx cpy ./package.json ./deno && npx replace \".js';\" \".ts';\" ./deno -r && npx replace '.js\";' '.ts\";' ./deno -r && npx replace \"'./DashManifest.ts';\" \"'./DashManifest.js';\" ./deno -r && npx replace \"'jintr';\" \"'https://esm.sh/jintr';\" ./deno -r",
"bundle:node": "npx esbuild ./dist/src/platform/node.js --bundle --target=node10 --keep-names --format=cjs --platform=node --outfile=./bundle/node.cjs --external:jintr --external:undici --external:linkedom --external:tslib --sourcemap --banner:js=\"/* eslint-disable */\"",
"bundle:browser": "npx esbuild ./dist/src/platform/web.js --banner:js=\"/* eslint-disable */\" --bundle --target=chrome58 --keep-names --format=esm --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/browser.js --platform=browser",
"bundle:react-native": "npx esbuild ./dist/src/platform/react-native.js --bundle --target=es2020 --keep-names --format=esm --platform=neutral --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/react-native.js",
"bundle:browser:prod": "npm run bundle:browser -- --outfile=./bundle/browser.min.js --minify",
"build:parser-map": "node ./scripts/build-parser-map.js",
"build:proto": "npx protoc --ts_out ./src/proto --proto_path ./src/proto ./src/proto/youtube.proto",
"bundle:cf-worker": "npx esbuild ./dist/src/platform/cf-worker.js --banner:js=\"/* eslint-disable */\" --bundle --target=es2020 --keep-names --format=esm --sourcemap --define:global=globalThis --conditions=module --outfile=./bundle/cf-worker.js --platform=node",
"prepare": "npm run build",
"watch": "npx tsc --watch"
},
@@ -39,24 +103,31 @@
},
"license": "MIT",
"dependencies": {
"@protobuf-ts/runtime": "^2.7.0",
"jintr": "^0.3.1",
"linkedom": "^0.14.12",
"undici": "^5.7.0"
"jintr": "^2.0.0",
"tslib": "^2.5.0",
"undici": "^5.19.1"
},
"overrides": {
"typescript": "^5.0.0"
},
"devDependencies": {
"@protobuf-ts/plugin": "^2.7.0",
"@types/glob": "^8.1.0",
"@types/jest": "^28.1.7",
"@types/node": "^17.0.45",
"@typescript-eslint/eslint-plugin": "^5.30.6",
"@typescript-eslint/parser": "^5.30.6",
"cpy-cli": "^4.2.0",
"esbuild": "^0.14.49",
"eslint": "^8.19.0",
"eslint-plugin-tsdoc": "^0.2.16",
"glob": "^8.0.3",
"jest": "^28.1.3",
"ts-jest": "^28.0.8",
"typescript": "^4.7.4"
"jest": "^29.7.0",
"pbkit": "^0.0.59",
"replace": "^1.2.2",
"ts-jest": "^29.1.4",
"ts-patch": "^3.0.2",
"ts-transformer-inline-file": "^0.2.0",
"typescript": "^5.0.0"
},
"bugs": {
"url": "https://github.com/LuanRT/YouTube.js/issues"
@@ -72,7 +143,6 @@
"youtube-downloader",
"youtube-music",
"youtube-studio",
"innertubeapi",
"innertube",
"unofficial",
"downloader",
@@ -81,7 +151,6 @@
"upload",
"ytmusic",
"search",
"comment",
"music",
"api"
]

View File

@@ -1,48 +0,0 @@
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const import_list = [];
const json = [];
glob.sync('../src/parser/classes/**/*.{js,ts}', { cwd: __dirname })
.forEach((file) => {
if (file.includes('/misc/')) return;
// Trim path
file = file.replace('../src/parser/classes/', '').replace('.js', '').replace('.ts', '');
const import_name = file.split('/').pop();
import_list.push(`import { default as ${import_name} } from './classes/${file}';`);
json.push(import_name);
});
fs.writeFileSync(
path.resolve(__dirname, '../src/parser/map.ts'),
`// This file was auto generated, do not edit.
// See ./scripts/build-parser-map.js
import { YTNodeConstructor } from './helpers';
${import_list.join('\n')}
export const YTNodes = {
${json.join(',\n ')}
};
const map: Record<string, YTNodeConstructor> = YTNodes;
/**
* @param name - Name of the node to be parsed
*/
export default function GetParserByName(name: string) {
const ParserConstructor = map[name];
if (!ParserConstructor) {
const error = new Error(\`Module not found: \${name}\`);
(error as any).code = 'MODULE_NOT_FOUND';
throw error;
}
return ParserConstructor;
}
`
);

View File

@@ -1,52 +0,0 @@
import { fetch } from "undici";
import { gunzip } from "zlib";
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { writeFile } from "fs/promises";
(async () => {
const __dirname = dirname(fileURLToPath(import.meta.url));
const buf = await (await fetch('https://github.com/intoli/user-agents/blob/master/src/user-agents.json.gz?raw=true')).arrayBuffer();
const bytes = new Uint8Array(buf);
// Only get desktop and mobile agents
const allowed_agents = new Set([
'desktop',
'mobile',
])
const decompressed = await new Promise((resolve, reject) => {
gunzip(bytes, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result.buffer);
}
});
});
const contents = new TextDecoder().decode(decompressed);
const agents = JSON.parse(contents);
if (!Array.isArray(agents)) {
throw new Error('Invalid user-agents.json');
}
const agentsByDevice = agents.reduce((acc, agent) => {
const device = agent.deviceCategory;
if (!allowed_agents.has(device))
return acc;
if (!acc[device]) {
acc[device] = [];
}
// we dont want to massive of a list of agents for each device
if (acc[device].length <= 25) acc[device].push(agent.userAgent);
return acc;
}, {});
await writeFile(resolve(__dirname, '..', 'src', 'utils', 'user-agents.json'), JSON.stringify(agentsByDevice, null, 2));
})();

View File

@@ -1,63 +1,70 @@
import Session from './core/Session.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 Session, { SessionOptions } from './core/Session';
import type { ParsedResponse } from './parser';
import type { ActionsResponse } from './core/Actions';
import {
BrowseEndpoint,
GetNotificationMenuEndpoint,
GuideEndpoint,
NextEndpoint,
PlayerEndpoint,
ResolveURLEndpoint,
SearchEndpoint,
Reel,
Notification
} from './core/endpoints/index.js';
import NavigationEndpoint from './parser/classes/NavigationEndpoint';
import Channel from './parser/youtube/Channel';
import Comments from './parser/youtube/Comments';
import History from './parser/youtube/History';
import Library from './parser/youtube/Library';
import NotificationsMenu from './parser/youtube/NotificationsMenu';
import Playlist from './parser/youtube/Playlist';
import Search from './parser/youtube/Search';
import VideoInfo, { DownloadOptions, FormatOptions } from './parser/youtube/VideoInfo';
import {
Channel,
Comments,
Guide,
HashtagFeed,
History,
HomeFeed,
Library,
NotificationsMenu,
Playlist,
Search,
VideoInfo
} from './parser/youtube/index.js';
import AccountManager from './core/AccountManager';
import Feed from './core/Feed';
import InteractionManager from './core/InteractionManager';
import YTMusic from './core/Music';
import PlaylistManager from './core/PlaylistManager';
import Studio from './core/Studio';
import TabbedFeed from './core/TabbedFeed';
import HomeFeed from './parser/youtube/HomeFeed';
import Proto from './proto/index';
import Constants from './utils/Constants';
import { VideoInfo as ShortsVideoInfo } from './parser/ytshorts/index.js';
import type Actions from './core/Actions';
import type Format from './parser/classes/misc/Format';
import NavigationEndpoint from './parser/classes/NavigationEndpoint.js';
import { generateRandomString, throwIfMissing } from './utils/Utils';
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 { INextRequest } from './types/index.js';
import type { IBrowseResponse, IParsedResponse } from './parser/types/index.js';
import type { DownloadOptions, FormatOptions } from './types/FormatUtils.js';
import type { SessionOptions } from './core/Session.js';
import type Format from './parser/classes/misc/Format.js';
export type InnertubeConfig = SessionOptions;
export interface SearchFilters {
upload_date?: 'all' | 'hour' | 'today' | 'week' | 'month' | 'year';
type?: 'all' | 'video' | 'channel' | 'playlist' | 'movie';
duration?: 'all' | 'short' | 'medium' | 'long';
sort_by?: 'relevance' | 'rating' | 'upload_date' | 'view_count';
features?: ('hd' | 'subtitles' | 'creative_commons' | '3d' | 'live' | 'purchased' | '4k' | '360' | 'location' | 'hdr' | 'vr180')[];
}
export type InnerTubeClient = 'WEB' | 'iOS' | 'ANDROID' | 'YTMUSIC_ANDROID' | 'YTMUSIC' | 'YTSTUDIO_ANDROID' | 'TV_EMBEDDED' | 'YTKIDS';
export type InnerTubeClient = 'WEB' | 'ANDROID' | 'YTMUSIC_ANDROID' | 'YTMUSIC' | 'YTSTUDIO_ANDROID' | 'TV_EMBEDDED';
export type SearchFilters = Partial<{
upload_date: 'all' | 'hour' | 'today' | 'week' | 'month' | 'year';
type: 'all' | 'video' | 'channel' | 'playlist' | 'movie';
duration: 'all' | 'short' | 'medium' | 'long';
sort_by: 'relevance' | 'rating' | 'upload_date' | 'view_count';
features: ('hd' | 'subtitles' | 'creative_commons' | '3d' | 'live' | 'purchased' | '4k' | '360' | 'location' | 'hdr' | 'vr180')[];
}>;
class Innertube {
session: Session;
account: AccountManager;
playlist: PlaylistManager;
interact: InteractionManager;
music: YTMusic;
studio: Studio;
actions: Actions;
/**
* Provides access to various services and modules in the YouTube API.
*/
export default class Innertube {
#session: Session;
constructor(session: Session) {
this.session = session;
this.account = new AccountManager(this.session.actions);
this.playlist = new PlaylistManager(this.session.actions);
this.interact = new InteractionManager(this.session.actions);
this.music = new YTMusic(this.session);
this.studio = new Studio(this.session);
this.actions = this.session.actions;
this.#session = session;
}
static async create(config: InnertubeConfig = {}): Promise<Innertube> {
@@ -66,19 +73,46 @@ class Innertube {
/**
* Retrieves video info.
* @param video_id - The video id.
* @param target - The video id or `NavigationEndpoint`.
* @param client - The client to use.
*/
async getInfo(video_id: string, client?: InnerTubeClient): Promise<VideoInfo> {
throwIfMissing({ video_id });
async getInfo(target: string | NavigationEndpoint, client?: InnerTubeClient): Promise<VideoInfo> {
throwIfMissing({ target });
let next_payload: INextRequest;
if (target instanceof NavigationEndpoint) {
next_payload = NextEndpoint.build({
video_id: target.payload?.videoId,
playlist_id: target.payload?.playlistId,
params: target.payload?.params,
playlist_index: target.payload?.index
});
} else if (typeof target === 'string') {
next_payload = NextEndpoint.build({
video_id: target
});
} else {
throw new InnertubeError('Invalid target, expected either a video id or a valid NavigationEndpoint', target);
}
if (!next_payload.videoId)
throw new InnertubeError('Video id cannot be empty', next_payload);
const player_payload = PlayerEndpoint.build({
video_id: next_payload.videoId,
playlist_id: next_payload?.playlistId,
client: client,
sts: this.#session.player?.sts
});
const player_response = this.actions.execute(PlayerEndpoint.PATH, player_payload);
const next_response = this.actions.execute(NextEndpoint.PATH, next_payload);
const response = await Promise.all([ player_response, next_response ]);
const cpn = generateRandomString(16);
const initial_info = this.actions.getVideoInfo(video_id, cpn, client);
const continuation = this.actions.execute('/next', { videoId: video_id });
const response = await Promise.all([ initial_info, continuation ]);
return new VideoInfo(response, this.actions, this.session.player, cpn);
return new VideoInfo(response, this.actions, cpn);
}
/**
@@ -89,10 +123,43 @@ class Innertube {
async getBasicInfo(video_id: string, client?: InnerTubeClient): Promise<VideoInfo> {
throwIfMissing({ video_id });
const cpn = generateRandomString(16);
const response = await this.actions.getVideoInfo(video_id, cpn, client);
const response = await this.actions.execute(
PlayerEndpoint.PATH, PlayerEndpoint.build({
video_id: video_id,
client: client,
sts: this.#session.player?.sts
})
);
return new VideoInfo([ response ], this.actions, this.session.player, cpn);
const cpn = generateRandomString(16);
return new VideoInfo([ response ], this.actions, cpn);
}
/**
* Retrieves shorts info.
* @param short_id - The short id.
* @param client - The client to use.
*/
async getShortsWatchItem(short_id: string, client?: InnerTubeClient): Promise<ShortsVideoInfo> {
throwIfMissing({ short_id });
const watchResponse = this.actions.execute(
Reel.WatchEndpoint.PATH, Reel.WatchEndpoint.build({
short_id: short_id,
client: client
})
);
const sequenceResponse = this.actions.execute(
Reel.WatchSequenceEndpoint.PATH, Reel.WatchSequenceEndpoint.build({
sequenceParams: Proto.encodeReelSequence(short_id)
})
);
const response = await Promise.all([ watchResponse, sequenceResponse ]);
return new ShortsVideoInfo(response, this.actions);
}
/**
@@ -103,16 +170,13 @@ class Innertube {
async search(query: string, filters: SearchFilters = {}): Promise<Search> {
throwIfMissing({ query });
const args = {
query,
...{
params: filters ? Proto.encodeSearchFilters(filters) : undefined
}
};
const response = await this.actions.execute(
SearchEndpoint.PATH, SearchEndpoint.build({
query, params: filters ? Proto.encodeSearchFilters(filters) : undefined
})
);
const response = await this.actions.execute('/search', args);
return new Search(this.actions, response.data);
return new Search(this.actions, response);
}
/**
@@ -124,14 +188,14 @@ class Innertube {
const url = new URL(`${Constants.URLS.YT_SUGGESTIONS}search`);
url.searchParams.set('q', query);
url.searchParams.set('hl', this.session.context.client.hl);
url.searchParams.set('gl', this.session.context.client.gl);
url.searchParams.set('hl', this.#session.context.client.hl);
url.searchParams.set('gl', this.#session.context.client.gl);
url.searchParams.set('ds', 'yt');
url.searchParams.set('client', 'youtube');
url.searchParams.set('xssi', 't');
url.searchParams.set('oe', 'UTF');
const response = await this.session.http.fetch(url);
const response = await this.#session.http.fetch(url);
const response_data = await response.text();
const data = JSON.parse(response_data.replace(')]}\'', ''));
@@ -148,11 +212,13 @@ class Innertube {
async getComments(video_id: string, sort_by?: 'TOP_COMMENTS' | 'NEWEST_FIRST'): Promise<Comments> {
throwIfMissing({ video_id });
const payload = Proto.encodeCommentsSectionParams(video_id, {
sort_by: sort_by || 'TOP_COMMENTS'
});
const response = await this.actions.execute('/next', { continuation: payload });
const response = await this.actions.execute(
NextEndpoint.PATH, NextEndpoint.build({
continuation: Proto.encodeCommentsSectionParams(video_id, {
sort_by: sort_by || 'TOP_COMMENTS'
})
})
);
return new Comments(this.actions, response.data);
}
@@ -161,16 +227,28 @@ class Innertube {
* Retrieves YouTube's home feed (aka recommendations).
*/
async getHomeFeed(): Promise<HomeFeed> {
const response = await this.actions.execute('/browse', { browseId: 'FEwhat_to_watch' });
return new HomeFeed(this.actions, response.data);
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({ browse_id: 'FEwhat_to_watch' })
);
return new HomeFeed(this.actions, response);
}
/**
* Retrieves YouTube's content guide.
*/
async getGuide(): Promise<Guide> {
const response = await this.actions.execute(GuideEndpoint.PATH);
return new Guide(response.data);
}
/**
* Returns the account's library.
*/
async getLibrary(): Promise<Library> {
const response = await this.actions.execute('/browse', { browseId: 'FElibrary' });
return new Library(response.data, this.actions);
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({ browse_id: 'FElibrary' })
);
return new Library(this.actions, response);
}
/**
@@ -178,24 +256,40 @@ class Innertube {
* Which can also be achieved with {@link getLibrary}.
*/
async getHistory(): Promise<History> {
const response = await this.actions.execute('/browse', { browseId: 'FEhistory' });
return new History(this.actions, response.data);
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({ browse_id: 'FEhistory' })
);
return new History(this.actions, response);
}
/**
* Retrieves trending content.
* Retrieves Trending content.
*/
async getTrending(): Promise<TabbedFeed> {
const response = await this.actions.execute('/browse', { browseId: 'FEtrending' });
return new TabbedFeed(this.actions, response.data);
async getTrending(): Promise<TabbedFeed<IBrowseResponse>> {
const response = await this.actions.execute(
BrowseEndpoint.PATH, { ...BrowseEndpoint.build({ browse_id: 'FEtrending' }), parse: true }
);
return new TabbedFeed(this.actions, response);
}
/**
* Retrieves subscriptions feed.
* Retrieves Subscriptions feed.
*/
async getSubscriptionsFeed(): Promise<Feed> {
const response = await this.actions.execute('/browse', { browseId: 'FEsubscriptions' });
return new Feed(this.actions, response.data);
async getSubscriptionsFeed(): Promise<Feed<IBrowseResponse>> {
const response = await this.actions.execute(
BrowseEndpoint.PATH, { ...BrowseEndpoint.build({ browse_id: 'FEsubscriptions' }), parse: true }
);
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);
}
/**
@@ -204,15 +298,21 @@ class Innertube {
*/
async getChannel(id: string): Promise<Channel> {
throwIfMissing({ id });
const response = await this.actions.execute('/browse', { browseId: id });
return new Channel(this.actions, response.data);
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({ browse_id: id })
);
return new Channel(this.actions, response);
}
/**
* Retrieves notifications.
*/
async getNotifications(): Promise<NotificationsMenu> {
const response = await this.actions.execute('/notification/get_notification_menu', { notificationsMenuRequestType: 'NOTIFICATIONS_MENU_REQUEST_TYPE_INBOX' });
const response = await this.actions.execute(
GetNotificationMenuEndpoint.PATH, GetNotificationMenuEndpoint.build({
notifications_menu_request_type: 'NOTIFICATIONS_MENU_REQUEST_TYPE_INBOX'
})
);
return new NotificationsMenu(this.actions, response);
}
@@ -220,11 +320,21 @@ class Innertube {
* Retrieves unseen notifications count.
*/
async getUnseenNotificationsCount(): Promise<number> {
const response = await this.actions.execute('/notification/get_unseen_count');
const response = await this.actions.execute(Notification.GetUnseenCountEndpoint.PATH);
// TODO: properly parse this
return response.data?.unseenCount || response.data?.actions?.[0].updateNotificationsUnseenCountAction?.unseenCount || 0;
}
/**
* Retrieves playlists.
*/
async getPlaylists(): Promise<Feed<IBrowseResponse>> {
const response = await this.actions.execute(
BrowseEndpoint.PATH, { ...BrowseEndpoint.build({ browse_id: 'FEplaylist_aggregation' }), parse: true }
);
return new Feed(this.actions, response);
}
/**
* Retrieves playlist contents.
* @param id - Playlist id
@@ -236,8 +346,28 @@ class Innertube {
id = `VL${id}`;
}
const response = await this.actions.execute('/browse', { browseId: id });
return new Playlist(this.actions, response.data);
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({ browse_id: id })
);
return new Playlist(this.actions, response);
}
/**
* Retrieves a given hashtag's page.
* @param hashtag - The hashtag to fetch.
*/
async getHashtag(hashtag: string): Promise<HashtagFeed> {
throwIfMissing({ hashtag });
const response = await this.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
browse_id: 'FEhashtag',
params: Proto.encodeHashtag(hashtag)
})
);
return new HashtagFeed(this.actions, response);
}
/**
@@ -269,8 +399,10 @@ class Innertube {
* @param url - The URL.
*/
async resolveURL(url: string): Promise<NavigationEndpoint> {
const response = await this.actions.execute('/navigation/resolve_url', { url, parse: true });
return response.endpoint as NavigationEndpoint;
const response = await this.actions.execute(
ResolveURLEndpoint.PATH, { ...ResolveURLEndpoint.build({ url }), parse: true }
);
return response.endpoint;
}
/**
@@ -278,11 +410,65 @@ class Innertube {
* @param endpoint -The endpoint to call.
* @param args - Call arguments.
*/
call(endpoint: NavigationEndpoint, args: { [key: string]: any; parse: true }): Promise<ParsedResponse>;
call(endpoint: NavigationEndpoint, args?: { [key: string]: any; parse?: false }): Promise<ActionsResponse>;
call(endpoint: NavigationEndpoint, args?: object): Promise<ActionsResponse | ParsedResponse> {
call<T extends IParsedResponse>(endpoint: NavigationEndpoint, args: { [key: string]: any; parse: true }): Promise<T>;
call(endpoint: NavigationEndpoint, args?: { [key: string]: any; parse?: false }): Promise<ApiResponse>;
call(endpoint: NavigationEndpoint, args?: object): Promise<IParsedResponse | ApiResponse> {
return endpoint.call(this.actions, args);
}
}
export default Innertube;
/**
* An interface for interacting with YouTube Music.
*/
get music() {
return new Music(this.#session);
}
/**
* An interface for interacting with YouTube Studio.
*/
get studio() {
return new Studio(this.#session);
}
/**
* An interface for interacting with YouTube Kids.
*/
get kids() {
return new Kids(this.#session);
}
/**
* An interface for managing and retrieving account information.
*/
get account() {
return new AccountManager(this.#session.actions);
}
/**
* An interface for managing playlists.
*/
get playlist() {
return new PlaylistManager(this.#session.actions);
}
/**
* An interface for directly interacting with certain YouTube features.
*/
get interact() {
return new InteractionManager(this.#session.actions);
}
/**
* An internal class used to dispatch requests.
*/
get actions() {
return this.#session.actions;
}
/**
* The session used by this instance.
*/
get session() {
return this.#session;
}
}

View File

@@ -1,110 +0,0 @@
import Proto from '../proto/index';
import type Actions from './Actions';
import type { ActionsResponse } from './Actions';
import Analytics from '../parser/youtube/Analytics';
import TimeWatched from '../parser/youtube/TimeWatched';
import AccountInfo from '../parser/youtube/AccountInfo';
import Settings from '../parser/youtube/Settings';
import { InnertubeError } from '../utils/Utils';
class AccountManager {
#actions: Actions;
channel: {
editName: (new_name: string) => Promise<ActionsResponse>;
editDescription: (new_description: string) => Promise<ActionsResponse>;
getBasicAnalytics: () => Promise<Analytics>;
};
constructor(actions: Actions) {
this.#actions = actions;
this.channel = {
/**
* Edits channel name.
* @param new_name - The new channel name.
*/
editName: (new_name: string) => {
if (!this.#actions.session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
return this.#actions.execute('/channel/edit_name', {
givenName: new_name,
client: 'ANDROID'
});
},
/**
* Edits channel description.
* @param new_description - The new description.
*/
editDescription: (new_description: string) => {
if (!this.#actions.session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
return this.#actions.execute('/channel/edit_description', {
givenDescription: new_description,
client: 'ANDROID'
});
},
/**
* Retrieves basic channel analytics.
*/
getBasicAnalytics: () => this.getAnalytics()
};
}
/**
* Retrieves channel info.
*/
async getInfo(): Promise<AccountInfo> {
if (!this.#actions.session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
const response = await this.#actions.execute('/account/accounts_list', { client: 'ANDROID' });
return new AccountInfo(response);
}
/**
* Retrieves time watched statistics.
*/
async getTimeWatched(): Promise<TimeWatched> {
const response = await this.#actions.execute('/browse', {
browseId: 'SPtime_watched',
client: 'ANDROID'
});
return new TimeWatched(response);
}
/**
* Opens YouTube settings.
*/
async getSettings(): Promise<Settings> {
const response = await this.#actions.execute('/browse', {
browseId: 'SPaccount_overview'
});
return new Settings(this.#actions, response);
}
/**
* Retrieves basic channel analytics.
*/
async getAnalytics(): Promise<Analytics> {
const info = await this.getInfo();
const params = Proto.encodeChannelAnalyticsParams(info.footers?.endpoint.payload.browseId);
const response = await this.#actions.execute('/browse', {
browseId: 'FEanalytics_screen',
client: 'ANDROID',
params
});
return new Analytics(response);
}
}
export default AccountManager;

View File

@@ -1,24 +1,38 @@
import Parser, { ParsedResponse } from '../parser/index';
import { InnertubeError } from '../utils/Utils';
import type Session from './Session';
import { Parser, NavigateAction } from '../parser/index.js';
import { InnertubeError } from '../utils/Utils.js';
import type { Session } from './index.js';
import type {
IBrowseResponse, IGetNotificationsMenuResponse,
INextResponse, IPlayerResponse, IResolveURLResponse,
ISearchResponse, IUpdatedMetadataResponse,
IParsedResponse, IRawResponse
} from '../parser/types/index.js';
export interface ApiResponse {
success: boolean;
status_code: number;
data: any;
data: IRawResponse;
}
export type ActionsResponse = Promise<ApiResponse>;
export type InnertubeEndpoint = '/player' | '/search' | '/browse' | '/next' | '/reel' | '/updated_metadata' | '/notification/get_notification_menu' | string;
class Actions {
#session: Session;
export type ParsedResponse<T> =
T extends '/player' ? IPlayerResponse :
T extends '/search' ? ISearchResponse :
T extends '/browse' ? IBrowseResponse :
T extends '/next' ? INextResponse :
T extends '/updated_metadata' ? IUpdatedMetadataResponse :
T extends '/navigation/resolve_url' ? IResolveURLResponse :
T extends '/notification/get_notification_menu' ? IGetNotificationsMenuResponse :
IParsedResponse;
export default class Actions {
session: Session;
constructor(session: Session) {
this.#session = session;
}
get session(): Session {
return this.#session;
this.session = session;
}
/**
@@ -33,57 +47,6 @@ class Actions {
};
}
/**
* Used to retrieve video info.
* @param id - The video ID.
* @param cpn - Content Playback Nonce.
* @param client - The client to use.
* @param playlist_id - The playlist ID.
*/
async getVideoInfo(id: string, cpn?: string, client?: string, playlist_id?: string): Promise<ActionsResponse> {
const data: Record<string, any> = {
playbackContext: {
contentPlaybackContext: {
vis: 0,
splay: false,
referer: 'https://www.youtube.com',
currentUrl: `/watch?v=${id}`,
autonavState: 'STATE_OFF',
signatureTimestamp: this.#session.player?.sts || 0,
autoCaptionsDefaultOn: false,
html5Preference: 'HTML5_PREF_WANTS',
lactMilliseconds: '-1'
}
},
attestationRequest: {
omitBotguardData: true
},
videoId: id
};
if (client) {
data.client = client;
}
if (cpn) {
data.cpn = cpn;
}
if (playlist_id) {
data.playlistId = playlist_id;
}
const response = await this.#session.http.fetch('/player', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});
return this.#wrap(response);
}
/**
* Makes calls to the playback tracking API.
* @param url - The URL to call.
@@ -102,26 +65,26 @@ class Actions {
s_url.searchParams.set(key, params[key]);
}
const response = await this.#session.http.fetch(s_url);
const response = await this.session.http.fetch(s_url);
return response;
}
/**
* Executes an API call.
* @param action - The endpoint to call.
* @param endpoint - The endpoint to call.
* @param args - Call arguments
*/
async execute(action: string, args: { [key: string]: any; parse: true; protobuf?: false; serialized_data?: any }) : Promise<ParsedResponse>;
async execute(action: string, args?: { [key: string]: any; parse?: false; protobuf?: true; serialized_data?: any }) : Promise<ActionsResponse>;
async execute(action: string, args?: { [key: string]: any; parse?: boolean; protobuf?: boolean; serialized_data?: any }): Promise<ParsedResponse | ActionsResponse> {
async execute<T extends InnertubeEndpoint>(endpoint: T, args: { [key: string]: any; parse: true; protobuf?: false; serialized_data?: any }): Promise<ParsedResponse<T>>;
async execute<T extends InnertubeEndpoint>(endpoint: T, args?: { [key: string]: any; parse?: false; protobuf?: true; serialized_data?: any }): Promise<ApiResponse>;
async execute<T extends InnertubeEndpoint>(endpoint: T, args?: { [key: string]: any; parse?: boolean; protobuf?: boolean; serialized_data?: any }): Promise<ParsedResponse<T> | ApiResponse> {
let data;
if (args && !args.protobuf) {
data = { ...args };
if (Reflect.has(data, 'browseId')) {
if (this.#needsLogin(data.browseId) && !this.#session.logged_in)
if (this.#needsLogin(data.browseId) && !this.session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
}
@@ -162,9 +125,9 @@ class Actions {
data = args.serialized_data;
}
const endpoint = Reflect.has(args || {}, 'override_endpoint') ? args?.override_endpoint : action;
const target_endpoint = Reflect.has(args || {}, 'override_endpoint') ? args?.override_endpoint : endpoint;
const response = await this.#session.http.fetch(endpoint, {
const response = await this.session.http.fetch(target_endpoint, {
method: 'POST',
body: args?.protobuf ? data : JSON.stringify((data || {})),
headers: {
@@ -175,17 +138,33 @@ class Actions {
});
if (args?.parse) {
return Parser.parseResponse(await response.json());
let parsed_response = Parser.parseResponse<ParsedResponse<T>>(await response.json());
// Handle redirects
if (this.#isBrowse(parsed_response) && parsed_response.on_response_received_actions?.first()?.type === 'navigateAction') {
const navigate_action = parsed_response.on_response_received_actions.firstOfType(NavigateAction);
if (navigate_action) {
parsed_response = await navigate_action.endpoint.call(this, { parse: true });
}
}
return parsed_response;
}
return this.#wrap(response);
}
#isBrowse(response: IParsedResponse): response is IBrowseResponse {
return 'on_response_received_actions' in response;
}
#needsLogin(id: string) {
return [
'FElibrary',
'FEhistory',
'FEsubscriptions',
'FEchannels',
'FEplaylist_aggregation',
'FEmusic_listening_review',
'FEmusic_library_landing',
'SPaccount_overview',
@@ -194,6 +173,4 @@ class Actions {
'SPtime_watched'
].includes(id);
}
}
export default Actions;
}

View File

@@ -1,204 +0,0 @@
import type { Memo, ObservedArray, SuperParsedResult, YTNode } from '../parser/helpers';
import Parser, { ParsedResponse, ReloadContinuationItemsCommand } from '../parser/index';
import { concatMemos, InnertubeError } from '../utils/Utils';
import type Actions from './Actions';
import BackstagePost from '../parser/classes/BackstagePost';
import Channel from '../parser/classes/Channel';
import CompactVideo from '../parser/classes/CompactVideo';
import GridChannel from '../parser/classes/GridChannel';
import GridPlaylist from '../parser/classes/GridPlaylist';
import GridVideo from '../parser/classes/GridVideo';
import Playlist from '../parser/classes/Playlist';
import PlaylistPanelVideo from '../parser/classes/PlaylistPanelVideo';
import PlaylistVideo from '../parser/classes/PlaylistVideo';
import Post from '../parser/classes/Post';
import ReelItem from '../parser/classes/ReelItem';
import ReelShelf from '../parser/classes/ReelShelf';
import RichShelf from '../parser/classes/RichShelf';
import Shelf from '../parser/classes/Shelf';
import Tab from '../parser/classes/Tab';
import Video from '../parser/classes/Video';
import AppendContinuationItemsAction from '../parser/classes/actions/AppendContinuationItemsAction';
import ContinuationItem from '../parser/classes/ContinuationItem';
import TwoColumnBrowseResults from '../parser/classes/TwoColumnBrowseResults';
import TwoColumnSearchResults from '../parser/classes/TwoColumnSearchResults';
import WatchCardCompactVideo from '../parser/classes/WatchCardCompactVideo';
import type MusicQueue from '../parser/classes/MusicQueue';
import type RichGrid from '../parser/classes/RichGrid';
import type SectionList from '../parser/classes/SectionList';
class Feed {
#page: ParsedResponse;
#continuation?: ObservedArray<ContinuationItem>;
#actions: Actions;
#memo: Memo;
constructor(actions: Actions, data: any, already_parsed = false) {
if (data.on_response_received_actions || data.on_response_received_endpoints || already_parsed) {
this.#page = data;
} else {
this.#page = Parser.parseResponse(data);
}
const memo = concatMemos(
this.#page.contents_memo,
this.#page.on_response_received_commands_memo,
this.#page.on_response_received_endpoints_memo,
this.#page.on_response_received_actions_memo,
this.#page.sidebar_memo,
this.#page.header_memo
);
if (!memo)
throw new InnertubeError('No memo found in feed');
this.#memo = memo;
this.#actions = actions;
}
/**
* Get all videos on a given page via memo
*/
static getVideosFromMemo(memo: Memo) {
return memo.getType<Video | GridVideo | ReelItem | CompactVideo | PlaylistVideo | PlaylistPanelVideo | WatchCardCompactVideo>([
Video,
GridVideo,
ReelItem,
CompactVideo,
PlaylistVideo,
PlaylistPanelVideo,
WatchCardCompactVideo
]);
}
/**
* Get all playlists on a given page via memo
*/
static getPlaylistsFromMemo(memo: Memo) {
return memo.getType<Playlist | GridPlaylist>([ Playlist, GridPlaylist ]);
}
/**
* Get all the videos in the feed
*/
get videos() {
return Feed.getVideosFromMemo(this.#memo);
}
/**
* Get all the community posts in the feed
*/
get posts() {
return this.#memo.getType<Post | BackstagePost>([ BackstagePost, Post ]);
}
/**
* Get all the channels in the feed
*/
get channels() {
return this.#memo.getType<Channel | GridChannel>([ Channel, GridChannel ]);
}
/**
* Get all playlists in the feed
*/
get playlists() {
return Feed.getPlaylistsFromMemo(this.#memo);
}
get memo() {
return this.#memo;
}
/**
* Returns contents from the page.
*/
get page_contents(): SectionList | MusicQueue | RichGrid | ReloadContinuationItemsCommand {
const tab_content = this.#memo.getType(Tab)?.[0]?.content;
const reload_continuation_items = this.#memo.getType(ReloadContinuationItemsCommand)?.[0];
const append_continuation_items = this.#memo.getType(AppendContinuationItemsAction)?.[0];
return tab_content || reload_continuation_items || append_continuation_items;
}
/**
* Returns all segments/sections from the page.
*/
get shelves() {
return this.#memo.getType<Shelf | RichShelf | ReelShelf>([ Shelf, RichShelf, ReelShelf ]);
}
/**
* Finds shelf by title.
*/
getShelf(title: string) {
return this.shelves.get({ title });
}
/**
* Returns secondary contents from the page.
*/
get secondary_contents(): SuperParsedResult<YTNode> | undefined {
if (!this.#page.contents.is_node)
return undefined;
const node = this.#page.contents.item();
if (!node.is(TwoColumnBrowseResults, TwoColumnSearchResults))
return undefined;
return node.secondary_contents;
}
get actions(): Actions {
return this.#actions;
}
/**
* Get the original page data
*/
get page(): ParsedResponse {
return this.#page;
}
/**
* Checks if the feed has continuation.
*/
get has_continuation(): boolean {
return (this.#memo.get('ContinuationItem') || []).length > 0;
}
/**
* Retrieves continuation data as it is.
*/
async getContinuationData(): Promise<ParsedResponse | undefined> {
if (this.#continuation) {
if (this.#continuation.length > 1)
throw new InnertubeError('There are too many continuations, you\'ll need to find the correct one yourself in this.page');
if (this.#continuation.length === 0)
throw new InnertubeError('There are no continuations');
const response = await this.#continuation[0].endpoint.call(this.#actions, { parse: true });
return response;
}
this.#continuation = this.#memo.getType(ContinuationItem);
if (this.#continuation)
return this.getContinuationData();
}
/**
* Retrieves next batch of contents and returns a new {@link Feed} object.
*/
async getContinuation(): Promise<Feed> {
const continuation_data = await this.getContinuationData();
return new Feed(this.actions, continuation_data, true);
}
}
export default Feed;

View File

@@ -1,269 +0,0 @@
import Constants from '../utils/Constants';
import { OAuthError, uuidv4 } from '../utils/Utils';
import type Session from './Session';
export interface Credentials {
/**
* Token used to sign in.
*/
access_token: string;
/**
* Token used to get a new access token.
*/
refresh_token: string;
/**
* Access token's expiration date, which is usually 24hrs-ish.
*/
expires: Date;
}
// TODO: actual type info for this.
export type OAuthAuthPendingData = any;
export type OAuthAuthEventHandler = (data: {
credentials: Credentials;
status: 'SUCCESS';
}) => any;
export type OAuthAuthPendingEventHandler = (data: OAuthAuthPendingData) => any;
export type OAuthAuthErrorEventHandler = (err: OAuthError) => any;
class OAuth {
#identity?: Record<string, string>;
#session: Session;
#credentials?: Credentials;
#polling_interval = 5;
constructor(session: Session) {
this.#session = session;
}
/**
* Starts the auth flow in case no valid credentials are available.
*/
async init(credentials?: Credentials): Promise<void> {
this.#credentials = credentials;
if (this.validateCredentials()) {
if (!this.has_access_token_expired)
this.#session.emit('auth', {
credentials: this.#credentials,
status: 'SUCCESS'
});
} else if (!(await this.#loadCachedCredentials())) {
await this.#getUserCode();
}
}
async cacheCredentials(): Promise<void> {
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(this.#credentials));
await this.#session.cache?.set('youtubei_oauth_credentials', data.buffer);
}
async #loadCachedCredentials(): Promise<boolean> {
const data = await this.#session.cache?.get('youtubei_oauth_credentials');
if (!data) return false;
const decoder = new TextDecoder();
const credentials = JSON.parse(decoder.decode(data));
this.#credentials = {
access_token: credentials.access_token,
refresh_token: credentials.refresh_token,
expires: new Date(credentials.expires)
};
this.#session.emit('auth', {
credentials: this.#credentials,
status: 'SUCCESS'
});
return true;
}
async removeCache(): Promise<void> {
await this.#session.cache?.remove('youtubei_oauth_credentials');
}
/**
* Asks the server for a user code and verification URL.
*/
async #getUserCode(): Promise<void> {
this.#identity = await this.#getClientIdentity();
const data = {
client_id: this.#identity.client_id,
scope: Constants.OAUTH.SCOPE,
device_id: uuidv4(),
model_name: Constants.OAUTH.MODEL_NAME
};
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/device/code', Constants.URLS.YT_BASE), {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const response_data = await response.json();
this.#session.emit('auth-pending', response_data);
this.#polling_interval = response_data.interval;
this.#startPolling(response_data.device_code);
}
/**
* Polls the authorization server until access is granted by the user.
*/
#startPolling(device_code: string): void {
const poller = setInterval(async () => {
const data = {
...this.#identity,
code: device_code,
grant_type: Constants.OAUTH.GRANT_TYPE
};
try {
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/token', Constants.URLS.YT_BASE), {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const response_data = await response.json();
if (response_data.error) {
switch (response_data.error) {
case 'access_denied':
this.#session.emit('auth-error', new OAuthError('Access was denied.', { status: 'ACCESS_DENIED' }));
break;
case 'expired_token':
this.#session.emit('auth-error', new OAuthError('The device code has expired, restarting auth flow.', { status: 'DEVICE_CODE_EXPIRED' }));
clearInterval(poller);
this.#getUserCode();
break;
default:
break;
}
return;
}
const expiration_date = new Date(new Date().getTime() + response_data.expires_in * 1000);
this.#credentials = {
access_token: response_data.access_token,
refresh_token: response_data.refresh_token,
expires: expiration_date
};
this.#session.emit('auth', {
credentials: this.#credentials,
status: 'SUCCESS'
});
clearInterval(poller);
} catch (err) {
clearInterval(poller);
return this.#session.emit('auth-error', new OAuthError('Could not obtain user code.', { status: 'FAILED', error: err }));
}
}, this.#polling_interval * 1000);
}
/**
* Refresh access token if the same has expired.
*/
async refreshIfRequired(): Promise<void> {
if (this.has_access_token_expired) {
await this.#refreshAccessToken();
}
}
async #refreshAccessToken(): Promise<void> {
if (!this.#credentials) return;
this.#identity = await this.#getClientIdentity();
const data = {
...this.#identity,
refresh_token: this.#credentials.refresh_token,
grant_type: 'refresh_token'
};
const response = await this.#session.http.fetch_function(new URL('/o/oauth2/token', Constants.URLS.YT_BASE), {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const response_data = await response.json();
const expiration_date = new Date(new Date().getTime() + response_data.expires_in * 1000);
this.#credentials = {
access_token: response_data.access_token,
refresh_token: response_data.refresh_token || this.#credentials.refresh_token,
expires: expiration_date
};
this.#session.emit('update-credentials', {
credentials: this.#credentials,
status: 'SUCCESS'
});
}
async revokeCredentials(): Promise<Response | undefined> {
if (!this.#credentials) return;
await this.removeCache();
return this.#session.http.fetch_function(new URL(`/o/oauth2/revoke?token=${encodeURIComponent(this.#credentials.access_token)}`, Constants.URLS.YT_BASE), {
method: 'post'
});
}
/**
* Retrieves client identity from YouTube TV.
*/
async #getClientIdentity(): Promise<{ [key: string]: string; }> {
const response = await this.#session.http.fetch_function(new URL('/tv', Constants.URLS.YT_BASE), { headers: Constants.OAUTH.HEADERS });
const response_data = await response.text();
const url_body = Constants.OAUTH.REGEX.AUTH_SCRIPT.exec(response_data)?.[1];
if (!url_body)
throw new OAuthError('Could not obtain script url.', { status: 'FAILED' });
const script = await this.#session.http.fetch(url_body, { baseURL: Constants.URLS.YT_BASE });
const client_identity = (await script.text())
.replace(/\n/g, '')
.match(Constants.OAUTH.REGEX.CLIENT_IDENTITY);
const groups = client_identity?.groups;
if (!groups)
throw new OAuthError('Could not obtain client identity.', { status: 'FAILED' });
return groups;
}
get credentials(): Credentials | undefined {
return this.#credentials;
}
get has_access_token_expired(): boolean {
const timestamp = this.#credentials ? new Date(this.#credentials.expires).getTime() : -Infinity;
return new Date().getTime() > timestamp;
}
validateCredentials(): this is this & { credentials: Credentials } {
return this.#credentials &&
Reflect.has(this.#credentials, 'access_token') &&
Reflect.has(this.#credentials, 'refresh_token') &&
Reflect.has(this.#credentials, 'expires') || false;
}
}
export default OAuth;

338
src/core/OAuth2.ts Normal file
View File

@@ -0,0 +1,338 @@
import { OAuth2Error, Platform } from '../utils/Utils.js';
import { Log, Constants } from '../utils/index.js';
import type Session from './Session.js';
const TAG = 'OAuth2';
export type OAuth2ClientID = {
client_id: string;
client_secret: string;
};
export type OAuth2Tokens = {
access_token: string;
expiry_date: string;
expires_in?: number;
refresh_token: string;
scope?: string;
token_type?: string;
client?: OAuth2ClientID;
};
export type DeviceAndUserCode = {
device_code: string;
expires_in: number;
interval: number;
user_code: string;
verification_url: string;
error_code?: string;
};
export type OAuth2AuthEventHandler = (data: { credentials: OAuth2Tokens; }) => void;
export type OAuth2AuthPendingEventHandler = (data: DeviceAndUserCode) => void;
export type OAuth2AuthErrorEventHandler = (err: OAuth2Error) => void;
export default class OAuth2 {
#session: Session;
YTTV_URL: URL;
AUTH_SERVER_CODE_URL: URL;
AUTH_SERVER_TOKEN_URL: URL;
AUTH_SERVER_REVOKE_TOKEN_URL: URL;
client_id: OAuth2ClientID | undefined;
oauth2_tokens: OAuth2Tokens | undefined;
constructor(session: Session) {
this.#session = session;
this.YTTV_URL = new URL('/tv', Constants.URLS.YT_BASE);
this.AUTH_SERVER_CODE_URL = new URL('/o/oauth2/device/code', Constants.URLS.YT_BASE);
this.AUTH_SERVER_TOKEN_URL = new URL('/o/oauth2/token', Constants.URLS.YT_BASE);
this.AUTH_SERVER_REVOKE_TOKEN_URL = new URL('/o/oauth2/revoke', Constants.URLS.YT_BASE);
}
async init(tokens?: OAuth2Tokens): Promise<void> {
if (tokens) {
this.setTokens(tokens);
if (this.shouldRefreshToken()) {
await this.refreshAccessToken();
}
this.#session.emit('auth', { credentials: this.oauth2_tokens });
return;
}
const loaded_from_cache = await this.#loadFromCache();
if (loaded_from_cache) {
Log.info(TAG, 'Loaded OAuth2 tokens from cache.', this.oauth2_tokens);
return;
}
if (!this.client_id)
this.client_id = await this.getClientID();
// Initialize OAuth2 flow
const device_and_user_code = await this.getDeviceAndUserCode();
this.#session.emit('auth-pending', device_and_user_code);
this.pollForAccessToken(device_and_user_code);
}
setTokens(tokens: OAuth2Tokens): void {
const tokensMod = tokens;
// Convert access token remaining lifetime to ISO string
if (tokensMod.expires_in) {
tokensMod.expiry_date = new Date(Date.now() + tokensMod.expires_in * 1000).toISOString();
delete tokensMod.expires_in; // We don't need this anymore
}
if (!this.validateTokens(tokensMod))
throw new OAuth2Error('Invalid tokens provided.');
this.oauth2_tokens = tokensMod;
if (tokensMod.client) {
Log.info(TAG, 'Using provided client id and secret.');
this.client_id = tokensMod.client;
}
}
async cacheCredentials(): Promise<void> {
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(this.oauth2_tokens));
await this.#session.cache?.set('youtubei_oauth_credentials', data.buffer);
}
async #loadFromCache(): Promise<boolean> {
const data = await this.#session.cache?.get('youtubei_oauth_credentials');
if (!data)
return false;
const decoder = new TextDecoder();
const credentials = JSON.parse(decoder.decode(data));
this.setTokens(credentials);
this.#session.emit('auth', { credentials });
return true;
}
async removeCache(): Promise<void> {
await this.#session.cache?.remove('youtubei_oauth_credentials');
}
async pollForAccessToken(device_and_user_code: DeviceAndUserCode): Promise<void> {
if (!this.client_id)
throw new OAuth2Error('Client ID is missing.');
const { device_code, interval } = device_and_user_code;
const { client_id, client_secret } = this.client_id;
const payload = {
client_id,
client_secret,
code: device_code,
grant_type: 'http://oauth.net/grant_type/device/1.0'
};
const connInterval = setInterval(async () => {
const response = await this.#http.fetch_function(this.AUTH_SERVER_TOKEN_URL, {
body: JSON.stringify(payload),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const response_data = await response.json();
if (response_data.error) {
switch (response_data.error) {
case 'access_denied':
this.#session.emit('auth-error', new OAuth2Error('Access was denied.', response_data));
clearInterval(connInterval);
break;
case 'expired_token':
this.#session.emit('auth-error', new OAuth2Error('The device code has expired.', response_data));
clearInterval(connInterval);
break;
case 'authorization_pending':
case 'slow_down':
Log.info(TAG, 'Polling for access token...');
break;
default:
this.#session.emit('auth-error', new OAuth2Error('Server returned an unexpected error.', response_data));
clearInterval(connInterval);
break;
}
return;
}
this.setTokens(response_data);
this.#session.emit('auth', { credentials: this.oauth2_tokens });
clearInterval(connInterval);
}, interval * 1000);
}
async revokeCredentials(): Promise<Response | undefined> {
if (!this.oauth2_tokens)
throw new OAuth2Error('Access token not found');
await this.removeCache();
const url = this.AUTH_SERVER_REVOKE_TOKEN_URL;
url.searchParams.set('token', this.oauth2_tokens.access_token);
return this.#session.http.fetch_function(url, { method: 'POST' });
}
async refreshAccessToken(): Promise<void> {
if (!this.client_id)
this.client_id = await this.getClientID();
if (!this.oauth2_tokens)
throw new OAuth2Error('No tokens available to refresh.');
const { client_id, client_secret } = this.client_id;
const { refresh_token } = this.oauth2_tokens;
const payload = {
client_id,
client_secret,
refresh_token,
grant_type: 'refresh_token'
};
const response = await this.#http.fetch_function(this.AUTH_SERVER_TOKEN_URL, {
body: JSON.stringify(payload),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok)
throw new OAuth2Error(`Failed to refresh access token: ${response.status}`);
const response_data = await response.json();
if (response_data.error_code)
throw new OAuth2Error('Authorization server returned an error', response_data);
this.oauth2_tokens.access_token = response_data.access_token;
this.oauth2_tokens.expiry_date = new Date(Date.now() + response_data.expires_in * 1000).toISOString();
this.#session.emit('update-credentials', { credentials: this.oauth2_tokens });
}
async getDeviceAndUserCode(): Promise<DeviceAndUserCode> {
if (!this.client_id)
throw new OAuth2Error('Client ID is missing.');
const { client_id } = this.client_id;
const payload = {
client_id,
scope: 'http://gdata.youtube.com https://www.googleapis.com/auth/youtube-paid-content',
device_id: Platform.shim.uuidv4(),
device_model: 'ytlr::'
};
const response = await this.#http.fetch_function(this.AUTH_SERVER_CODE_URL, {
body: JSON.stringify(payload),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok)
throw new OAuth2Error(`Failed to get device/user code: ${response.status}`);
const response_data = await response.json();
if (response_data.error_code)
throw new OAuth2Error('Authorization server returned an error', response_data);
return response_data;
}
async getClientID(): Promise<OAuth2ClientID> {
const yttv_response = await this.#http.fetch_function(this.YTTV_URL, {
headers: {
'User-Agent': 'Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version',
'Referer': 'https://www.youtube.com/tv',
'Accept-Language': 'en-US'
}
});
if (!yttv_response.ok)
throw new OAuth2Error(`Failed to get client ID: ${yttv_response.status}`);
const yttv_response_data = await yttv_response.text();
let script_url_body: RegExpExecArray | null;
if ((script_url_body = Constants.OAUTH.REGEX.TV_SCRIPT.exec(yttv_response_data)) !== null) {
Log.info(TAG, `Got YouTubeTV script URL (${script_url_body[1]})`);
const script_response = await this.#http.fetch(script_url_body[1], { baseURL: Constants.URLS.YT_BASE });
if (!script_response.ok)
throw new OAuth2Error(`TV script request failed with status code ${script_response.status}`);
const script_response_data = await script_response.text();
const client_identity = script_response_data
.match(Constants.OAUTH.REGEX.CLIENT_IDENTITY);
if (!client_identity || !client_identity.groups)
throw new OAuth2Error('Could not obtain client ID.');
const { client_id, client_secret } = client_identity.groups;
Log.info(TAG, `Client identity retrieved (clientId=${client_id}, clientSecret=${client_secret}).`);
return {
client_id,
client_secret
};
}
throw new OAuth2Error('Could not obtain script URL.');
}
shouldRefreshToken(): boolean {
if (!this.oauth2_tokens)
return false;
return Date.now() > new Date(this.oauth2_tokens.expiry_date).getTime();
}
validateTokens(tokens: OAuth2Tokens): boolean {
const propertiesAreValid = (
Boolean(tokens.access_token) &&
Boolean(tokens.expiry_date) &&
Boolean(tokens.refresh_token)
);
const typesAreValid = (
typeof tokens.access_token === 'string' &&
typeof tokens.expiry_date === 'string' &&
typeof tokens.refresh_token === 'string'
);
return typesAreValid && propertiesAreValid;
}
get #http() {
return this.#session.http;
}
}

View File

@@ -1,29 +1,26 @@
import { getRandomUserAgent, getStringBetweenStrings, PlayerError } from '../utils/Utils';
import { Log, LZW, Constants } from '../utils/index.js';
import { Platform, getRandomUserAgent, getStringBetweenStrings, PlayerError } from '../utils/Utils.js';
import type { ICache, FetchFunction } from '../types/index.js';
import Constants from '../utils/Constants';
import UniversalCache from '../utils/Cache';
// See: https://github.com/LuanRT/Jinter
import Jinter from 'jintr';
import type { FetchFunction } from '../utils/HTTPClient';
const TAG = 'Player';
/**
* Represents YouTube's player script. This is required to decipher signatures.
*/
export default class Player {
#nsig_sc;
#sig_sc;
#sig_sc_timestamp;
#player_id;
nsig_sc;
sig_sc;
sts;
player_id;
constructor(signature_timestamp: number, sig_sc: string, nsig_sc: string, player_id: string) {
this.#nsig_sc = nsig_sc;
this.#sig_sc = sig_sc;
this.#sig_sc_timestamp = signature_timestamp;
this.#player_id = player_id;
this.nsig_sc = nsig_sc;
this.sig_sc = sig_sc;
this.sts = signature_timestamp;
this.player_id = player_id;
}
static async create(cache: UniversalCache | undefined, fetch: FetchFunction = globalThis.fetch): Promise<Player> {
static async create(cache: ICache | undefined, fetch: FetchFunction = Platform.shim.fetch): Promise<Player> {
const url = new URL('/iframe_api', Constants.URLS.YT_BASE);
const res = await fetch(url);
@@ -34,18 +31,24 @@ export default class Player {
const player_id = getStringBetweenStrings(js, 'player\\/', '\\/');
Log.info(TAG, `Got player id (${player_id}). Checking for cached players..`);
if (!player_id)
throw new PlayerError('Failed to get player id');
// We have the playerID now we can check if we have a cached player
// We have the player id, now we can check if we have a cached player.
if (cache) {
const cached_player = await Player.fromCache(cache, player_id);
if (cached_player)
if (cached_player) {
Log.info(TAG, 'Found up-to-date player data in cache.');
return cached_player;
}
}
const player_url = new URL(`/s/player/${player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE);
Log.info(TAG, `Could not find any cached player. Will download a new player from ${player_url}.`);
const player_res = await fetch(player_url, {
headers: {
'user-agent': getRandomUserAgent('desktop')
@@ -59,14 +62,15 @@ export default class Player {
const player_js = await player_res.text();
const sig_timestamp = this.extractSigTimestamp(player_js);
const sig_sc = this.extractSigSourceCode(player_js);
const nsig_sc = this.extractNSigSourceCode(player_js);
Log.info(TAG, `Got signature timestamp (${sig_timestamp}) and algorithms needed to decipher signatures.`);
return await Player.fromSource(cache, sig_timestamp, sig_sc, nsig_sc, player_id);
}
decipher(url?: string, signature_cipher?: string, cipher?: string): string {
decipher(url?: string, signature_cipher?: string, cipher?: string, this_response_nsig_cache?: Map<string, string>): string {
url = url || signature_cipher || cipher;
if (!url)
@@ -75,13 +79,15 @@ export default class Player {
const args = new URLSearchParams(url);
const url_components = new URL(args.get('url') || url);
url_components.searchParams.set('ratebypass', 'yes');
if (signature_cipher || cipher) {
const sig_decipher = new Jinter(this.#sig_sc);
sig_decipher.scope.set('sig', args.get('s'));
const signature = Platform.shim.eval(this.sig_sc, {
sig: args.get('s')
});
const signature = sig_decipher.interpret();
Log.info(TAG, `Transformed signature from ${args.get('s')} to ${signature}.`);
if (typeof signature !== 'string')
throw new PlayerError('Failed to decipher signature');
const sp = args.get('sp');
@@ -93,22 +99,61 @@ export default class Player {
const n = url_components.searchParams.get('n');
if (n) {
const nsig_decipher = new Jinter(this.#nsig_sc);
nsig_decipher.scope.set('nsig', n);
let nsig;
const nsig = nsig_decipher.interpret();
if (this_response_nsig_cache && this_response_nsig_cache.has(n)) {
nsig = this_response_nsig_cache.get(n) as string;
} else {
nsig = Platform.shim.eval(this.nsig_sc, {
nsig: n
});
if (nsig.startsWith('enhanced_except_')) {
console.warn('Warning:\nCould not transform nsig, download may be throttled.\nChanging the InnerTube client to "ANDROID" might help!');
Log.info(TAG, `Transformed n signature from ${n} to ${nsig}.`);
if (typeof nsig !== 'string')
throw new PlayerError('Failed to decipher nsig');
if (nsig.startsWith('enhanced_except_')) {
Log.warn(TAG, 'Could not transform nsig, download may be throttled.');
} else if (this_response_nsig_cache) {
this_response_nsig_cache.set(n, nsig);
}
}
url_components.searchParams.set('n', nsig);
}
const client = url_components.searchParams.get('c');
switch (client) {
case 'WEB':
url_components.searchParams.set('cver', Constants.CLIENTS.WEB.VERSION);
break;
case 'WEB_REMIX':
url_components.searchParams.set('cver', Constants.CLIENTS.YTMUSIC.VERSION);
break;
case 'WEB_KIDS':
url_components.searchParams.set('cver', Constants.CLIENTS.WEB_KIDS.VERSION);
break;
case 'ANDROID':
url_components.searchParams.set('cver', Constants.CLIENTS.ANDROID.VERSION);
break;
case 'ANDROID_MUSIC':
url_components.searchParams.set('cver', Constants.CLIENTS.YTMUSIC_ANDROID.VERSION);
break;
case 'TVHTML5_SIMPLY_EMBEDDED_PLAYER':
url_components.searchParams.set('cver', Constants.CLIENTS.TV_EMBEDDED.VERSION);
break;
}
const result = url_components.toString();
Log.info(TAG, `Deciphered URL: ${result}`);
return url_components.toString();
}
static async fromCache(cache: UniversalCache, player_id: string): Promise<Player | null> {
static async fromCache(cache: ICache, player_id: string): Promise<Player | null> {
const buffer = await cache.get(player_id);
if (!buffer)
@@ -126,39 +171,37 @@ export default class Player {
const sig_buf = buffer.slice(12, 12 + sig_len);
const nsig_buf = buffer.slice(12 + sig_len);
const decoder = new TextDecoder();
const sig_sc = decoder.decode(sig_buf);
const nsig_sc = decoder.decode(nsig_buf);
const sig_sc = LZW.decompress(new TextDecoder().decode(sig_buf));
const nsig_sc = LZW.decompress(new TextDecoder().decode(nsig_buf));
return new Player(sig_timestamp, sig_sc, nsig_sc, player_id);
}
static async fromSource(cache: UniversalCache | undefined, sig_timestamp: number, sig_sc: string, nsig_sc: string, player_id: string): Promise<Player> {
static async fromSource(cache: ICache | undefined, sig_timestamp: number, sig_sc: string, nsig_sc: string, player_id: string): Promise<Player> {
const player = new Player(sig_timestamp, sig_sc, nsig_sc, player_id);
await player.cache(cache);
return player;
}
async cache(cache?: UniversalCache): Promise<void> {
async cache(cache?: ICache): Promise<void> {
if (!cache) return;
const encoder = new TextEncoder();
const sig_buf = encoder.encode(this.#sig_sc);
const nsig_buf = encoder.encode(this.#nsig_sc);
const sig_buf = encoder.encode(LZW.compress(this.sig_sc));
const nsig_buf = encoder.encode(LZW.compress(this.nsig_sc));
const buffer = new ArrayBuffer(12 + sig_buf.byteLength + nsig_buf.byteLength);
const view = new DataView(buffer);
view.setUint32(0, Player.LIBRARY_VERSION, true);
view.setUint32(4, this.#sig_sc_timestamp, true);
view.setUint32(4, this.sts, true);
view.setUint32(8, sig_buf.byteLength, true);
new Uint8Array(buffer).set(sig_buf, 12);
new Uint8Array(buffer).set(nsig_buf, 12 + sig_buf.byteLength);
await cache.set(this.#player_id, new Uint8Array(buffer));
await cache.set(this.player_id, new Uint8Array(buffer));
}
static extractSigTimestamp(data: string): number {
@@ -171,37 +214,26 @@ export default class Player {
const functions = getStringBetweenStrings(data, `var ${obj_name}={`, '};');
if (!functions || !calls)
console.warn(new PlayerError('Failed to extract signature decipher algorithm'));
Log.warn(TAG, 'Failed to extract signature decipher algorithm.');
return `function descramble_sig(a) { a = a.split(""); let ${obj_name}={${functions}}${calls} return a.join("") } descramble_sig(sig);`;
}
static extractNSigSourceCode(data: string): string {
const sc = `function descramble_nsig(a) { let b=a.split("")${getStringBetweenStrings(data, 'b=a.split("")', '}return b.join("")}')}} return b.join(""); } descramble_nsig(nsig)`;
const match = data.match(/b=(?:a\.split\(|String\.prototype\.split\.call\(a,)""\).*?\}return (?:b\.join\(|Array\.prototype\.join\.call\(b,)""\)\}/s);
if (!sc)
console.warn(new PlayerError('Failed to extract n-token decipher algorithm'));
if (!match) {
throw new PlayerError('Failed to extract n-token decipher algorithm');
}
return sc;
return `function descramble_nsig(a) { let ${match[0]} descramble_nsig(nsig)`;
}
get url(): string {
return new URL(`/s/player/${this.#player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE).toString();
}
get sts(): number {
return this.#sig_sc_timestamp;
}
get nsig_sc(): string {
return this.#nsig_sc;
}
get sig_sc(): string {
return this.#sig_sc;
return new URL(`/s/player/${this.player_id}/player_ias.vflset/en_US/base.js`, Constants.URLS.YT_BASE).toString();
}
static get LIBRARY_VERSION(): number {
return 2;
return 11;
}
}

View File

@@ -1,64 +1,112 @@
import UniversalCache from '../utils/Cache';
import Constants, { CLIENTS } from '../utils/Constants';
import EventEmitterLike from '../utils/EventEmitterLike';
import Actions from './Actions';
import Player from './Player';
import OAuth2 from './OAuth2.js';
import { Log, EventEmitter, HTTPClient, LZW } from '../utils/index.js';
import * as Constants from '../utils/Constants.js';
import * as Proto from '../proto/index.js';
import Actions from './Actions.js';
import Player from './Player.js';
import HTTPClient, { FetchFunction } from '../utils/HTTPClient';
import { DeviceCategory, generateRandomString, getRandomUserAgent, InnertubeError, SessionError } from '../utils/Utils';
import OAuth, { Credentials, OAuthAuthErrorEventHandler, OAuthAuthEventHandler, OAuthAuthPendingEventHandler } from './OAuth';
import Proto from '../proto';
import {
generateRandomString, getRandomUserAgent,
InnertubeError, Platform, SessionError
} from '../utils/Utils.js';
import type { DeviceCategory } from '../utils/Utils.js';
import type { FetchFunction, ICache } from '../types/index.js';
import type { OAuth2Tokens, OAuth2AuthErrorEventHandler, OAuth2AuthPendingEventHandler, OAuth2AuthEventHandler } from './OAuth2.js';
export enum ClientType {
WEB = 'WEB',
KIDS = 'WEB_KIDS',
MUSIC = 'WEB_REMIX',
IOS = 'iOS',
ANDROID = 'ANDROID',
ANDROID_MUSIC = 'ANDROID_MUSIC',
ANDROID_CREATOR = 'ANDROID_CREATOR',
TV_EMBEDDED = 'TVHTML5_SIMPLY_EMBEDDED_PLAYER'
}
export interface Context {
export type Context = {
client: {
hl: string;
gl: string;
remoteHost?: string;
screenDensityFloat: number;
screenHeightPoints: number;
screenPixelDensity: number;
screenWidthPoints: number;
visitorData: string;
userAgent: string;
screenDensityFloat?: number;
screenHeightPoints?: number;
screenPixelDensity?: number;
screenWidthPoints?: number;
visitorData?: string;
clientName: string;
clientVersion: string;
clientScreen?: string,
androidSdkVersion?: string;
androidSdkVersion?: number;
osName: string;
osVersion: string;
platform: string;
clientFormFactor: string;
userInterfaceTheme: string;
userInterfaceTheme?: string;
timeZone: string;
userAgent?: string;
browserName?: string;
browserVersion?: string;
originalUrl: string;
originalUrl?: string;
deviceMake: string;
deviceModel: string;
utcOffsetMinutes: number;
mainAppWebInfo?: {
graftUrl: string;
pwaInstallabilityStatus: string;
webDisplayMode: string;
isWebNativeShareAvailable: boolean;
};
memoryTotalKbytes?: string;
configInfo?: {
appInstallData: string;
},
kidsAppInfo?: {
categorySettings: {
enabledCategories: string[];
};
contentSettings: {
corpusPreference: string;
kidsNoSearchMode: string;
};
};
};
user: {
enableSafetyMode: boolean;
lockedSafetyMode: boolean;
onBehalfOfUser?: string;
};
thirdParty?: {
embedUrl: string;
};
request: {
useSsl: true;
request?: {
useSsl: boolean;
internalExperimentFlags: any[];
};
}
export interface SessionOptions {
type ContextData = {
hl: string;
gl: string;
remote_host?: string;
visitor_data: string;
client_name: string;
client_version: string;
os_name: string;
os_version: string;
device_category: string;
time_zone: string;
enable_safety_mode: boolean;
browser_name?: string;
browser_version?: string;
app_install_data?: string;
device_make: string;
device_model: string;
on_behalf_of_user?: string;
}
export type SessionOptions = {
/**
* Language.
*/
@@ -69,12 +117,17 @@ export interface SessionOptions {
location?: string;
/**
* The account index to use. This is useful if you have multiple accounts logged in.
* **NOTE:**
* Only works if you are signed in with cookies.
*
* **NOTE:** Only works if you are signed in with cookies.
*/
account_index?: number;
/**
* Specify the Page ID of the YouTube profile/channel to use, if the logged-in account has multiple profiles.
*/
on_behalf_of_user?: string;
/**
* Specifies whether to retrieve the JS player. Disabling this will make session creation faster.
*
* **NOTE:** Deciphering formats is not possible without the JS player.
*/
retrieve_player?: boolean;
@@ -85,8 +138,15 @@ export interface SessionOptions {
/**
* Specifies whether to generate the session data locally or retrieve it from YouTube.
* This can be useful if you need more performance.
*
* **NOTE:** If you are using the cache option and a session has already been generated, this will be ignored.
* If you want to force a new session to be generated, you must clear the cache or disable session caching.
*/
generate_session_locally?: boolean;
/**
* Specifies whether the session data should be cached.
*/
enable_session_cache?: boolean;
/**
* Platform to use for the session.
*/
@@ -100,64 +160,90 @@ export interface SessionOptions {
*/
timezone?: string;
/**
* Used to cache the deciphering functions from the JS player.
* Used to cache algorithms, session data, and OAuth2 tokens.
*/
cache?: UniversalCache;
cache?: ICache;
/**
* YouTube cookies.
*/
cookie?: string;
/**
* Setting this to a valid and persistent visitor data string will allow YouTube to give this session tailored content even when not logged in.
* A good way to get a valid one is by either grabbing it from a browser or calling InnerTube's `/visitor_id` endpoint.
*/
visitor_data?: string;
/**
* Fetch function to use.
*/
fetch?: FetchFunction;
}
export interface SessionData {
export type SessionData = {
context: Context;
api_key: string;
api_version: string;
}
export default class Session extends EventEmitterLike {
#api_version: string;
#key: string;
#context: Context;
#account_index: number;
#player?: Player;
export type SWSessionData = {
context_data: ContextData;
api_key: string;
api_version: string;
}
oauth: OAuth;
export type SessionArgs = {
lang: string;
location: string;
time_zone: string;
device_category: DeviceCategory;
client_name: ClientType;
enable_safety_mode: boolean;
visitor_data: string;
on_behalf_of_user: string | undefined;
}
const TAG = 'Session';
/**
* Represents an InnerTube session. This holds all the data needed to make requests to YouTube.
*/
export default class Session extends EventEmitter {
context: Context;
player?: Player;
oauth: OAuth2;
http: HTTPClient;
logged_in: boolean;
actions: Actions;
cache?: UniversalCache;
cache?: ICache;
key: string;
api_version: string;
account_index: number;
constructor(context: Context, api_key: string, api_version: string, account_index: number, player?: Player, cookie?: string, fetch?: FetchFunction, cache?: UniversalCache) {
constructor(context: Context, api_key: string, api_version: string, account_index: number, player?: Player, cookie?: string, fetch?: FetchFunction, cache?: ICache) {
super();
this.#context = context;
this.#account_index = account_index;
this.#key = api_key;
this.#api_version = api_version;
this.#player = player;
this.http = new HTTPClient(this, cookie, fetch);
this.actions = new Actions(this);
this.oauth = new OAuth(this);
this.oauth = new OAuth2(this);
this.logged_in = !!cookie;
this.cache = cache;
this.account_index = account_index;
this.key = api_key;
this.api_version = api_version;
this.context = context;
this.player = player;
}
on(type: 'auth', listener: OAuthAuthEventHandler): void;
on(type: 'auth-pending', listener: OAuthAuthPendingEventHandler): void;
on(type: 'auth-error', listener: OAuthAuthErrorEventHandler): void;
on(type: 'update-credentials', listener: OAuthAuthEventHandler): void;
on(type: 'auth', listener: OAuth2AuthEventHandler): void;
on(type: 'auth-pending', listener: OAuth2AuthPendingEventHandler): void;
on(type: 'auth-error', listener: OAuth2AuthErrorEventHandler): void;
on(type: 'update-credentials', listener: OAuth2AuthEventHandler): void;
on(type: string, listener: (...args: any[]) => void): void {
super.on(type, listener);
}
once(type: 'auth', listener: OAuthAuthEventHandler): void;
once(type: 'auth-pending', listener: OAuthAuthPendingEventHandler): void;
once(type: 'auth-error', listener: OAuthAuthErrorEventHandler): void;
once(type: 'auth', listener: OAuth2AuthEventHandler): void;
once(type: 'auth-pending', listener: OAuth2AuthPendingEventHandler): void;
once(type: 'auth-error', listener: OAuth2AuthErrorEventHandler): void;
once(type: string, listener: (...args: any[]) => void): void {
super.once(type, listener);
@@ -168,12 +254,16 @@ export default class Session extends EventEmitterLike {
options.lang,
options.location,
options.account_index,
options.visitor_data,
options.enable_safety_mode,
options.generate_session_locally,
options.device_category,
options.client_type,
options.timezone,
options.fetch
options.fetch,
options.on_behalf_of_user,
options.cache,
options.enable_session_cache
);
return new Session(
@@ -183,45 +273,153 @@ export default class Session extends EventEmitterLike {
);
}
/**
* Retrieves session data from cache.
* @param cache - A valid cache implementation.
* @param session_args - User provided session arguments.
*/
static async fromCache(cache: ICache, session_args: SessionArgs): Promise<SessionData | null> {
const buffer = await cache.get('innertube_session_data');
if (!buffer)
return null;
const data = new TextDecoder().decode(buffer.slice(4));
try {
const result = JSON.parse(LZW.decompress(data)) as SessionData;
if (session_args.visitor_data) {
result.context.client.visitorData = session_args.visitor_data;
}
if (session_args.lang)
result.context.client.hl = session_args.lang;
if (session_args.location)
result.context.client.gl = session_args.location;
if (session_args.on_behalf_of_user)
result.context.user.onBehalfOfUser = session_args.on_behalf_of_user;
result.context.client.timeZone = session_args.time_zone;
result.context.client.platform = session_args.device_category.toUpperCase();
result.context.client.clientName = session_args.client_name;
result.context.user.enableSafetyMode = session_args.enable_safety_mode;
return result;
} catch (error) {
Log.error(TAG, 'Failed to parse session data from cache.', error);
return null;
}
}
static async getSessionData(
lang = '',
location = '',
account_index = 0,
visitor_data = '',
enable_safety_mode = false,
generate_session_locally = false,
device_category: DeviceCategory = 'desktop',
client_name: ClientType = ClientType.WEB,
tz: string = Intl.DateTimeFormat().resolvedOptions().timeZone,
fetch: FetchFunction = globalThis.fetch
fetch: FetchFunction = Platform.shim.fetch,
on_behalf_of_user?: string,
cache?: ICache,
enable_session_cache = true
) {
let session_data: SessionData;
const session_args = { lang, location, time_zone: tz, device_category, client_name, enable_safety_mode, visitor_data, on_behalf_of_user };
if (generate_session_locally) {
session_data = this.#generateSessionData({ lang, location, time_zone: tz, device_category, client_name, enable_safety_mode });
} else {
session_data = await this.#retrieveSessionData({ lang, location, time_zone: tz, device_category, client_name, enable_safety_mode }, fetch);
let session_data: SessionData | undefined;
if (cache && enable_session_cache) {
const cached_session_data = await this.fromCache(cache, session_args);
if (cached_session_data) {
Log.info(TAG, 'Found session data in cache.');
session_data = cached_session_data;
}
}
if (!session_data) {
Log.info(TAG, 'Generating session data.');
let api_key = Constants.CLIENTS.WEB.API_KEY;
let api_version = Constants.CLIENTS.WEB.API_VERSION;
let context_data: ContextData = {
hl: lang || 'en',
gl: location || 'US',
remote_host: '',
visitor_data: visitor_data || Proto.encodeVisitorData(generateRandomString(11), Math.floor(Date.now() / 1000)),
client_name: client_name,
client_version: Constants.CLIENTS.WEB.VERSION,
device_category: device_category.toUpperCase(),
os_name: 'Windows',
os_version: '10.0',
time_zone: tz,
browser_name: 'Chrome',
browser_version: '125.0.0.0',
device_make: '',
device_model: '',
enable_safety_mode: enable_safety_mode
};
if (!generate_session_locally) {
try {
const sw_session_data = await this.#getSessionData(session_args, fetch);
api_key = sw_session_data.api_key;
api_version = sw_session_data.api_version;
context_data = sw_session_data.context_data;
} catch (error) {
Log.error(TAG, 'Failed to retrieve session data from server. Session data generated locally will be used instead.', error);
}
}
session_data = {
api_key,
api_version,
context: this.#buildContext(context_data)
};
if (enable_session_cache)
await this.#storeSession(session_data, cache);
}
Log.debug(TAG, 'Session data:', session_data);
return { ...session_data, account_index };
}
static async #retrieveSessionData(options: {
lang: string;
location: string;
time_zone: string;
device_category: string;
client_name: string;
enable_safety_mode: boolean;
}, fetch: FetchFunction = globalThis.fetch): Promise<SessionData> {
static async #storeSession(session_data: SessionData, cache?: ICache) {
if (!cache) return;
Log.info(TAG, 'Compressing and caching session data.');
const compressed_session_data = new TextEncoder().encode(LZW.compress(JSON.stringify(session_data)));
const buffer = new ArrayBuffer(4 + compressed_session_data.byteLength);
new DataView(buffer).setUint32(0, compressed_session_data.byteLength, true); // (Luan) XX: Leave this here for debugging purposes
new Uint8Array(buffer).set(compressed_session_data, 4);
await cache.set('innertube_session_data', new Uint8Array(buffer));
}
static async #getSessionData(options: SessionArgs, fetch: FetchFunction = Platform.shim.fetch): Promise<SWSessionData> {
let visitor_id = generateRandomString(11);
if (options.visitor_data)
visitor_id = this.#getVisitorID(options.visitor_data);
const url = new URL('/sw.js_data', Constants.URLS.YT_BASE);
const res = await fetch(url, {
headers: {
'accept-language': options.lang || 'en-US',
'user-agent': getRandomUserAgent('desktop'),
'accept': '*/*',
'referer': 'https://www.youtube.com/sw.js',
'cookie': `PREF=tz=${options.time_zone.replace('/', '.')}`
'Accept-Language': options.lang || 'en-US',
'User-Agent': getRandomUserAgent('desktop'),
'Accept': '*/*',
'Referer': `${Constants.URLS.YT_BASE}/sw.js`,
'Cookie': `PREF=tz=${options.time_zone.replace('/', '.')};VISITOR_INFO1_LIVE=${visitor_id};`
}
});
@@ -229,123 +427,114 @@ export default class Session extends EventEmitterLike {
throw new SessionError(`Failed to retrieve session data: ${res.status}`);
const text = await res.text();
if (!text.startsWith(')]}\''))
throw new SessionError('Invalid JSPB response');
const data = JSON.parse(text.replace(/^\)\]\}'/, ''));
const ytcfg = data[0][2];
const api_version = `v${ytcfg[0][0][6]}`;
const api_version = Constants.CLIENTS.WEB.API_VERSION;
const [ [ device_info ], api_key ] = ytcfg;
const context: Context = {
client: {
hl: device_info[0],
gl: options.location || device_info[2],
remoteHost: device_info[3],
screenDensityFloat: 1,
screenHeightPoints: 1080,
screenPixelDensity: 1,
screenWidthPoints: 1920,
visitorData: device_info[13],
userAgent: device_info[14],
clientName: options.client_name,
clientVersion: device_info[16],
osName: device_info[17],
osVersion: device_info[18],
platform: options.device_category.toUpperCase(),
clientFormFactor: 'UNKNOWN_FORM_FACTOR',
userInterfaceTheme: 'USER_INTERFACE_THEME_LIGHT',
timeZone: device_info[79] || options.time_zone,
browserName: device_info[86],
browserVersion: device_info[87],
originalUrl: Constants.URLS.YT_BASE,
deviceMake: device_info[11],
deviceModel: device_info[12],
utcOffsetMinutes: new Date().getTimezoneOffset()
},
user: {
enableSafetyMode: options.enable_safety_mode,
lockedSafetyMode: false
},
request: {
useSsl: true
}
const config_info = device_info[61];
const app_install_data = config_info[config_info.length - 1];
const context_info = {
hl: options.lang || device_info[0],
gl: options.location || device_info[2],
remote_host: device_info[3],
visitor_data: device_info[13],
client_name: options.client_name,
client_version: device_info[16],
os_name: device_info[17],
os_version: device_info[18],
time_zone: device_info[79] || options.time_zone,
device_category: options.device_category,
browser_name: device_info[86],
browser_version: device_info[87],
device_make: device_info[11],
device_model: device_info[12],
app_install_data: app_install_data,
enable_safety_mode: options.enable_safety_mode
};
return { context, api_key, api_version };
return { context_data: context_info, api_key, api_version };
}
static #generateSessionData(options: {
lang: string;
location: string;
time_zone: string;
device_category: DeviceCategory;
client_name: string;
enable_safety_mode: boolean
}): SessionData {
const id = generateRandomString(11);
const timestamp = Math.floor(Date.now() / 1000);
static #buildContext(args: ContextData) {
const context: Context = {
client: {
hl: options.lang || 'en',
gl: options.location || 'US',
hl: args.hl,
gl: args.gl,
remoteHost: args.remote_host,
screenDensityFloat: 1,
screenHeightPoints: 1080,
screenHeightPoints: 1440,
screenPixelDensity: 1,
screenWidthPoints: 1920,
visitorData: Proto.encodeVisitorData(id, timestamp),
userAgent: getRandomUserAgent('desktop'),
clientName: options.client_name,
clientVersion: CLIENTS.WEB.VERSION,
osName: 'Windows',
osVersion: '10.0',
platform: options.device_category.toUpperCase(),
screenWidthPoints: 2560,
visitorData: args.visitor_data,
clientName: args.client_name,
clientVersion: args.client_version,
osName: args.os_name,
osVersion: args.os_version,
platform: args.device_category.toUpperCase(),
clientFormFactor: 'UNKNOWN_FORM_FACTOR',
userInterfaceTheme: 'USER_INTERFACE_THEME_LIGHT',
timeZone: options.time_zone,
timeZone: args.time_zone,
originalUrl: Constants.URLS.YT_BASE,
deviceMake: '',
deviceModel: '',
utcOffsetMinutes: new Date().getTimezoneOffset()
},
user: {
enableSafetyMode: options.enable_safety_mode,
lockedSafetyMode: false
},
request: {
useSsl: true
}
};
return { context, api_key: CLIENTS.WEB.API_KEY, api_version: CLIENTS.WEB.API_VERSION };
}
async signIn(credentials?: Credentials): Promise<void> {
return new Promise(async (resolve, reject) => {
const error_handler: OAuthAuthErrorEventHandler = (err) => reject(err);
this.once('auth', (data) => {
this.off('auth-error', error_handler);
if (data.status === 'SUCCESS') {
this.logged_in = true;
resolve();
deviceMake: args.device_make,
deviceModel: args.device_model,
browserName: args.browser_name,
browserVersion: args.browser_version,
utcOffsetMinutes: -Math.floor((new Date()).getTimezoneOffset()),
memoryTotalKbytes: '8000000',
mainAppWebInfo: {
graftUrl: Constants.URLS.YT_BASE,
pwaInstallabilityStatus: 'PWA_INSTALLABILITY_STATUS_UNKNOWN',
webDisplayMode: 'WEB_DISPLAY_MODE_BROWSER',
isWebNativeShareAvailable: true
}
},
user: {
enableSafetyMode: args.enable_safety_mode,
lockedSafetyMode: false
},
request: {
useSsl: true,
internalExperimentFlags: []
}
};
reject(data);
});
if (args.app_install_data)
context.client.configInfo = { appInstallData: args.app_install_data };
if (args.on_behalf_of_user)
context.user.onBehalfOfUser = args.on_behalf_of_user;
return context;
}
static #getVisitorID(visitor_data: string) {
const decoded_visitor_data = Proto.decodeVisitorData(visitor_data);
return decoded_visitor_data.id;
}
async signIn(credentials?: OAuth2Tokens): Promise<void> {
return new Promise(async (resolve, reject) => {
const error_handler: OAuth2AuthErrorEventHandler = (err) => reject(err);
this.once('auth-error', error_handler);
this.once('auth', () => {
this.off('auth-error', error_handler);
this.logged_in = true;
resolve();
});
try {
await this.oauth.init(credentials);
if (this.oauth.validateCredentials()) {
await this.oauth.refreshIfRequired();
this.logged_in = true;
resolve();
}
} catch (err) {
reject(err);
}
@@ -365,41 +554,15 @@ export default class Session extends EventEmitterLike {
return response;
}
/**
* InnerTube API key.
*/
get key(): string {
return this.#key;
}
/**
* InnerTube API version.
*/
get api_version(): string {
return this.#api_version;
}
get client_version(): string {
return this.#context.client.clientVersion;
return this.context.client.clientVersion;
}
get client_name(): string {
return this.#context.client.clientName;
}
get account_index(): number {
return this.#account_index;
}
get context(): Context {
return this.#context;
}
get player(): Player | undefined {
return this.#player;
return this.context.client.clientName;
}
get lang(): string {
return this.#context.client.hl;
return this.context.client.hl;
}
}

View File

@@ -1,55 +0,0 @@
import Tab from '../parser/classes/Tab';
import Feed from './Feed';
import { InnertubeError } from '../utils/Utils';
import type Actions from './Actions';
import type { ObservedArray } from '../parser/helpers';
class TabbedFeed extends Feed {
#tabs: ObservedArray<Tab>;
#actions: Actions;
constructor(actions: Actions, data: any, already_parsed = false) {
super(actions, data, already_parsed);
this.#actions = actions;
this.#tabs = this.page.contents_memo.getType(Tab);
}
get tabs(): string[] {
return this.#tabs.map((tab) => tab.title.toString());
}
async getTabByName(title: string): Promise<TabbedFeed> {
const tab = this.#tabs.find((tab) => tab.title.toLowerCase() === title.toLowerCase());
if (!tab)
throw new InnertubeError(`Tab "${title}" not found`);
if (tab.selected)
return this;
const response = await tab.endpoint.call(this.#actions);
return new TabbedFeed(this.#actions, response.data, false);
}
async getTabByURL(url: string): Promise<TabbedFeed> {
const tab = this.#tabs.find((tab) => tab.endpoint.metadata.url?.split('/').pop() === url);
if (!tab)
throw new InnertubeError(`Tab "${url}" not found`);
if (tab.selected)
return this;
const response = await tab.endpoint.call(this.#actions);
return new TabbedFeed(this.#actions, response.data, false);
}
get title(): string | undefined {
return this.page.contents_memo.getType(Tab)?.find((tab) => tab.selected)?.title.toString();
}
}
export default TabbedFeed;

118
src/core/clients/Kids.ts Normal file
View File

@@ -0,0 +1,118 @@
import { Parser } from '../../parser/index.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,
PlayerEndpoint, SearchEndpoint
} from '../endpoints/index.js';
import { BlocklistPickerEndpoint } from '../endpoints/kids/index.js';
import type { Session, ApiResponse } from '../index.js';
export default class Kids {
#session: Session;
constructor(session: Session) {
this.#session = session;
}
/**
* Searches the given query.
* @param query - The query.
*/
async search(query: string): Promise<Search> {
const response = await this.#session.actions.execute(
SearchEndpoint.PATH, SearchEndpoint.build({ client: 'YTKIDS', query })
);
return new Search(this.#session.actions, response);
}
/**
* Retrieves video info.
* @param video_id - The video id.
*/
async getInfo(video_id: string): Promise<VideoInfo> {
const player_payload = PlayerEndpoint.build({
sts: this.#session.player?.sts,
client: 'YTKIDS',
video_id
});
const next_payload = NextEndpoint.build({
video_id,
client: 'YTKIDS'
});
const player_response = this.#session.actions.execute(PlayerEndpoint.PATH, player_payload);
const next_response = this.#session.actions.execute(NextEndpoint.PATH, next_payload);
const response = await Promise.all([ player_response, next_response ]);
const cpn = generateRandomString(16);
return new VideoInfo(response, this.#session.actions, cpn);
}
/**
* Retrieves the contents of the given channel.
* @param channel_id - The channel id.
*/
async getChannel(channel_id: string): Promise<Channel> {
const response = await this.#session.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
browse_id: channel_id,
client: 'YTKIDS'
})
);
return new Channel(this.#session.actions, response);
}
/**
* Retrieves the home feed.
*/
async getHomeFeed(): Promise<HomeFeed> {
const response = await this.#session.actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
browse_id: 'FEkids_home',
client: 'YTKIDS'
})
);
return new HomeFeed(this.#session.actions, response);
}
/**
* Retrieves the list of supervised accounts that the signed-in user has
* access to, and blocks the given channel for each of them.
* @param channel_id - The channel id to block.
* @returns A list of API responses.
*/
async blockChannel(channel_id: string): Promise<ApiResponse[]> {
if (!this.#session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
const blocklist_payload = BlocklistPickerEndpoint.build({ channel_id: channel_id });
const response = await this.#session.actions.execute(BlocklistPickerEndpoint.PATH, blocklist_payload );
const popup = response.data.command.confirmDialogEndpoint;
const popup_fragment = { contents: popup.content, engagementPanels: [] };
const kid_picker = Parser.parseResponse(popup_fragment);
const kids = kid_picker.contents_memo?.getType(KidsBlocklistPickerItem);
if (!kids)
throw new InnertubeError('Could not find any kids profiles or supervised accounts.');
// Iterate through the kids and block the channel if not already blocked.
const responses: ApiResponse[] = [];
for (const kid of kids) {
if (!kid.block_button?.is_toggled) {
kid.setActions(this.#session.actions);
// Block channel and add to the response list.
responses.push(await kid.blockChannel());
}
}
return responses;
}
}

View File

@@ -1,34 +1,36 @@
import * as Proto from '../../proto/index.js';
import { InnertubeError, generateRandomString, throwIfMissing } from '../../utils/Utils.js';
import Album from '../parser/ytmusic/Album';
import Artist from '../parser/ytmusic/Artist';
import Explore from '../parser/ytmusic/Explore';
import HomeFeed from '../parser/ytmusic/HomeFeed';
import Library from '../parser/ytmusic/Library';
import Playlist from '../parser/ytmusic/Playlist';
import Recap from '../parser/ytmusic/Recap';
import Search from '../parser/ytmusic/Search';
import TrackInfo from '../parser/ytmusic/TrackInfo';
import {
Album, Artist, Explore,
HomeFeed, Library, Playlist,
Recap, Search, TrackInfo
} from '../../parser/ytmusic/index.js';
import AutomixPreviewVideo from '../parser/classes/AutomixPreviewVideo';
import Message from '../parser/classes/Message';
import MusicCarouselShelf from '../parser/classes/MusicCarouselShelf';
import MusicDescriptionShelf from '../parser/classes/MusicDescriptionShelf';
import MusicQueue from '../parser/classes/MusicQueue';
import MusicTwoRowItem from '../parser/classes/MusicTwoRowItem';
import PlaylistPanel from '../parser/classes/PlaylistPanel';
import SearchSuggestionsSection from '../parser/classes/SearchSuggestionsSection';
import SectionList from '../parser/classes/SectionList';
import Tab from '../parser/classes/Tab';
import AutomixPreviewVideo from '../../parser/classes/AutomixPreviewVideo.js';
import Message from '../../parser/classes/Message.js';
import MusicDescriptionShelf from '../../parser/classes/MusicDescriptionShelf.js';
import MusicQueue from '../../parser/classes/MusicQueue.js';
import MusicTwoRowItem from '../../parser/classes/MusicTwoRowItem.js';
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 { observe } from '../parser/helpers';
import Proto from '../proto';
import { generateRandomString, InnertubeError, throwIfMissing } from '../utils/Utils';
import {
BrowseEndpoint,
NextEndpoint,
PlayerEndpoint,
SearchEndpoint
} from '../endpoints/index.js';
import type { ObservedArray, YTNode } from '../parser/helpers';
import type Actions from './Actions';
import type Session from './Session';
import { GetSearchSuggestionsEndpoint } from '../endpoints/music/index.js';
class Music {
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;
@@ -52,25 +54,23 @@ class Music {
}
async #fetchInfoFromVideoId(video_id: string): Promise<TrackInfo> {
const player_payload = PlayerEndpoint.build({
video_id,
sts: this.#session.player?.sts,
client: 'YTMUSIC'
});
const next_payload = NextEndpoint.build({
video_id,
client: 'YTMUSIC'
});
const player_response = this.#actions.execute(PlayerEndpoint.PATH, player_payload);
const next_response = this.#actions.execute(NextEndpoint.PATH, next_payload);
const response = await Promise.all([ player_response, next_response ]);
const cpn = generateRandomString(16);
const initial_info = this.#actions.execute('/player', {
cpn,
client: 'YTMUSIC',
videoId: video_id,
playbackContext: {
contentPlaybackContext: {
signatureTimestamp: this.#session.player?.sts || 0
}
}
});
const continuation = this.#actions.execute('/next', {
client: 'YTMUSIC',
videoId: video_id
});
const response = await Promise.all([ initial_info, continuation ]);
return new TrackInfo(response, this.#actions, cpn);
}
@@ -81,25 +81,26 @@ class Music {
if (!list_item.endpoint)
throw new Error('This item does not have an endpoint.');
const cpn = generateRandomString(16);
const initial_info = list_item.endpoint.call(this.#actions, {
cpn,
const player_response = list_item.endpoint.call(this.#actions, {
client: 'YTMUSIC',
playbackContext: {
contentPlaybackContext: {
signatureTimestamp: this.#session.player?.sts || 0
...{
signatureTimestamp: this.#session.player?.sts
}
}
}
});
const continuation = list_item.endpoint.call(this.#actions, {
const next_response = list_item.endpoint.call(this.#actions, {
client: 'YTMUSIC',
enablePersistentPlaylistPanel: true,
override_endpoint: '/next'
});
const response = await Promise.all([ initial_info, continuation ]);
const cpn = generateRandomString(16);
const response = await Promise.all([ player_response, next_response ]);
return new TrackInfo(response, this.#actions, cpn);
}
@@ -108,34 +109,29 @@ class Music {
* @param query - Search query.
* @param filters - Search filters.
*/
async search(query: string, filters: {
type?: 'all' | 'song' | 'video' | 'album' | 'playlist' | 'artist';
} = {}): Promise<Search> {
async search(query: string, filters: MusicSearchFilters = {}): Promise<Search> {
throwIfMissing({ query });
const payload: {
query: string;
client: string;
params?: string;
} = { query, client: 'YTMUSIC' };
const response = await this.#actions.execute(
SearchEndpoint.PATH, SearchEndpoint.build({
query, client: 'YTMUSIC',
params: filters.type && filters.type !== 'all' ? Proto.encodeMusicSearchFilters(filters) : undefined
})
);
if (filters.type && filters.type !== 'all') {
payload.params = Proto.encodeMusicSearchFilters(filters);
}
const response = await this.#actions.execute('/search', payload);
return new Search(response, this.#actions, { is_filtered: Reflect.has(filters, 'type') && filters.type !== 'all' });
return new Search(response, this.#actions, Reflect.has(filters, 'type') && filters.type !== 'all');
}
/**
* Retrieves the home feed.
*/
async getHomeFeed(): Promise<HomeFeed> {
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: 'FEmusic_home'
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
browse_id: 'FEmusic_home',
client: 'YTMUSIC'
})
);
return new HomeFeed(response, this.#actions);
}
@@ -144,10 +140,12 @@ class Music {
* Retrieves the Explore feed.
*/
async getExplore(): Promise<Explore> {
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: 'FEmusic_explore'
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC',
browse_id: 'FEmusic_explore'
})
);
return new Explore(response);
// TODO: return new Explore(response, this.#actions);
@@ -157,10 +155,12 @@ class Music {
* Retrieves the library.
*/
async getLibrary(): Promise<Library> {
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: 'FEmusic_library_landing'
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC',
browse_id: 'FEmusic_library_landing'
})
);
return new Library(response, this.#actions);
}
@@ -175,10 +175,12 @@ class Music {
if (!artist_id.startsWith('UC') && !artist_id.startsWith('FEmusic_library_privately_owned_artist'))
throw new InnertubeError('Invalid artist id', artist_id);
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: artist_id
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC',
browse_id: artist_id
})
);
return new Artist(response, this.#actions);
}
@@ -193,12 +195,14 @@ class Music {
if (!album_id.startsWith('MPR') && !album_id.startsWith('FEmusic_library_privately_owned_release'))
throw new InnertubeError('Invalid album id', album_id);
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: album_id
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC',
browse_id: album_id
})
);
return new Album(response, this.#actions);
return new Album(response);
}
/**
@@ -212,10 +216,12 @@ class Music {
playlist_id = `VL${playlist_id}`;
}
const response = await this.#actions.execute('/browse', {
client: 'YTMUSIC',
browseId: playlist_id
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC',
browse_id: playlist_id
})
);
return new Playlist(response, this.#actions);
}
@@ -228,15 +234,13 @@ class Music {
async getUpNext(video_id: string, automix = true): Promise<PlaylistPanel> {
throwIfMissing({ video_id });
const data = await this.#actions.execute('/next', {
videoId: video_id,
client: 'YTMUSIC',
parse: true
});
const response = await this.#actions.execute(
NextEndpoint.PATH, { ...NextEndpoint.build({ video_id, client: 'YTMUSIC' }), parse: true }
);
const tabs = data.contents_memo.getType(Tab);
const tabs = response.contents_memo?.getType(Tab);
const tab = tabs?.[0];
const tab = tabs?.first();
if (!tab)
throw new InnertubeError('Could not find target tab.');
@@ -260,10 +264,10 @@ class Music {
parse: true
});
if (!page)
if (!page || !page.contents_memo)
throw new InnertubeError('Could not fetch automix');
return page.contents_memo.getType(PlaylistPanel)?.[0];
return page.contents_memo.getType(PlaylistPanel).first();
}
return playlist_panel;
@@ -273,16 +277,14 @@ class Music {
* Retrieves related content.
* @param video_id - The video id.
*/
async getRelated(video_id: string): Promise<ObservedArray<MusicCarouselShelf | MusicDescriptionShelf>> {
async getRelated(video_id: string): Promise<SectionList | Message> {
throwIfMissing({ video_id });
const data = await this.#actions.execute('/next', {
videoId: video_id,
client: 'YTMUSIC',
parse: true
});
const response = await this.#actions.execute(
NextEndpoint.PATH, { ...NextEndpoint.build({ video_id, client: 'YTMUSIC' }), parse: true }
);
const tabs = data.contents_memo.getType(Tab);
const tabs = response.contents_memo?.getType(Tab);
const tab = tabs?.matchCondition((tab) => tab.endpoint.payload.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType === 'MUSIC_PAGE_TYPE_TRACK_RELATED');
@@ -291,9 +293,12 @@ class Music {
const page = await tab.endpoint.call(this.#actions, { client: 'YTMUSIC', parse: true });
const shelves = page.contents.item().as(SectionList).contents.as(MusicCarouselShelf, MusicDescriptionShelf);
if (!page.contents)
throw new InnertubeError('Unexpected response', page);
return shelves;
const contents = page.contents.item().as(SectionList, Message);
return contents;
}
/**
@@ -303,13 +308,11 @@ class Music {
async getLyrics(video_id: string): Promise<MusicDescriptionShelf | undefined> {
throwIfMissing({ video_id });
const data = await this.#actions.execute('/next', {
videoId: video_id,
client: 'YTMUSIC',
parse: true
});
const response = await this.#actions.execute(
NextEndpoint.PATH, { ...NextEndpoint.build({ video_id, client: 'YTMUSIC' }), parse: true }
);
const tabs = data.contents_memo.getType(Tab);
const tabs = response.contents_memo?.getType(Tab);
const tab = tabs?.matchCondition((tab) => tab.endpoint.payload.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType === 'MUSIC_PAGE_TYPE_TRACK_LYRICS');
@@ -318,10 +321,14 @@ class Music {
const page = await tab.endpoint.call(this.#actions, { client: 'YTMUSIC', parse: true });
if (page.contents.item().key('type').string() === 'Message')
throw new InnertubeError(page.contents.item().as(Message).text, video_id);
if (!page.contents)
throw new InnertubeError('Unexpected response', page);
if (page.contents.item().type === 'Message')
throw new InnertubeError(page.contents.item().as(Message).text.toString(), video_id);
const section_list = page.contents.item().as(SectionList).contents;
return section_list.firstOfType(MusicDescriptionShelf);
}
@@ -329,10 +336,12 @@ class Music {
* Retrieves recap.
*/
async getRecap(): Promise<Recap> {
const response = await this.#actions.execute('/browse', {
browseId: 'FEmusic_listening_review',
client: 'YTMUSIC_ANDROID'
});
const response = await this.#actions.execute(
BrowseEndpoint.PATH, BrowseEndpoint.build({
client: 'YTMUSIC_ANDROID',
browse_id: 'FEmusic_listening_review'
})
);
return new Recap(response, this.#actions);
}
@@ -341,20 +350,17 @@ class Music {
* Retrieves search suggestions for the given query.
* @param query - The query.
*/
async getSearchSuggestions(query: string): Promise<ObservedArray<YTNode>> {
const response = await this.#actions.execute('/music/get_search_suggestions', {
parse: true,
input: query,
client: 'YTMUSIC'
});
async getSearchSuggestions(query: string): Promise<ObservedArray<SearchSuggestionsSection>> {
const response = await this.#actions.execute(
GetSearchSuggestionsEndpoint.PATH,
{ ...GetSearchSuggestionsEndpoint.build({ input: query }), parse: true }
);
const search_suggestions_section = response.contents_memo.getType(SearchSuggestionsSection)?.[0];
if (!response.contents_memo)
return [] as unknown as ObservedArray<SearchSuggestionsSection>;
if (!search_suggestions_section?.contents.is_array)
return observe([] as YTNode[]);
const search_suggestions_sections = response.contents_memo.getType(SearchSuggestionsSection);
return search_suggestions_section?.contents.array();
return search_suggestions_sections;
}
}
export default Music;
}

View File

@@ -1,9 +1,10 @@
import Proto from '../proto';
import { Constants } from '../utils';
import { InnertubeError, MissingParamError, uuidv4 } from '../utils/Utils';
import * as Proto from '../../proto/index.js';
import { Constants } from '../../utils/index.js';
import { InnertubeError, MissingParamError, Platform } from '../../utils/Utils.js';
import { CreateVideoEndpoint } from '../endpoints/upload/index.js';
import type { ApiResponse } from './Actions';
import type Session from './Session';
import type { UpdateVideoMetadataOptions, UploadedVideoMetadataOptions } from '../../types/Clients.js';
import type { ApiResponse, Session } from '../index.js';
interface UploadResult {
status: string;
@@ -18,25 +19,7 @@ interface InitialUploadData {
chunk_granularity: string;
}
export interface VideoMetadata {
title?: string;
description?: string;
tags?: string[];
category?: number;
license?: string;
age_restricted?: boolean;
made_for_kids?: boolean;
privacy?: 'PUBLIC' | 'PRIVATE' | 'UNLISTED';
}
export interface UploadedVideoMetadata {
title?: string;
description?: string;
privacy?: 'PUBLIC' | 'PRIVATE' | 'UNLISTED';
is_draft?: boolean;
}
class Studio {
export default class Studio {
#session: Session;
constructor(session: Session) {
@@ -69,7 +52,7 @@ class Studio {
}
/**
* Updates given video's metadata.
* Updates a given video's metadata.
* @example
* ```ts
* const response = await yt.studio.updateVideoMetadata('videoid', {
@@ -82,7 +65,7 @@ class Studio {
* });
* ```
*/
async updateVideoMetadata(video_id: string, metadata: VideoMetadata): Promise<ApiResponse> {
async updateVideoMetadata(video_id: string, metadata: UpdateVideoMetadataOptions): Promise<ApiResponse> {
if (!this.#session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
@@ -104,7 +87,7 @@ class Studio {
* const response = await yt.studio.upload(file.buffer, { title: 'Wow!' });
* ```
*/
async upload(file: BodyInit, metadata: UploadedVideoMetadata = {}): Promise<ApiResponse> {
async upload(file: BodyInit, metadata: UploadedVideoMetadataOptions = {}): Promise<ApiResponse> {
if (!this.#session.logged_in)
throw new InnertubeError('You must be signed in to perform this operation.');
@@ -120,12 +103,12 @@ class Studio {
}
async #getInitialUploadData(): Promise<InitialUploadData> {
const frontend_upload_id = `innertube_android:${uuidv4()}:0:v=3,api=1,cf=3`;
const frontend_upload_id = `innertube_android:${Platform.shim.uuidv4()}:0:v=3,api=1,cf=3`;
const payload = {
frontendUploadId: frontend_upload_id,
deviceDisplayName: 'Pixel 6 Pro',
fileId: `goog-edited-video://generated?videoFileUri=content://media/external/video/media/${uuidv4()}`,
fileId: `goog-edited-video://generated?videoFileUri=content://media/external/video/media/${Platform.shim.uuidv4()}`,
mp4MoovAtomRelocationStatus: 'UNSUPPORTED',
transcodeResult: 'DISABLED',
connectionType: 'WIFI'
@@ -174,38 +157,34 @@ class Studio {
return data;
}
async #setVideoMetadata(initial_data: InitialUploadData, upload_result: UploadResult, metadata: UploadedVideoMetadata) {
const metadata_payload = {
resourceId: {
scottyResourceId: {
id: upload_result.scottyResourceId
}
},
frontendUploadId: initial_data.frontend_upload_id,
initialMetadata: {
title: {
newTitle: metadata.title || new Date().toDateString()
async #setVideoMetadata(initial_data: InitialUploadData, upload_result: UploadResult, metadata: UploadedVideoMetadataOptions) {
const response = await this.#session.actions.execute(
CreateVideoEndpoint.PATH, CreateVideoEndpoint.build({
resource_id: {
scotty_resource_id: {
id: upload_result.scottyResourceId
}
},
description: {
newDescription: metadata.description || '',
shouldSegment: true
frontend_upload_id: initial_data.frontend_upload_id,
initial_metadata: {
title: {
new_title: metadata.title || new Date().toDateString()
},
description: {
new_description: metadata.description || '',
should_segment: true
},
privacy: {
new_privacy: metadata.privacy || 'PRIVATE'
},
draft_state: {
is_draft: metadata.is_draft
}
},
privacy: {
newPrivacy: metadata.privacy || 'PRIVATE'
},
draftState: {
isDraft: metadata.is_draft || false
}
}
};
const response = await this.#session.actions.execute('/upload/createvideo', {
client: 'ANDROID',
...metadata_payload
});
client: 'ANDROID'
})
);
return response;
}
}
export default Studio;
}

View File

@@ -0,0 +1,3 @@
export { default as Kids } from './Kids.js';
export { default as Music } from './Music.js';
export { default as Studio } from './Studio.js';

View File

@@ -0,0 +1,19 @@
import type { IBrowseRequest, BrowseEndpointOptions } from '../../types/index.js';
export const PATH = '/browse';
/**
* Builds a `/browse` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: BrowseEndpointOptions): IBrowseRequest {
return {
...{
browseId: opts.browse_id,
params: opts.params,
continuation: opts.continuation,
client: opts.client
}
};
}

View File

@@ -0,0 +1,16 @@
import type { IGetNotificationMenuRequest, GetNotificationMenuEndpointOptions } from '../../types/index.js';
export const PATH = '/notification/get_notification_menu';
/**
* Builds a `/get_notification_menu` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: GetNotificationMenuEndpointOptions): IGetNotificationMenuRequest {
return {
...{
notificationsMenuRequestType: opts.notifications_menu_request_type
}
};
}

View File

@@ -0,0 +1 @@
export const PATH = '/guide';

View File

@@ -0,0 +1,21 @@
import type { INextRequest, NextEndpointOptions } from '../../types/index.js';
export const PATH = '/next';
/**
* Builds a `/next` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: NextEndpointOptions): INextRequest {
return {
...{
videoId: opts.video_id,
playlistId: opts.playlist_id,
params: opts.params,
playlistIndex: opts.playlist_index,
client: opts.client,
continuation: opts.continuation
}
};
}

View File

@@ -0,0 +1,43 @@
import type { IPlayerRequest, PlayerEndpointOptions } from '../../types/index.js';
export const PATH = '/player';
/**
* Builds a `/player` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: PlayerEndpointOptions): IPlayerRequest {
return {
playbackContext: {
contentPlaybackContext: {
vis: 0,
splay: false,
referer: opts.playlist_id ?
`https://www.youtube.com/watch?v=${opts.video_id}&list=${opts.playlist_id}` :
`https://www.youtube.com/watch?v=${opts.video_id}`,
currentUrl: opts.playlist_id ?
`/watch?v=${opts.video_id}&list=${opts.playlist_id}` :
`/watch?v=${opts.video_id}`,
autonavState: 'STATE_ON',
autoCaptionsDefaultOn: false,
html5Preference: 'HTML5_PREF_WANTS',
lactMilliseconds: '-1',
...{
signatureTimestamp: opts.sts
}
}
},
attestationRequest: {
omitBotguardData: true
},
racyCheckOk: true,
contentCheckOk: true,
videoId: opts.video_id,
...{
client: opts.client,
playlistId: opts.playlist_id,
params: opts.params
}
};
}

View File

@@ -0,0 +1,16 @@
import type { IResolveURLRequest, ResolveURLEndpointOptions } from '../../types/index.js';
export const PATH = '/navigation/resolve_url';
/**
* Builds a `/resolve_url` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: ResolveURLEndpointOptions): IResolveURLRequest {
return {
...{
url: opts.url
}
};
}

View File

@@ -0,0 +1,19 @@
import type { ISearchRequest, SearchEndpointOptions } from '../../types/index.js';
export const PATH = '/search';
/**
* Builds a `/search` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: SearchEndpointOptions): ISearchRequest {
return {
...{
query: opts.query,
params: opts.params,
continuation: opts.continuation,
client: opts.client
}
};
}

View File

@@ -0,0 +1,13 @@
import type { IAccountListRequest } from '../../../types/index.js';
export const PATH = '/account/accounts_list';
/**
* Builds a `/account/accounts_list` request payload.
* @returns The payload.
*/
export function build(): IAccountListRequest {
return {
client: 'ANDROID'
};
}

View File

@@ -0,0 +1 @@
export * as AccountListEndpoint from './AccountListEndpoint.js';

View File

@@ -0,0 +1,24 @@
import type { IEditPlaylistRequest, EditPlaylistEndpointOptions } from '../../../types/index.js';
export const PATH = '/browse/edit_playlist';
/**
* Builds a `/browse/edit_playlist` request payload.
* @param opts - The options to use.
* @returns The payload.
*/
export function build(opts: EditPlaylistEndpointOptions): IEditPlaylistRequest {
return {
playlistId: opts.playlist_id,
actions: opts.actions.map((action) => ({
action: action.action,
...{
addedVideoId: action.added_video_id,
setVideoId: action.set_video_id,
movedSetVideoIdPredecessor: action.moved_set_video_id_predecessor,
playlistDescription: action.playlist_description,
playlistName: action.playlist_name
}
}))
};
}

View File

@@ -0,0 +1 @@
export * as EditPlaylistEndpoint from './EditPlaylistEndpoint.js';

View File

@@ -0,0 +1,15 @@
import type { IChannelEditDescriptionRequest, ChannelEditDescriptionEndpointOptions } from '../../../types/Endpoints.js';
export const PATH = '/channel/edit_description';
/**
* Builds a `/channel/edit_description` request payload.
* @param options - The options to use.
* @returns The payload.
*/
export function build(options: ChannelEditDescriptionEndpointOptions): IChannelEditDescriptionRequest {
return {
givenDescription: options.given_description,
client: 'ANDROID'
};
}

View File

@@ -0,0 +1,15 @@
import type { IChannelEditNameRequest, ChannelEditNameEndpointOptions } from '../../../types/index.js';
export const PATH = '/channel/edit_name';
/**
* Builds a `/channel/edit_name` request payload.
* @param options - The options to use.
* @returns The payload.
*/
export function build(options: ChannelEditNameEndpointOptions): IChannelEditNameRequest {
return {
givenName: options.given_name,
client: 'ANDROID'
};
}

View File

@@ -0,0 +1,2 @@
export * as EditNameEndpoint from './EditNameEndpoint.js';
export * as EditDescriptionEndpoint from './EditDescriptionEndpoint.js';

View File

@@ -0,0 +1,18 @@
import type { ICreateCommentRequest, CreateCommentEndpointOptions } from '../../../types/index.js';
export const PATH = '/comment/create_comment';
/**
* Builds a `/comment/create_comment` request payload.
* @param options - The options to use.
* @returns The payload.
*/
export function build(options: CreateCommentEndpointOptions): ICreateCommentRequest {
return {
commentText: options.comment_text,
createCommentParams: options.create_comment_params,
...{
client: options.client
}
};
}

View File

@@ -0,0 +1,17 @@
import type { IPerformCommentActionRequest, PerformCommentActionEndpointOptions } from '../../../types/index.js';
export const PATH = '/comment/perform_comment_action';
/**
* Builds a `/comment/perform_comment_action` request payload.
* @param options - The options to use.
* @returns The payload.
*/
export function build(options: PerformCommentActionEndpointOptions): IPerformCommentActionRequest {
return {
actions: options.actions,
...{
client: options.client
}
};
}

View File

@@ -0,0 +1,2 @@
export * as PerformCommentActionEndpoint from './PerformCommentActionEndpoint.js';
export * as CreateCommentEndpoint from './CreateCommentEndpoint.js';

View File

@@ -0,0 +1,20 @@
export * as BrowseEndpoint from './BrowseEndpoint.js';
export * as GetNotificationMenuEndpoint from './GetNotificationMenuEndpoint.js';
export * as GuideEndpoint from './GuideEndpoint.js';
export * as NextEndpoint from './NextEndpoint.js';
export * as PlayerEndpoint from './PlayerEndpoint.js';
export * as ResolveURLEndpoint from './ResolveURLEndpoint.js';
export * as SearchEndpoint from './SearchEndpoint.js';
export * as Account from './account/index.js';
export * as Browse from './browse/index.js';
export * as Channel from './channel/index.js';
export * as Comment from './comment/index.js';
export * as Like from './like/index.js';
export * as Music from './music/index.js';
export * as Notification from './notification/index.js';
export * as Playlist from './playlist/index.js';
export * as Subscription from './subscription/index.js';
export * as Reel from './reel/index.js';
export * as Upload from './upload/index.js';
export * as Kids from './kids/index.js';

View File

@@ -0,0 +1,12 @@
import type { IBlocklistPickerRequest, BlocklistPickerRequestEndpointOptions } from '../../../types/index.js';
export const PATH = '/kids/get_kids_blocklist_picker';
/**
* Builds a `/kids/get_kids_blocklist_picker` request payload.
* @param options - The options to use.
* @returns The payload.
*/
export function build(options: BlocklistPickerRequestEndpointOptions): IBlocklistPickerRequest {
return { blockedForKidsContent: { external_channel_id: options.channel_id } };
}

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