info.js 20 KB

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