forked from TimeForANinja/node-ytsr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
executable file
·187 lines (169 loc) · 5.25 KB
/
main.js
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
const PARSE_ITEM = require('./parseItem.js');
const { request } = require('undici');
const UTIL = require('./util.js');
const BASE_SEARCH_URL = 'https://www.youtube.com/results';
const BASE_API_URL = 'https://www.youtube.com/youtubei/v1/search';
const CACHE = new Map([
// ['apiKey', 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'],
['clientVersion', '2.20240606.06.00'],
['playlistParams', 'EgIQAw%3D%3D'],
]);
const saveCache = (parsed, opts) => {
// if (parsed.apiKey) CACHE.set('apiKey', parsed.apiKey);
// else if (CACHE.has('apiKey')) parsed.apiKey = CACHE.get('apiKey');
if (parsed.context && parsed.context.client && parsed.context.client.clientVersion) {
CACHE.set('clientVersion', parsed.context.client.clientVersion);
} else if (CACHE.has('clientVersion')) {
parsed.context = UTIL.buildPostContext(CACHE.get('clientVersion'), opts);
}
const plParams =
UTIL.getPlaylistParams(parsed) ||
(parsed.body ? UTIL.betweenFromRight(parsed.body, `"params":"`, '"}},"tooltip":"Search for Playlist"') : null);
if (plParams) CACHE.set('playlistParams', plParams);
};
// eslint-disable-next-line complexity
const main = (module.exports = async (searchString, options, rt = 3) => {
UTIL.checkForUpdates();
if (rt === 2) {
// CACHE.delete('apiKey');
CACHE.delete('clientVersion');
CACHE.delete('playlistParams');
}
if (rt === 0) throw new Error('Unable to find JSON!');
// Set default values
const opts = UTIL.checkArgs(searchString, options);
let parsed = {};
if (
!opts.safeSearch ||
!CACHE.has('clientVersion') ||
!CACHE.has('playlistParams')
// || !CACHE.has('apiKey')
) {
const res = await request(BASE_SEARCH_URL, Object.assign({}, opts.requestOptions, { query: opts.query }));
const body = await res.body.text();
parsed = UTIL.parseBody(body, opts);
}
saveCache(parsed, opts);
if (opts.type === 'playlist') {
const params = CACHE.get('playlistParams');
parsed.json = await UTIL.doPost(
BASE_API_URL,
Object.assign({}, opts.requestOptions, {
query: {
// key: parsed.apiKey,
prettyPrint: false,
},
}),
{
context: parsed.context,
params,
query: searchString,
},
);
if (!parsed.json) throw new Error('Cannot searching for Playlist!');
} else if (opts.safeSearch || !parsed.json) {
try {
parsed.json = await UTIL.doPost(
BASE_API_URL,
Object.assign({}, opts.requestOptions, {
query: {
// key: parsed.apiKey,
prettyPrint: false,
},
}),
{
context: parsed.context,
query: searchString,
},
);
} catch (e) {
if (rt === 1) throw e;
}
}
if (!parsed.json) return main(searchString, options, rt - 1);
const resp = { query: opts.search };
try {
// Parse items
const { rawItems, continuation } = UTIL.parseWrapper(
parsed.json.contents.twoColumnSearchResultsRenderer.primaryContents,
);
// Parse items
resp.items = rawItems
.map(a => PARSE_ITEM(a, resp))
.filter(r => r && r.type === opts.type)
.filter((_, index) => index < opts.limit);
// Adjust tracker
opts.limit -= resp.items.length;
// Get amount of results
resp.results = Number(parsed.json.estimatedResults) || 0;
let token = null;
if (continuation) token = continuation.continuationItemRenderer.continuationEndpoint.continuationCommand.token;
// We're already on last page or hit the limit
if (!token || opts.limit < 1) return resp;
// Recursively fetch more items
const nestedResp = await parsePage2(
// parsed.apiKey,
token,
parsed.context,
opts,
);
// Merge the responses
resp.items.push(...nestedResp);
return resp;
} catch (e) {
parsed.query = searchString;
parsed.requestOptions = opts.requestOptions;
parsed.error = UTIL.errorToObject(e);
UTIL.logger(parsed);
throw e;
}
});
const parsePage2 = async (
// apiKey,
token,
context,
opts,
) => {
const json = await UTIL.doPost(
BASE_API_URL,
Object.assign({}, opts.requestOptions, {
query: {
// key: apiKey,
prettyPrint: false,
},
}),
{ context, continuation: token },
);
if (!Array.isArray(json.onResponseReceivedCommands)) {
// No more content
return [];
}
try {
const { rawItems, continuation } = UTIL.parsePage2Wrapper(
json.onResponseReceivedCommands[0].appendContinuationItemsAction.continuationItems,
);
const parsedItems = rawItems
.map(PARSE_ITEM)
.filter(r => r && r.type === opts.type)
.filter((_, index) => index < opts.limit);
// Adjust tracker
opts.limit -= parsedItems.length;
let nextToken = null;
if (continuation) nextToken = continuation.continuationItemRenderer.continuationEndpoint.continuationCommand.token;
// We're already on last page or hit the limit
if (!nextToken || opts.limit < 1) return parsedItems;
// Recursively fetch more items
const nestedResp = await parsePage2(
// apiKey,
nextToken,
context,
opts,
);
parsedItems.push(...nestedResp);
return parsedItems;
} catch (e) {
json.error = UTIL.errorToObject(e);
UTIL.logger(json);
return [];
}
};