info.js 25 KB

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