video.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. console.log('bundle2!')
  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");
  81. }
  82. console.log(`request url:${url}`)
  83. console.log(`request data:${data}`)
  84. console.log(`request method:${method}`)
  85. console.log(`request headers:${JSON.stringify((headers))}`)
  86. if (platform === "WEB") {
  87. const res = await fetch(url, {
  88. 'mode': 'cors',
  89. 'method': method,
  90. 'headers': headers,
  91. 'body': data
  92. })
  93. const resData = await res.text()
  94. return Promise.resolve({
  95. 'data': resData,
  96. 'headers': res.headers
  97. });
  98. }
  99. return new Promise((resolve, reject) => {
  100. AF.request(url, method, data, headers, (data, headers, err) => {
  101. if (err) {
  102. reject(err);
  103. } else {
  104. console.log(`response headers: ${headers}`);
  105. resolve({
  106. 'data': data,
  107. 'headers': JSON.parse(headers)
  108. });
  109. }
  110. });
  111. })
  112. }
  113. getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {
  114. const x = string.indexOf(needleStart);
  115. const y = needleEnd ? string.indexOf(needleEnd, x) : string.length;
  116. return string.substring(x + needleStart.length + offsetEnd, y + offsetStart);
  117. }
  118. findFunction = (jsCode, regexp, platform) => {
  119. const match = jsCode.match(regexp)
  120. if (!match && match.length <= 1) {
  121. return null;
  122. }
  123. let result = "";
  124. const dependencyMatches = match[0].match(/([$a-zA-Z0-9]+\.[$a-zA-Z0-9]+)/g)
  125. const existDependencies = [];
  126. if (dependencyMatches && dependencyMatches.length >= 1) {
  127. for (let currentMatch of dependencyMatches) {
  128. const varName = currentMatch.split('.')[0];
  129. if (existDependencies.includes(varName)) {
  130. continue
  131. }
  132. if (!/^[$A-Z]+$/.test(varName)) {
  133. continue
  134. }
  135. const varNameMatch = jsCode.match(new RegExp(`var \\${varName}={(.|\\n)*?};`), 'ig');
  136. if (varNameMatch && varNameMatch.length >= 1) {
  137. result += varNameMatch[0] + "\n";
  138. }
  139. existDependencies.push(varName);
  140. }
  141. }
  142. result += `\n${match[0]}`;
  143. if (printable(platform)) {
  144. console.log(`findFunction result: ` + result);
  145. }
  146. return eval(result);
  147. };
  148. const cache = {};
  149. fetchBaseJSContent = async (baseJsUrl, platform) => {
  150. const cacheKey = `jsContent:${baseJsUrl}`;
  151. if (cache[cacheKey]) {
  152. console.log(`baseContent from cache: ${baseJsUrl}`);
  153. return cache[cacheKey];
  154. }
  155. console.log(`extract baseUrl: ${baseJsUrl}`);
  156. const baseContentResp = await request('GET', baseJsUrl, null, {
  157. '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',
  158. }, platform);
  159. const {data, _} = baseContentResp;
  160. cache[cacheKey] = data;
  161. return data;
  162. }
  163. extractJSSignatureFunction = async (baseJsUrl, platform) => {
  164. const cacheKey = `jsSign:${baseJsUrl}`
  165. if (cache[cacheKey]) {
  166. console.log(`jsSign from cache: ${baseJsUrl}`);
  167. return cache[cacheKey];
  168. }
  169. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  170. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{a=a\.split\(""\).*};/, platform);
  171. cache[cacheKey] = result
  172. return result
  173. }
  174. extractNJSFunction = async (baseJsUrl, platform) => {
  175. const cacheKey = `jsN:${baseJsUrl}`
  176. if (cache[cacheKey]) {
  177. console.log(`jsN from cache: ${baseJsUrl}`);
  178. return cache[cacheKey];
  179. }
  180. const baseJsContent = await fetchBaseJSContent(baseJsUrl, platform);
  181. const result = findFunction(baseJsContent, /([a-zA-Z0-9]+)=function\([a-zA-Z0-9]+\)\{var b=a\.split\(""\)[\s\S]*?};/, platform);
  182. cache[cacheKey] = result
  183. return result
  184. }
  185. signUrl = async (signatureCipher, baseJsUrl, platform) => {
  186. const searchParams = {}
  187. for (const item of signatureCipher.split('&')) {
  188. const [key, value] = item.split('=');
  189. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  190. }
  191. const [url, signature, sp] = [searchParams['url'], searchParams['s'], searchParams['sp']];
  192. const decipher = await extractJSSignatureFunction(baseJsUrl, platform);
  193. if (!decipher) {
  194. return null;
  195. }
  196. if (printable(platform)) {
  197. console.log(`signatureCipher=${signatureCipher}, url=${url}, signature=${signature}, sp=${sp}`)
  198. }
  199. let newUrl = `${url}&${sp}=${decipher(signature)}`;
  200. function replaceUrlParam(url, paramName, paramValue) {
  201. let pattern = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i');
  202. let newUrl = url.replace(pattern, `$1${paramName}=${paramValue}$2`);
  203. if (newUrl === url && url.indexOf('?') === -1) {
  204. newUrl += `?${paramName}=${paramValue}`;
  205. } else if (newUrl === url) {
  206. newUrl += `&${paramName}=${paramValue}`;
  207. }
  208. return newUrl;
  209. }
  210. for (const item of url.split('&')) {
  211. const [key, value] = item.split('=');
  212. searchParams[decodeURIComponent(key)] = decodeURIComponent(value);
  213. }
  214. const nFunction = await extractNJSFunction(baseJsUrl, platform);
  215. const n = searchParams['n']
  216. if (n && nFunction) {
  217. const newN = nFunction(n);
  218. return replaceUrlParam(newUrl, 'n', newN);
  219. }
  220. return newUrl;
  221. }
  222. detail = async (url, platform) => {
  223. try {
  224. const htmlResp = await request('GET', `${url}&bpctr=9999999999&has_verified=1`, null, {
  225. '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',
  226. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  227. 'Accept-Language': 'en-us,en;q=0.5',
  228. 'Sec-Fetch-Mode': 'navigate',
  229. 'Accept-Encoding': 'gzip, deflate, br',
  230. 'Cookie': 'PREF=hl=en&tz=UTC; SOCS=CAI'
  231. }, platform);
  232. let {data: html, headers: htmlHeaders} = htmlResp;
  233. let regex = /var ytInitialPlayerResponse\s*=\s*({.*?});/;
  234. let match = html.match(regex);
  235. if (!match || !match.length) {
  236. console.log('can not found JSON: ytInitialPlayerResponse');
  237. throw new Error('JSON not found: ytInitialPlayerResponse');
  238. }
  239. const ytInitialPlayerResponse = JSON.parse(match[1]);
  240. if (printable(platform)) {
  241. console.log(ytInitialPlayerResponse);
  242. }
  243. const originVideoDetails = ytInitialPlayerResponse['videoDetails'];
  244. const thumbnails = []
  245. for (const item of originVideoDetails['thumbnail']['thumbnails']) {
  246. thumbnails.push({
  247. 'url': item['url'],
  248. 'width': item['width'] + "",
  249. 'height': item['height'] + ""
  250. })
  251. }
  252. let originFormats = [];
  253. // // web
  254. // const currentFormats = [];
  255. // for (const format of ytInitialPlayerResponse["streamingData"]["formats"].concat(ytInitialPlayerResponse["streamingData"]["adaptiveFormats"])) {
  256. // if (format) {
  257. // format["from"] = "web"
  258. // currentFormats.push(format);
  259. // }
  260. // }
  261. // originFormats = originFormats.concat(currentFormats);
  262. // console.log(`after html, format size:${originFormats.length}`);
  263. // android
  264. try {
  265. const apiKey = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
  266. const apiUrl = `https://www.youtube.com/youtubei/v1/player?key=${apiKey}`;
  267. const apiResp = await request('POST', apiUrl, JSON.stringify({
  268. "videoId": url.replace('https://www.youtube.com/watch?v=', ''),
  269. "contentCheckOk": true,
  270. "params": "8AEB",
  271. "context": {
  272. "client": {
  273. "clientName": "ANDROID_MUSIC",
  274. "clientVersion": "5.16.51",
  275. "androidSdkVersion": 30
  276. }
  277. },
  278. "racyCheckOk": true
  279. }), {
  280. 'Host': 'www.youtube.com',
  281. 'Connection': 'keep-alive',
  282. 'User-Agent': 'com.google.android.apps.youtube.music/17.31.35 (Linux; U; Android 11) gzip',
  283. 'Accept-Language': 'en-US,en',
  284. 'Cookie': parseSetCookie(htmlHeaders),
  285. 'Content-Type': 'application/json'
  286. }, platform);
  287. let {data: apiData, _} = apiResp;
  288. console.log(`android api result: ${JSON.stringify(apiResp)}`);
  289. const res = JSON.parse(apiData);
  290. const currentFormats = [];
  291. for (const format of [].concat(res["streamingData"]["formats"]).concat(res["streamingData"]["adaptiveFormats"])) {
  292. if (format) {
  293. format["from"] = "android"
  294. currentFormats.push(format);
  295. }
  296. }
  297. originFormats = originFormats.concat(currentFormats);
  298. } catch (e) {
  299. console.log(`can not found format android api error: ${e}`);
  300. }
  301. console.log(`after android api, format size:${originFormats.length}`);
  302. const baseJsUrl = `https://www.youtube.com${JSON.parse(html.match(/set\(({.+?})\);/)[1])["PLAYER_JS_URL"]}`
  303. let formatIds = [];
  304. const formats = [];
  305. for (let format of originFormats) {
  306. if (printable(platform)) {
  307. console.log(format);
  308. }
  309. if (format && formatIds.indexOf(format['itag']) === -1) {
  310. if (!format["url"]) {
  311. format["url"] = await signUrl(format["signatureCipher"], baseJsUrl, platform);
  312. }
  313. if (format["url"]) {
  314. const {vcodec, acodec} = parseCodecs(format)
  315. if (vcodec && acodec) {
  316. const current = {
  317. "width": format["width"] + "",
  318. "height": format["height"] + "",
  319. "type": format["mimeType"],
  320. "quality": format["qualityLabel"],
  321. "itag": format["itag"],
  322. "fps": format["fps"] + "",
  323. "bitrate": format["bitrate"] + "",
  324. "url": format["url"],
  325. "ext": "mp4",
  326. "vcodec": vcodec,
  327. "acodec": acodec,
  328. "vbr": "0",
  329. "abr": "0",
  330. "container": "mp4_dash",
  331. "from": format["from"]
  332. }
  333. if (platform === "WEB") {
  334. current["source"] = format
  335. }
  336. formats.push(current)
  337. formatIds.push(format["itag"]);
  338. }
  339. }
  340. }
  341. }
  342. const ytInitialDataMatch = html.match(/var ytInitialData\s*=\s*({.*?});/);
  343. const recommendInfo = [];
  344. if (ytInitialDataMatch && ytInitialDataMatch.length === 2) {
  345. const ytInitialData = JSON.parse(ytInitialDataMatch[1]);
  346. if (printable(platform)) {
  347. console.log(ytInitialData);
  348. }
  349. for (const item of ytInitialData["contents"]?.["twoColumnWatchNextResults"]?.["secondaryResults"]?.["secondaryResults"]?.["results"] || []) {
  350. if (item["compactVideoRenderer"]) {
  351. const recommendVideo = item["compactVideoRenderer"];
  352. console.log(`recommend video: ${JSON.stringify(recommendVideo)}`);
  353. if (recommendVideo["videoId"]) {
  354. recommendInfo.push({
  355. "type": "gridVideoRenderer",
  356. "videoId": recommendVideo["videoId"],
  357. "title": recommendVideo["title"]?.["simpleText"],
  358. "thumbnails": recommendVideo["thumbnail"]?.["thumbnails"],
  359. "channelName": recommendVideo["longBylineText"]?.["runs"]?.[0]?.["text"],
  360. "publishedTimeText": recommendVideo["publishedTimeText"]?.["simpleText"],
  361. "viewCountText": recommendVideo["viewCountText"]?.["simpleText"],
  362. "shortViewCountText": recommendVideo["shortViewCountText"]?.["simpleText"],
  363. "lengthText": recommendVideo["lengthText"]?.["simpleText"]
  364. })
  365. }
  366. }
  367. }
  368. }
  369. formats.sort((a, b) => parseInt(a["height"]) - parseInt(b["height"]));
  370. const videoDetails = {
  371. "isLiveContent": originVideoDetails["isLiveContent"],
  372. "title": originVideoDetails["title"],
  373. "thumbnails": thumbnails,
  374. "description": originVideoDetails["shortDescription"],
  375. "lengthSeconds": originVideoDetails["lengthSeconds"],
  376. "viewCount": originVideoDetails["viewCount"],
  377. "keywords": originVideoDetails["keywords"],
  378. "author": originVideoDetails["author"],
  379. "channelID": originVideoDetails["channelId"],
  380. "recommendInfo": recommendInfo,
  381. "channelURL": `https://www.youtube.com/channel/${originVideoDetails["channelId"]}`,
  382. "videoId": originVideoDetails["videoId"]
  383. }
  384. const ret = {
  385. "code": 200,
  386. "msg": "",
  387. "data": {
  388. "videoDetails": videoDetails,
  389. "streamingData": {
  390. "formats": formats
  391. }
  392. },
  393. "id": "MusicDetailViewModel_detail_url"
  394. }
  395. console.log(`detail result: ${JSON.stringify(ret)}`);
  396. return ret;
  397. } catch (e) {
  398. const ret = {
  399. "code": -1,
  400. "msg": e.toString()
  401. }
  402. console.log(`detail result error: ${JSON.stringify(ret)}`);
  403. console.log(e);
  404. return ret;
  405. }
  406. }
  407. search = async (keyword, next, platform) => {
  408. try {
  409. console.log(`search keyword: ${keyword}`);
  410. console.log(`search next: ${next}`);
  411. if (next) {
  412. const nextObject = JSON.parse(next);
  413. const key = nextObject["key"];
  414. const body = {
  415. context: {
  416. client: {
  417. clientName: "WEB",
  418. clientVersion: "2.20240506.01.00",
  419. },
  420. },
  421. continuation: nextObject["continuation"]
  422. };
  423. let res = await request('POST', `https://www.youtube.com/youtubei/v1/search?key=${key}`, JSON.stringify(body), {}, platform);
  424. const {data, _} = res;
  425. res = JSON.parse(data);
  426. const videos = [];
  427. for (const item of res["onResponseReceivedCommands"][0]["appendContinuationItemsAction"]["continuationItems"][0]["itemSectionRenderer"]["contents"]) {
  428. const video = item["videoRenderer"];
  429. if (printable(platform)) {
  430. console.log(video);
  431. }
  432. if (video && video["videoId"]) {
  433. videos.push({
  434. "type": "videoWithContextRenderer",
  435. "data": {
  436. "videoId": video["videoId"],
  437. "title": video["title"]?.["runs"]?.[0]?.["text"],
  438. "thumbnails": video["thumbnail"]?.["thumbnails"],
  439. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  440. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  441. "viewCountText": video["viewCountText"]?.["simpleText"],
  442. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  443. "lengthText": video["lengthText"]?.["simpleText"]
  444. }
  445. });
  446. }
  447. }
  448. const ret = {
  449. "code": 200,
  450. "msg": "",
  451. "data": {
  452. "data": videos,
  453. "next": JSON.stringify({
  454. "key": nextObject["key"],
  455. "continuation": res["onResponseReceivedCommands"]?.[0]?.["appendContinuationItemsAction"]?.["continuationItems"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"],
  456. }),
  457. },
  458. "id": "MusicSearchResultViewModel_search_result"
  459. }
  460. console.log(`[next] search result: ${JSON.stringify(ret)}`);
  461. return ret;
  462. } else {
  463. let url = `https://www.youtube.com/results?q=${encodeURIComponent(keyword)}&sp=EgIQAQ%253D%253D`;
  464. const htmlRes = await request('GET', url, null, {}, platform);
  465. const {data: html, _} = htmlRes;
  466. let regex = /var ytInitialData\s*=\s*({.*?});/;
  467. let match = html.match(regex);
  468. if (!match || !match.length) {
  469. console.log("can not found ytInitialData");
  470. throw new Error('JSON not found: ytInitialData');
  471. }
  472. const ytInitialDataResp = JSON.parse(match[1]);
  473. const videos = [];
  474. for (const item of ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[0]?.["itemSectionRenderer"]?.["contents"]) {
  475. if (item["videoRenderer"]) {
  476. const video = item["videoRenderer"];
  477. if (printable(platform)) {
  478. console.log(video);
  479. }
  480. if (video && video["videoId"]) {
  481. videos.push({
  482. "type": "videoWithContextRenderer",
  483. "data": {
  484. "videoId": video["videoId"],
  485. "title": video["title"]?.["runs"]?.[0]?.["text"],
  486. "thumbnails": video["thumbnail"]?.["thumbnails"],
  487. "channelName": video["longBylineText"]?.["runs"]?.[0]?.["text"],
  488. "publishedTimeText": video["publishedTimeText"]?.["simpleText"],
  489. "viewCountText": video["viewCountText"]?.["simpleText"],
  490. "shortViewCountText": video["shortViewCountText"]?.["simpleText"],
  491. "lengthText": video["lengthText"]?.["simpleText"]
  492. }
  493. });
  494. }
  495. }
  496. }
  497. let next = {};
  498. if (html.split("innertubeApiKey").length > 0) {
  499. next["key"] = html
  500. .split("innertubeApiKey")[1]
  501. .trim()
  502. .split(",")[0]
  503. .split('"')[2];
  504. }
  505. next["continuation"] = ytInitialDataResp["contents"]?.["twoColumnSearchResultsRenderer"]?.["primaryContents"]?.["sectionListRenderer"]?.["contents"]?.[1]?.["continuationItemRenderer"]?.["continuationEndpoint"]?.["continuationCommand"]?.["token"]
  506. const ret = {
  507. "code": 200,
  508. "msg": "",
  509. "data": {
  510. "data": videos,
  511. "next": JSON.stringify(next),
  512. },
  513. "id": "MusicSearchResultViewModel_search_result"
  514. }
  515. console.log(`unnext search result: ${JSON.stringify(ret)}`);
  516. return ret;
  517. }
  518. } catch (e) {
  519. const ret = {
  520. "code": -1,
  521. "msg": e.toString()
  522. }
  523. console.log(`search result error: ${JSON.stringify(ret)}`);
  524. return ret;
  525. }
  526. }