BaseList.js 17 KB

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