alist.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // import _ from 'https://underscorejs.org/underscore-esm-min.js'
  2. // import {distance} from 'https://unpkg.com/fastest-levenshtein@1.0.16/esm/mod.js'
  3. import {distance} from 'https://gitcode.net/qq_32394351/dr_py/-/raw/master/libs/mod.js'
  4. import {sortListByCN} from 'https://gitcode.net/qq_32394351/dr_py/-/raw/master/libs/sortName.js'
  5. /**
  6. * alist js
  7. * 配置设置 {"key":"Alist","name":"Alist","type":3,"api":"http://xxx.com/alist.js","searchable":0,"quickSearch":0,"filterable":0,"ext":"http://xxx.com/alist.json"}
  8. * alist.json [{
  9. name:'名称',
  10. server:'地址',
  11. startPage:'/', //启动文件夹
  12. showAll: false , //是否显示全部文件,默认false只显示 音视频和文件夹
  13. search: true, // 启用小雅的搜索,搜索只会搜第一个开启此开关的磁盘
  14. params:{ //对应文件夹参数 如设置对应文件夹的密码
  15. '/abc':{ password : '123' },
  16. '/abc/abc':{ password : '123' },
  17. }
  18. }]
  19. * 提示 想要加载文件夹里面全部视频到详情(看剧可以自动播放下一集支持历史记录)
  20. * 需要改软件才能支持,,建议长按文件夹时添加判断 tag == folder 时跳转 DetailActivity
  21. */
  22. String.prototype.rstrip = function (chars) {
  23. let regex = new RegExp(chars + "$");
  24. return this.replace(regex, "");
  25. };
  26. var showMode = 'single';
  27. var searchDriver = '';
  28. var limit_search_show = 200;
  29. var search_type = '';
  30. var detail_order = 'name';
  31. const request_timeout = 5000;
  32. const VERSION = 'alist v2/v3 20221129';
  33. /**
  34. * 打印日志
  35. * @param any 任意变量
  36. */
  37. function print(any){
  38. any = any||'';
  39. if(typeof(any)=='object'&&Object.keys(any).length>0){
  40. try {
  41. any = JSON.stringify(any);
  42. console.log(any);
  43. }catch (e) {
  44. // console.log('print:'+e.message);
  45. console.log(typeof(any)+':'+any.length);
  46. }
  47. }else if(typeof(any)=='object'&&Object.keys(any).length<1){
  48. console.log('null object');
  49. }else{
  50. console.log(any);
  51. }
  52. }
  53. const http = function (url, options = {}) {
  54. if(options.method ==='POST' && options.data){
  55. options.body = JSON.stringify(options.data);
  56. options.headers = Object.assign({'content-type':'application/json'}, options.headers);
  57. }
  58. options.timeout = request_timeout;
  59. try {
  60. const res = req(url, options);
  61. res.json = () => res&&res.content ? JSON.parse(res.content) : null;
  62. res.text = () => res&&res.content ? res.content:'';
  63. return res
  64. }catch (e) {
  65. return {
  66. json() {
  67. return null
  68. }, text() {
  69. return ''
  70. }
  71. }
  72. }
  73. };
  74. ["get", "post"].forEach(method => {
  75. http[method] = function (url, options = {}) {
  76. return http(url, Object.assign(options, {method: method.toUpperCase()}));
  77. }
  78. });
  79. const __drives = {};
  80. function isMedia(file){
  81. return /\.(dff|dsf|mp3|aac|wav|wma|cda|flac|m4a|mid|mka|mp2|mpa|mpc|ape|ofr|ogg|ra|wv|tta|ac3|dts|tak|webm|wmv|mpeg|mov|ram|swf|mp4|avi|rm|rmvb|flv|mpg|mkv|m3u8|ts|3gp|asf)$/.test(file.toLowerCase());
  82. }
  83. function get_drives_path(tid) {
  84. const index = tid.indexOf('$');
  85. const name = tid.substring(0, index);
  86. const path = tid.substring(index + 1);
  87. return { drives: get_drives(name), path };
  88. }
  89. function get_drives(name) {
  90. const { settings, api, server } = __drives[name];
  91. if (settings.v3 == null) { //获取 设置
  92. settings.v3 = false;
  93. const data = http.get(server + '/api/public/settings').json().data;
  94. if (Array.isArray(data)) {
  95. settings.title = data.find(x => x.key === 'title')?.value;
  96. settings.v3 = false;
  97. settings.version = data.find(x => x.key === 'version')?.value;
  98. settings.enableSearch = data.find(x => x.key === 'enable search')?.value === 'true';
  99. } else {
  100. settings.title = data.title;
  101. settings.v3 = true;
  102. settings.version = data.version;
  103. settings.enableSearch = false; //v3 没有找到 搜索配置
  104. }
  105. //不同版本 接口不一样
  106. api.path = settings.v3 ? '/api/fs/list' : '/api/public/path';
  107. api.file = settings.v3 ? '/api/fs/get' : '/api/public/path';
  108. api.search = settings.v3 ? '/api/public/search' : '/api/public/search';
  109. }
  110. return __drives[name]
  111. }
  112. function init(ext) {
  113. console.log("当前版本号:"+VERSION);
  114. let data;
  115. if (typeof ext == 'object'){
  116. data = ext;
  117. print('alist ext:object');
  118. } else if (typeof ext == 'string') {
  119. if (ext.startsWith('http')) {
  120. let alist_data = ext.split(';');
  121. let alist_data_url = alist_data[0];
  122. limit_search_show = alist_data.length>1?Number(alist_data[1])||limit_search_show:limit_search_show;
  123. search_type = alist_data.length>2?alist_data[2]:search_type;
  124. print(alist_data_url);
  125. data = http.get(alist_data_url).json(); // .map(it=>{it.name='🙋丫仙女';return it})
  126. } else {
  127. print('alist ext:json string');
  128. data = JSON.parse(ext);
  129. }
  130. }
  131. // print(data); // 测试证明壳子标题支持emoji,是http请求源码不支持emoji
  132. let drives = [];
  133. if(Array.isArray(data) && data.length > 0 && data[0].hasOwnProperty('server') && data[0].hasOwnProperty('name')){
  134. drives = data;
  135. }else if(!Array.isArray(data)&&data.hasOwnProperty('drives')&&Array.isArray(data.drives)){
  136. drives = data.drives.filter(it=>(it.type&&it.type==='alist')||!it.type);
  137. }
  138. print(drives);
  139. searchDriver = (drives.find(x=>x.search)||{}).name||'';
  140. if(!searchDriver && drives.length > 0){
  141. searchDriver = drives[0].name;
  142. }
  143. print(searchDriver);
  144. drives.forEach(item => {
  145. let _path_param = [];
  146. if(item.params){
  147. _path_param = Object.keys(item.params);
  148. // 升序排列
  149. _path_param.sort((a,b)=>(a.length-b.length));
  150. }
  151. __drives[item.name] = {
  152. name: item.name,
  153. server: item.server.endsWith("/") ? item.server.rstrip("/") : item.server,
  154. startPage: item.startPage || '/', //首页
  155. showAll: item.showAll === true, //默认只显示 视频和文件夹,如果想显示全部 showAll 设置true
  156. search: !!item.search, //是否支持搜索,只有小丫的可以,多个可搜索只取最前面的一个
  157. params: item.params || {},
  158. _path_param: _path_param,
  159. settings: {},
  160. api: {},
  161. getParams(path) {
  162. const key = this._path_param.find(x => path.startsWith(x));
  163. return Object.assign({}, this.params[key], { path });
  164. },
  165. getPath(path) {
  166. const res = http.post(this.server + this.api.path, { data: this.getParams(path) }).json();
  167. return this.settings.v3 ? res.data.content : res.data.files
  168. },
  169. getFile(path) {
  170. let raw_url = this.server+'/d'+path;
  171. raw_url = encodeURI(raw_url);
  172. // print('raw_url:'+raw_url);
  173. return {raw_url:raw_url};
  174. // const res = http.post(this.server + this.api.file, { data: this.getParams(path) }).json();
  175. // const data = this.settings.v3 ? res.data : res.data.files[0];
  176. // if (!this.settings.v3) {
  177. // data.raw_url = data.url; //v2 的url和v3不一样
  178. // }
  179. // return data
  180. },
  181. isFolder(data) { return data.type === 1 },
  182. isVideo(data) { //判断是否是 视频文件
  183. // return this.settings.v3 ? data.type === 2 : data.type === 3
  184. // 增加音乐识别 视频,其他,音频
  185. return this.settings.v3 ? (data.type === 2||data.type===0||data.type===3) : (data.type === 3||data.type===0||data.type === 4)
  186. },
  187. is_subt(data) {
  188. if (data.type === 1) {
  189. return false;
  190. }
  191. const ext = /\.(srt|ass|scc|stl|ttml)$/; // [".srt", ".ass", ".scc", ".stl", ".ttml"];
  192. // return ext.some(x => data.name.endsWith(x));
  193. return ext.test(data.name);
  194. },
  195. getPic(data) {
  196. let pic = this.settings.v3 ? data.thumb : data.thumbnail;
  197. return pic || (this.isFolder(data) ? "http://img1.3png.com/281e284a670865a71d91515866552b5f172b.png" : '');
  198. },
  199. getTime(data,isStandard) {
  200. isStandard = isStandard||false;
  201. try {
  202. let tTime = data.updated_at || data.time_str || data.modified || "";
  203. let date = '';
  204. if(tTime){
  205. tTime = tTime.split("T");
  206. date = tTime[0];
  207. if(isStandard){
  208. date = date.replace(/-/g,"/");
  209. }
  210. tTime = tTime[1].split(/Z|\./);
  211. date += " " + tTime[0];
  212. }
  213. return date;
  214. }catch (e) {
  215. // print(e.message);
  216. // print(data);
  217. return ''
  218. }
  219. },
  220. }
  221. }
  222. );
  223. print('init执行完毕');
  224. }
  225. function home(filter) {
  226. let classes = Object.keys(__drives).map(key => ({
  227. type_id: `${key}$${__drives[key].startPage}`,
  228. type_name: key,
  229. type_flag: '1',
  230. }));
  231. let filter_dict = {};
  232. let filters = [{'key': 'order', 'name': '排序', 'value': [{'n': '名称⬆️', 'v': 'vod_name_asc'}, {'n': '名称⬇️', 'v': 'vod_name_desc'},
  233. {'n': '中英⬆️', 'v': 'vod_cn_asc'}, {'n': '中英⬇️', 'v': 'vod_cn_desc'},
  234. {'n': '时间⬆️', 'v': 'vod_time_asc'}, {'n': '时间⬇️', 'v': 'vod_time_desc'},
  235. {'n': '大小⬆️', 'v': 'vod_size_asc'}, {'n': '大小⬇️', 'v': 'vod_size_desc'},{'n': '无', 'v': 'none'}]},
  236. {'key': 'show', 'name': '播放展示', 'value': [{'n': '单集', 'v': 'single'},{'n': '全集', 'v': 'all'}]}
  237. ];
  238. classes.forEach(it=>{
  239. filter_dict[it.type_id] = filters;
  240. });
  241. print("----home----");
  242. print(classes);
  243. return JSON.stringify({ 'class': classes,'filters': filter_dict});
  244. }
  245. function homeVod(params) {
  246. return JSON.stringify({ 'list': [] });
  247. }
  248. function category(tid, pg, filter, extend) {
  249. let orid = tid.replace(/#all#|#search#/g,'');
  250. let { drives, path } = get_drives_path(orid);
  251. const id = orid.endsWith('/') ? orid : orid + '/';
  252. const list = drives.getPath(path);
  253. let subList = [];
  254. let vodFiles = [];
  255. let allList = [];
  256. let fl = filter?extend:{};
  257. if(fl.show){
  258. showMode = fl.show;
  259. }
  260. list.forEach(item => {
  261. if (drives.is_subt(item)) {
  262. subList.push(item.name);
  263. }
  264. if (!drives.showAll && !drives.isFolder(item) && !drives.isVideo(item)) {
  265. return //只显示视频文件和文件夹
  266. }
  267. let vod_time = drives.getTime(item);
  268. let vod_size = get_size(item.size);
  269. let remark = vod_time.split(' ')[0].substr(3)+'\t'+vod_size;
  270. let vod_id = id + item.name + (drives.isFolder(item) ? '/' : '');
  271. if(showMode==='all'){
  272. vod_id+='#all#';
  273. }
  274. print(vod_id);
  275. const vod = {
  276. 'vod_id': vod_id,
  277. 'vod_name': item.name.replaceAll("$", "").replaceAll("#", ""),
  278. 'vod_pic': drives.getPic(item),
  279. 'vod_time':vod_time ,
  280. 'vod_size':item.size ,
  281. 'vod_tag': drives.isFolder(item) ? 'folder' : 'file',
  282. 'vod_remarks': drives.isFolder(item) ? remark + ' 文件夹' : remark
  283. };
  284. if (drives.isVideo(item)) {
  285. vodFiles.push(vod);
  286. }
  287. allList.push(vod);
  288. });
  289. if (vodFiles.length === 1 && subList.length > 0) { //只有一个视频 一个或者多个字幕 取相似度最高的
  290. // let sub = subList.length === 1 ? subList[0] : _.chain(allList).sortBy(x => (x.includes('chs') ? 100 : 0) + levenshteinDistance(x, vodFiles[0].vod_name)).last().value();
  291. let sub; // 字幕文件名称
  292. if(subList.length === 1){
  293. sub = subList[0];
  294. }else {
  295. let subs = JSON.parse(JSON.stringify(subList));
  296. subs.sort((a,b)=>{
  297. // chs是简体中文字幕
  298. let a_similar = (a.includes('chs') ? 100 : 0) + levenshteinDistance(a, vodFiles[0].vod_name);
  299. let b_similar = (b.includes('chs') ? 100 : 0) + levenshteinDistance(b, vodFiles[0].vod_name);
  300. if(a_similar>b_similar) { // 按相似度正序排列
  301. return 1;
  302. }else{ //否则,位置不变
  303. return -1;
  304. }
  305. });
  306. sub = subs.slice(-1)[0];
  307. }
  308. vodFiles[0].vod_id += "@@@" + sub;
  309. // vodFiles[0].vod_remarks += " 有字幕";
  310. vodFiles[0].vod_remarks += "🏷️";
  311. } else {
  312. vodFiles.forEach(item => {
  313. const lh = 0;
  314. let sub;
  315. subList.forEach(s => {
  316. //编辑距离相似度
  317. const l = levenshteinDistance(s, item.vod_name);
  318. if (l > 60 && l > lh) {
  319. sub = s;
  320. }
  321. });
  322. if (sub) {
  323. item.vod_id += "@@@" + sub;
  324. // item.vod_remarks += " 有字幕";
  325. item.vod_remarks += "🏷️";
  326. }
  327. });
  328. }
  329. if(fl.order){
  330. // print(fl.order);
  331. let key = fl.order.split('_').slice(0,-1).join('_');
  332. let order = fl.order.split('_').slice(-1)[0];
  333. print(`排序key:${key},排序order:${order}`);
  334. if(key.includes('name')){
  335. detail_order = 'name';
  336. allList = sortListByName(allList,key,order);
  337. }else if(key.includes('cn')){
  338. detail_order = 'cn';
  339. allList = sortListByCN(allList,'vod_name',order);
  340. }else if(key.includes('time')){
  341. detail_order = 'time';
  342. allList = sortListByTime(allList,key,order);
  343. }else if(key.includes('size')){
  344. detail_order = 'size';
  345. allList = sortListBySize(allList,key,order);
  346. }else if(fl.order.includes('none')){
  347. detail_order = 'none';
  348. print('不排序');
  349. }
  350. }else{
  351. // 没传order是其他地方调用的,自动按名称正序排序方便追剧,如果传了none进去就不排序,假装云盘里本身文件顺序是正常的
  352. if(detail_order!=='none'){
  353. allList = sortListByName(allList,'vod_name','asc');
  354. }
  355. }
  356. print("----category----"+`tid:${tid},detail_order:${detail_order},showMode:${showMode}`);
  357. // print(allList);
  358. return JSON.stringify({
  359. 'page': 1,
  360. 'pagecount': 1,
  361. 'limit': allList.length,
  362. 'total': allList.length,
  363. 'list': allList,
  364. });
  365. }
  366. function getAll(otid,tid,drives,path){
  367. try {
  368. const content = category(tid, null, false, null);
  369. const isFile = isMedia(otid.replace(/#all#|#search#/g,'').split('@@@')[0]);
  370. const { list } = JSON.parse(content);
  371. let vod_play_url = [];
  372. list.forEach(x => {
  373. if (x.vod_tag === 'file'){
  374. let vid = x.vod_id.replace(/#all#|#search#/g,'');
  375. vod_play_url.push(`${x.vod_name}$${vid.substring(vid.indexOf('$') + 1)}`);
  376. }
  377. });
  378. const pl = path.split("/").filter(it=>it);
  379. let vod_name = pl[pl.length - 1] || drives.name;
  380. if(vod_name === drives.name){
  381. print(pl);
  382. }
  383. if(otid.includes('#search#')){
  384. vod_name+='[搜]';
  385. }
  386. let vod = {
  387. // vod_id: tid,
  388. vod_id: otid,
  389. vod_name: vod_name,
  390. type_name: "文件夹",
  391. vod_pic: "https://avatars.githubusercontent.com/u/97389433?s=120&v=4",
  392. vod_content: tid,
  393. vod_tag: 'folder',
  394. vod_play_from: drives.name,
  395. vod_play_url: vod_play_url.join('#'),
  396. vod_remarks: drives.settings.title,
  397. }
  398. print("----detail1----");
  399. print(vod);
  400. return JSON.stringify({ 'list': [vod] });
  401. }catch (e) {
  402. print(e.message);
  403. return JSON.stringify({ 'list': [{}] });
  404. }
  405. }
  406. function detail(tid) {
  407. let isSearch = tid.includes('#search#');
  408. let isAll = tid.includes('#all#');
  409. let otid = tid;
  410. tid = tid.replace(/#all#|#search#/g,'');
  411. let isFile = isMedia(tid.split('@@@')[0]);
  412. print(`isFile:${tid}?${isFile}`);
  413. let { drives, path } = get_drives_path(tid);
  414. print(`drives:${drives},path:${path}`);
  415. if (path.endsWith("/")) { //长按文件夹可以 加载里面全部视频到详情
  416. return getAll(otid,tid,drives,path);
  417. } else {
  418. if(isSearch&&!isFile){ // 搜索结果 当前目录获取所有文件
  419. return getAll(otid,tid,drives,path);
  420. }else if(isAll){ // 上级目录获取所有文件 不管是搜索还是分类,只要不是 搜索到的文件夹,且展示模式为全部,都获取上级目录的所有文件
  421. // 是文件就取上级目录
  422. let new_tid;
  423. if(isFile){
  424. new_tid = tid.split('/').slice(0,-1).join('/')+'/';
  425. }else{
  426. new_tid = tid;
  427. }
  428. print(`全集模式 tid:${tid}=>tid:${new_tid}`);
  429. let { drives, path } = get_drives_path(new_tid);
  430. return getAll(otid,new_tid,drives,path);
  431. } else if(isFile){ // 单文件进入
  432. let paths = path.split("@@@");
  433. let vod_name = paths[0].substring(paths[0].lastIndexOf("/") + 1);
  434. let vod_title = vod_name;
  435. if(otid.includes('#search#')){
  436. vod_title+='[搜]';
  437. }
  438. let vod = {
  439. vod_id: otid,
  440. vod_name: vod_title,
  441. type_name: "文件",
  442. vod_pic: "https://avatars.githubusercontent.com/u/97389433?s=120&v=4",
  443. vod_content: tid,
  444. vod_play_from: drives.name,
  445. vod_play_url: vod_name + "$" + path,
  446. vod_remarks: drives.settings.title,
  447. };
  448. print("----detail2----");
  449. print(vod);
  450. return JSON.stringify({
  451. 'list': [vod]
  452. });
  453. }else{
  454. return JSON.stringify({
  455. 'list': []
  456. });
  457. }
  458. }
  459. }
  460. function play(flag, id, flags) {
  461. const drives = get_drives(flag);
  462. const urls = id.split("@@@"); // @@@ 分割前是 相对文件path,分割后是字幕文件
  463. let vod = {
  464. 'parse': 0,
  465. 'playUrl': '',
  466. 'url': drives.getFile(urls[0]).raw_url
  467. };
  468. if (urls.length >= 2) {
  469. const path = urls[0].substring(0, urls[0].lastIndexOf('/') + 1);
  470. vod.subt = drives.getFile(path + urls[1]).raw_url;
  471. }
  472. print("----play----");
  473. print(vod);
  474. return JSON.stringify(vod);
  475. }
  476. function search(wd, quick) {
  477. print(__drives);
  478. print('可搜索的alist驱动:'+searchDriver);
  479. if(!searchDriver||!wd){
  480. return JSON.stringify({
  481. 'list': []
  482. });
  483. }else{
  484. let driver = __drives[searchDriver];
  485. wd = wd.split(' ').filter(it=>it.trim()).join('+');
  486. print(driver);
  487. let surl = driver.server + '/search?box='+wd+'&url=';
  488. if(search_type){
  489. surl+='&type='+search_type;
  490. }
  491. print('搜索链接:'+surl);
  492. let html = http.get(surl).text();
  493. let lists = [];
  494. try {
  495. lists = pdfa(html,'div&&ul&&a');
  496. }catch (e) {}
  497. print(`搜索结果数:${lists.length},搜索结果显示数量限制:${limit_search_show}`);
  498. let vods = [];
  499. let excludeReg = /\.(pdf|epub|mobi|txt|doc|lrc)$/; // 过滤后缀文件
  500. let cnt = 0;
  501. lists.forEach(it=>{
  502. let vhref = pdfh(it,'a&&href');
  503. if(vhref){
  504. vhref = unescape(vhref);
  505. }
  506. if(excludeReg.test(vhref)){
  507. return; //跳过本次循环
  508. }
  509. if(cnt < limit_search_show){
  510. print(vhref);
  511. }
  512. cnt ++;
  513. let vid = searchDriver+'$'+vhref+'#search#';
  514. if(showMode==='all'){
  515. vid+='#all#';
  516. }
  517. vods.push({
  518. vod_name:pdfh(it,'a&&Text'),
  519. vod_id:vid,
  520. vod_tag: isMedia(vhref) ? 'file' : 'folder',
  521. vod_pic:'http://img1.3png.com/281e284a670865a71d91515866552b5f172b.png',
  522. vod_remarks:searchDriver
  523. });
  524. });
  525. // 截取搜索结果
  526. vods = vods.slice(0,limit_search_show);
  527. print(vods);
  528. return JSON.stringify({
  529. 'list': vods
  530. });
  531. }
  532. }
  533. function get_size(sz) {
  534. if (sz <= 0) {
  535. return "";
  536. }
  537. let filesize = "";
  538. if (sz > 1024 * 1024 * 1024 * 1024.0) {
  539. sz /= (1024 * 1024 * 1024 * 1024.0);
  540. filesize = "TB";
  541. } else if (sz > 1024 * 1024 * 1024.0) {
  542. sz /= (1024 * 1024 * 1024.0);
  543. filesize = "GB";
  544. } else if (sz > 1024 * 1024.0) {
  545. sz /= (1024 * 1024.0);
  546. filesize = "MB";
  547. } else if( sz > 1024.0){
  548. sz /= 1024.0;
  549. filesize = "KB";
  550. }else{
  551. filesize = "B";
  552. }
  553. // 转成字符串
  554. let sizeStr = sz.toFixed(2) + filesize,
  555. // 获取小数点处的索引
  556. index = sizeStr.indexOf("."),
  557. // 获取小数点后两位的值
  558. dou = sizeStr.substr(index + 1, 2);
  559. if (dou === "00") {
  560. return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
  561. }else{
  562. return sizeStr;
  563. }
  564. }
  565. // 相似度获取
  566. function levenshteinDistance(str1, str2) {
  567. return 100 - 100 * distance(str1, str2) / Math.max(str1.length, str2.length);
  568. }
  569. /**
  570. * 自然排序
  571. * ["第1集","第10集","第20集","第2集","1","2","10","12","23","01","02"].sort(naturalSort())
  572. * @param options {{key,caseSensitive, order: string}}
  573. */
  574. function naturalSort(options) {
  575. if (!options) {
  576. options = {};
  577. }
  578. return function (a, b) {
  579. if(options.key){
  580. a = a[options.key];
  581. b = b[options.key];
  582. }
  583. var EQUAL = 0;
  584. var GREATER = (options.order === 'desc' ?
  585. -1 :
  586. 1
  587. );
  588. var SMALLER = -GREATER;
  589. var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi;
  590. var sre = /(^[ ]*|[ ]*$)/g;
  591. var dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/;
  592. var hre = /^0x[0-9a-f]+$/i;
  593. var ore = /^0/;
  594. var normalize = function normalize(value) {
  595. var string = '' + value;
  596. return (options.caseSensitive ?
  597. string :
  598. string.toLowerCase()
  599. );
  600. };
  601. // Normalize values to strings
  602. var x = normalize(a).replace(sre, '') || '';
  603. var y = normalize(b).replace(sre, '') || '';
  604. // chunk/tokenize
  605. var xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0');
  606. var yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0');
  607. // Return immediately if at least one of the values is empty.
  608. if (!x && !y) return EQUAL;
  609. if (!x && y) return GREATER;
  610. if (x && !y) return SMALLER;
  611. // numeric, hex or date detection
  612. var xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x));
  613. var yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null;
  614. var oFxNcL, oFyNcL;
  615. // first try and sort Hex codes or Dates
  616. if (yD) {
  617. if (xD < yD) return SMALLER;
  618. else if (xD > yD) return GREATER;
  619. }
  620. // natural sorting through split numeric strings and default strings
  621. for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
  622. // find floats not starting with '0', string or 0 if not defined (Clint Priest)
  623. oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
  624. oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
  625. // handle numeric vs string comparison - number < string - (Kyle Adams)
  626. if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? GREATER : SMALLER;
  627. // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
  628. else if (typeof oFxNcL !== typeof oFyNcL) {
  629. oFxNcL += '';
  630. oFyNcL += '';
  631. }
  632. if (oFxNcL < oFyNcL) return SMALLER;
  633. if (oFxNcL > oFyNcL) return GREATER;
  634. }
  635. return EQUAL;
  636. };
  637. }
  638. // 完整名称排序
  639. const sortListByName = (vodList,key,order) => {
  640. if(!key){
  641. return vodList
  642. }
  643. order = order||'asc'; // 默认正序
  644. // 排序键,顺序,区分大小写
  645. return vodList.sort(naturalSort({key: key, order: order,caseSensitive:true}))
  646. };
  647. const getTimeInt = (timeStr) => {
  648. return (new Date(timeStr)).getTime();
  649. };
  650. // 时间
  651. const sortListByTime = (vodList,key,order) => {
  652. if (!key) {
  653. return vodList
  654. }
  655. let ASCarr = vodList.sort((a, b) => {
  656. a = a[key];
  657. b = b[key];
  658. return getTimeInt(a) - getTimeInt(b);
  659. });
  660. if(order==='desc'){
  661. ASCarr.reverse();
  662. }
  663. return ASCarr
  664. };
  665. // 大小
  666. const sortListBySize = (vodList,key,order) => {
  667. if (!key) {
  668. return vodList
  669. }
  670. let ASCarr = vodList.sort((a, b) => {
  671. a = a[key];
  672. b = b[key];
  673. return (Number(a) || 0) - (Number(b) || 0);
  674. });
  675. if(order==='desc'){
  676. ASCarr.reverse();
  677. }
  678. return ASCarr
  679. };
  680. // 导出函数对象
  681. export default {
  682. init: init,
  683. home: home,
  684. homeVod: homeVod,
  685. category: category,
  686. detail: detail,
  687. play: play,
  688. search: search
  689. }