BaseList.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import axios from 'axios';
  2. import dayjs from 'dayjs';
  3. import _ from 'lodash';
  4. import authorBooksStorage from './authorBooksStorage';
  5. import BookView from './BookView/BookView.vue';
  6. import LoadingMessage from './LoadingMessage/LoadingMessage.vue';
  7. import * as utils from '../../share/utils';
  8. const showMoreCount = 100;//значение для "Показать еще"
  9. const maxItemCount = 500;//выше этого значения показываем "Загрузка"
  10. const componentOptions = {
  11. components: {
  12. BookView,
  13. LoadingMessage,
  14. },
  15. watch: {
  16. settings() {
  17. this.loadSettings();
  18. },
  19. search: {
  20. handler() {
  21. if (!this.isExtendedSearch)
  22. this.refresh();
  23. },
  24. deep: true,
  25. },
  26. extSearch: {
  27. handler() {
  28. if (this.isExtendedSearch)
  29. this.refresh();
  30. },
  31. deep: true,
  32. },
  33. showDeleted() {
  34. this.refresh();
  35. },
  36. },
  37. };
  38. export default class BaseList {
  39. _options = componentOptions;
  40. _props = {
  41. list: Object,
  42. search: Object,
  43. extSearch: Object,
  44. genreMap: Object,
  45. };
  46. error = '';
  47. loadingMessage = '';
  48. loadingMessage2 = '';
  49. //settings
  50. expandedAuthor = [];
  51. expandedSeries = [];
  52. downloadAsZip = false;
  53. showCounts = true;
  54. showRates = true;
  55. showGenres = true;
  56. showDeleted = false;
  57. abCacheEnabled = true;
  58. //stuff
  59. refreshing = false;
  60. showMoreCount = showMoreCount;
  61. maxItemCount = maxItemCount;
  62. searchResult = {};
  63. tableData = [];
  64. created() {
  65. this.isExtendedSearch = false;
  66. this.commit = this.$store.commit;
  67. this.api = this.$root.api;
  68. this.loadSettings();
  69. }
  70. mounted() {
  71. this.refresh();//no await
  72. }
  73. loadSettings() {
  74. const settings = this.settings;
  75. this.expandedAuthor = _.cloneDeep(settings.expandedAuthor);
  76. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  77. this.downloadAsZip = settings.downloadAsZip;
  78. this.showCounts = settings.showCounts;
  79. this.showRates = settings.showRates;
  80. this.showGenres = settings.showGenres;
  81. this.showDeleted = settings.showDeleted;
  82. this.abCacheEnabled = settings.abCacheEnabled;
  83. }
  84. get config() {
  85. return this.$store.state.config;
  86. }
  87. get settings() {
  88. return this.$store.state.settings;
  89. }
  90. get showReadLink() {
  91. return this.config.bookReadLink != '' || this.list.liberamaReady;
  92. }
  93. scrollToTop() {
  94. this.$emit('listEvent', {action: 'scrollToTop'});
  95. }
  96. selectAuthor(author) {
  97. const search = (this.isExtendedSearch ? this.extSearch : this.search);
  98. search.author = `=${author}`;
  99. this.scrollToTop();
  100. }
  101. selectSeries(series) {
  102. const search = (this.isExtendedSearch ? this.extSearch : this.search);
  103. search.series = `=${series}`;
  104. }
  105. selectTitle(title) {
  106. const search = (this.isExtendedSearch ? this.extSearch : this.search);
  107. search.title = `=${title}`;
  108. }
  109. async download(book, action) {
  110. if (this.downloadFlag)
  111. return;
  112. this.downloadFlag = true;
  113. (async() => {
  114. await utils.sleep(200);
  115. if (this.downloadFlag)
  116. this.loadingMessage2 = 'Подготовка файла...';
  117. })();
  118. try {
  119. //подготовка
  120. const response = await this.api.getBookLink(book._uid);
  121. const link = response.link;
  122. let href = `${window.location.origin}${link}`;
  123. //downloadAsZip
  124. if (this.downloadAsZip && (action == 'download' || action == 'copyLink')) {
  125. href += '/zip';
  126. //подожлем формирования zip-файла
  127. await axios.head(href);
  128. }
  129. //action
  130. if (action == 'download') {
  131. //скачивание
  132. const d = this.$refs.download;
  133. d.href = href;
  134. d.click();
  135. } else if (action == 'copyLink') {
  136. //копирование ссылки
  137. if (await utils.copyTextToClipboard(href))
  138. this.$root.notify.success('Ссылка успешно скопирована');
  139. else
  140. this.$root.stdDialog.alert(
  141. `Копирование ссылки не удалось. Пожалуйста, попробуйте еще раз.
  142. <br><br>
  143. <b>Пояснение</b>: вероятно, браузер запретил копирование, т.к. прошло<br>
  144. слишком много времени с момента нажатия на кнопку (инициация<br>
  145. пользовательского события). Сейчас ссылка уже закеширована,<br>
  146. поэтому повторная попытка должна быть успешной.`, 'Ошибка');
  147. } else if (action == 'readBook') {
  148. //читать
  149. if (this.list.liberamaReady) {
  150. this.$emit('listEvent', {action: 'submitUrl', data: href});
  151. } else {
  152. const bookReadLink = this.config.bookReadLink;
  153. let url = bookReadLink;
  154. if (bookReadLink.indexOf('${DOWNLOAD_LINK}') >= 0) {
  155. url = bookReadLink.replace('${DOWNLOAD_LINK}', href);
  156. } else if (bookReadLink.indexOf('${DOWNLOAD_URI}') >= 0) {
  157. const hrefUrl = new URL(href);
  158. const urlWithoutHost = hrefUrl.pathname + hrefUrl.search + hrefUrl.hash;
  159. url = bookReadLink.replace('${DOWNLOAD_URI}', urlWithoutHost);
  160. }
  161. window.open(url, '_blank');
  162. }
  163. } else if (action == 'bookInfo') {
  164. //информация о книге
  165. const response = await this.api.getBookInfo(book._uid);
  166. this.$emit('listEvent', {action: 'bookInfo', data: response.bookInfo});
  167. }
  168. } catch(e) {
  169. this.$root.stdDialog.alert(e.message, 'Ошибка');
  170. } finally {
  171. this.downloadFlag = false;
  172. this.loadingMessage2 = '';
  173. }
  174. }
  175. bookEvent(event) {
  176. switch (event.action) {
  177. case 'authorClick':
  178. this.selectAuthor(event.book.author);
  179. break;
  180. case 'seriesClick':
  181. this.selectSeries(event.book.series);
  182. break;
  183. case 'titleClick':
  184. this.selectTitle(event.book.title);
  185. break;
  186. case 'download':
  187. case 'copyLink':
  188. case 'readBook':
  189. case 'bookInfo':
  190. this.download(event.book, event.action);//no await
  191. break;
  192. }
  193. }
  194. isExpandedAuthor(item) {
  195. return this.expandedAuthor.indexOf(item.author) >= 0;
  196. }
  197. isExpandedSeries(seriesItem) {
  198. return this.expandedSeries.indexOf(seriesItem.key) >= 0;
  199. }
  200. setSetting(name, newValue) {
  201. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  202. }
  203. highlightPageScroller(query) {
  204. this.$emit('listEvent', {action: 'highlightPageScroller', query});
  205. }
  206. async expandSeries(seriesItem) {
  207. this.$emit('listEvent', {action: 'ignoreScroll'});
  208. const expandedSeries = _.cloneDeep(this.expandedSeries);
  209. const key = seriesItem.key;
  210. if (!this.isExpandedSeries(seriesItem)) {
  211. expandedSeries.push(key);
  212. if (expandedSeries.length > 100) {
  213. expandedSeries.shift();
  214. }
  215. this.getSeriesBooks(seriesItem); //no await
  216. this.setSetting('expandedSeries', expandedSeries);
  217. } else {
  218. const i = expandedSeries.indexOf(key);
  219. if (i >= 0) {
  220. expandedSeries.splice(i, 1);
  221. this.setSetting('expandedSeries', expandedSeries);
  222. }
  223. }
  224. }
  225. async loadAuthorBooks(authorId) {
  226. try {
  227. let result;
  228. if (this.abCacheEnabled) {
  229. const key = `author-${authorId}-${this.list.inpxHash}`;
  230. const data = await authorBooksStorage.getData(key);
  231. if (data) {
  232. result = JSON.parse(data);
  233. } else {
  234. result = await this.api.getAuthorBookList(authorId);
  235. await authorBooksStorage.setData(key, JSON.stringify(result));
  236. }
  237. } else {
  238. result = await this.api.getAuthorBookList(authorId);
  239. }
  240. return result.books;
  241. } catch (e) {
  242. this.$root.stdDialog.alert(e.message, 'Ошибка');
  243. }
  244. }
  245. async loadAuthorSeries(authorId) {
  246. try {
  247. let result;
  248. if (this.abCacheEnabled) {
  249. const key = `author-${authorId}-series-${this.list.inpxHash}`;
  250. const data = await authorBooksStorage.getData(key);
  251. if (data) {
  252. result = JSON.parse(data);
  253. } else {
  254. result = await this.api.getAuthorSeriesList(authorId);
  255. await authorBooksStorage.setData(key, JSON.stringify(result));
  256. }
  257. } else {
  258. result = await this.api.getAuthorSeriesList(authorId);
  259. }
  260. return result.series;
  261. } catch (e) {
  262. this.$root.stdDialog.alert(e.message, 'Ошибка');
  263. }
  264. }
  265. async loadSeriesBooks(series) {
  266. try {
  267. let result;
  268. if (this.abCacheEnabled) {
  269. const key = `series-${series}-${this.list.inpxHash}`;
  270. const data = await authorBooksStorage.getData(key);
  271. if (data) {
  272. result = JSON.parse(data);
  273. } else {
  274. result = await this.api.getSeriesBookList(series);
  275. await authorBooksStorage.setData(key, JSON.stringify(result));
  276. }
  277. } else {
  278. result = await this.api.getSeriesBookList(series);
  279. }
  280. return result.books;
  281. } catch (e) {
  282. this.$root.stdDialog.alert(e.message, 'Ошибка');
  283. }
  284. }
  285. async getSeriesBooks(seriesItem) {
  286. //блокируем повторный вызов
  287. if (seriesItem.seriesBookLoading)
  288. return;
  289. seriesItem.seriesBookLoading = true;
  290. try {
  291. seriesItem.allBooksLoaded = await this.loadSeriesBooks(seriesItem.series);
  292. if (seriesItem.allBooksLoaded) {
  293. seriesItem.allBooksLoaded = seriesItem.allBooksLoaded.filter(book => (this.showDeleted || !book.del));
  294. this.sortSeriesBooks(seriesItem.allBooksLoaded);
  295. this.showMoreAll(seriesItem);
  296. }
  297. } finally {
  298. seriesItem.seriesBookLoading = false;
  299. }
  300. }
  301. filterBooks(books) {
  302. const s = this.search;
  303. const emptyFieldValue = '?';
  304. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  305. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  306. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  307. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  308. const splitAuthor = (author) => {
  309. if (!author) {
  310. author = emptyFieldValue;
  311. }
  312. const result = author.split(',');
  313. if (result.length > 1)
  314. result.push(author);
  315. return result;
  316. };
  317. const filterBySearch = (bookValue, searchValue) => {
  318. if (!searchValue)
  319. return true;
  320. if (!bookValue)
  321. bookValue = emptyFieldValue;
  322. bookValue = bookValue.toLowerCase();
  323. if (searchValue[0] !== '~')
  324. searchValue = searchValue.toLowerCase();
  325. //особая обработка префиксов
  326. if (searchValue[0] === '=') {
  327. searchValue = searchValue.substring(1);
  328. return bookValue.localeCompare(searchValue) == 0;
  329. } else if (searchValue[0] === '%') {
  330. searchValue = searchValue.substring(1);
  331. const words = searchValue.split(' ').filter(a => a);
  332. if (!words.length)
  333. words.push('');
  334. for (const w of words)
  335. if (bookValue !== emptyFieldValue && bookValue.indexOf(w) >= 0)
  336. return true;
  337. return false;
  338. } else if (searchValue[0] === '*') {
  339. searchValue = searchValue.substring(1);
  340. return bookValue !== emptyFieldValue && bookValue.indexOf(searchValue) >= 0;
  341. } else if (searchValue[0] === '#') {
  342. searchValue = searchValue.substring(1);
  343. if (!bookValue)
  344. return false;
  345. return bookValue !== emptyFieldValue && !enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0;
  346. } else if (searchValue[0] === '~') {//RegExp
  347. searchValue = searchValue.substring(1);
  348. const re = new RegExp(searchValue, 'i');
  349. return re.test(bookValue);
  350. } else {
  351. //where = `@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  352. return bookValue.localeCompare(searchValue) >= 0 && bookValue.localeCompare(searchValue + maxUtf8Char) <= 0;
  353. }
  354. };
  355. return books.filter((book) => {
  356. //author
  357. let authorFound = false;
  358. const authors = splitAuthor(book.author);
  359. for (const a of authors) {
  360. if (filterBySearch(a, s.author)) {
  361. authorFound = true;
  362. break;
  363. }
  364. }
  365. //genre
  366. let genreFound = !s.genre;
  367. if (!genreFound) {
  368. const searchGenres = new Set(s.genre.split(','));
  369. const bookGenres = book.genre.split(',');
  370. for (let g of bookGenres) {
  371. if (!g)
  372. g = emptyFieldValue;
  373. if (searchGenres.has(g)) {
  374. genreFound = true;
  375. break;
  376. }
  377. }
  378. }
  379. //lang
  380. let langFound = !s.lang;
  381. if (!langFound) {
  382. const searchLang = new Set(s.lang.split(','));
  383. langFound = searchLang.has(book.lang || emptyFieldValue);
  384. }
  385. //date
  386. let dateFound = !s.date;
  387. if (!dateFound) {
  388. const date = this.queryDate(s.date).split(',');
  389. let [from = '0000-00-00', to = '9999-99-99'] = date;
  390. dateFound = (book.date >= from && book.date <= to);
  391. }
  392. //librate
  393. let librateFound = !s.librate;
  394. if (!librateFound) {
  395. const searchLibrate = new Set(s.librate.split(',').map(n => parseInt(n, 10)).filter(n => !isNaN(n)));
  396. librateFound = searchLibrate.has(book.librate);
  397. }
  398. //ext
  399. let extFound = !s.ext;
  400. if (!extFound) {
  401. const searchExt = new Set(s.ext.split('|'));
  402. extFound = searchExt.has(book.ext.toLowerCase() || emptyFieldValue);
  403. }
  404. return (this.showDeleted || !book.del)
  405. && authorFound
  406. && filterBySearch(book.series, s.series)
  407. && filterBySearch(book.title, s.title)
  408. && genreFound
  409. && langFound
  410. && dateFound
  411. && librateFound
  412. && extFound
  413. ;
  414. });
  415. }
  416. showMore(item, all = false) {
  417. if (item.booksLoaded) {
  418. const currentLen = (item.books ? item.books.length : 0);
  419. let books;
  420. if (all || currentLen + this.showMoreCount*1.5 > item.booksLoaded.length) {
  421. books = item.booksLoaded;
  422. } else {
  423. books = item.booksLoaded.slice(0, currentLen + this.showMoreCount);
  424. }
  425. item.showMore = (books.length < item.booksLoaded.length);
  426. item.books = books;
  427. }
  428. }
  429. showMoreAll(seriesItem, all = false) {
  430. if (seriesItem.allBooksLoaded) {
  431. const currentLen = (seriesItem.allBooks ? seriesItem.allBooks.length : 0);
  432. let books;
  433. if (all || currentLen + this.showMoreCount*1.5 > seriesItem.allBooksLoaded.length) {
  434. books = seriesItem.allBooksLoaded;
  435. } else {
  436. books = seriesItem.allBooksLoaded.slice(0, currentLen + this.showMoreCount);
  437. }
  438. seriesItem.showMoreAll = (books.length < seriesItem.allBooksLoaded.length);
  439. seriesItem.allBooks = books;
  440. }
  441. }
  442. sortSeriesBooks(seriesBooks) {
  443. seriesBooks.sort((a, b) => {
  444. const dserno = (a.serno || Number.MAX_VALUE) - (b.serno || Number.MAX_VALUE);
  445. const dtitle = a.title.localeCompare(b.title);
  446. const dext = a.ext.localeCompare(b.ext);
  447. return (dserno ? dserno : (dtitle ? dtitle : dext));
  448. });
  449. }
  450. queryDate(date) {
  451. if (!utils.isManualDate(date)) {//!manual
  452. /*
  453. {label: 'сегодня', value: 'today'},
  454. {label: 'за 3 дня', value: '3days'},
  455. {label: 'за неделю', value: 'week'},
  456. {label: 'за 2 недели', value: '2weeks'},
  457. {label: 'за месяц', value: 'month'},
  458. {label: 'за 2 месяца', value: '2months'},
  459. {label: 'за 3 месяца', value: '3months'},
  460. {label: 'указать даты', value: 'manual'},
  461. */
  462. const sqlFormat = 'YYYY-MM-DD';
  463. switch (date) {
  464. case 'today': date = utils.dateFormat(dayjs(), sqlFormat); break;
  465. case '3days': date = utils.dateFormat(dayjs().subtract(3, 'days'), sqlFormat); break;
  466. case 'week': date = utils.dateFormat(dayjs().subtract(1, 'weeks'), sqlFormat); break;
  467. case '2weeks': date = utils.dateFormat(dayjs().subtract(2, 'weeks'), sqlFormat); break;
  468. case 'month': date = utils.dateFormat(dayjs().subtract(1, 'months'), sqlFormat); break;
  469. case '2months': date = utils.dateFormat(dayjs().subtract(2, 'months'), sqlFormat); break;
  470. case '3months': date = utils.dateFormat(dayjs().subtract(3, 'months'), sqlFormat); break;
  471. default:
  472. date = '';
  473. }
  474. }
  475. return date;
  476. }
  477. getQuery() {
  478. const search = (this.isExtendedSearch ? this.extSearch : this.search);
  479. const newQuery = {};
  480. search.setDefaults(newQuery, search);
  481. //дата
  482. if (newQuery.date) {
  483. newQuery.date = this.queryDate(newQuery.date);
  484. }
  485. //offset
  486. newQuery.offset = (newQuery.page - 1)*newQuery.limit;
  487. //del
  488. if (!newQuery.del && !this.showDeleted)
  489. newQuery.del = '0';
  490. return newQuery;
  491. }
  492. }