BaseList.js 18 KB

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