info.js 26 KB

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