info.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. console.log('bundle2!')
  2. printable = (platform) => {
  3. return platform === "WEB";
  4. }
  5. parseCodecs = (format) => {
  6. const mimeType = format['mimeType']
  7. if (!mimeType) {
  8. return {};
  9. }
  10. const regex = /(?<mimetype>[^/]+\/[^;]+)(?:;\s*codecs="?(?<codecs>[^"]+))?/;
  11. const match = mimeType.match(regex);
  12. if (!match) {
  13. return {};
  14. }
  15. const codecs = match.groups.codecs;
  16. if (!codecs) {
  17. return {};
  18. }
  19. const splitCodecs = codecs.trim().replace(/,$/, '').split(',').map(str => str.trim()).filter(Boolean);
  20. let vcodec = null;
  21. let acodec = null;
  22. for (const fullCodec of splitCodecs) {
  23. const codec = fullCodec.split('.')[0];
  24. if (['avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'].includes(codec)) {
  25. if (!vcodec) {
  26. vcodec = fullCodec;
  27. }
  28. } else if (['mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'].includes(codec)) {
  29. if (!acodec) {
  30. acodec = fullCodec;
  31. }
  32. } else {
  33. console.log(`WARNING: Unknown codec ${fullCodec}`);
  34. }
  35. }
  36. if (!vcodec && !acodec) {
  37. if (splitCodecs.length === 2) {
  38. return {
  39. vcodec: splitCodecs[0],
  40. acodec: splitCodecs[1]
  41. };
  42. }
  43. } else {
  44. return {
  45. vcodec: vcodec,
  46. acodec: acodec
  47. };
  48. }
  49. return {};
  50. }
  51. parseSetCookie = (headers) => {
  52. if (!headers) {
  53. return ""
  54. }
  55. const setCookie = headers['Set-Cookie']
  56. if (!setCookie) {
  57. return ""
  58. }
  59. console.log(`setCookie: ${setCookie}`)
  60. let result = 'PREF=hl=en&tz=UTC; SOCS=CAI; GPS=1; ';
  61. const needCookieNames = ['YSC', 'VISITOR_INFO1_LIVE', 'VISITOR_PRIVACY_METADATA'];
  62. for (const i in needCookieNames) {
  63. const cookieName = needCookieNames[i];
  64. const regexp = new RegExp(`${cookieName}=([^;,]+)`)
  65. const match = setCookie.match(regexp)
  66. if (match && match.length === 2) {
  67. const cookieValue = match[1]
  68. if (i != needCookieNames.length - 1) {
  69. result += `${cookieName}=${cookieValue}; `
  70. } else {
  71. result += `${cookieName}=${cookieValue}`
  72. }
  73. }
  74. }
  75. console.log(`current cookie: ${result}`)
  76. return result;
  77. }
  78. request = async (method, url, data = null, headers = {}, platform) => {
  79. if (platform === "WEB") {
  80. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  81. }
  82. console.log(`request url:${url}`)
  83. console.log(`request data:${data}`)
  84. console.log(`request method:${method}`)
  85. console.log(`request headers:${JSON.stringify((headers))}`)
  86. if (platform === "WEB") {
  87. const res = await fetch(url, {
  88. 'mode': 'cors',
  89. 'method': method,
  90. 'headers': headers,
  91. 'body': data
  92. })
  93. const resData = await res.text()
  94. return Promise.resolve({
  95. 'data': resData,
  96. 'headers': res.headers
  97. });
  98. }
  99. return new Promise((resolve, reject) => {
  100. AF.request(url, method, data, headers, (data, headers, err) => {
  101. if (err) {
  102. reject(err);
  103. } else {
  104. console.log(`response headers: ${headers}`);
  105. resolve({
  106. 'data': data,
  107. 'headers': JSON.parse(headers)
  108. });
  109. }
  110. });
  111. })
  112. }
  113. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  114. const x = string.indexOf(needleStart);
  115. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  116. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  117. }
  118. findFunction = (jsCode, regexp, platform) => {
  119. const match = jsCode.match(regexp)
  120. if (!match && match.length <= 1) {
  121. return null;
  122. }
  123. let result = "";
  124. const dependencyMatches = match[0].match(/([$a-zA-Z0-9]+\.[$a-zA-Z0-9]+)/g)
  125. const existDependencies = [];
  126. if (dependencyMatches && dependencyMatches.length >= 1) {
  127. for (let currentMatch of dependencyMatches) {
  128. const varName = currentMatch.split('.')[0];
  129. if (existDependencies.includes(varName)) {
  130. continue
  131. }
  132. const varNameMatch = jsCode.match(new RegExp(`var \\${varName}={(.|\\n)*?};`), 'ig');
  133. if (varNameMatch && varNameMatch.length >= 1) {
  134. result += varNameMatch[0] + "\n";
  135. }
  136. existDependencies.push(varName);
  137. }
  138. }
  139. result += `\n${match[0]}`;
  140. if (printable(platform)) {
  141. console.log(`decipherFunction result: ` + result);
  142. }
  143. return eval(result);
  144. };
  145. const cache = {};
  146. fetchBaseJSContent = async (baseJsUrl, platform) => {
  147. const cacheKey = `jsContent:${baseJsUrl}`;
  148. if (cache[cacheKey]) {
  149. console.log(`baseContent from cache: ${baseJsUrl}`);
  150. return cache[cacheKey];
  151. }
  152. console.log(`extract baseUrl: ${baseJsUrl}`);
  153. const baseContentResp = await request('GET', baseJsUrl, null, {
  154. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Safari/537.36',
  155. }, platform);
  156. const {data, _} = baseContentResp;
  157. cache[cacheKey] = data;
  158. return data;
  159. }
  160. extractJSSignatureFunction = async (baseJsUrl, platform) => {
  161. const cacheKey = `jsSign:${baseJsUrl}`
  162. if (cache[cacheKey]) {
  163. console.log(`jsSign from cache: ${baseJsUrl}`);
  164. return cache[cacheKey];
  165. }
  166. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  167. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{a=a\.split\(""\).*};/, platform);
  168. cache[cacheKey] = result
  169. return result
  170. }
  171. extractNJSFunction = async (baseJsUrl, platform) => {
  172. const cacheKey = `jsN:${baseJsUrl}`
  173. if (cache[cacheKey]) {
  174. console.log(`jsN from cache: ${baseJsUrl}`);
  175. return cache[cacheKey];
  176. }
  177. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  178. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{var b=a\.split\(""\)[\s\S]*?};/, platform);
  179. cache[cacheKey] = result
  180. return result
  181. }
  182. signUrl = async (signatureCipher, baseJsUrl, platform) => {
  183. const searchParams = {}
  184. for (const item of signatureCipher.split('&')) {
  185. const [key, value] = item.split('=');
  186. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  187. }
  188. const [url, signature, sp] = [searchParams['url'], searchParams['s'], searchParams['sp']];
  189. const decipher = await extractJSSignatureFunction(baseJsUrl, platform);
  190. if (!decipher) {
  191. return null;
  192. }
  193. if (printable(platform)) {
  194. console.log(`signatureCipher=${signatureCipher}, url=${url}, signature=${signature}, sp=${sp}`)
  195. }
  196. let newUrl = `${url}&${sp}=${decipher(signature)}`;
  197. function replaceUrlParam(url, paramName, paramValue) {
  198. let pattern = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i');
  199. let newUrl = url.replace(pattern, `$1${paramName}=${paramValue}$2`);
  200. if (newUrl === url && url.indexOf('?') === -1) {
  201. newUrl += `?${paramName}=${paramValue}`;
  202. } else if (newUrl === url) {
  203. newUrl += `&${paramName}=${paramValue}`;
  204. }
  205. return newUrl;
  206. }
  207. for (const item of url.split('&')) {
  208. const [key, value] = item.split('=');
  209. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  210. }
  211. const nFunction = await extractNJSFunction(baseJsUrl, platform);
  212. const n = searchParams['n']
  213. if (n && nFunction) {
  214. const newN = nFunction(n);
  215. return replaceUrlParam(newUrl, 'n', newN);
  216. }
  217. return newUrl;
  218. }
  219. detail = async (url, platform) => {
  220. try {
  221. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  222. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
  223. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  224. 'Accept-Language': 'en-us,en;q=0.5',
  225. 'Sec-Fetch-Mode': 'navigate',
  226. 'Accept-Encoding': 'gzip, deflate, br',
  227. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  228. }, platform);
  229. let {data: html, headers: htmlHeaders} = htmlResp;
  230. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  231. let match = html.match(regex);
  232. if (!match || !match.length) {
  233. console.log('can not found JSON: ytInitialPlayerResponse');
  234. throw new Error('JSON not found: ytInitialPlayerResponse');
  235. }
  236. const ytInitialPlayerResponse = JSON.parse(match[1]);
  237. if (printable(platform)) {
  238. console.log(ytInitialPlayerResponse);
  239. }
  240. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  241. const thumbnails = []
  242. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  243. thumbnails.push({
  244. 'url': item['url'],
  245. 'width': item['width'] + "",
  246. 'height': item['height'] + ""
  247. })
  248. }
  249. let originFormats = [];
  250. const currentFormats = [];
  251. for (const format of ytInitialPlayerResponse["streamingData"]["formats"].concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  252. if (format) {
  253. format["from"] = "web"
  254. currentFormats.push(format);
  255. }
  256. }
  257. originFormats = originFormats.concat(currentFormats);
  258. console.log(`after html, format size:${originFormats.length}`);
  259. // // android
  260. // try {
  261. // const apiKey = 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w'
  262. // const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  263. // const apiResp = await request('POST', apiUrl, JSON.stringify({
  264. // "context": {
  265. // "client": {
  266. // "clientName": "ANDROID",
  267. // "clientVersion": "19.09.37",
  268. // "androidSdkVersion": 30,
  269. // 'userAgent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  270. // "hl": "en",
  271. // "timeZone": "UTC",
  272. // "utcOffsetMinutes": 0
  273. // }
  274. // },
  275. // 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  276. // "params": "CgIIAQ==",
  277. // "playbackContext": {
  278. // "contentPlaybackContext": {
  279. // "html5Preference": "HTML5_PREF_WANTS"
  280. // }
  281. // },
  282. // "contentCheckOk": true,
  283. // "racyCheckOk": true
  284. // }), {
  285. // 'Host': 'www.youtube.com',
  286. // 'Connection': 'keep-alive',
  287. // 'User-Agent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  288. // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  289. // 'Accept-Language': 'en-us,en;q=0.5',
  290. // 'Sec-Fetch-Mode': 'navigate',
  291. // 'X-YouTube-Client-Name': '3',
  292. // 'X-YouTube-Client-Version': '19.09.37',
  293. // 'Origin': 'https://www.youtube.com',
  294. // 'Accept-Encoding': 'gzip, deflate, br',
  295. // 'Cookie': parseSetCookie(htmlHeaders),
  296. // 'Content-Type': 'application/json'
  297. // }, platform);
  298. // let {data: apiData, _} = apiResp;
  299. // console.log(`android api result: ${JSON.stringify(apiResp)}`);
  300. // const res = JSON.parse(apiData);
  301. // const currentFormats = [];
  302. // for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  303. // if (format) {
  304. // format["from"] = "android"
  305. // currentFormats.push(format);
  306. // }
  307. // }
  308. // originFormats = originFormats.concat(currentFormats);
  309. // } catch (e) {
  310. // console.log(`can not found format android api error: ${e}`);
  311. // }
  312. // console.log(`after android api, format size:${originFormats.length}`);
  313. // // ios
  314. // try {
  315. // const apiKey = 'AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc'
  316. // const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  317. // let apiResp = await request('POST', apiUrl, JSON.stringify({
  318. // "context": {
  319. // "client": {
  320. // 'clientName': 'IOS',
  321. // 'clientVersion': '19.09.3',
  322. // 'deviceModel': 'iPhone14,3',
  323. // 'userAgent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  324. // "hl": "en",
  325. // "timeZone": "UTC",
  326. // "utcOffsetMinutes": 0
  327. // }
  328. // },
  329. // 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  330. // "playbackContext": {
  331. // "contentPlaybackContext": {
  332. // "html5Preference": "HTML5_PREF_WANTS"
  333. // }
  334. // },
  335. // "contentCheckOk": true,
  336. // "racyCheckOk": true
  337. // }), {
  338. // 'Host': 'www.youtube.com',
  339. // 'Connection': 'keep-alive',
  340. // 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  341. // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  342. // 'Accept-Language': 'en-us,en;q=0.5',
  343. // 'Sec-Fetch-Mode': 'navigate',
  344. // 'X-YouTube-Client-Name': '5',
  345. // 'X-YouTube-Client-Version': '19.09.3',
  346. // 'Origin': 'https://www.youtube.com',
  347. // 'Accept-Encoding': 'gzip, deflate, br',
  348. // 'Cookie': parseSetCookie(htmlHeaders),
  349. // 'Content-Type': 'application/json'
  350. // }, platform);
  351. // let {data: apiData, _} = apiResp;
  352. // console.log(`ios api result: ${JSON.stringify(apiResp)}`);
  353. // const res = JSON.parse(apiData);
  354. // const currentFormats = [];
  355. // for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  356. // if (format) {
  357. // format["from"] = "ios"
  358. // currentFormats.push(format);
  359. // }
  360. // }
  361. // originFormats = originFormats.concat(currentFormats);
  362. // } catch (e) {
  363. // console.log(`can not found format ios api error: ${e}`);
  364. // }
  365. // console.log(`after ios api, format size:${originFormats.length}`);
  366. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  367. let formatIds = [];
  368. const formats = [];
  369. for (let format of originFormats) {
  370. if (printable(platform)) {
  371. console.log(format);
  372. }
  373. if (format && formatIds.indexOf(format['itag']) === -1) {
  374. if (!format["url"]) {
  375. format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  376. }
  377. if (format["url"]) {
  378. const {vcodec, acodec} = parseCodecs(format)
  379. if (vcodec && acodec) {
  380. const current = {
  381. "width": format["width"] + "",
  382. "height": format["height"] + "",
  383. "type": format["mimeType"],
  384. "quality": format["quality"],
  385. "itag": format["itag"],
  386. "fps": format["fps"] + "",
  387. "bitrate": format["bitrate"] + "",
  388. "url": format["url"],
  389. "ext": "mp4",
  390. "vcodec": vcodec,
  391. "acodec": acodec,
  392. "vbr": "0",
  393. "abr": "0",
  394. "container": "mp4_dash",
  395. "from": format["from"]
  396. }
  397. if (platform === "WEB") {
  398. current["source"] = format
  399. }
  400. formats.push(current)
  401. formatIds.push(format["itag"]);
  402. }
  403. }
  404. }
  405. }
  406. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  407. const recommendInfo = [];
  408. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  409. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  410. if (printable(platform)) {
  411. console.log(ytInitialData);
  412. }
  413. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  414. if (item["compactVideoRenderer"]) {
  415. const recommendVideo = item["compactVideoRenderer"];
  416. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  417. if (recommendVideo["videoId"]) {
  418. recommendInfo.push({
  419. "type": "gridVideoRenderer",
  420. "videoId": recommendVideo["videoId"],
  421. "title": recommendVideo["title"]?.["simpleText"],
  422. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  423. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  424. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  425. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  426. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  427. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  428. })
  429. }
  430. }
  431. }
  432. }
  433. const videoDetails = {
  434. "isLiveContent": originVideoDetails["isLiveContent"],
  435. "title": originVideoDetails["title"],
  436. "thumbnails": thumbnails,
  437. "description": originVideoDetails["shortDescription"],
  438. "lengthSeconds": originVideoDetails["lengthSeconds"],
  439. "viewCount": originVideoDetails["viewCount"],
  440. "keywords": originVideoDetails["keywords"],
  441. "author": originVideoDetails["author"],
  442. "channelID": originVideoDetails["channelId"],
  443. "recommendInfo": recommendInfo,
  444. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  445. "videoId": originVideoDetails["videoId"]
  446. }
  447. const ret = {
  448. "code": 200,
  449. "msg": "",
  450. "data": {
  451. "videoDetails": videoDetails,
  452. "streamingData": {
  453. "formats": formats.reverse()
  454. }
  455. },
  456. "id": "MusicDetailViewModel_detail_url"
  457. }
  458. console.log(`detail result: ${JSON.stringify(ret)}`);
  459. return ret;
  460. } catch (e) {
  461. const ret = {
  462. "code": -1,
  463. "msg": e.toString()
  464. }
  465. console.log(`detail result error: ${JSON.stringify(ret)}`);
  466. console.log(e);
  467. return ret;
  468. }
  469. }
  470. search = async (keyword, next, platform) => {
  471. try {
  472. console.log(`search keyword: ${keyword}`);
  473. console.log(`search next: ${next}`);
  474. if (next) {
  475. const nextObject = JSON.parse(next);
  476. const key = nextObject["key"];
  477. const body = {
  478. context: {
  479. client: {
  480. clientName: "WEB",
  481. clientVersion: "2.20240506.01.00",
  482. },
  483. },
  484. continuation: nextObject["continuation"]
  485. };
  486. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  487. const {data, _} = res;
  488. res = JSON.parse(data);
  489. const videos = [];
  490. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  491. const video = item["videoRenderer"];
  492. if (printable(platform)) {
  493. console.log(video);
  494. }
  495. if (video && video["videoId"]) {
  496. videos.push({
  497. "type": "videoWithContextRenderer",
  498. "data": {
  499. "videoId": video["videoId"],
  500. "title": video["title"]?.["runs"]?.[0]?.["text"],
  501. "thumbnails": video["thumbnail"]?.["thumbnails"],
  502. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  503. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  504. "viewCountText": video["viewCountText"]?.["simpleText"],
  505. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  506. "lengthText": video["lengthText"]?.["simpleText"]
  507. }
  508. });
  509. }
  510. }
  511. const ret = {
  512. "code": 200,
  513. "msg": "",
  514. "data": {
  515. "data": videos,
  516. "next": JSON.stringify({
  517. "key": nextObject["key"],
  518. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  519. }),
  520. },
  521. "id": "MusicSearchResultViewModel_search_result"
  522. }
  523. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  524. return ret;
  525. } else {
  526. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  527. const htmlRes = await request('GET', url, null, {}, platform);
  528. const {data: html, _} = htmlRes;
  529. let regex = /var ytInitialData\s*=\s*({.*?});/;
  530. let match = html.match(regex);
  531. if (!match || !match.length) {
  532. console.log("can not found ytInitialData");
  533. throw new Error('JSON not found: ytInitialData');
  534. }
  535. const ytInitialDataResp = JSON.parse(match[1]);
  536. const videos = [];
  537. for (const item of ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[0]?.["itemSectionRenderer"]?.["contents"]) {
  538. if (item["videoRenderer"]) {
  539. const video = item["videoRenderer"];
  540. if (printable(platform)) {
  541. console.log(video);
  542. }
  543. if (video && video["videoId"]) {
  544. videos.push({
  545. "type": "videoWithContextRenderer",
  546. "data": {
  547. "videoId": video["videoId"],
  548. "title": video["title"]?.["runs"]?.[0]?.["text"],
  549. "thumbnails": video["thumbnail"]?.["thumbnails"],
  550. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  551. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  552. "viewCountText": video["viewCountText"]?.["simpleText"],
  553. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  554. "lengthText": video["lengthText"]?.["simpleText"]
  555. }
  556. });
  557. }
  558. }
  559. }
  560. let next = {};
  561. if (html.split("innertubeApiKey").length > 0) {
  562. next["key"] = html
  563. .split("innertubeApiKey")[1]
  564. .trim()
  565. .split(",")[0]
  566. .split('"')[2];
  567. }
  568. next["continuation"] = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  569. const ret = {
  570. "code": 200,
  571. "msg": "",
  572. "data": {
  573. "data": videos,
  574. "next": JSON.stringify(next),
  575. },
  576. "id": "MusicSearchResultViewModel_search_result"
  577. }
  578. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  579. return ret;
  580. }
  581. } catch (e) {
  582. const ret = {
  583. "code": -1,
  584. "msg": e.toString()
  585. }
  586. console.log(`search result error: ${JSON.stringify(ret)}`);
  587. return ret;
  588. }
  589. }