info.js 13 KB

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