info.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. console.log(signatureCipher, url, signature, sp);
  78. return `${url}&${sp}=${decipher(signature)}`;
  79. }
  80. getDecipherFunction = (string) => {
  81. const js = string.replace("var _yt_player={}", "");
  82. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  83. const beginningOfFunction =
  84. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  85. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  86. console.log(side + top);
  87. return eval(side + top);
  88. };
  89. detail = async (url, local) => {
  90. const headers = {
  91. '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',
  92. }
  93. if (local) {
  94. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  95. }
  96. const html = await request('GET', url, null, headers);
  97. let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  98. if (local) {
  99. baseJsUrl = baseJsUrl.replace("https://www.youtube.com", "http://127.0.0.1");
  100. }
  101. console.log(baseJsUrl);
  102. const baseContent = await request('GET', baseJsUrl, null, headers);
  103. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  104. let match = html.match(regex);
  105. if (!match || !match.length) {
  106. throw new Error('JSON not found.');
  107. }
  108. const ytInitialPlayerResponse = JSON.parse(match[1]);
  109. console.log(ytInitialPlayerResponse);
  110. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  111. const thumbnails = []
  112. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  113. thumbnails.push({
  114. "url": item["url"],
  115. "width": item["width"] + "",
  116. "height": item["height"] + ""
  117. })
  118. }
  119. const formats = []
  120. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  121. console.log(format);
  122. if (!format["url"]) {
  123. format["url"] = getUrlFromSignature(format["signatureCipher"], baseContent);
  124. }
  125. if (format["url"]) {
  126. const {vcodec, acodec} = parseCodecs(format)
  127. if (vcodec && acodec) {
  128. formats.push({
  129. "width": format["width"] + "",
  130. "height": format["height"] + "",
  131. "type": format["mimeType"],
  132. "quality": format["quality"],
  133. "itag": format["itag"],
  134. "fps": format["fps"] + "",
  135. "bitrate": format["bitrate"] + "",
  136. "url": format["url"],
  137. "ext": "mp4",
  138. "vcodec": vcodec,
  139. "acodec": acodec,
  140. "vbr": "0",
  141. "abr": "0",
  142. "container": "mp4_dash"
  143. })
  144. }
  145. }
  146. }
  147. regex = /var ytInitialData\s*=\s*({.*?});/;
  148. match = html.match(regex);
  149. if (!match || !match.length) {
  150. throw new Error('JSON not found.');
  151. }
  152. if (!match || !match.length) {
  153. throw new Error('JSON not found.');
  154. }
  155. const ytInitialData = JSON.parse(match[1]);
  156. console.log(ytInitialData);
  157. const recommendInfo = [];
  158. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  159. if (item["compactVideoRenderer"]) {
  160. const recommendVideo = item["compactVideoRenderer"];
  161. console.log(recommendVideo);
  162. if (recommendVideo["videoId"]) {
  163. recommendInfo.push({
  164. "type": "gridVideoRenderer",
  165. "videoId": recommendVideo["videoId"],
  166. "title": recommendVideo["title"]?.["simpleText"],
  167. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  168. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  169. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  170. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  171. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  172. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  173. })
  174. }
  175. }
  176. }
  177. const videoDetails = {
  178. "isLiveContent": originVideoDetails["isLiveContent"],
  179. "title": originVideoDetails["title"],
  180. "thumbnails": thumbnails,
  181. "description": originVideoDetails["shortDescription"],
  182. "lengthSeconds": originVideoDetails["lengthSeconds"],
  183. "viewCount": originVideoDetails["viewCount"],
  184. "keywords": originVideoDetails["keywords"],
  185. "author": originVideoDetails["author"],
  186. "channelID": originVideoDetails["channelId"],
  187. "recommendInfo": recommendInfo,
  188. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  189. "videoId": originVideoDetails["videoId"]
  190. }
  191. return {
  192. "code": 200,
  193. "msg": "",
  194. "data": {
  195. "videoDetails": videoDetails,
  196. "streamingData": {
  197. "formats": formats
  198. }
  199. },
  200. "id": "MusicDetailViewModel_detail_url"
  201. }
  202. }