bili_open.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import { Crypto, jinja2, _ } from 'assets://js/lib/cat.js';
  2. let siteKey = '';
  3. let siteType = 0;
  4. let cookie = '';
  5. let login = '';
  6. let vip = false;
  7. let extendObj = {};
  8. let bili_jct = '';
  9. let vod_audio_id = {
  10. 30280: 192000,
  11. 30232: 132000,
  12. 30216: 64000,
  13. };
  14. let vod_codec = {
  15. // 13: 'AV1',
  16. 12: 'HEVC',
  17. 7: 'AVC',
  18. };
  19. const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36';
  20. async function request(reqUrl, ua, buffer) {
  21. let res = await req(reqUrl, {
  22. method: 'get',
  23. headers: ua ? ua : { 'User-Agent': UA },
  24. timeout: 60000,
  25. buffer: buffer ? 1 : 0,
  26. });
  27. return res.content;
  28. }
  29. async function post(reqUrl, postData, ua, posttype) {
  30. let res = await req(reqUrl, {
  31. method: 'post',
  32. headers: ua ? ua : { 'User-Agent': UA },
  33. data: postData,
  34. timeout: 60000,
  35. postType: posttype,
  36. });
  37. return res.content;
  38. }
  39. function getHeaders() {
  40. const headers = {
  41. 'User-Agent': UA,
  42. };
  43. if (!_.isEmpty(cookie)) {
  44. headers.cookie = cookie;
  45. }
  46. return headers;
  47. }
  48. async function getCookie() {
  49. let result = await req('https://www.bilibili.com', {
  50. method: 'get',
  51. headers: { 'User-Agent': UA },
  52. timeout: 60000,
  53. });
  54. const setCookieHeaders = result.headers['set-cookie'];
  55. cookie = setCookieHeaders.map((kk) => kk.split(';')[0] + ';').join('');
  56. }
  57. async function init(cfg) {
  58. siteKey = cfg.skey;
  59. siteType = cfg.stype;
  60. let extend = cfg.ext;
  61. if (cfg.ext.hasOwnProperty('categories')) extend = cfg.ext.categories;
  62. if (cfg.ext.hasOwnProperty('cookie')) cookie = cfg.ext.cookie;
  63. if (cookie.startsWith('http')) cookie = await request(cookie);
  64. // 获取csrf
  65. const cookies = cookie.split(';');
  66. cookies.forEach(cookie => {
  67. if (cookie.includes('bili_jct')) {
  68. bili_jct = cookie.split('=')[1];
  69. }
  70. });
  71. if (_.isEmpty(cookie)) await getCookie();
  72. let result = JSON.parse(await request('https://api.bilibili.com/x/web-interface/nav', getHeaders()));
  73. login = result.data.isLogin;
  74. vip = result.data.vipStatus;
  75. const ext = extend.split('#');
  76. const jsonData = [
  77. {
  78. key: 'order',
  79. name: '排序',
  80. value: [
  81. { n: '综合排序', v: '0' },
  82. { n: '最多点击', v: 'click' },
  83. { n: '最新发布', v: 'pubdate' },
  84. { n: '最多弹幕', v: 'dm' },
  85. { n: '最多收藏', v: 'stow' },
  86. ],
  87. },
  88. {
  89. key: 'duration',
  90. name: '时长',
  91. value: [
  92. { n: '全部时长', v: '0' },
  93. { n: '60分钟以上', v: '4' },
  94. { n: '30~60分钟', v: '3' },
  95. { n: '10~30分钟', v: '2' },
  96. { n: '10分钟以下', v: '1' },
  97. ],
  98. },
  99. ];
  100. const newarr = [];
  101. const d = {};
  102. const sc = {
  103. type_name: "首页",
  104. type_id: "首页",
  105. land: 1,
  106. ratio: 1.33,
  107. }
  108. newarr.push(sc);
  109. for (const kk of ext) {
  110. const c = {
  111. type_name: kk,
  112. type_id: kk,
  113. land: 1,
  114. ratio: 1.33,
  115. };
  116. newarr.push(c);
  117. d[kk] = jsonData;
  118. }
  119. if (!_.isEmpty(bili_jct)) {
  120. const hc = {
  121. type_name: "历史记录",
  122. type_id: "历史记录",
  123. land: 1,
  124. ratio: 1.33,
  125. }
  126. newarr.push(hc);
  127. }
  128. extendObj = {
  129. classes: newarr,
  130. filter: d,
  131. };
  132. }
  133. function home(filter) {
  134. try {
  135. const jSONObject = {
  136. class: extendObj.classes,
  137. };
  138. if (filter) {
  139. jSONObject.filters = extendObj.filter;
  140. }
  141. return JSON.stringify(jSONObject);
  142. } catch (e) {
  143. return '';
  144. }
  145. }
  146. async function homeVod() {
  147. try {
  148. const list = [];
  149. const url = 'https://api.bilibili.com/x/web-interface/index/top/rcmd?ps=14&fresh_idx=1&fresh_idx_1h=1';
  150. const response = await request(url, getHeaders());
  151. const responseData = JSON.parse(response);
  152. const vods = responseData.data.item;
  153. for (const item of vods) {
  154. const vod = {};
  155. let imageUrl = item.pic;
  156. if (imageUrl.startsWith('//')) {
  157. imageUrl = 'https:' + imageUrl;
  158. }
  159. let cd = getFullTime(item.duration);
  160. vod.vod_id = item.bvid;
  161. vod.vod_name = removeTags(item.title);
  162. vod.vod_pic = imageUrl;
  163. vod.vod_remarks = cd;
  164. vod.style = {
  165. type: 'rect',
  166. ratio: 1.33,
  167. },
  168. list.push(vod);
  169. }
  170. const result = { list: list };
  171. return JSON.stringify(result);
  172. } catch (e) { }
  173. }
  174. async function category(tid, page, filter, ext) {
  175. if (page < 1) page = 1;
  176. try {
  177. if (Object.keys(ext).length > 0 && ext.hasOwnProperty('tid') && ext['tid'].length > 0) {
  178. tid = ext['tid'];
  179. }
  180. let url = '';
  181. url = `https://api.bilibili.com/x/web-interface/search/type?search_type=video&keyword=${encodeURIComponent(tid)}`;
  182. if (Object.keys(ext).length > 0) {
  183. for (const k in ext) {
  184. if (k == 'tid') {
  185. continue;
  186. }
  187. url += `&${encodeURIComponent(k)}=${encodeURIComponent(ext[k])}`;
  188. }
  189. }
  190. url += `&page=${encodeURIComponent(page)}`;
  191. if (tid == "首页") {
  192. url = "https://api.bilibili.com/x/web-interface/index/top/rcmd?ps=14&fresh_idx=" + page + "&fresh_idx_1h=" + page;
  193. } else if (tid == "历史记录") {
  194. url = "https://api.bilibili.com/x/v2/history?pn=" + page;
  195. }
  196. const data = JSON.parse(await request(url, getHeaders())).data;
  197. let items = data.result;
  198. if (tid == "首页") {
  199. items = data.item;
  200. } else if (tid == "历史记录") {
  201. items = data;
  202. }
  203. const videos = [];
  204. for (const item of items) {
  205. const video = {};
  206. let pic = item.pic;
  207. if (pic.startsWith('//')) {
  208. pic = 'https:' + pic;
  209. }
  210. let cd = getFullTime(item.duration);
  211. video.vod_remarks = cd;
  212. video.vod_id = item.bvid;
  213. video.vod_name = removeTags(item.title);
  214. video.vod_pic = pic;
  215. video.style = {
  216. type: 'rect',
  217. ratio: 1.33,
  218. },
  219. videos.push(video);
  220. }
  221. const result = {
  222. page: page,
  223. pagecount: data.numPages ?? (page + 1),
  224. limit: videos.length,
  225. total: videos.length * (page + 1),
  226. list: videos,
  227. };
  228. return JSON.stringify(result);
  229. } catch (e) { }
  230. return null;
  231. }
  232. async function detail(ids) {
  233. try {
  234. const bvid = ids;
  235. const detailUrl = `https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`;
  236. const detailData = JSON.parse(await request(detailUrl, getHeaders())).data;
  237. // 记录历史
  238. if (!_.isEmpty(bili_jct)) {
  239. const historyReport = 'https://api.bilibili.com/x/v2/history/report';
  240. let dataPost = {
  241. aid: detailData.aid,
  242. cid: detailData.cid,
  243. csrf: bili_jct,
  244. }
  245. await post(historyReport, dataPost, getHeaders(), 'form');
  246. }
  247. let cd = getFullTime(detailData.duration);
  248. const aid = detailData.aid;
  249. const video = {
  250. vod_id: bvid,
  251. vod_name: detailData.title,
  252. vod_pic: detailData.pic,
  253. type_name: detailData.tname,
  254. vod_year: '',
  255. vod_area: '',
  256. vod_remarks: cd,
  257. vod_actor: '',
  258. vod_director: '',
  259. vod_content: detailData.desc,
  260. };
  261. const playurldata = 'https://api.bilibili.com/x/player/playurl?avid=' + aid + '&cid=' + detailData.cid + '&qn=127&fnval=4048&fourk=1';
  262. const playurldatas = JSON.parse(await request(playurldata, getHeaders()));
  263. const playurldatalist = playurldatas.data;
  264. const accept_quality = playurldatalist.accept_quality;
  265. const accept_description = playurldatalist.accept_description;
  266. const qualitylist = [];
  267. const descriptionList = [];
  268. for (let i = 0; i < accept_quality.length; i++) {
  269. if (!vip) {
  270. if (!login) {
  271. if (accept_quality[i] > 32) continue;
  272. } else {
  273. if (accept_quality[i] > 80) continue;
  274. }
  275. }
  276. descriptionList.push(base64Encode(accept_description[i]));
  277. qualitylist.push(accept_quality[i]);
  278. }
  279. let treeMap = {};
  280. const jSONArray = detailData.pages;
  281. let playList = [];
  282. for (let j = 0; j < jSONArray.length; j++) {
  283. const jSONObject6 = jSONArray[j];
  284. const cid = jSONObject6.cid;
  285. const playUrl = j + '$' + aid + '+' + cid + '+' + qualitylist.join(':') + '+' + descriptionList.join(':');
  286. playList.push(playUrl);
  287. }
  288. treeMap['dash'] = playList.join('#');
  289. treeMap['mp4'] = playList.join('#');
  290. const relatedUrl = 'https://api.bilibili.com/x/web-interface/archive/related?bvid=' + bvid;
  291. const relatedData = JSON.parse(await request(relatedUrl, getHeaders())).data;
  292. playList = [];
  293. for (let j = 0; j < relatedData.length; j++) {
  294. const jSONObject6 = relatedData[j];
  295. const cid = jSONObject6.cid;
  296. const title = jSONObject6.title;
  297. const aaid = jSONObject6.aid;
  298. const playUrl = title + '$' + aaid + '+' + cid + '+' + qualitylist.join(':') + '+' + descriptionList.join(':');
  299. playList.push(playUrl);
  300. }
  301. treeMap['相关'] = playList.join('#');
  302. video.vod_play_from = Object.keys(treeMap).join("$$$");
  303. video.vod_play_url = Object.values(treeMap).join("$$$");
  304. const list = [video];
  305. const result = { list };
  306. return JSON.stringify(result);
  307. } catch (e) { }
  308. return null;
  309. }
  310. async function play(flag, id, flags) {
  311. try {
  312. const playHeaders = { Referer: 'https://www.bilibili.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36' };
  313. const ids = id.split('+');
  314. const aid = ids[0];
  315. const cid = ids[1];
  316. const qualityIds = ids[2].split(':');
  317. const qualityName = ids[3].split(':');
  318. if (flag == 'dash' || flag == '相关') {
  319. // dash mpd 代理
  320. const js2Base = await js2Proxy(true, siteType, siteKey, 'dash/', {});
  321. let urls = [];
  322. for (let i = 0; i < qualityIds.length; i++) {
  323. urls.push(base64Decode(qualityName[i]), js2Base + base64Encode(aid + '+' + cid + '+' + qualityIds[i]));
  324. }
  325. return JSON.stringify({
  326. parse: 0,
  327. url: urls,
  328. header: playHeaders,
  329. });
  330. } else if (flag == 'mp4') {
  331. // 直链
  332. let urls = [];
  333. for (let i = 0; i < qualityIds.length; i++) {
  334. const url = `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&qn=${qualityIds[i]}&fourk=1`;
  335. const resp = JSON.parse(await request(url, getHeaders()));
  336. const data = resp.data;
  337. if (data.quality != qualityIds[i]) continue;
  338. let durl = data.durl[0].url;
  339. urls.push(base64Decode(qualityName[i]), durl);
  340. }
  341. return JSON.stringify({
  342. parse: 0,
  343. url: urls,
  344. header: playHeaders,
  345. });
  346. } else {
  347. // 音频外挂
  348. let urls = [];
  349. let audios = [];
  350. for (let i = 0; i < qualityIds.length; i++) {
  351. const url = `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&qn=${qualityIds[i]}&fnval=4048&fourk=1`;
  352. let resp = JSON.parse(await request(url, getHeaders()));
  353. const dash = resp.data.dash;
  354. const video = dash.video;
  355. const audio = dash.audio;
  356. for (let j = 0; j < video.length; j++) {
  357. const dashjson = video[j];
  358. if (dashjson.id == qualityIds[i]) {
  359. for (const key in vod_codec) {
  360. if (dashjson.codecid == key) {
  361. urls.push(base64Decode(qualityName[i]) + ' ' + vod_codec[key], dashjson.baseUrl);
  362. }
  363. }
  364. }
  365. }
  366. if (audios.length == 0) {
  367. for (let j = 0; j < audio.length; j++) {
  368. const dashjson = audio[j];
  369. for (const key in vod_audio_id) {
  370. if (dashjson.id == key) {
  371. audios.push({
  372. title: _.floor(parseInt(vod_audio_id[key]) / 1024) + 'Kbps',
  373. bit: vod_audio_id[key],
  374. url: dashjson.baseUrl,
  375. });
  376. }
  377. }
  378. }
  379. audios = _.sortBy(audios, 'bit');
  380. }
  381. }
  382. return JSON.stringify({
  383. parse: 0,
  384. url: urls,
  385. extra: {
  386. audio: audios,
  387. },
  388. header: playHeaders,
  389. });
  390. }
  391. } catch (e) { }
  392. return null;
  393. }
  394. async function search(key, quick, pg) {
  395. let page = pg || 1;
  396. if (page == 0) page = 1;
  397. try {
  398. const ext = {
  399. duration: '0',
  400. };
  401. let resp = JSON.parse(await category(key, page, true, ext));
  402. const catVideos = resp.list;
  403. const pageCount = resp.pagecount;
  404. const videos = [];
  405. for (let i = 0; i < catVideos.length; ++i) {
  406. videos.push(catVideos[i]);
  407. }
  408. const result = {
  409. page: page,
  410. pagecount: pageCount,
  411. land: 1,
  412. ratio: 1.33,
  413. list: videos,
  414. };
  415. return JSON.stringify(result);
  416. } catch (e) { }
  417. return null;
  418. }
  419. async function proxy(segments, headers) {
  420. let what = segments[0];
  421. let url = base64Decode(segments[1]);
  422. if (what == 'dash') {
  423. const ids = url.split('+');
  424. const aid = ids[0];
  425. const cid = ids[1];
  426. const str5 = ids[2];
  427. const urls = `https://api.bilibili.com/x/player/playurl?avid=${aid}&cid=${cid}&qn=${str5}&fnval=4048&fourk=1`;
  428. let videoList = '';
  429. let audioList = '';
  430. let resp = JSON.parse(await request(urls, getHeaders()));
  431. const dash = resp.data.dash;
  432. const video = dash.video;
  433. const audio = dash.audio;
  434. for (let i = 0; i < video.length; i++) {
  435. // if (i > 0) continue; // 只取一个
  436. const dashjson = video[i];
  437. if (dashjson.id == str5) {
  438. videoList += getDashMedia(dashjson);
  439. }
  440. }
  441. for (let i = 0; i < audio.length; i++) {
  442. // if (i > 0) continue;
  443. const ajson = audio[i];
  444. for (const key in vod_audio_id) {
  445. if (ajson.id == key) {
  446. audioList += getDashMedia(ajson);
  447. }
  448. }
  449. }
  450. let mpd = getDash(resp, videoList, audioList);
  451. return JSON.stringify({
  452. code: 200,
  453. content: mpd,
  454. headers: {
  455. 'Content-Type': 'application/dash+xml',
  456. },
  457. });
  458. }
  459. return JSON.stringify({
  460. code: 500,
  461. content: '',
  462. });
  463. }
  464. function getDashMedia(dash) {
  465. try {
  466. let qnid = dash.id;
  467. const codecid = dash.codecid;
  468. const media_codecs = dash.codecs;
  469. const media_bandwidth = dash.bandwidth;
  470. const media_startWithSAP = dash.startWithSap;
  471. const media_mimeType = dash.mimeType;
  472. const media_BaseURL = dash.baseUrl.replace(/&/g, '&amp;');
  473. const media_SegmentBase_indexRange = dash.SegmentBase.indexRange;
  474. const media_SegmentBase_Initialization = dash.SegmentBase.Initialization;
  475. const mediaType = media_mimeType.split('/')[0];
  476. let media_type_params = '';
  477. if (mediaType == 'video') {
  478. const media_frameRate = dash.frameRate;
  479. const media_sar = dash.sar;
  480. const media_width = dash.width;
  481. const media_height = dash.height;
  482. media_type_params = `height='${media_height}' width='${media_width}' frameRate='${media_frameRate}' sar='${media_sar}'`;
  483. } else if (mediaType == 'audio') {
  484. for (const key in vod_audio_id) {
  485. if (qnid == key) {
  486. const audioSamplingRate = vod_audio_id[key];
  487. media_type_params = `numChannels='2' sampleRate='${audioSamplingRate}'`;
  488. }
  489. }
  490. }
  491. qnid += '_' + codecid;
  492. return `<AdaptationSet lang="chi">
  493. <ContentComponent contentType="${mediaType}"/>
  494. <Representation id="${qnid}" bandwidth="${media_bandwidth}" codecs="${media_codecs}" mimeType="${media_mimeType}" ${media_type_params} startWithSAP="${media_startWithSAP}">
  495. <BaseURL>${media_BaseURL}</BaseURL>
  496. <SegmentBase indexRange="${media_SegmentBase_indexRange}">
  497. <Initialization range="${media_SegmentBase_Initialization}"/>
  498. </SegmentBase>
  499. </Representation>
  500. </AdaptationSet>`;
  501. } catch (e) {
  502. // Handle exceptions here
  503. }
  504. }
  505. function getDash(ja, videoList, audioList) {
  506. const duration = ja.data.dash.duration;
  507. const minBufferTime = ja.data.dash.minBufferTime;
  508. return `<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd" type="static" mediaPresentationDuration="PT${duration}S" minBufferTime="PT${minBufferTime}S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">
  509. <Period duration="PT${duration}S" start="PT0S">
  510. ${videoList}
  511. ${audioList}
  512. </Period>
  513. </MPD>`;
  514. }
  515. function base64Encode(text) {
  516. return Crypto.enc.Base64.stringify(Crypto.enc.Utf8.parse(text));
  517. }
  518. function base64Decode(text) {
  519. return Crypto.enc.Utf8.stringify(Crypto.enc.Base64.parse(text));
  520. }
  521. function removeTags(input) {
  522. return input.replace(/<[^>]*>/g, '');
  523. }
  524. function getFullTime(numberSec) {
  525. let totalSeconds = '';
  526. try {
  527. var timeParts = numberSec.split(":");
  528. var min = parseInt(timeParts[0]);
  529. var sec = parseInt(timeParts[1]);
  530. totalSeconds = min * 60 + sec;
  531. } catch (e) {
  532. totalSeconds = parseInt(numberSec);
  533. }
  534. if (isNaN(totalSeconds)) {
  535. return '无效输入';
  536. }
  537. if (totalSeconds >= 3600) {
  538. const hours = Math.floor(totalSeconds / 3600);
  539. const remainingSecondsAfterHours = totalSeconds % 3600;
  540. const minutes = Math.floor(remainingSecondsAfterHours / 60);
  541. const seconds = remainingSecondsAfterHours % 60;
  542. return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
  543. } else {
  544. const minutes = Math.floor(totalSeconds / 60);
  545. const seconds = totalSeconds % 60;
  546. return `${minutes}分钟 ${seconds}秒`;
  547. }
  548. }
  549. export function __jsEvalReturn() {
  550. return {
  551. init: init,
  552. home: home,
  553. homeVod: homeVod,
  554. category: category,
  555. detail: detail,
  556. play: play,
  557. proxy: proxy,
  558. search: search,
  559. };
  560. }