-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathYTMusic.ts
More file actions
228 lines (196 loc) Β· 6.21 KB
/
Copy pathYTMusic.ts
File metadata and controls
228 lines (196 loc) Β· 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { config } from '../renderer/renderer';
import type { LyricProvider, LyricResult, SearchSongInfo } from '../types';
import type { MusicPlayerAppElement } from '@/types/music-player-app-element';
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
const client = {
clientName: '26',
clientVersion: '7.01.05',
};
export class YTMusic implements LyricProvider {
public name = 'YTMusic';
public baseUrl =
'https://music.\u0079\u006f\u0075\u0074\u0075\u0062\u0065.com/';
// prettier-ignore
public async search(
{ videoId, title, artist }: SearchSongInfo,
): Promise<LyricResult | null> {
const data = await this.fetchNext(videoId);
const { tabs } =
data?.contents?.singleColumnMusicWatchNextResultsRenderer?.tabbedRenderer
?.watchNextTabbedResultsRenderer ?? {};
if (!Array.isArray(tabs)) return null;
const lyricsTab = tabs.find((it) => {
const pageType = it?.tabRenderer?.endpoint?.browseEndpoint
?.browseEndpointContextSupportedConfigs
?.browseEndpointContextMusicConfig?.pageType;
return pageType === 'MUSIC_PAGE_TYPE_TRACK_LYRICS';
});
if (!lyricsTab) return null;
const { browseId } = lyricsTab?.tabRenderer?.endpoint?.browseEndpoint ?? {};
if (!browseId) return null;
const { contents } = await this.fetchBrowse(browseId);
if (!contents) return null;
/*
NOTE: Due to the nature of the library, the json responses are not consistent,
this means we have to check for multiple possible paths to get the lyrics.
*/
const syncedLines = contents?.elementRenderer?.newElement?.type
?.componentType?.model?.timedLyricsModel?.lyricsData?.timedLyricsData;
const synced = syncedLines?.length && syncedLines[0]?.cueRange
? syncedLines.map((it) => ({
time: this.millisToTime(parseInt(it.cueRange.startTimeMilliseconds)),
timeInMs: parseInt(it.cueRange.startTimeMilliseconds),
duration: parseInt(it.cueRange.endTimeMilliseconds) -
parseInt(it.cueRange.startTimeMilliseconds),
text: it.lyricLine.trim() === 'βͺ' ? '' : it.lyricLine.trim(),
status: 'upcoming' as const,
}))
: undefined;
const plain = !synced
? syncedLines?.length
? syncedLines.map((it) => it.lyricLine).join('\n')
: contents?.messageRenderer
? contents?.messageRenderer?.text?.runs?.map((it) => it.text).join('\n')
: contents?.sectionListRenderer?.contents?.[0]
?.musicDescriptionShelfRenderer?.description?.runs?.map((it) =>
it.text
)?.join('\n')
: undefined;
if (typeof plain === 'string' && plain === 'Lyrics not available') {
return null;
}
if (synced?.length && synced[0].timeInMs > 300) {
synced.unshift({
duration: 0,
text: '',
time: '00:00.00',
timeInMs: 0,
status: 'upcoming' as const,
});
}
return {
title,
artists: [artist],
lyrics: plain,
lines: synced,
};
}
private millisToTime(millis: number) {
const minutes = Math.floor(millis / 60000);
const seconds = Math.floor((millis - minutes * 60 * 1000) / 1000);
const remaining = (millis - minutes * 60 * 1000 - seconds * 1000) / 10;
return `${minutes.toString().padStart(2, '0')}:${seconds
.toString()
.padStart(2, '0')}.${remaining.toString().padStart(2, '0')}`;
}
// RATE LIMITED (2 req per sec)
private PROXIED_ENDPOINT = 'https://ytmbrowseproxy.zvz.be/';
private fetchNext(videoId: string) {
const app = document.querySelector<MusicPlayerAppElement>('ytmusic-app');
if (!app) return null;
return app.networkManager.fetch<
NextData,
{
videoId: string;
}
>('/next?prettyPrint=false', {
videoId,
});
}
private fetchBrowse(browseId: string): Promise<BrowseData> {
if (config()?.useYTMLyricsWithoutProxy) {
return this.fetchBrowseDirect(browseId);
}
return fetch(this.PROXIED_ENDPOINT + 'browse?prettyPrint=false', {
headers,
method: 'POST',
body: JSON.stringify({
browseId,
context: { client },
}),
}).then((res) => res.json()) as Promise<BrowseData>;
}
// Calls YouTube Music's browse endpoint directly via the app's authenticated
// network manager, which injects the visitor/auth tokens that the request
// would otherwise be missing when called from regions where the unauthenticated
// call is geo-restricted.
private async fetchBrowseDirect(browseId: string): Promise<BrowseData> {
const app = document.querySelector<MusicPlayerAppElement>('ytmusic-app');
if (!app) {
throw new Error('ytmusic-app element not found');
}
return await app.networkManager.fetch<BrowseData, { browseId: string }>(
'/browse?prettyPrint=false',
{ browseId },
);
}
}
interface NextData {
contents: {
singleColumnMusicWatchNextResultsRenderer: {
tabbedRenderer: {
watchNextTabbedResultsRenderer: {
tabs: {
tabRenderer: {
endpoint: {
browseEndpoint: {
browseId: string;
browseEndpointContextSupportedConfigs: {
browseEndpointContextMusicConfig: {
pageType: string;
};
};
};
};
};
}[];
};
};
};
};
}
interface BrowseData {
contents: {
elementRenderer: {
newElement: {
type: {
componentType: {
model: {
timedLyricsModel: {
lyricsData: {
timedLyricsData: SyncedLyricLine[];
};
};
};
};
};
};
};
messageRenderer: {
text: PlainLyricsTextRenderer;
};
sectionListRenderer: {
contents: {
musicDescriptionShelfRenderer: {
description: PlainLyricsTextRenderer;
};
}[];
};
};
}
interface SyncedLyricLine {
lyricLine: string;
cueRange: CueRange;
}
interface CueRange {
startTimeMilliseconds: string;
endTimeMilliseconds: string;
}
interface PlainLyricsTextRenderer {
runs: {
text: string;
}[];
}