youtubev2.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. 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', '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.log(`WARNING: Unknown codec ${fullCodec}`);
  30. }
  31. }
  32. if (!vcodec && !acodec) {
  33. if (splitCodecs.length === 2) {
  34. return {
  35. vcodec: splitCodecs[0], acodec: splitCodecs[1]
  36. };
  37. }
  38. } else {
  39. return {
  40. vcodec: vcodec, acodec: acodec
  41. };
  42. }
  43. return {};
  44. }
  45. parseSetCookie = (headers) => {
  46. if (!headers) {
  47. return ""
  48. }
  49. const setCookie = headers['Set-Cookie']
  50. if (!setCookie) {
  51. return ""
  52. }
  53. console.log(`setCookie: ${setCookie}`)
  54. let result = 'PREF=hl=en&tz=UTC; SOCS=CAI; GPS=1; ';
  55. const needCookieNames = ['YSC', 'VISITOR_INFO1_LIVE', 'VISITOR_PRIVACY_METADATA'];
  56. for (const i in needCookieNames) {
  57. const cookieName = needCookieNames[i];
  58. const regexp = new RegExp(`${cookieName}=([^;,]+)`)
  59. const match = setCookie.match(regexp)
  60. if (match && match.length === 2) {
  61. const cookieValue = match[1]
  62. if (i !== needCookieNames.length - 1) {
  63. result += `${cookieName}=${cookieValue}; `
  64. } else {
  65. result += `${cookieName}=${cookieValue}`
  66. }
  67. }
  68. }
  69. console.log(`current cookie: ${result}`)
  70. return result;
  71. }
  72. request = async (method, url, data = null, headers = {}, requestId, platform) => {
  73. if (platform === "WEB") {
  74. url = url.replace("https://www.youtube.com/", "http://16.162.163.175:80/");
  75. url = url.replace("https://music.youtube.com/", "http://16.162.163.175:80/");
  76. }
  77. console.log(`request url:${url}`)
  78. console.log(`request data:${data}`)
  79. console.log(`request method:${method}`)
  80. console.log(`request headers:${JSON.stringify((headers))}`)
  81. if (platform === "WEB") {
  82. const res = await fetch(url, {
  83. 'mode': 'cors', 'method': method, 'headers': headers, 'body': data
  84. })
  85. const resData = await res.text()
  86. return Promise.resolve({
  87. 'data': resData, 'headers': res.headers
  88. });
  89. }
  90. return new Promise((resolve, reject) => {
  91. AF.request(url, method, data, headers, requestId, (data, headers, err) => {
  92. if (err) {
  93. reject(err);
  94. } else {
  95. console.log(`response headers: ${headers}`);
  96. resolve({
  97. 'data': data, 'headers': JSON.parse(headers)
  98. });
  99. }
  100. });
  101. })
  102. }
  103. detail = async (url, requestId, platform) => {
  104. try {
  105. // fetch recommend
  106. const recommendInfo = [];
  107. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  108. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
  109. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  110. 'Accept-Language': 'en-us,en;q=0.5',
  111. 'Sec-Fetch-Mode': 'navigate',
  112. 'Accept-Encoding': 'gzip, deflate, br',
  113. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  114. }, requestId, platform);
  115. let {data: html, headers: htmlHeaders} = htmlResp;
  116. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  117. let match = html.match(regex);
  118. if (match) {
  119. const ytInitialPlayerResponse = JSON.parse(match[1]);
  120. console.log(ytInitialPlayerResponse);
  121. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  122. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  123. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  124. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  125. console.log(ytInitialData);
  126. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  127. if (item["compactVideoRenderer"]) {
  128. const recommendVideo = item["compactVideoRenderer"];
  129. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  130. if (recommendVideo["videoId"]) {
  131. recommendInfo.push({
  132. "type": "gridVideoRenderer",
  133. "videoId": recommendVideo["videoId"],
  134. "title": recommendVideo["title"]?.["simpleText"],
  135. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  136. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  137. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  138. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  139. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  140. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  141. })
  142. }
  143. }
  144. }
  145. }
  146. }
  147. let thumbnails = [];
  148. let originFormats = [];
  149. let originVideoDetails = undefined;
  150. // android
  151. try {
  152. const apiUrl = `https://music.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8`;
  153. const apiResp = await request('POST', apiUrl, JSON.stringify({
  154. "context": {
  155. "client": {
  156. "clientName": "ANDROID", "hl": "en", "clientVersion": "18.49.37", "gl": "US"
  157. }
  158. }, "videoId": url.replace('https://www.youtube.com/watch?v=', ''), "params": "CgIQBg"
  159. }), {
  160. 'Host': 'www.youtube.com',
  161. 'Connection': 'keep-alive',
  162. 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  163. 'Accept-Language': 'en-US,en',
  164. 'Cookie': parseSetCookie(htmlHeaders),
  165. 'Content-Type': 'application/json'
  166. }, requestId, platform);
  167. let {data: apiData, _} = apiResp;
  168. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  169. const res = JSON.parse(apiData);
  170. const currentFormats = [];
  171. originVideoDetails = res["videoDetails"];
  172. for (const format of [].concat(res["streamingData"]["formats"] || []).concat(res["streamingData"]["adaptiveFormats"] || [])) {
  173. if (format) {
  174. format["from"] = "android"
  175. currentFormats.push(format);
  176. }
  177. }
  178. originFormats = originFormats.concat(currentFormats);
  179. } catch (e) {
  180. console.log(`can not found format android api error: ${e}`);
  181. const ret = {
  182. "code": -1, "msg": e.toString()
  183. }
  184. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  185. return ret;
  186. }
  187. console.log(`after android api, format size:${originFormats.length}`);
  188. let audioUrl = ""
  189. for (let format of originFormats) {
  190. if (format["url"]) {
  191. const {vcodec, acodec} = parseCodecs(format)
  192. if (!vcodec && acodec) {
  193. audioUrl = format["url"]
  194. break
  195. }
  196. }
  197. }
  198. const formats = [];
  199. const qualities = [];
  200. for (let format of originFormats) {
  201. console.log(format);
  202. if (format["height"] && parseInt(format["height"]) > 720) {
  203. continue
  204. }
  205. if (format && qualities.indexOf(format['qualityLabel']) === -1) {
  206. if (format["url"]) {
  207. const {vcodec, acodec} = parseCodecs(format)
  208. if (vcodec && acodec) {
  209. const current = {
  210. "width": format["width"] + "",
  211. "height": format["height"] + "",
  212. "type": format["mimeType"],
  213. "quality": format["qualityLabel"],
  214. "itag": format["itag"],
  215. "fps": format["fps"] + "",
  216. "bitrate": format["bitrate"] + "",
  217. "videoUrl": format["url"],
  218. "ext": "mp4",
  219. "vcodec": vcodec,
  220. "acodec": acodec,
  221. "vbr": "0",
  222. "abr": "0",
  223. "container": "mp4_dash",
  224. "from": format["from"],
  225. "audioUrl": audioUrl
  226. }
  227. if (platform === "WEB") {
  228. current["source"] = format
  229. }
  230. formats.push(current)
  231. qualities.push(format["qualityLabel"]);
  232. } else if (vcodec && !acodec) {
  233. const current = {
  234. "width": format["width"] + "",
  235. "height": format["height"] + "",
  236. "type": format["mimeType"],
  237. "quality": format["qualityLabel"],
  238. "itag": format["itag"],
  239. "fps": format["fps"] + "",
  240. "bitrate": format["bitrate"] + "",
  241. "videoUrl": format["url"],
  242. "ext": "mp4",
  243. "vcodec": vcodec,
  244. "acodec": acodec,
  245. "vbr": "0",
  246. "abr": "0",
  247. "container": "mp4_dash",
  248. "from": format["from"],
  249. "audioUrl": audioUrl
  250. }
  251. if (platform === "WEB") {
  252. current["source"] = format
  253. }
  254. formats.push(current)
  255. qualities.push(format["qualityLabel"]);
  256. }
  257. }
  258. }
  259. }
  260. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  261. thumbnails.push({
  262. 'url': item['url'], 'width': item['width'] + "", 'height': item['height'] + ""
  263. })
  264. }
  265. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  266. const videoDetails = {
  267. "isLiveContent": originVideoDetails["isLiveContent"],
  268. "title": originVideoDetails["title"],
  269. "thumbnails": thumbnails,
  270. "description": originVideoDetails["shortDescription"],
  271. "lengthSeconds": originVideoDetails["lengthSeconds"],
  272. "viewCount": originVideoDetails["viewCount"],
  273. "keywords": originVideoDetails["keywords"],
  274. "author": originVideoDetails["author"],
  275. "channelID": originVideoDetails["channelId"],
  276. "recommendInfo": recommendInfo,
  277. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  278. "videoId": originVideoDetails["videoId"]
  279. }
  280. const ret = {
  281. "code": 200, "msg": "", "requestId": requestId, "data": {
  282. "videoDetails": videoDetails, "streamingData": {
  283. "formats": formats
  284. }
  285. }, "id": "MusicDetailViewModel_detail_url"
  286. }
  287. console.log(`detail result: ${JSON.stringify(ret)}`);
  288. return ret;
  289. } catch (e) {
  290. const ret = {
  291. "code": -1, "msg": e.toString(), "requestId": requestId,
  292. }
  293. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  294. console.log(e);
  295. return ret;
  296. }
  297. }
  298. search = async (keyword, next, requestId, platform) => {
  299. try {
  300. console.log(`search keyword: ${keyword}`);
  301. console.log(`search next: ${next}`);
  302. if (next) {
  303. const nextObject = JSON.parse(next);
  304. const key = nextObject["key"];
  305. const body = {
  306. context: {
  307. client: {
  308. clientName: "WEB", clientVersion: "2.20240506.01.00",
  309. },
  310. }, continuation: nextObject["continuation"]
  311. };
  312. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, requestId, platform);
  313. const {data, _} = res;
  314. res = JSON.parse(data);
  315. const videos = [];
  316. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  317. const video = item["videoRenderer"];
  318. console.log(video);
  319. if (video && video["videoId"] && video["lengthText"]) {
  320. videos.push({
  321. "type": "videoWithContextRenderer", "data": {
  322. "videoId": video["videoId"],
  323. "title": video["title"]?.["runs"]?.[0]?.["text"],
  324. "thumbnails": video["thumbnail"]?.["thumbnails"],
  325. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  326. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  327. "viewCountText": video["viewCountText"]?.["simpleText"],
  328. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  329. "lengthText": video["lengthText"]?.["simpleText"]
  330. }
  331. });
  332. }
  333. }
  334. const ret = {
  335. "code": 200, "msg": "", "requestId": requestId, "data": {
  336. "data": videos, "next": JSON.stringify({
  337. "key": nextObject["key"],
  338. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  339. }),
  340. }, "id": "MusicSearchResultViewModel_search_result"
  341. }
  342. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  343. return ret;
  344. } else {
  345. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  346. const htmlRes = await request('GET', url, null, {}, requestId, platform);
  347. const {data: html, _} = htmlRes;
  348. let regex = /var ytInitialData\s*=\s*({.*?});/;
  349. let match = html.match(regex);
  350. if (!match || !match.length) {
  351. console.log("can not found ytInitialData");
  352. throw new Error('JSON not found: ytInitialData');
  353. }
  354. const ytInitialDataResp = JSON.parse(match[1]);
  355. console.log(ytInitialDataResp);
  356. const videos = [];
  357. const contents = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"] || []
  358. for (const content of contents) {
  359. const currentContents = content["itemSectionRenderer"]?.["contents"]
  360. if (Array.isArray(currentContents)) {
  361. for (const currentContent of currentContents) {
  362. if (currentContent["videoRenderer"]) {
  363. const video = currentContent["videoRenderer"];
  364. console.log(video);
  365. if (video && video["videoId"] && video["lengthText"]) {
  366. videos.push({
  367. "type": "videoWithContextRenderer", "data": {
  368. "videoId": video["videoId"],
  369. "title": video["title"]?.["runs"]?.[0]?.["text"],
  370. "thumbnails": video["thumbnail"]?.["thumbnails"],
  371. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  372. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  373. "viewCountText": video["viewCountText"]?.["simpleText"],
  374. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  375. "lengthText": video["lengthText"]?.["simpleText"]
  376. }
  377. });
  378. }
  379. }
  380. }
  381. }
  382. }
  383. let next = {};
  384. if (html.split("innertubeApiKey").length > 0) {
  385. next["key"] = html
  386. .split("innertubeApiKey")[1]
  387. .trim()
  388. .split(",")[0]
  389. .split('"')[2];
  390. }
  391. next["continuation"] = contents[contents.length - 1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  392. const ret = {
  393. "code": 200, "msg": "", "requestId": requestId, "data": {
  394. "data": videos, "next": JSON.stringify(next),
  395. }, "id": "MusicSearchResultViewModel_search_result"
  396. }
  397. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  398. return ret;
  399. }
  400. } catch (e) {
  401. const ret = {
  402. "code": -1, "msg": e.toString(), "requestId": requestId,
  403. }
  404. console.log(`search result error: ${JSON.stringify(ret)}`);
  405. return ret;
  406. }
  407. }