info.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 new Promise((resolve, reject) => {
  60. AF.request(url, method, data, headers, (data, err) => {
  61. if (err) {
  62. reject(err);
  63. }
  64. resolve(data);
  65. });
  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 = {}
  76. for (const item of signatureCipher.split("&")) {
  77. const [key, value] = item.split('=');
  78. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  79. }
  80. const [url, signature, sp] = [searchParams["url"], searchParams["s"], searchParams["sp"]];
  81. console.log(signatureCipher, url, signature, sp);
  82. return `${url}&${sp}=${decipher(signature)}`;
  83. }
  84. getDecipherFunction = (string) => {
  85. const js = string.replace("var _yt_player={}", "");
  86. const top = getStringBetween(js, `a=a.split("")`, "};", 1, -28);
  87. const beginningOfFunction =
  88. "var " + getStringBetween(top, `a=a.split("")`, "(", 10, 1).split(".")[0] + "=";
  89. const side = getStringBetween(js, beginningOfFunction, "};", 2, -beginningOfFunction.length);
  90. console.log(side + top);
  91. return eval(side + top);
  92. };
  93. detail = async (url, local) => {
  94. try {
  95. console.log(url);
  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 html = await request('GET', url, null, headers, local);
  100. let baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  101. console.log(baseJsUrl);
  102. const baseContent = await request('GET', baseJsUrl, null, headers, local);
  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. const ret = {
  192. "code": 200,
  193. "msg": "",
  194. "data": {
  195. "videoDetails": videoDetails,
  196. "streamingData": {
  197. "formats": formats
  198. }
  199. },
  200. "id": "MusicDetailViewModel_detail_url"
  201. }
  202. console.log(ret);
  203. return ret;
  204. } catch (e) {
  205. console.log(e);
  206. return {
  207. "code": -1,
  208. "msg": e.toString()
  209. }
  210. }
  211. }
  212. search = async (keyword, next, local) => {
  213. try {
  214. if (next) {
  215. const nextObject = JSON.parse(next);
  216. const key = nextObject["key"];
  217. const body = {
  218. context: {
  219. client: {
  220. clientName: "WEB",
  221. clientVersion: "2.20240506.01.00",
  222. },
  223. },
  224. continuation: nextObject["continuation"]
  225. };
  226. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, local);
  227. res = JSON.parse(res);
  228. console.log(res);
  229. const videos = [];
  230. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  231. const video = item["videoRenderer"];
  232. if (video && video["videoId"]) {
  233. videos.push({
  234. "type": "videoWithContextRenderer",
  235. "data": {
  236. "videoId": video["videoId"],
  237. "title": video["title"]?.["runs"]?.[0]?.["text"],
  238. "thumbnails": video["thumbnail"]?.["thumbnails"],
  239. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  240. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  241. "viewCountText": video["viewCountText"]?.["simpleText"],
  242. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  243. "lengthText": video["lengthText"]?.["simpleText"]
  244. }
  245. });
  246. }
  247. }
  248. const ret = {
  249. "code": 200,
  250. "msg": "",
  251. "data": {
  252. "data": videos,
  253. "next": JSON.stringify({
  254. "key": nextObject["key"],
  255. "continuation": res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"],
  256. }),
  257. },
  258. "id": "MusicSearchResultViewModel_search_result"
  259. }
  260. console.log(ret);
  261. return ret;
  262. } else {
  263. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  264. const html = await request('GET', url, null, {}, local);
  265. let regex = /var ytInitialData\s*=\s*({.*?});/;
  266. let match = html.match(regex);
  267. if (!match || !match.length) {
  268. throw new Error('JSON not found.');
  269. }
  270. const ytInitialDataResp = JSON.parse(match[1]);
  271. console.log(ytInitialDataResp);
  272. const videos = [];
  273. for (const item of ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]) {
  274. if (item["videoRenderer"]) {
  275. const video = item["videoRenderer"];
  276. if (video && video["videoId"]) {
  277. videos.push({
  278. "type": "videoWithContextRenderer",
  279. "data": {
  280. "videoId": video["videoId"],
  281. "title": video["title"]?.["runs"]?.[0]?.["text"],
  282. "thumbnails": video["thumbnail"]?.["thumbnails"],
  283. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  284. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  285. "viewCountText": video["viewCountText"]?.["simpleText"],
  286. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  287. "lengthText": video["lengthText"]?.["simpleText"]
  288. }
  289. });
  290. }
  291. }
  292. }
  293. let next = {};
  294. if (html.split("innertubeApiKey").length > 0) {
  295. // 写入path
  296. next["key"] = html
  297. .split("innertubeApiKey")[1]
  298. .trim()
  299. .split(",")[0]
  300. .split('"')[2];
  301. }
  302. next["continuation"] = ytInitialDataResp["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]["continuationItemRenderer"]["continuationEndpoint"]["continuationCommand"]["token"]
  303. const ret = {
  304. "code": 200,
  305. "msg": "",
  306. "data": {
  307. "data": videos,
  308. "next": JSON.stringify(next),
  309. },
  310. "id": "MusicSearchResultViewModel_search_result"
  311. }
  312. console.log(ret);
  313. return ret;
  314. }
  315. } catch (e) {
  316. console.log(e);
  317. return {
  318. "code": -1,
  319. "msg": e.toString()
  320. }
  321. }
  322. }