youtubev2.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. console.log('v2')
  2. printable = (platform) => {
  3. return platform === "WEB";
  4. }
  5. parseCodecs = (format) => {
  6. const mimeType = format['mimeType']
  7. if (!mimeType) {
  8. return {};
  9. }
  10. const regex = /(?<mimetype>[^/]+\/[^;]+)(?:;\s*codecs="?(?<codecs>[^"]+))?/;
  11. const match = mimeType.match(regex);
  12. if (!match) {
  13. return {};
  14. }
  15. const codecs = match.groups.codecs;
  16. if (!codecs) {
  17. return {};
  18. }
  19. const splitCodecs = codecs.trim().replace(/,$/, '').split(',').map(str => str.trim()).filter(Boolean);
  20. let vcodec = null;
  21. let acodec = null;
  22. for (const fullCodec of splitCodecs) {
  23. const codec = fullCodec.split('.')[0];
  24. if (['avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'].includes(codec)) {
  25. if (!vcodec) {
  26. vcodec = fullCodec;
  27. }
  28. } else if (['mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'].includes(codec)) {
  29. if (!acodec) {
  30. acodec = fullCodec;
  31. }
  32. } else {
  33. console.log(`WARNING: Unknown codec ${fullCodec}`);
  34. }
  35. }
  36. if (!vcodec && !acodec) {
  37. if (splitCodecs.length === 2) {
  38. return {
  39. vcodec: splitCodecs[0],
  40. acodec: splitCodecs[1]
  41. };
  42. }
  43. } else {
  44. return {
  45. vcodec: vcodec,
  46. acodec: acodec
  47. };
  48. }
  49. return {};
  50. }
  51. parseSetCookie = (headers) => {
  52. if (!headers) {
  53. return ""
  54. }
  55. const setCookie = headers['Set-Cookie']
  56. if (!setCookie) {
  57. return ""
  58. }
  59. console.log(`setCookie: ${setCookie}`)
  60. let result = 'PREF=hl=en&tz=UTC; SOCS=CAI; GPS=1; ';
  61. const needCookieNames = ['YSC', 'VISITOR_INFO1_LIVE', 'VISITOR_PRIVACY_METADATA'];
  62. for (const i in needCookieNames) {
  63. const cookieName = needCookieNames[i];
  64. const regexp = new RegExp(`${cookieName}=([^;,]+)`)
  65. const match = setCookie.match(regexp)
  66. if (match && match.length === 2) {
  67. const cookieValue = match[1]
  68. if (i != needCookieNames.length - 1) {
  69. result += `${cookieName}=${cookieValue}; `
  70. } else {
  71. result += `${cookieName}=${cookieValue}`
  72. }
  73. }
  74. }
  75. console.log(`current cookie: ${result}`)
  76. return result;
  77. }
  78. request = async (method, url, data = null, headers = {}, platform) => {
  79. if (platform === "WEB") {
  80. url = url.replace("https://www.youtube.com/", "http://127.0.0.1:80/");
  81. url = url.replace("https://music.youtube.com/", "http://127.0.0.1:80/");
  82. }
  83. console.log(`request url:${url}`)
  84. console.log(`request data:${data}`)
  85. console.log(`request method:${method}`)
  86. console.log(`request headers:${JSON.stringify((headers))}`)
  87. if (platform === "WEB") {
  88. const res = await fetch(url, {
  89. 'mode': 'cors',
  90. 'method': method,
  91. 'headers': headers,
  92. 'body': data
  93. })
  94. const resData = await res.text()
  95. return Promise.resolve({
  96. 'data': resData,
  97. 'headers': res.headers
  98. });
  99. }
  100. return new Promise((resolve, reject) => {
  101. AF.request(url, method, data, headers, (data, headers, err) => {
  102. if (err) {
  103. reject(err);
  104. } else {
  105. console.log(`response headers: ${headers}`);
  106. resolve({
  107. 'data': data,
  108. 'headers': JSON.parse(headers)
  109. });
  110. }
  111. });
  112. })
  113. }
  114. detail = async (url, platform) => {
  115. try {
  116. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  117. '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',
  118. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  119. 'Accept-Language': 'en-us,en;q=0.5',
  120. 'Sec-Fetch-Mode': 'navigate',
  121. 'Accept-Encoding': 'gzip, deflate, br',
  122. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  123. }, platform);
  124. let {data: html, headers: htmlHeaders} = htmlResp;
  125. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  126. let match = html.match(regex);
  127. if (!match || !match.length) {
  128. console.log('can not found JSON: ytInitialPlayerResponse');
  129. throw new Error('JSON not found: ytInitialPlayerResponse');
  130. }
  131. const ytInitialPlayerResponse = JSON.parse(match[1]);
  132. if (printable(platform)) {
  133. console.log(ytInitialPlayerResponse);
  134. }
  135. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  136. const thumbnails = []
  137. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  138. thumbnails.push({
  139. 'url': item['url'],
  140. 'width': item['width'] + "",
  141. 'height': item['height'] + ""
  142. })
  143. }
  144. let originFormats = [];
  145. // android
  146. try {
  147. const apiUrl = `https://music.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8`;
  148. const apiResp = await request('POST', apiUrl, JSON.stringify({
  149. "context": {
  150. "client": {
  151. "clientName": "ANDROID",
  152. "hl": "en",
  153. "clientVersion": "18.49.37",
  154. "gl": "US"
  155. }
  156. },
  157. "videoId": url.replace('https://www.youtube.com/watch?v=', ''),
  158. "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. }, 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. for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  172. if (format) {
  173. format["from"] = "android"
  174. currentFormats.push(format);
  175. }
  176. }
  177. originFormats = originFormats.concat(currentFormats);
  178. } catch (e) {
  179. console.log(`can not found format android api error: ${e}`);
  180. const ret = {
  181. "code": -1,
  182. "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. // web
  189. const currentFormats = [];
  190. for (const format of ytInitialPlayerResponse["streamingData"]["formats"].concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  191. if (format) {
  192. format["from"] = "web"
  193. currentFormats.push(format);
  194. }
  195. }
  196. originFormats = originFormats.concat(currentFormats);
  197. console.log(`after html, format size:${originFormats.length}`);
  198. let audioUrl = ""
  199. for (let format of originFormats) {
  200. if (format["url"]) {
  201. const {vcodec, acodec} = parseCodecs(format)
  202. if (!vcodec && acodec) {
  203. audioUrl = format["url"]
  204. break
  205. }
  206. }
  207. }
  208. const formats = [];
  209. const qualities = [];
  210. for (let format of originFormats) {
  211. if (printable(platform)) {
  212. console.log(format);
  213. }
  214. if (format && qualities.indexOf(format['qualityLabel']) === -1) {
  215. if (format["url"]) {
  216. const {vcodec, acodec} = parseCodecs(format)
  217. if (vcodec && acodec) {
  218. const current = {
  219. "width": format["width"] + "",
  220. "height": format["height"] + "",
  221. "type": format["mimeType"],
  222. "quality": format["qualityLabel"],
  223. "itag": format["itag"],
  224. "fps": format["fps"] + "",
  225. "bitrate": format["bitrate"] + "",
  226. "url": format["url"],
  227. "ext": "mp4",
  228. "vcodec": vcodec,
  229. "acodec": acodec,
  230. "vbr": "0",
  231. "abr": "0",
  232. "container": "mp4_dash",
  233. "from": format["from"],
  234. "audioUrl": audioUrl
  235. }
  236. if (platform === "WEB") {
  237. current["source"] = format
  238. }
  239. formats.push(current)
  240. qualities.push(format["qualityLabel"]);
  241. } else if (vcodec && !acodec) {
  242. const current = {
  243. "width": format["width"] + "",
  244. "height": format["height"] + "",
  245. "type": format["mimeType"],
  246. "quality": format["qualityLabel"],
  247. "itag": format["itag"],
  248. "fps": format["fps"] + "",
  249. "bitrate": format["bitrate"] + "",
  250. "videoUrl": format["url"],
  251. "ext": "mp4",
  252. "vcodec": vcodec,
  253. "acodec": acodec,
  254. "vbr": "0",
  255. "abr": "0",
  256. "container": "mp4_dash",
  257. "from": format["from"],
  258. "audioUrl": audioUrl
  259. }
  260. if (platform === "WEB") {
  261. current["source"] = format
  262. }
  263. formats.push(current)
  264. qualities.push(format["qualityLabel"]);
  265. }
  266. }
  267. }
  268. }
  269. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  270. const recommendInfo = [];
  271. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  272. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  273. if (printable(platform)) {
  274. console.log(ytInitialData);
  275. }
  276. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  277. if (item["compactVideoRenderer"]) {
  278. const recommendVideo = item["compactVideoRenderer"];
  279. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  280. if (recommendVideo["videoId"]) {
  281. recommendInfo.push({
  282. "type": "gridVideoRenderer",
  283. "videoId": recommendVideo["videoId"],
  284. "title": recommendVideo["title"]?.["simpleText"],
  285. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  286. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  287. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  288. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  289. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  290. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  291. })
  292. }
  293. }
  294. }
  295. }
  296. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  297. const videoDetails = {
  298. "isLiveContent": originVideoDetails["isLiveContent"],
  299. "title": originVideoDetails["title"],
  300. "thumbnails": thumbnails,
  301. "description": originVideoDetails["shortDescription"],
  302. "lengthSeconds": originVideoDetails["lengthSeconds"],
  303. "viewCount": originVideoDetails["viewCount"],
  304. "keywords": originVideoDetails["keywords"],
  305. "author": originVideoDetails["author"],
  306. "channelID": originVideoDetails["channelId"],
  307. "recommendInfo": recommendInfo,
  308. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  309. "videoId": originVideoDetails["videoId"]
  310. }
  311. const ret = {
  312. "code": 200,
  313. "msg": "",
  314. "data": {
  315. "videoDetails": videoDetails,
  316. "streamingData": {
  317. "formats": formats
  318. }
  319. },
  320. "id": "MusicDetailViewModel_detail_url"
  321. }
  322. console.log(`detail result: ${JSON.stringify(ret)}`);
  323. return ret;
  324. } catch (e) {
  325. const ret = {
  326. "code": -1,
  327. "msg": e.toString()
  328. }
  329. console.log(`detail2 result error: ${JSON.stringify(ret)}`);
  330. console.log(e);
  331. return ret;
  332. }
  333. }
  334. search = async (keyword, next, platform) => {
  335. try {
  336. console.log(`search keyword: ${keyword}`);
  337. console.log(`search next: ${next}`);
  338. if (next) {
  339. const nextObject = JSON.parse(next);
  340. const key = nextObject["key"];
  341. const body = {
  342. context: {
  343. client: {
  344. clientName: "WEB",
  345. clientVersion: "2.20240506.01.00",
  346. },
  347. },
  348. continuation: nextObject["continuation"]
  349. };
  350. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  351. const {data, _} = res;
  352. res = JSON.parse(data);
  353. const videos = [];
  354. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  355. const video = item["videoRenderer"];
  356. if (printable(platform)) {
  357. console.log(video);
  358. }
  359. if (video && video["videoId"] && video["lengthText"]) {
  360. videos.push({
  361. "type": "videoWithContextRenderer",
  362. "data": {
  363. "videoId": video["videoId"],
  364. "title": video["title"]?.["runs"]?.[0]?.["text"],
  365. "thumbnails": video["thumbnail"]?.["thumbnails"],
  366. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  367. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  368. "viewCountText": video["viewCountText"]?.["simpleText"],
  369. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  370. "lengthText": video["lengthText"]?.["simpleText"]
  371. }
  372. });
  373. }
  374. }
  375. const ret = {
  376. "code": 200,
  377. "msg": "",
  378. "data": {
  379. "data": videos,
  380. "next": JSON.stringify({
  381. "key": nextObject["key"],
  382. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  383. }),
  384. },
  385. "id": "MusicSearchResultViewModel_search_result"
  386. }
  387. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  388. return ret;
  389. } else {
  390. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  391. const htmlRes = await request('GET', url, null, {}, platform);
  392. const {data: html, _} = htmlRes;
  393. let regex = /var ytInitialData\s*=\s*({.*?});/;
  394. let match = html.match(regex);
  395. if (!match || !match.length) {
  396. console.log("can not found ytInitialData");
  397. throw new Error('JSON not found: ytInitialData');
  398. }
  399. const ytInitialDataResp = JSON.parse(match[1]);
  400. if (printable(platform)) {
  401. console.log(ytInitialDataResp);
  402. }
  403. const videos = [];
  404. const contents = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"] || []
  405. for (const content of contents) {
  406. const currentContents = content["itemSectionRenderer"]?.["contents"]
  407. if (Array.isArray(currentContents)) {
  408. for (const currentContent of currentContents) {
  409. if (currentContent["videoRenderer"]) {
  410. const video = currentContent["videoRenderer"];
  411. if (printable(platform)) {
  412. console.log(video);
  413. }
  414. if (video && video["videoId"] && video["lengthText"]) {
  415. videos.push({
  416. "type": "videoWithContextRenderer",
  417. "data": {
  418. "videoId": video["videoId"],
  419. "title": video["title"]?.["runs"]?.[0]?.["text"],
  420. "thumbnails": video["thumbnail"]?.["thumbnails"],
  421. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  422. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  423. "viewCountText": video["viewCountText"]?.["simpleText"],
  424. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  425. "lengthText": video["lengthText"]?.["simpleText"]
  426. }
  427. });
  428. }
  429. }
  430. }
  431. }
  432. }
  433. let next = {};
  434. if (html.split("innertubeApiKey").length > 0) {
  435. next["key"] = html
  436. .split("innertubeApiKey")[1]
  437. .trim()
  438. .split(",")[0]
  439. .split('"')[2];
  440. }
  441. next["continuation"] = contents[contents.length - 1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  442. const ret = {
  443. "code": 200,
  444. "msg": "",
  445. "data": {
  446. "data": videos,
  447. "next": JSON.stringify(next),
  448. },
  449. "id": "MusicSearchResultViewModel_search_result"
  450. }
  451. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  452. return ret;
  453. }
  454. } catch (e) {
  455. const ret = {
  456. "code": -1,
  457. "msg": e.toString()
  458. }
  459. console.log(`search result error: ${JSON.stringify(ret)}`);
  460. return ret;
  461. }
  462. }