youtubev1.js 19 KB

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