info.js 22 KB

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