info.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. function 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 = {}) => {
  48. return new Promise(function (resolve, reject) {
  49. const xhr = new XMLHttpRequest();
  50. xhr.open(method, url);
  51. // 设置请求头
  52. Object.keys(headers).forEach(function (key) {
  53. xhr.setRequestHeader(key, headers[key]);
  54. });
  55. xhr.onload = function () {
  56. if (xhr.status >= 200 && xhr.status < 300) {
  57. resolve(xhr.responseText);
  58. } else {
  59. reject(new Error('Request failed with status: ' + xhr.status));
  60. }
  61. };
  62. xhr.onerror = function () {
  63. reject(new Error('Request failed'));
  64. };
  65. xhr.send(data);
  66. });
  67. }
  68. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  69. const x = string.indexOf(needleStart);
  70. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  71. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  72. }
  73. getUrlFromSignature = (signatureCipher, baseContent) => {
  74. const decipher = getDecipherFunction(baseContent);
  75. const searchParams = new URLSearchParams(signatureCipher);
  76. const [url, signature, sp] = [searchParams.get("url"), searchParams.get("s"), searchParams.get("sp")];
  77. return `${url}&${sp}=${decipher(signature)}`;
  78. }
  79. getDecipherFunction = (string) => {
  80. const js = string.replace("var _yt_player={}", "");
  81. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  82. const beginningOfFunction =
  83. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  84. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  85. return eval(side + top);
  86. };
  87. detail = async (url, local) => {
  88. const headers = {
  89. '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',
  90. }
  91. if (local) {
  92. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  93. }
  94. const html = await request('GET', url, null, headers);
  95. let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  96. if (local) {
  97. baseJsUrl = baseJsUrl.replace("https://www.youtube.com", "http://127.0.0.1");
  98. }
  99. console.log(baseJsUrl);
  100. const baseContent = await request('GET', baseJsUrl, null, headers);
  101. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  102. let match = html.match(regex);
  103. if (!match || !match.length) {
  104. throw new Error('JSON not found.');
  105. }
  106. const ytInitialPlayerResponse = JSON.parse(match[1]);
  107. console.log(ytInitialPlayerResponse);
  108. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  109. const thumbnails = []
  110. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  111. thumbnails.push({
  112. "url": item["url"],
  113. "width": item["width"] + "",
  114. "height": item["height"] + ""
  115. })
  116. }
  117. const formats = []
  118. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  119. console.log(format);
  120. format.url = getUrlFromSignature(format["signatureCipher"], baseContent);
  121. const {vcodec, acodec} = parseCodecs(format)
  122. if (vcodec && acodec) {
  123. formats.push({
  124. "width": format["width"] + "",
  125. "height": format["height"] + "",
  126. "type": format["mimeType"],
  127. "quality": format["quality"],
  128. "itag": format["itag"],
  129. "fps": format["fps"] + "",
  130. "bitrate": format["bitrate"] + "",
  131. "url": format["url"],
  132. "ext": "mp4",
  133. "vcodec": vcodec,
  134. "acodec": acodec,
  135. "vbr": "0",
  136. "abr": "0",
  137. "container": "mp4_dash"
  138. })
  139. }
  140. }
  141. regex = /var ytInitialData\s*=\s*({.*?});/;
  142. match = html.match(regex);
  143. if (!match || !match.length) {
  144. throw new Error('JSON not found.');
  145. }
  146. if (!match || !match.length) {
  147. throw new Error('JSON not found.');
  148. }
  149. const ytInitialData = JSON.parse(match[1]);
  150. console.log(ytInitialData);
  151. const recommendInfo = [];
  152. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  153. if (item["compactVideoRenderer"]) {
  154. const recommendVideo = item["compactVideoRenderer"];
  155. console.log(recommendVideo);
  156. if (recommendVideo["videoId"]) {
  157. recommendInfo.push({
  158. "type": "gridVideoRenderer",
  159. "videoId": recommendVideo["videoId"],
  160. "title": recommendVideo["title"]?.["simpleText"],
  161. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  162. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  163. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  164. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  165. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  166. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  167. })
  168. }
  169. }
  170. }
  171. const videoDetails = {
  172. "isLiveContent": originVideoDetails["isLiveContent"],
  173. "title": originVideoDetails["title"],
  174. "thumbnails": thumbnails,
  175. "description": originVideoDetails["shortDescription"],
  176. "lengthSeconds": originVideoDetails["lengthSeconds"],
  177. "viewCount": originVideoDetails["viewCount"],
  178. "keywords": originVideoDetails["keywords"],
  179. "author": originVideoDetails["author"],
  180. "channelID": originVideoDetails["channelId"],
  181. "recommendInfo": recommendInfo,
  182. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  183. "videoId": originVideoDetails["videoId"]
  184. }
  185. return {
  186. "code": 200,
  187. "msg": "",
  188. "data": {
  189. "videoDetails": videoDetails,
  190. "streamingData": {
  191. "formats": formats
  192. }
  193. },
  194. "id": "MusicDetailViewModel_detail_url"
  195. }
  196. }