info.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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.warn(`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 = {}, local) => {
  48. if (local) {
  49. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  50. }
  51. console.log(`请求url:${url}`)
  52. console.log(`请求data:${data}`)
  53. console.log(`请求method:${method}`)
  54. console.log(`请求headers:${JSON.stringify((headers))}`)
  55. if (local) {
  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. console.log(`请求失败: ${err}`)
  66. reject(err);
  67. } else {
  68. resolve(data);
  69. }
  70. });
  71. })
  72. }
  73. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  74. const x = string.indexOf(needleStart);
  75. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  76. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  77. }
  78. getDecipherFunction = (string) => {
  79. const js = string.replace("var _yt_player={}", "");
  80. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  81. const beginningOfFunction =
  82. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  83. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  84. console.log(`side: ${side}`);
  85. console.log(`top: ${top}`);
  86. return eval(side + top);
  87. };
  88. const cache = {};
  89. extractJSSignatureFunction = async (baseJsUrl, local) => {
  90. console.log(`解析baseUrl: ${baseJsUrl}`);
  91. const cacheKey = `js:${baseJsUrl}`;
  92. if (cache[cacheKey]) {
  93. console.log(`从缓存中获取JSSignatureFunction: ${baseJsUrl}`);
  94. return cache[cacheKey];
  95. }
  96. const headers = {
  97. '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',
  98. }
  99. const baseContent = await request('GET', baseJsUrl, null, headers, local);
  100. const decipher = getDecipherFunction(baseContent);
  101. if (decipher) {
  102. cache[cacheKey] = decipher;
  103. }
  104. return decipher;
  105. }
  106. getUrlFromSignature = async (signatureCipher, baseJsUrl, local) => {
  107. const decipher = await extractJSSignatureFunction(baseJsUrl, local);
  108. const searchParams = {}
  109. for (const item of signatureCipher.split("&")) {
  110. const [key, value] = item.split('=');
  111. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  112. }
  113. const [url, signature, sp] = [searchParams["url"], searchParams["s"], searchParams["sp"]];
  114. console.log(signatureCipher, url, signature, sp);
  115. return `${url}&${sp}=${decipher(signature)}`;
  116. }
  117. detail = async (url, local) => {
  118. try {
  119. if (url.includes('?')) {
  120. url = `${url}&bpctr=9999999999&has_verified=1`;
  121. } else {
  122. url = `${url}?bpctr=9999999999&has_verified=1`;
  123. }
  124. console.log(`接受到解析请求: ${url}`);
  125. const headers = {
  126. 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  127. }
  128. const html = await request('GET', url, null, headers, local);
  129. // 尝试找到更好的
  130. try {
  131. let regex = /ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;/
  132. let match = html.match(regex);
  133. if (match == null || match.length !== 2) {
  134. console.log(`无法找到更好的format`);
  135. } else {
  136. const masterYtConfig = JSON.parse(match[1]);
  137. const headers = {
  138. 'Origin': 'https://www.youtube.com',
  139. 'X-YouTube-Client-Name': masterYtConfig['INNERTUBE_CONTEXT_CLIENT_NAME'],
  140. 'X-YouTube-Client-Version': masterYtConfig['INNERTUBE_CLIENT_VERSION'],
  141. 'User-Agent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  142. 'Content-Type': 'application/json'
  143. }
  144. const apiKey = masterYtConfig['INNERTUBE_API_KEY']
  145. const data = {
  146. 'context': masterYtConfig['INNERTUBE_CONTEXT'],
  147. 'videoId': url.replace('https://www.youtube.com/watch?v=', ''),
  148. 'playbackContext': {
  149. 'contentPlaybackContext': {
  150. 'html5Preference': 'HTML5_PREF_WANTS',
  151. 'signatureTimestamp': 0
  152. }
  153. },
  154. 'contentCheckOk': true,
  155. 'racyCheckOk': true
  156. }
  157. const jsUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}&prettyPrint=false`;
  158. const res = await request('POST', jsUrl, JSON.stringify(data), headers, local);
  159. console.log(`找到了更好的`);
  160. console.log(JSON.stringify(res));
  161. }
  162. } catch (e) {
  163. console.log(`无法找到更好的format,并且报错了: ${e}`);
  164. }
  165. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  166. let match = html.match(regex);
  167. if (!match || !match.length) {
  168. console.log("解释失败: 无法找到json");
  169. throw new Error('JSON not found.');
  170. }
  171. const ytInitialPlayerResponse = JSON.parse(match[1]);
  172. console.log(ytInitialPlayerResponse);
  173. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  174. console.log(`videoDetails: ${JSON.stringify(originVideoDetails)}`);
  175. const thumbnails = []
  176. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  177. thumbnails.push({
  178. "url": item["url"],
  179. "width": item["width"] + "",
  180. "height": item["height"] + ""
  181. })
  182. }
  183. const formats = []
  184. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  185. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  186. console.log(`current format: ${JSON.stringify(format)}`);
  187. if (!format["url"]) {
  188. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, local);
  189. }
  190. if (format["url"]) {
  191. const {vcodec, acodec} = parseCodecs(format)
  192. if (vcodec && acodec) {
  193. formats.push({
  194. "width": format["width"] + "",
  195. "height": format["height"] + "",
  196. "type": format["mimeType"],
  197. "quality": format["quality"],
  198. "itag": format["itag"],
  199. "fps": format["fps"] + "",
  200. "bitrate": format["bitrate"] + "",
  201. "url": format["url"],
  202. "ext": "mp4",
  203. "vcodec": vcodec,
  204. "acodec": acodec,
  205. "vbr": "0",
  206. "abr": "0",
  207. "container": "mp4_dash"
  208. })
  209. }
  210. }
  211. }
  212. regex = /var ytInitialData\s*=\s*({.*?});/;
  213. match = html.match(regex);
  214. if (!match || !match.length) {
  215. console.log(`解析失败,无法找到 ytInitialData`);
  216. throw new Error('JSON not found.');
  217. }
  218. const ytInitialData = JSON.parse(match[1]);
  219. const recommendInfo = [];
  220. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  221. if (item["compactVideoRenderer"]) {
  222. const recommendVideo = item["compactVideoRenderer"];
  223. console.log(`推荐视频: ${JSON.stringify(recommendVideo)}`);
  224. if (recommendVideo["videoId"]) {
  225. recommendInfo.push({
  226. "type": "gridVideoRenderer",
  227. "videoId": recommendVideo["videoId"],
  228. "title": recommendVideo["title"]?.["simpleText"],
  229. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  230. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  231. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  232. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  233. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  234. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  235. })
  236. }
  237. }
  238. }
  239. const videoDetails = {
  240. "isLiveContent": originVideoDetails["isLiveContent"],
  241. "title": originVideoDetails["title"],
  242. "thumbnails": thumbnails,
  243. "description": originVideoDetails["shortDescription"],
  244. "lengthSeconds": originVideoDetails["lengthSeconds"],
  245. "viewCount": originVideoDetails["viewCount"],
  246. "keywords": originVideoDetails["keywords"],
  247. "author": originVideoDetails["author"],
  248. "channelID": originVideoDetails["channelId"],
  249. "recommendInfo": recommendInfo,
  250. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  251. "videoId": originVideoDetails["videoId"]
  252. }
  253. const ret = {
  254. "code": 200,
  255. "msg": "",
  256. "data": {
  257. "videoDetails": videoDetails,
  258. "streamingData": {
  259. "formats": formats
  260. }
  261. },
  262. "id": "MusicDetailViewModel_detail_url"
  263. }
  264. console.log(`解析结果: ${JSON.stringify(ret)}`);
  265. return ret;
  266. } catch (e) {
  267. const ret = {
  268. "code": -1,
  269. "msg": e.toString()
  270. }
  271. console.log(`解析失败: ${JSON.stringify(ret)}`);
  272. return ret;
  273. }
  274. }
  275. search = async (keyword, next, local) => {
  276. try {
  277. console.log(`接受到搜索请求 keyword: ${keyword}`);
  278. console.log(`接收到搜索请求 next: ${next}`);
  279. if (next) {
  280. const nextObject = JSON.parse(next);
  281. const key = nextObject["key"];
  282. const body = {
  283. context: {
  284. client: {
  285. clientName: "WEB",
  286. clientVersion: "2.20240506.01.00",
  287. },
  288. },
  289. continuation: nextObject["continuation"]
  290. };
  291. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
  292. res = JSON.parse(res);
  293. const videos = [];
  294. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  295. const video = item["videoRenderer"];
  296. console.log(`搜索结果: ${JSON.stringify(video)}`);
  297. if (video && video["videoId"]) {
  298. videos.push({
  299. "type": "videoWithContextRenderer",
  300. "data": {
  301. "videoId": video["videoId"],
  302. "title": video["title"]?.["runs"]?.[0]?.["text"],
  303. "thumbnails": video["thumbnail"]?.["thumbnails"],
  304. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  305. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  306. "viewCountText": video["viewCountText"]?.["simpleText"],
  307. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  308. "lengthText": video["lengthText"]?.["simpleText"]
  309. }
  310. });
  311. }
  312. }
  313. const ret = {
  314. "code": 200,
  315. "msg": "",
  316. "data": {
  317. "data": videos,
  318. "next": JSON.stringify({
  319. "key": nextObject["key"],
  320. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  321. }),
  322. },
  323. "id": "MusicSearchResultViewModel_search_result"
  324. }
  325. console.log(`携带next搜索结果成功: ${JSON.stringify(ret)}`);
  326. return ret;
  327. } else {
  328. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  329. const html = await request('GET', url, null, {}, local);
  330. let regex = /var ytInitialData\s*=\s*({.*?});/;
  331. let match = html.match(regex);
  332. if (!match || !match.length) {
  333. console.log("搜索失败:无法找到ytInitialData");
  334. throw new Error('JSON not found.');
  335. }
  336. const ytInitialDataResp = JSON.parse(match[1]);
  337. const videos = [];
  338. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  339. if (item["videoRenderer"]) {
  340. const video = item["videoRenderer"];
  341. console.log(`搜索结果: ${JSON.stringify(video)}`);
  342. if (video && video["videoId"]) {
  343. videos.push({
  344. "type": "videoWithContextRenderer",
  345. "data": {
  346. "videoId": video["videoId"],
  347. "title": video["title"]?.["runs"]?.[0]?.["text"],
  348. "thumbnails": video["thumbnail"]?.["thumbnails"],
  349. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  350. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  351. "viewCountText": video["viewCountText"]?.["simpleText"],
  352. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  353. "lengthText": video["lengthText"]?.["simpleText"]
  354. }
  355. });
  356. }
  357. }
  358. }
  359. let next = {};
  360. if (html.split("innertubeApiKey").length > 0) {
  361. next["key"] = html
  362. .split("innertubeApiKey")[1]
  363. .trim()
  364. .split(",")[0]
  365. .split('"')[2];
  366. }
  367. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  368. const ret = {
  369. "code": 200,
  370. "msg": "",
  371. "data": {
  372. "data": videos,
  373. "next": JSON.stringify(next),
  374. },
  375. "id": "MusicSearchResultViewModel_search_result"
  376. }
  377. console.log(`未携带next搜索结果成功: ${JSON.stringify(ret)}`);
  378. return ret;
  379. }
  380. } catch (e) {
  381. const ret = {
  382. "code": -1,
  383. "msg": e.toString()
  384. }
  385. console.log(`搜索失败: ${JSON.stringify(ret)}`);
  386. return ret;
  387. }
  388. }