BaseList.js 16 KB

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