info.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. console.log(`接受到解析请求: ${url}`);
  120. const headers = {
  121. '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',
  122. }
  123. const html = await request('GET', url, null, headers, local);
  124. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  125. let match = html.match(regex);
  126. if (!match || !match.length) {
  127. console.log("解释失败: 无法找到json");
  128. throw new Error('JSON not found.');
  129. }
  130. const ytInitialPlayerResponse = JSON.parse(match[1]);
  131. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  132. console.log(`videoDetails: ${JSON.stringify(originVideoDetails)}`);
  133. const thumbnails = []
  134. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  135. thumbnails.push({
  136. "url": item["url"],
  137. "width": item["width"] + "",
  138. "height": item["height"] + ""
  139. })
  140. }
  141. const formats = []
  142. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  143. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  144. console.log(`current format: ${JSON.stringify(format)}`);
  145. if (!format["url"]) {
  146. format["url"] = await getUrlFromSignature(format["signatureCipher"], baseJsUrl, local);
  147. }
  148. if (format["url"]) {
  149. const {vcodec, acodec} = parseCodecs(format)
  150. if (vcodec && acodec) {
  151. formats.push({
  152. "width": format["width"] + "",
  153. "height": format["height"] + "",
  154. "type": format["mimeType"],
  155. "quality": format["quality"],
  156. "itag": format["itag"],
  157. "fps": format["fps"] + "",
  158. "bitrate": format["bitrate"] + "",
  159. "url": format["url"],
  160. "ext": "mp4",
  161. "vcodec": vcodec,
  162. "acodec": acodec,
  163. "vbr": "0",
  164. "abr": "0",
  165. "container": "mp4_dash"
  166. })
  167. }
  168. }
  169. }
  170. regex = /var ytInitialData\s*=\s*({.*?});/;
  171. match = html.match(regex);
  172. if (!match || !match.length) {
  173. console.log(`解析失败,无法找到 ytInitialData`);
  174. throw new Error('JSON not found.');
  175. }
  176. const ytInitialData = JSON.parse(match[1]);
  177. const recommendInfo = [];
  178. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  179. if (item["compactVideoRenderer"]) {
  180. const recommendVideo = item["compactVideoRenderer"];
  181. console.log(`推荐视频: ${JSON.stringify(recommendVideo)}`);
  182. if (recommendVideo["videoId"]) {
  183. recommendInfo.push({
  184. "type": "gridVideoRenderer",
  185. "videoId": recommendVideo["videoId"],
  186. "title": recommendVideo["title"]?.["simpleText"],
  187. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  188. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  189. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  190. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  191. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  192. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  193. })
  194. }
  195. }
  196. }
  197. const videoDetails = {
  198. "isLiveContent": originVideoDetails["isLiveContent"],
  199. "title": originVideoDetails["title"],
  200. "thumbnails": thumbnails,
  201. "description": originVideoDetails["shortDescription"],
  202. "lengthSeconds": originVideoDetails["lengthSeconds"],
  203. "viewCount": originVideoDetails["viewCount"],
  204. "keywords": originVideoDetails["keywords"],
  205. "author": originVideoDetails["author"],
  206. "channelID": originVideoDetails["channelId"],
  207. "recommendInfo": recommendInfo,
  208. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  209. "videoId": originVideoDetails["videoId"]
  210. }
  211. const ret = {
  212. "code": 200,
  213. "msg": "",
  214. "data": {
  215. "videoDetails": videoDetails,
  216. "streamingData": {
  217. "formats": formats
  218. }
  219. },
  220. "id": "MusicDetailViewModel_detail_url"
  221. }
  222. console.log(`解析结果: ${JSON.stringify(ret)}`);
  223. return ret;
  224. } catch (e) {
  225. const ret = {
  226. "code": -1,
  227. "msg": e.toString()
  228. }
  229. console.log(`解析失败: ${JSON.stringify(ret)}`);
  230. return ret;
  231. }
  232. }
  233. search = async (keyword, next, local) => {
  234. try {
  235. console.log(`接受到搜索请求 keyword: ${keyword}`);
  236. console.log(`接收到搜索请求 next: ${next}`);
  237. if (next) {
  238. const nextObject = JSON.parse(next);
  239. const key = nextObject["key"];
  240. const body = {
  241. context: {
  242. client: {
  243. clientName: "WEB",
  244. clientVersion: "2.20240506.01.00",
  245. },
  246. },
  247. continuation: nextObject["continuation"]
  248. };
  249. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
  250. res = JSON.parse(res);
  251. const videos = [];
  252. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  253. const video = item["videoRenderer"];
  254. console.log(`搜索结果: ${JSON.stringify(video)}`);
  255. if (video && video["videoId"]) {
  256. videos.push({
  257. "type": "videoWithContextRenderer",
  258. "data": {
  259. "videoId": video["videoId"],
  260. "title": video["title"]?.["runs"]?.[0]?.["text"],
  261. "thumbnails": video["thumbnail"]?.["thumbnails"],
  262. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  263. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  264. "viewCountText": video["viewCountText"]?.["simpleText"],
  265. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  266. "lengthText": video["lengthText"]?.["simpleText"]
  267. }
  268. });
  269. }
  270. }
  271. const ret = {
  272. "code": 200,
  273. "msg": "",
  274. "data": {
  275. "data": videos,
  276. "next": JSON.stringify({
  277. "key": nextObject["key"],
  278. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  279. }),
  280. },
  281. "id": "MusicSearchResultViewModel_search_result"
  282. }
  283. console.log(`携带next搜索结果成功: ${JSON.stringify(ret)}`);
  284. return ret;
  285. } else {
  286. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  287. const html = await request('GET', url, null, {}, local);
  288. let regex = /var ytInitialData\s*=\s*({.*?});/;
  289. let match = html.match(regex);
  290. if (!match || !match.length) {
  291. console.log("搜索失败:无法找到ytInitialData");
  292. throw new Error('JSON not found.');
  293. }
  294. const ytInitialDataResp = JSON.parse(match[1]);
  295. const videos = [];
  296. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  297. if (item["videoRenderer"]) {
  298. const video = item["videoRenderer"];
  299. console.log(`搜索结果: ${JSON.stringify(video)}`);
  300. if (video && video["videoId"]) {
  301. videos.push({
  302. "type": "videoWithContextRenderer",
  303. "data": {
  304. "videoId": video["videoId"],
  305. "title": video["title"]?.["runs"]?.[0]?.["text"],
  306. "thumbnails": video["thumbnail"]?.["thumbnails"],
  307. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  308. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  309. "viewCountText": video["viewCountText"]?.["simpleText"],
  310. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  311. "lengthText": video["lengthText"]?.["simpleText"]
  312. }
  313. });
  314. }
  315. }
  316. }
  317. let next = {};
  318. if (html.split("innertubeApiKey").length > 0) {
  319. next["key"] = html
  320. .split("innertubeApiKey")[1]
  321. .trim()
  322. .split(",")[0]
  323. .split('"')[2];
  324. }
  325. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  326. const ret = {
  327. "code": 200,
  328. "msg": "",
  329. "data": {
  330. "data": videos,
  331. "next": JSON.stringify(next),
  332. },
  333. "id": "MusicSearchResultViewModel_search_result"
  334. }
  335. console.log(`未携带next搜索结果成功: ${JSON.stringify(ret)}`);
  336. return ret;
  337. }
  338. } catch (e) {
  339. const ret = {
  340. "code": -1,
  341. "msg": e.toString()
  342. }
  343. console.log(`搜索失败: ${JSON.stringify(ret)}`);
  344. return ret;
  345. }
  346. }