youtubev1.js 18 KB

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