BaseList.js 14 KB

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