info.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. currentFormats.reverse()
  258. originFormats = originFormats.concat(currentFormats);
  259. console.log(`after html, format size:${originFormats.length}`);
  260. // // android
  261. // try {
  262. // const apiKey = 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w'
  263. // const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  264. // const apiResp = await request('POST', apiUrl, JSON.stringify({
  265. // "context": {
  266. // "client": {
  267. // "clientName": "ANDROID",
  268. // "clientVersion": "19.09.37",
  269. // "androidSdkVersion": 30,
  270. // 'userAgent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  271. // "hl": "en",
  272. // "timeZone": "UTC",
  273. // "utcOffsetMinutes": 0
  274. // }
  275. // },
  276. // 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  277. // "params": "CgIIAQ==",
  278. // "playbackContext": {
  279. // "contentPlaybackContext": {
  280. // "html5Preference": "HTML5_PREF_WANTS"
  281. // }
  282. // },
  283. // "contentCheckOk": true,
  284. // "racyCheckOk": true
  285. // }), {
  286. // 'Host': 'www.youtube.com',
  287. // 'Connection': 'keep-alive',
  288. // 'User-Agent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  289. // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  290. // 'Accept-Language': 'en-us,en;q=0.5',
  291. // 'Sec-Fetch-Mode': 'navigate',
  292. // 'X-YouTube-Client-Name': '3',
  293. // 'X-YouTube-Client-Version': '19.09.37',
  294. // 'Origin': 'https://www.youtube.com',
  295. // 'Accept-Encoding': 'gzip, deflate, br',
  296. // 'Cookie': parseSetCookie(htmlHeaders),
  297. // 'Content-Type': 'application/json'
  298. // }, platform);
  299. // let {data: apiData, _} = apiResp;
  300. // console.log(`android api result: ${JSON.stringify(apiResp)}`);
  301. // const res = JSON.parse(apiData);
  302. // const currentFormats = [];
  303. // for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  304. // if (format) {
  305. // format["from"] = "android"
  306. // currentFormats.push(format);
  307. // }
  308. // }
  309. // originFormats = originFormats.concat(currentFormats);
  310. // } catch (e) {
  311. // console.log(`can not found format android api error: ${e}`);
  312. // }
  313. // console.log(`after android api, format size:${originFormats.length}`);
  314. // // ios
  315. // try {
  316. // const apiKey = 'AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc'
  317. // const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  318. // let apiResp = await request('POST', apiUrl, JSON.stringify({
  319. // "context": {
  320. // "client": {
  321. // 'clientName': 'IOS',
  322. // 'clientVersion': '19.09.3',
  323. // 'deviceModel': 'iPhone14,3',
  324. // 'userAgent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  325. // "hl": "en",
  326. // "timeZone": "UTC",
  327. // "utcOffsetMinutes": 0
  328. // }
  329. // },
  330. // 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  331. // "playbackContext": {
  332. // "contentPlaybackContext": {
  333. // "html5Preference": "HTML5_PREF_WANTS"
  334. // }
  335. // },
  336. // "contentCheckOk": true,
  337. // "racyCheckOk": true
  338. // }), {
  339. // 'Host': 'www.youtube.com',
  340. // 'Connection': 'keep-alive',
  341. // 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  342. // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  343. // 'Accept-Language': 'en-us,en;q=0.5',
  344. // 'Sec-Fetch-Mode': 'navigate',
  345. // 'X-YouTube-Client-Name': '5',
  346. // 'X-YouTube-Client-Version': '19.09.3',
  347. // 'Origin': 'https://www.youtube.com',
  348. // 'Accept-Encoding': 'gzip, deflate, br',
  349. // 'Cookie': parseSetCookie(htmlHeaders),
  350. // 'Content-Type': 'application/json'
  351. // }, platform);
  352. // let {data: apiData, _} = apiResp;
  353. // console.log(`ios api result: ${JSON.stringify(apiResp)}`);
  354. // const res = JSON.parse(apiData);
  355. // const currentFormats = [];
  356. // for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  357. // if (format) {
  358. // format["from"] = "ios"
  359. // currentFormats.push(format);
  360. // }
  361. // }
  362. // originFormats = originFormats.concat(currentFormats);
  363. // } catch (e) {
  364. // console.log(`can not found format ios api error: ${e}`);
  365. // }
  366. // console.log(`after ios api, format size:${originFormats.length}`);
  367. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  368. let formatIds = [];
  369. const formats = [];
  370. for (let format of originFormats) {
  371. if (printable(platform)) {
  372. console.log(format);
  373. }
  374. if (format && formatIds.indexOf(format['itag']) === -1) {
  375. if (!format["url"]) {
  376. format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  377. }
  378. if (format["url"]) {
  379. const {vcodec, acodec} = parseCodecs(format)
  380. if (vcodec && acodec) {
  381. const current = {
  382. "width": format["width"] + "",
  383. "height": format["height"] + "",
  384. "type": format["mimeType"],
  385. "quality": format["quality"],
  386. "itag": format["itag"],
  387. "fps": format["fps"] + "",
  388. "bitrate": format["bitrate"] + "",
  389. "url": format["url"],
  390. "ext": "mp4",
  391. "vcodec": vcodec,
  392. "acodec": acodec,
  393. "vbr": "0",
  394. "abr": "0",
  395. "container": "mp4_dash",
  396. "from": format["from"]
  397. }
  398. if (platform === "WEB") {
  399. current["source"] = format
  400. }
  401. formats.push(current)
  402. formatIds.push(format["itag"]);
  403. }
  404. }
  405. }
  406. }
  407. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  408. const recommendInfo = [];
  409. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  410. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  411. if (printable(platform)) {
  412. console.log(ytInitialData);
  413. }
  414. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  415. if (item["compactVideoRenderer"]) {
  416. const recommendVideo = item["compactVideoRenderer"];
  417. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  418. if (recommendVideo["videoId"]) {
  419. recommendInfo.push({
  420. "type": "gridVideoRenderer",
  421. "videoId": recommendVideo["videoId"],
  422. "title": recommendVideo["title"]?.["simpleText"],
  423. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  424. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  425. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  426. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  427. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  428. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  429. })
  430. }
  431. }
  432. }
  433. }
  434. const videoDetails = {
  435. "isLiveContent": originVideoDetails["isLiveContent"],
  436. "title": originVideoDetails["title"],
  437. "thumbnails": thumbnails,
  438. "description": originVideoDetails["shortDescription"],
  439. "lengthSeconds": originVideoDetails["lengthSeconds"],
  440. "viewCount": originVideoDetails["viewCount"],
  441. "keywords": originVideoDetails["keywords"],
  442. "author": originVideoDetails["author"],
  443. "channelID": originVideoDetails["channelId"],
  444. "recommendInfo": recommendInfo,
  445. "channelURL": 'https://www.yo' + 'utub' + 'e.com/ch' + `annel/${originVideoDetails["channelId"]}`,
  446. "videoId": originVideoDetails["videoId"]
  447. }
  448. const ret = {
  449. "code": 200,
  450. "msg": "",
  451. "data": {
  452. "videoDetails": videoDetails,
  453. "streamingData": {
  454. "formats": formats.reverse()
  455. }
  456. },
  457. "id": "MusicDetailViewModel_detail_url"
  458. }
  459. console.log(`detail result: ${JSON.stringify(ret)}`);
  460. return ret;
  461. } catch (e) {
  462. const ret = {
  463. "code": -1,
  464. "msg": e.toString()
  465. }
  466. console.log(`detail result error: ${JSON.stringify(ret)}`);
  467. console.log(e);
  468. return ret;
  469. }
  470. }
  471. search = async (keyword, next, platform) => {
  472. try {
  473. console.log(`search keyword: ${keyword}`);
  474. console.log(`search next: ${next}`);
  475. if (next) {
  476. const nextObject = JSON.parse(next);
  477. const key = nextObject["key"];
  478. const body = {
  479. context: {
  480. client: {
  481. clientName: "WEB",
  482. clientVersion: "2.20240506.01.00",
  483. },
  484. },
  485. continuation: nextObject["continuation"]
  486. };
  487. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  488. const {data, _} = res;
  489. res = JSON.parse(data);
  490. const videos = [];
  491. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  492. const video = item["videoRenderer"];
  493. if (printable(platform)) {
  494. console.log(video);
  495. }
  496. if (video && video["videoId"]) {
  497. videos.push({
  498. "type": "videoWithContextRenderer",
  499. "data": {
  500. "videoId": video["videoId"],
  501. "title": video["title"]?.["runs"]?.[0]?.["text"],
  502. "thumbnails": video["thumbnail"]?.["thumbnails"],
  503. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  504. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  505. "viewCountText": video["viewCountText"]?.["simpleText"],
  506. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  507. "lengthText": video["lengthText"]?.["simpleText"]
  508. }
  509. });
  510. }
  511. }
  512. const ret = {
  513. "code": 200,
  514. "msg": "",
  515. "data": {
  516. "data": videos,
  517. "next": JSON.stringify({
  518. "key": nextObject["key"],
  519. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  520. }),
  521. },
  522. "id": "MusicSearchResultViewModel_search_result"
  523. }
  524. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  525. return ret;
  526. } else {
  527. let url = 'https://ww' + 'w.yo' + 'utube.co' + 'm/re' + `sults?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  528. const htmlRes = await request('GET', url, null, {}, platform);
  529. const {data: html, _} = htmlRes;
  530. let regex = /var ytInitialData\s*=\s*({.*?});/;
  531. let match = html.match(regex);
  532. if (!match || !match.length) {
  533. console.log("can not found ytInitialData");
  534. throw new Error('JSON not found: ytInitialData');
  535. }
  536. const ytInitialDataResp = JSON.parse(match[1]);
  537. const videos = [];
  538. for (const item of ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[0]?.["itemSectionRenderer"]?.["contents"]) {
  539. if (item["videoRenderer"]) {
  540. const video = item["videoRenderer"];
  541. if (printable(platform)) {
  542. console.log(video);
  543. }
  544. if (video && video["videoId"]) {
  545. videos.push({
  546. "type": "videoWithContextRenderer",
  547. "data": {
  548. "videoId": video["videoId"],
  549. "title": video["title"]?.["runs"]?.[0]?.["text"],
  550. "thumbnails": video["thumbnail"]?.["thumbnails"],
  551. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  552. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  553. "viewCountText": video["viewCountText"]?.["simpleText"],
  554. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  555. "lengthText": video["lengthText"]?.["simpleText"]
  556. }
  557. });
  558. }
  559. }
  560. }
  561. let next = {};
  562. if (html.split("innertubeApiKey").length > 0) {
  563. next["key"] = html
  564. .split("innertubeApiKey")[1]
  565. .trim()
  566. .split(",")[0]
  567. .split('"')[2];
  568. }
  569. next["continuation"] = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  570. const ret = {
  571. "code": 200,
  572. "msg": "",
  573. "data": {
  574. "data": videos,
  575. "next": JSON.stringify(next),
  576. },
  577. "id": "MusicSearchResultViewModel_search_result"
  578. }
  579. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  580. return ret;
  581. }
  582. } catch (e) {
  583. const ret = {
  584. "code": -1,
  585. "msg": e.toString()
  586. }
  587. console.log(`search result error: ${JSON.stringify(ret)}`);
  588. return ret;
  589. }
  590. }