info.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 = {}, local) => {
  48. if (local) {
  49. url = url.replace("https://www.youtube.com", "http://127.0.0.1");
  50. }
  51. if (local) {
  52. console.log(url);
  53. return fetch(url, {
  54. "method": method,
  55. "headers": headers,
  56. "body": data,
  57. }).then(res => res.text())
  58. }
  59. }
  60. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  61. const x = string.indexOf(needleStart);
  62. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  63. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  64. }
  65. getUrlFromSignature = (signatureCipher, baseContent) => {
  66. const decipher = getDecipherFunction(baseContent);
  67. const searchParams = new URLSearchParams(signatureCipher);
  68. const [url, signature, sp] = [searchParams.get("url"), searchParams.get("s"), searchParams.get("sp")];
  69. console.log(signatureCipher, url, signature, sp);
  70. return `${url}&${sp}=${decipher(signature)}`;
  71. }
  72. getDecipherFunction = (string) => {
  73. const js = string.replace("var _yt_player={}", "");
  74. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  75. const beginningOfFunction =
  76. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  77. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  78. console.log(side + top);
  79. return eval(side + top);
  80. };
  81. detail = async (url, local) => {
  82. try {
  83. const headers = {
  84. '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',
  85. }
  86. const html = await request('GET', url, null, headers, local);
  87. let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  88. console.log(baseJsUrl);
  89. const baseContent = await request('GET', baseJsUrl, null, headers, local);
  90. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  91. let match = html.match(regex);
  92. if (!match || !match.length) {
  93. throw new Error('JSON not found.');
  94. }
  95. const ytInitialPlayerResponse = JSON.parse(match[1]);
  96. console.log(ytInitialPlayerResponse);
  97. const originVideoDetails = ytInitialPlayerResponse["videoDetails"];
  98. const thumbnails = []
  99. for (const item of originVideoDetails["thumbnail"]["thumbnails"]) {
  100. thumbnails.push({
  101. "url": item["url"],
  102. "width": item["width"] + "",
  103. "height": item["height"] + ""
  104. })
  105. }
  106. const formats = []
  107. for (let format of [].concat(ytInitialPlayerResponse["streamingData"]["formats"]).concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  108. console.log(format);
  109. if (!format["url"]) {
  110. format["url"] = getUrlFromSignature(format["signatureCipher"], baseContent);
  111. }
  112. if (format["url"]) {
  113. const {vcodec, acodec} = parseCodecs(format)
  114. if (vcodec && acodec) {
  115. formats.push({
  116. "width": format["width"] + "",
  117. "height": format["height"] + "",
  118. "type": format["mimeType"],
  119. "quality": format["quality"],
  120. "itag": format["itag"],
  121. "fps": format["fps"] + "",
  122. "bitrate": format["bitrate"] + "",
  123. "url": format["url"],
  124. "ext": "mp4",
  125. "vcodec": vcodec,
  126. "acodec": acodec,
  127. "vbr": "0",
  128. "abr": "0",
  129. "container": "mp4_dash"
  130. })
  131. }
  132. }
  133. }
  134. regex = /var ytInitialData\s*=\s*({.*?});/;
  135. match = html.match(regex);
  136. if (!match || !match.length) {
  137. throw new Error('JSON not found.');
  138. }
  139. if (!match || !match.length) {
  140. throw new Error('JSON not found.');
  141. }
  142. const ytInitialData = JSON.parse(match[1]);
  143. console.log(ytInitialData);
  144. const recommendInfo = [];
  145. for (const item of ytInitialData["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"]) {
  146. if (item["compactVideoRenderer"]) {
  147. const recommendVideo = item["compactVideoRenderer"];
  148. console.log(recommendVideo);
  149. if (recommendVideo["videoId"]) {
  150. recommendInfo.push({
  151. "type": "gridVideoRenderer",
  152. "videoId": recommendVideo["videoId"],
  153. "title": recommendVideo["title"]?.["simpleText"],
  154. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  155. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  156. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  157. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  158. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  159. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  160. })
  161. }
  162. }
  163. }
  164. const videoDetails = {
  165. "isLiveContent": originVideoDetails["isLiveContent"],
  166. "title": originVideoDetails["title"],
  167. "thumbnails": thumbnails,
  168. "description": originVideoDetails["shortDescription"],
  169. "lengthSeconds": originVideoDetails["lengthSeconds"],
  170. "viewCount": originVideoDetails["viewCount"],
  171. "keywords": originVideoDetails["keywords"],
  172. "author": originVideoDetails["author"],
  173. "channelID": originVideoDetails["channelId"],
  174. "recommendInfo": recommendInfo,
  175. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  176. "videoId": originVideoDetails["videoId"]
  177. }
  178. return {
  179. "code": 200,
  180. "msg": "",
  181. "data": {
  182. "videoDetails": videoDetails,
  183. "streamingData": {
  184. "formats": formats
  185. }
  186. },
  187. "id": "MusicDetailViewModel_detail_url"
  188. }
  189. } catch (e) {
  190. console.log(e);
  191. return {
  192. "code": -1,
  193. "msg": e.toString()
  194. }
  195. }
  196. }
  197. search = async (keyword, next, local) => {
  198. try {
  199. if (next) {
  200. const nextObject = JSON.parse(next);
  201. const key = nextObject["key"];
  202. const body = {
  203. context: {
  204. client: {
  205. clientName: "WEB",
  206. clientVersion: "2.20240506.01.00",
  207. },
  208. },
  209. continuation: nextObject["continuation"]
  210. };
  211. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
  212. res = JSON.parse(res);
  213. console.log(res);
  214. const videos = [];
  215. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  216. const video = item["videoRenderer"];
  217. if (video && video["videoId"]) {
  218. videos.push({
  219. "type": "videoWithContextRenderer",
  220. "data": {
  221. "videoId": video["videoId"],
  222. "title": video["title"]?.["runs"]?.[0]?.["text"],
  223. "thumbnails": video["thumbnail"]?.["thumbnails"],
  224. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  225. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  226. "viewCountText": video["viewCountText"]?.["simpleText"],
  227. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  228. "lengthText": video["lengthText"]?.["simpleText"]
  229. }
  230. });
  231. }
  232. }
  233. return {
  234. "code": 200,
  235. "msg": "",
  236. "data": {
  237. "data": videos,
  238. "next": JSON.stringify({
  239. "key": nextObject["key"],
  240. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  241. }),
  242. },
  243. "id": "MusicSearchResultViewModel_search_result"
  244. }
  245. } else {
  246. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  247. const html = await request('GET', url, null, {}, local);
  248. let regex = /var ytInitialData\s*=\s*({.*?});/;
  249. let match = html.match(regex);
  250. if (!match || !match.length) {
  251. throw new Error('JSON not found.');
  252. }
  253. const ytInitialDataResp = JSON.parse(match[1]);
  254. console.log(ytInitialDataResp);
  255. const videos = [];
  256. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  257. if (item["videoRenderer"]) {
  258. const video = item["videoRenderer"];
  259. if (video && video["videoId"]) {
  260. videos.push({
  261. "type": "videoWithContextRenderer",
  262. "data": {
  263. "videoId": video["videoId"],
  264. "title": video["title"]?.["runs"]?.[0]?.["text"],
  265. "thumbnails": video["thumbnail"]?.["thumbnails"],
  266. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  267. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  268. "viewCountText": video["viewCountText"]?.["simpleText"],
  269. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  270. "lengthText": video["lengthText"]?.["simpleText"]
  271. }
  272. });
  273. }
  274. }
  275. }
  276. let next = {};
  277. if (html.split("innertubeApiKey").length > 0) {
  278. // 写入path
  279. next["key"] = html
  280. .split("innertubeApiKey")[1]
  281. .trim()
  282. .split(",")[0]
  283. .split('"')[2];
  284. }
  285. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  286. return {
  287. "code": 200,
  288. "msg": "",
  289. "data": {
  290. "data": videos,
  291. "next": JSON.stringify(next),
  292. },
  293. "id": "MusicSearchResultViewModel_search_result"
  294. }
  295. }
  296. } catch (e) {
  297. console.log(e);
  298. return {
  299. "code": -1,
  300. "msg": e.toString()
  301. }
  302. }
  303. }