BaseList.js 18 KB

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