BaseList.js 18 KB

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