Search.vue 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. <template>
  2. <div class="root column fit" style="position: relative">
  3. <a ref="download" style="display: none;"></a>
  4. <div v-show="loadingMessage" class="fit row justify-center items-center" style="position: absolute; background-color: rgba(0, 0, 0, 0.2); z-index: 2">
  5. <div class="bg-white row justify-center items-center q-px-lg" style="min-width: 180px; height: 50px; border-radius: 10px; box-shadow: 2px 2px 10px #333333">
  6. <q-icon class="la la-spinner icon-rotate text-blue-8" size="28px" />
  7. <div class="q-ml-sm">
  8. {{ loadingMessage }}
  9. </div>
  10. </div>
  11. </div>
  12. <div v-show="loadingMessage2" class="fit row justify-center items-center" style="position: absolute; background-color: rgba(0, 0, 0, 0.2); z-index: 1">
  13. <div class="bg-white row justify-center items-center q-px-lg" style="min-width: 180px; height: 50px; border-radius: 10px; box-shadow: 2px 2px 10px #333333">
  14. <q-icon class="la la-spinner icon-rotate text-blue-8" size="28px" />
  15. <div class="q-ml-sm">
  16. {{ loadingMessage2 }}
  17. </div>
  18. </div>
  19. </div>
  20. <div ref="scroller" class="col fit column no-wrap" style="overflow: auto; position: relative" @scroll="onScroll">
  21. <div ref="toolPanel" class="tool-panel column bg-green-11" style="position: sticky; top: 0; z-index: 10;">
  22. <div class="header q-mx-md q-mb-xs q-mt-sm row items-center">
  23. <div class="row items-center" style="font-size: 150%;">
  24. <div class="q-mr-xs">
  25. Коллекция
  26. </div>
  27. <div class="clickable" @click="showCollectionInfo">
  28. {{ collection }}
  29. </div>
  30. </div>
  31. <DivBtn class="q-mx-md text-white bg-secondary" :size="30" :icon-size="24" :imt="1" icon="la la-cog" round @click="settingsDialogVisible = true">
  32. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  33. Настройки
  34. </q-tooltip>
  35. </DivBtn>
  36. <div class="col"></div>
  37. <div class="q-px-sm q-py-xs bg-green-12 clickable2" style="border: 1px solid #aaaaaa; border-radius: 6px" @click="openReleasePage">
  38. {{ projectName }}
  39. </div>
  40. </div>
  41. <div class="row q-mx-md q-mb-sm items-center">
  42. <q-input
  43. ref="authorInput" v-model="search.author" :maxlength="5000" :debounce="inputDebounce"
  44. class="bg-white q-mt-xs" style="width: 300px;" label="Автор" stack-label outlined dense clearable
  45. >
  46. <q-tooltip v-if="search.author" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  47. {{ search.author }}
  48. </q-tooltip>
  49. </q-input>
  50. <div class="q-mx-xs" />
  51. <q-input
  52. v-model="search.series" :maxlength="inputMaxLength" :debounce="inputDebounce"
  53. class="bg-white q-mt-xs" style="width: 200px;" label="Серия" stack-label outlined dense clearable
  54. >
  55. <q-tooltip v-if="search.series" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  56. {{ search.series }}
  57. </q-tooltip>
  58. </q-input>
  59. <div class="q-mx-xs" />
  60. <q-input
  61. v-model="search.title" :maxlength="inputMaxLength" :debounce="inputDebounce"
  62. class="bg-white q-mt-xs" style="width: 200px;" label="Название" stack-label outlined dense clearable
  63. >
  64. <q-tooltip v-if="search.title" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  65. {{ search.title }}
  66. </q-tooltip>
  67. </q-input>
  68. <div class="q-mx-xs" />
  69. <q-input
  70. v-model="genreNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
  71. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 200px;" label="Жанр" stack-label outlined dense clearable readonly
  72. @click="selectGenre"
  73. >
  74. <q-tooltip v-if="genreNames" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  75. {{ genreNames }}
  76. </q-tooltip>
  77. </q-input>
  78. <div class="q-mx-xs" />
  79. <q-input
  80. v-model="search.lang" :maxlength="inputMaxLength" :debounce="inputDebounce"
  81. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 80px;" label="Язык" stack-label outlined dense clearable readonly
  82. @click="selectLang"
  83. >
  84. <q-tooltip v-if="search.lang" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  85. {{ search.lang }}
  86. </q-tooltip>
  87. </q-input>
  88. <div class="q-mx-xs" />
  89. <DivBtn class="text-white q-mt-xs bg-grey-13" :size="30" :icon-size="24" icon="la la-broom" round @click="setDefaults">
  90. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  91. Сбросить поиск
  92. </q-tooltip>
  93. </DivBtn>
  94. <div class="q-mx-xs" />
  95. <DivBtn class="text-white q-mt-xs bg-grey-13" :size="30" :icon-size="24" icon="la la-question" round @click="showSearchHelp">
  96. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  97. Подсказка
  98. </q-tooltip>
  99. </DivBtn>
  100. <div class="q-mx-xs" />
  101. <div class="row items-center q-mt-xs">
  102. <div v-show="queryFound > 0">
  103. {{ foundAuthorsMessage }}
  104. </div>
  105. <div v-show="queryFound == 0">
  106. Ничего не найдено
  107. </div>
  108. </div>
  109. </div>
  110. </div>
  111. <div class="row justify-center" style="min-height: 48px">
  112. <PageScroller v-show="pageCount > 1" v-model="search.page" :page-count="pageCount" />
  113. </div>
  114. <!-- Формирование списка ------------------------------------------------------------------------>
  115. <div v-for="item in tableData" :key="item.key" class="column" :class="{'odd-author': item.num % 2}" style="font-size: 120%">
  116. <div class="row items-center q-ml-md q-mr-xs no-wrap">
  117. <div class="row items-center clickable2 q-py-xs no-wrap" @click="expandAuthor(item)">
  118. <div style="min-width: 30px">
  119. <div v-if="!isExpanded(item)">
  120. <q-icon name="la la-plus-square" size="28px" />
  121. </div>
  122. <div v-else>
  123. <q-icon name="la la-minus-square" size="28px" />
  124. </div>
  125. </div>
  126. </div>
  127. <div class="clickable2 q-ml-xs q-py-sm text-green-10 text-bold" @click="selectAuthor(item.author)">
  128. {{ item.name }}
  129. </div>
  130. <div class="q-ml-sm" style="font-weight: bold; color: #555">
  131. {{ getBookCount(item) }}
  132. </div>
  133. </div>
  134. <div v-if="item.bookLoading" class="book-row row items-center">
  135. <q-icon class="la la-spinner icon-rotate text-blue-8" size="28px" />
  136. <div class="q-ml-xs">
  137. Обработка...
  138. </div>
  139. </div>
  140. <div v-if="isExpanded(item) && item.books">
  141. <div v-for="book in item.books" :key="book._key" class="book-row column">
  142. <div v-if="book._type == 'series'" class="column">
  143. <div class="row items-center q-mr-xs no-wrap text-grey-9">
  144. <div class="row items-center clickable2 q-py-xs no-wrap" @click="expandSeries(book)">
  145. <div style="min-width: 30px">
  146. <div v-if="!isExpandedSeries(book)">
  147. <q-icon name="la la-plus-square" size="28px" />
  148. </div>
  149. <div v-else>
  150. <q-icon name="la la-minus-square" size="28px" />
  151. </div>
  152. </div>
  153. </div>
  154. <div class="clickable2 q-ml-xs q-py-sm" style="font-weight: bold" @click="selectSeries(book.series)">
  155. Серия: {{ book.series }}
  156. </div>
  157. </div>
  158. <div v-if="isExpandedSeries(book) && book.books" class="book-row column">
  159. <BookView v-for="subbook in book.books" :key="subbook._key" :book="subbook" :genre-tree="genreTree" @book-event="bookEvent" />
  160. </div>
  161. </div>
  162. <BookView v-else :book="book" :genre-tree="genreTree" @book-event="bookEvent" />
  163. </div>
  164. </div>
  165. </div>
  166. <!-- Формирование списка конец ------------------------------------------------------------------>
  167. <div v-show="hiddenCount" class="q-ml-lg q-py-sm clickable2 text-red" style="font-size: 120%" @click="showHiddenHelp">
  168. {{ hiddenResultsMessage }}
  169. </div>
  170. <div class="row justify-center">
  171. <PageScroller v-show="pageCount > 1" v-model="search.page" :page-count="pageCount" />
  172. </div>
  173. <div v-show="pageCount <= 1" class="q-mt-lg" />
  174. </div>
  175. <Dialog v-model="settingsDialogVisible">
  176. <template #header>
  177. <div class="row items-center" style="font-size: 130%">
  178. <q-icon class="q-mr-sm" name="la la-cog" size="28px"></q-icon>
  179. Настройки
  180. </div>
  181. </template>
  182. <div class="q-mx-md column" style="min-width: 300px; font-size: 120%;">
  183. <div class="row items-center q-ml-sm">
  184. <div class="q-mr-sm">
  185. Результатов на странице
  186. </div>
  187. <q-select
  188. v-model="limit" :options="limitOptions" class="bg-white"
  189. dropdown-icon="la la-angle-down la-sm"
  190. outlined dense emit-value map-options
  191. />
  192. </div>
  193. <q-checkbox v-model="showCounts" size="36px" label="Показывать количество" />
  194. <q-checkbox v-model="showGenres" size="36px" label="Показывать жанры" />
  195. <q-checkbox v-model="showDeleted" size="36px" label="Показывать удаленные" />
  196. <q-checkbox v-model="abCacheEnabled" size="36px" label="Кешировать запросы" />
  197. </div>
  198. <template #footer>
  199. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="settingsDialogVisible = false">
  200. OK
  201. </q-btn>
  202. </template>
  203. </Dialog>
  204. <SelectGenreDialog v-model="selectGenreDialogVisible" v-model:genre="search.genre" :genre-tree="genreTree" />
  205. <SelectLangDialog v-model="selectLangDialogVisible" v-model:lang="search.lang" :lang-list="langList" :lang-default="langDefault" />
  206. </div>
  207. </template>
  208. <script>
  209. //-----------------------------------------------------------------------------
  210. import vueComponent from '../vueComponent.js';
  211. import { reactive } from 'vue';
  212. import PageScroller from './PageScroller/PageScroller.vue';
  213. import SelectGenreDialog from './SelectGenreDialog/SelectGenreDialog.vue';
  214. import SelectLangDialog from './SelectLangDialog/SelectLangDialog.vue';
  215. import BookView from './BookView/BookView.vue';
  216. import authorBooksStorage from './authorBooksStorage';
  217. import DivBtn from '../share/DivBtn.vue';
  218. import Dialog from '../share/Dialog.vue';
  219. import * as utils from '../../share/utils';
  220. import diffUtils from '../../share/diffUtils';
  221. import _ from 'lodash';
  222. const maxItemCount = 500;//выше этого значения показываем "Загрузка"
  223. const componentOptions = {
  224. components: {
  225. PageScroller,
  226. SelectGenreDialog,
  227. SelectLangDialog,
  228. BookView,
  229. Dialog,
  230. DivBtn
  231. },
  232. watch: {
  233. config() {
  234. this.makeTitle();
  235. },
  236. settings() {
  237. this.loadSettings();
  238. },
  239. search: {
  240. handler(newValue) {
  241. this.limit = newValue.limit;
  242. this.refresh();
  243. },
  244. deep: true,
  245. },
  246. limit(newValue) {
  247. this.setSetting('limit', newValue);
  248. this.updatePageCount();
  249. },
  250. showCounts(newValue) {
  251. this.setSetting('showCounts', newValue);
  252. },
  253. showGenres(newValue) {
  254. this.setSetting('showGenres', newValue);
  255. },
  256. showDeleted(newValue) {
  257. this.setSetting('showDeleted', newValue);
  258. this.updateTableData();
  259. },
  260. abCacheEnabled(newValue) {
  261. this.setSetting('abCacheEnabled', newValue);
  262. },
  263. totalFound() {
  264. this.updatePageCount();
  265. },
  266. $route(to) {
  267. this.updateQueryFromRoute(to);
  268. },
  269. langDefault() {
  270. this.updateQueryFromRoute(this.$route);
  271. },
  272. },
  273. };
  274. class Search {
  275. _options = componentOptions;
  276. collection = '';
  277. projectName = '';
  278. loadingMessage = '';
  279. loadingMessage2 = '';
  280. settingsDialogVisible = false;
  281. selectGenreDialogVisible = false;
  282. selectLangDialogVisible = false;
  283. pageCount = 1;
  284. //input field consts
  285. inputMaxLength = 1000;
  286. inputDebounce = 200;
  287. //search fields
  288. search = {
  289. author: '',
  290. series: '',
  291. title: '',
  292. genre: '',
  293. lang: '',
  294. page: 1,
  295. limit: 50,
  296. };
  297. //settings
  298. expanded = [];
  299. expandedSeries = [];
  300. showCounts = true;
  301. showGenres = true;
  302. showDeleted = false;
  303. abCacheEnabled = true;
  304. langDefault = '';
  305. limit = 20;
  306. //stuff
  307. refreshing = false;
  308. queryFound = -1;
  309. totalFound = 0;
  310. bookRowsOnPage = 100;
  311. inpxHash = '';
  312. genreTree = [];
  313. langList = [];
  314. genreTreeInpxHash = '';
  315. cachedAuthors = {};
  316. hiddenCount = 0;
  317. limitOptions = [
  318. {label: '10', value: 10},
  319. {label: '20', value: 20},
  320. {label: '50', value: 50},
  321. {label: '100', value: 100},
  322. {label: '200', value: 200},
  323. {label: '500', value: 500},
  324. {label: '1000', value: 1000},
  325. ];
  326. searchResult = {};
  327. tableData = [];
  328. created() {
  329. this.commit = this.$store.commit;
  330. this.loadSettings();
  331. }
  332. mounted() {
  333. (async() => {
  334. await authorBooksStorage.init();
  335. this.api = this.$root.api;
  336. if (!this.$root.isMobileDevice)
  337. this.$refs.authorInput.focus();
  338. this.setDefaults();
  339. this.updateQueryFromRoute(this.$route);
  340. //чтоб не вызывался лишний refresh
  341. await utils.sleep(100);
  342. this.ready = true;
  343. this.refresh();//no await
  344. })();
  345. }
  346. loadSettings() {
  347. const settings = this.settings;
  348. this.search.limit = settings.limit;
  349. this.expanded = _.cloneDeep(settings.expanded);
  350. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  351. this.showCounts = settings.showCounts;
  352. this.showGenres = settings.showGenres;
  353. this.showDeleted = settings.showDeleted;
  354. this.abCacheEnabled = settings.abCacheEnabled;
  355. this.langDefault = settings.langDefault;
  356. }
  357. get config() {
  358. return this.$store.state.config;
  359. }
  360. get settings() {
  361. return this.$store.state.settings;
  362. }
  363. get genreNames() {
  364. let result = [];
  365. const genre = new Set(this.search.genre.split(','));
  366. for (const section of this.genreTree) {
  367. for (const g of section.value)
  368. if (genre.has(g.value))
  369. result.push(g.name);
  370. }
  371. return result.join(', ');
  372. }
  373. openReleasePage() {
  374. window.open('https://github.com/bookpauk/inpx-web', '_blank');
  375. }
  376. makeTitle() {
  377. const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
  378. this.collection = collection[0].trim();
  379. this.projectName = `${this.config.name} v${this.config.version}`;
  380. this.$root.setAppTitle(`Коллекция ${this.collection}`);
  381. }
  382. showSearchHelp() {
  383. this.$root.stdDialog.alert(`
  384. <p>
  385. Здесь должна быть подсказка<br>
  386. </p>
  387. `, 'Подсказка', {iconName: 'la la-info-circle'});
  388. }
  389. showHiddenHelp() {
  390. this.$root.stdDialog.alert(`
  391. Книги этих авторов помечены как удаленные. Для того, чтобы их увидеть, необходимо установить опцию "Показывать удаленные" в настройках.
  392. `, 'Пояснение', {iconName: 'la la-info-circle'});
  393. }
  394. showCollectionInfo() {
  395. /*
  396. "dbConfig": {
  397. "inpxInfo": {
  398. "collection": "Flibusta Offline 2 August 2022\r\nflibusta_all_local_2022-08-02\r\n65537\r\nFlibusta. A local collection. Total: 636591 books\r\nhttp://flibusta.is/",
  399. "structure": "AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;INSNO;FOLDER;LANG;LIBRATE;KEYWORDS;",
  400. "version": "20220802"
  401. },
  402. "stats": {
  403. "recsLoaded": 687063,
  404. "authorCount": 153364,
  405. "authorCountAll": 177034,
  406. "bookCount": 576018,
  407. "bookCountAll": 687063,
  408. "bookDelCount": 111045,
  409. "noAuthorBookCount": 4347,
  410. "titleCount": 512671,
  411. "seriesCount": 54472,
  412. "genreCount": 238,
  413. "langCount": 102
  414. },
  415. */
  416. let info = '';
  417. const inpxInfo = this.config.dbConfig.inpxInfo;
  418. const stat = this.config.dbConfig.stats;
  419. const keyStyle = 'style="display: inline-block; text-align: right; margin-right: 5px; min-width: 200px"';
  420. info += `<div style="min-width: 250px" />`;
  421. info += `
  422. <div><div ${keyStyle}>Найдено ссылок на файлы:</div><span>${stat.bookCountAll}</span></div>
  423. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.bookCount}</span></div>
  424. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.bookDelCount}</span></div>
  425. <div><div ${keyStyle}>Без автора:</div><span>${stat.noAuthorBookCount}</span></div>
  426. <br>
  427. <div><div ${keyStyle}>Распознано авторов:</div><span>${stat.authorCountAll}</span></div>
  428. <div><div ${keyStyle}>Авторов без соавторов:</div><span>${stat.authorCount}</span></div>
  429. <br>
  430. <div><div ${keyStyle}>Уникальных названий книг:</div><span>${stat.titleCount}</span></div>
  431. <div><div ${keyStyle}>Уникальных серий:</div><span>${stat.seriesCount}</span></div>
  432. <div><div ${keyStyle}>Найдено жанров:</div><span>${stat.genreCount}</span></div>
  433. <div><div ${keyStyle}>Найдено языков:</div><span>${stat.langCount}</span></div>
  434. `;
  435. info += `
  436. <div><hr/>
  437. <b>collection.info:</b>
  438. <pre>${inpxInfo.collection}</pre>
  439. </div>
  440. `;
  441. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  442. }
  443. selectGenre() {
  444. this.selectGenreDialogVisible = true;
  445. }
  446. selectLang() {
  447. this.selectLangDialogVisible = true;
  448. }
  449. onScroll() {
  450. if (this.ignoreScrolling)
  451. return;
  452. const curScrollTop = this.$refs.scroller.scrollTop;
  453. if (!this.lastScrollTop)
  454. this.lastScrollTop = 0;
  455. if (!this.lastScrollTop2)
  456. this.lastScrollTop2 = 0;
  457. if (curScrollTop - this.lastScrollTop > 0) {
  458. this.$refs.toolPanel.style.position = 'relative';
  459. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  460. } else if (curScrollTop - this.lastScrollTop <= 0) {
  461. this.$refs.toolPanel.style.position = 'sticky';
  462. this.$refs.toolPanel.style.top = 0;
  463. this.lastScrollTop2 = curScrollTop;
  464. }
  465. this.lastScrollTop = curScrollTop;
  466. }
  467. async ignoreScroll(ms = 50) {
  468. this.ignoreScrolling = true;
  469. await utils.sleep(ms);
  470. this.ignoreScrolling = false;
  471. }
  472. scrollToTop() {
  473. this.$refs.scroller.scrollTop = 0;
  474. this.lastScrollTop = 0;
  475. }
  476. get foundAuthorsMessage() {
  477. return `Найден${utils.wordEnding(this.totalFound, 2)} ${this.totalFound} автор${utils.wordEnding(this.totalFound)}`;
  478. }
  479. get hiddenResultsMessage() {
  480. return `+${this.hiddenCount} результат${utils.wordEnding(this.hiddenCount)} скрыт${utils.wordEnding(this.hiddenCount, 2)}`;
  481. }
  482. updatePageCount() {
  483. const prevPageCount = this.pageCount;
  484. this.pageCount = Math.ceil(this.totalFound/this.limit);
  485. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  486. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  487. this.search.page = this.prevPage;
  488. }
  489. if (this.search.page > this.pageCount) {
  490. this.prevPage = this.search.page;
  491. this.search.page = 1;
  492. }
  493. }
  494. getBookCount(item) {
  495. let result = '';
  496. if (!this.showCounts || item.count === undefined)
  497. return result;
  498. if (item.books) {
  499. let count = 0;
  500. for (const book of item.books) {
  501. if (book._type == 'series')
  502. count += book.books.length;
  503. else
  504. count++;
  505. }
  506. result = `${count}/${item.count}`;
  507. } else
  508. result = `#/${item.count}`;
  509. return `(${result})`;
  510. }
  511. selectAuthor(author) {
  512. this.search.author = `=${author}`;
  513. this.scrollToTop();
  514. }
  515. selectSeries(series) {
  516. this.search.series = `=${series}`;
  517. }
  518. async download(book, copy = false) {
  519. if (this.downloadFlag)
  520. return;
  521. this.downloadFlag = true;
  522. (async() => {
  523. await utils.sleep(200);
  524. if (this.downloadFlag)
  525. this.loadingMessage2 = 'Подготовка файла...';
  526. })();
  527. try {
  528. const makeValidFilenameOrEmpty = (s) => {
  529. try {
  530. return utils.makeValidFilename(s);
  531. } catch(e) {
  532. return '';
  533. }
  534. };
  535. //имя файла
  536. let downFileName = 'default-name';
  537. const author = book.author.split(',');
  538. const at = [author[0], book.title];
  539. downFileName = makeValidFilenameOrEmpty(at.filter(r => r).join(' - '))
  540. || makeValidFilenameOrEmpty(at[0])
  541. || makeValidFilenameOrEmpty(at[1])
  542. || downFileName;
  543. downFileName = `${downFileName.substring(0, 100)}.${book.ext}`;
  544. const bookPath = `${book.folder}/${book.file}.${book.ext}`;
  545. //подготовка
  546. const response = await this.api.getBookLink({bookPath, downFileName});
  547. const link = response.link;
  548. const href = `${window.location.origin}${link}`;
  549. if (!copy) {
  550. //скачивание
  551. const d = this.$refs.download;
  552. d.href = href;
  553. d.download = downFileName;
  554. d.click();
  555. } else {
  556. //копирование ссылки
  557. if (utils.copyTextToClipboard(href))
  558. this.$root.notify.success('Ссылка успешно скопирована');
  559. else
  560. this.$root.notify.error('Копирование ссылки не удалось');
  561. }
  562. } catch(e) {
  563. this.$root.stdDialog.alert(e.message, 'Ошибка');
  564. } finally {
  565. this.downloadFlag = false;
  566. this.loadingMessage2 = '';
  567. }
  568. }
  569. bookEvent(event) {
  570. switch (event.action) {
  571. case 'titleClick':
  572. this.search.title = `=${event.book.title}`;
  573. break;
  574. case 'download':
  575. this.download(event.book);//no await
  576. break;
  577. case 'copyLink':
  578. this.download(event.book, true);//no await
  579. break;
  580. }
  581. }
  582. isExpanded(item) {
  583. return this.expanded.indexOf(item.author) >= 0;
  584. }
  585. isExpandedSeries(seriesItem) {
  586. return this.expandedSeries.indexOf(seriesItem._key) >= 0;
  587. }
  588. setSetting(name, newValue) {
  589. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  590. }
  591. setDefaults() {
  592. this.search = Object.assign({}, this.search, {
  593. author: '',
  594. series: '',
  595. title: '',
  596. genre: '',
  597. lang: this.langDefault,
  598. });
  599. }
  600. async updateQueryFromRoute(to) {
  601. if (this.routeUpdating)
  602. return;
  603. const query = to.query;
  604. this.search = Object.assign({}, this.search, {
  605. author: query.author || '',
  606. series: query.series || '',
  607. title: query.title || '',
  608. genre: query.genre || '',
  609. lang: (query.lang == 'default' ? this.langDefault : query.lang || ''),
  610. page: parseInt(query.page, 10) || 1,
  611. limit: parseInt(query.limit, 10) || 20,
  612. });
  613. if (this.search.limit > 1000)
  614. this.search.limit = 1000;
  615. }
  616. updateRouteQuery() {
  617. this.routeUpdating = true;
  618. try {
  619. const oldQuery = this.$route.query;
  620. const query = _.pickBy(this.search);
  621. if (this.search.lang == this.langDefault)
  622. query.lang = 'default'
  623. const diff = diffUtils.getObjDiff(oldQuery, query);
  624. if (!diffUtils.isEmptyObjDiff(diff)) {
  625. this.$router.replace({query});
  626. }
  627. } finally {
  628. (async() => {
  629. await utils.sleep(100);
  630. this.routeUpdating = false;
  631. })();
  632. }
  633. }
  634. async expandAuthor(item) {
  635. const expanded = _.cloneDeep(this.expanded);
  636. const key = item.author;
  637. if (!this.isExpanded(item)) {
  638. expanded.push(key);
  639. await this.getBooks(item);
  640. if (expanded.length > 10) {
  641. expanded.shift();
  642. }
  643. this.setSetting('expanded', expanded);
  644. this.ignoreScroll();
  645. } else {
  646. const i = expanded.indexOf(key);
  647. if (i >= 0) {
  648. expanded.splice(i, 1);
  649. this.setSetting('expanded', expanded);
  650. }
  651. }
  652. }
  653. expandSeries(seriesItem) {
  654. const expandedSeries = _.cloneDeep(this.expandedSeries);
  655. const key = seriesItem._key;
  656. if (!this.isExpandedSeries(seriesItem)) {
  657. expandedSeries.push(key);
  658. if (expandedSeries.length > 100) {
  659. expandedSeries.shift();
  660. }
  661. this.setSetting('expandedSeries', expandedSeries);
  662. this.ignoreScroll();
  663. } else {
  664. const i = expandedSeries.indexOf(key);
  665. if (i >= 0) {
  666. expandedSeries.splice(i, 1);
  667. this.setSetting('expandedSeries', expandedSeries);
  668. }
  669. }
  670. }
  671. async loadBooks(authorId) {
  672. try {
  673. let result;
  674. if (this.abCacheEnabled) {
  675. const key = `${authorId}-${this.inpxHash}`;
  676. const data = await authorBooksStorage.getData(key);
  677. if (data) {
  678. result = JSON.parse(data);
  679. } else {
  680. result = await this.api.getBookList(authorId);
  681. await authorBooksStorage.setData(key, JSON.stringify(result));
  682. }
  683. } else {
  684. result = await this.api.getBookList(authorId);
  685. }
  686. return JSON.parse(result.books);
  687. } catch (e) {
  688. this.$root.stdDialog.alert(e.message, 'Ошибка');
  689. }
  690. }
  691. filterBooks(loadedBooks) {
  692. const s = this.search;
  693. const emptyFieldValue = '?';
  694. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  695. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  696. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  697. const splitAuthor = (author) => {
  698. if (!author) {
  699. author = emptyFieldValue;
  700. }
  701. const result = author.split(',');
  702. if (result.length > 1)
  703. result.push(author);
  704. return result;
  705. };
  706. const filterBySearch = (bookValue, searchValue) => {
  707. if (!searchValue)
  708. return true;
  709. bookValue = bookValue.toLowerCase();
  710. searchValue = searchValue.toLowerCase();
  711. //особая обработка префиксов
  712. if (searchValue[0] == '=') {
  713. searchValue = searchValue.substring(1);
  714. return bookValue == searchValue;
  715. } else if (searchValue[0] == '*') {
  716. searchValue = searchValue.substring(1);
  717. return bookValue.indexOf(searchValue) >= 0;
  718. } else if (searchValue[0] == '#') {
  719. searchValue = searchValue.substring(1);
  720. return !bookValue || (!enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  721. } else {
  722. return bookValue.indexOf(searchValue) == 0;
  723. }
  724. };
  725. return loadedBooks.filter((book) => {
  726. //author
  727. let authorFound = false;
  728. const authors = splitAuthor(book.author);
  729. for (const a of authors) {
  730. if (filterBySearch(a, s.author)) {
  731. authorFound = true;
  732. break;
  733. }
  734. }
  735. //genre
  736. let genreFound = !s.genre;
  737. if (!genreFound) {
  738. const searchGenres = new Set(s.genre.split(','));
  739. const bookGenres = book.genre.split(',');
  740. for (let g of bookGenres) {
  741. if (!g)
  742. g = emptyFieldValue;
  743. if (searchGenres.has(g)) {
  744. genreFound = true;
  745. break;
  746. }
  747. }
  748. }
  749. //lang
  750. let langFound = !s.lang;
  751. if (!langFound) {
  752. const searchLang = new Set(s.lang.split(','));
  753. langFound = searchLang.has(book.lang || emptyFieldValue);
  754. }
  755. return (this.showDeleted || !book.del)
  756. && authorFound
  757. && filterBySearch(book.series, s.series)
  758. && filterBySearch(book.title, s.title)
  759. && genreFound
  760. && langFound
  761. ;
  762. });
  763. }
  764. async getBooks(item) {
  765. if (item.books) {
  766. if (item.count > maxItemCount) {
  767. item.bookLoading = true;
  768. await utils.sleep(1);//для перерисовки списка
  769. item.bookLoading = false;
  770. }
  771. return;
  772. }
  773. if (!this.getBooksFlag)
  774. this.getBooksFlag = 0;
  775. this.getBooksFlag++;
  776. if (item.count > maxItemCount)
  777. item.bookLoading = true;
  778. try {
  779. if (this.getBooksFlag == 1) {
  780. (async() => {
  781. await utils.sleep(500);
  782. if (this.getBooksFlag > 0)
  783. this.loadingMessage2 = 'Загрузка списка книг...';
  784. })();
  785. }
  786. const loadedBooks = await this.loadBooks(item.key);
  787. const filtered = this.filterBooks(loadedBooks);
  788. const prepareBook = (book) => {
  789. return Object.assign(
  790. {
  791. _key: book.id,
  792. _type: 'book',
  793. },
  794. book
  795. );
  796. };
  797. //объединение по сериям
  798. const books = [];
  799. const seriesIndex = {};
  800. for (const book of filtered) {
  801. if (book.series) {
  802. let index = seriesIndex[book.series];
  803. if (index === undefined) {
  804. index = books.length;
  805. books.push({
  806. _key: `${item.author}-${book.series}`,
  807. _type: 'series',
  808. series: book.series,
  809. books: [],
  810. });
  811. seriesIndex[book.series] = index;
  812. }
  813. books[index].books.push(prepareBook(book));
  814. } else {
  815. books.push(prepareBook(book));
  816. }
  817. }
  818. //сортировка
  819. books.sort((a, b) => {
  820. if (a._type == 'series') {
  821. return (b._type == 'series' ? a._key.localeCompare(b._key) : -1);
  822. } else {
  823. return (b._type == 'book' ? a.title.localeCompare(b.title) : 1);
  824. }
  825. });
  826. //сортировка внутри серий
  827. for (const book of books) {
  828. if (book._type == 'series') {
  829. book.books.sort((a, b) => {
  830. const dserno = (a.serno || Number.MAX_VALUE) - (b.serno || Number.MAX_VALUE);
  831. const dtitle = a.title.localeCompare(b.title);
  832. const dext = a.ext.localeCompare(b.ext);
  833. return (dserno ? dserno : (dtitle ? dtitle : dext));
  834. });
  835. }
  836. }
  837. if (books.length == 1 && books[0]._type == 'series' && !this.isExpandedSeries(books[0])) {
  838. this.expandSeries(books[0]);
  839. }
  840. item.books = books;
  841. await this.$nextTick();
  842. } finally {
  843. item.bookLoading = false;
  844. this.getBooksFlag--;
  845. if (this.getBooksFlag == 0)
  846. this.loadingMessage2 = '';
  847. }
  848. }
  849. async updateGenreTreeIfNeeded() {
  850. try {
  851. if (this.genreTreeInpxHash !== this.inpxHash) {
  852. let result;
  853. if (this.abCacheEnabled) {
  854. const key = `genre-tree-${this.inpxHash}`;
  855. const data = await authorBooksStorage.getData(key);
  856. if (data) {
  857. result = JSON.parse(data);
  858. } else {
  859. result = await this.api.getGenreTree();
  860. await authorBooksStorage.setData(key, JSON.stringify(result));
  861. }
  862. } else {
  863. result = await this.api.getGenreTree();
  864. }
  865. this.genreTree = result.genreTree;
  866. this.langList = result.langList;
  867. this.genreTreeInpxHash = result.inpxHash;
  868. }
  869. } catch (e) {
  870. this.$root.stdDialog.alert(e.message, 'Ошибка');
  871. }
  872. }
  873. async updateTableData() {
  874. let result = [];
  875. const expandedSet = new Set(this.expanded);
  876. const authors = this.searchResult.author;
  877. if (!authors)
  878. return;
  879. let num = 0;
  880. this.hiddenCount = 0;
  881. for (const rec of authors) {
  882. this.cachedAuthors[rec.author] = rec;
  883. const count = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
  884. if (!count) {
  885. this.hiddenCount++;
  886. continue;
  887. }
  888. const item = reactive({
  889. key: rec.id,
  890. num,
  891. author: rec.author,
  892. name: rec.author.replace(/,/g, ', '),
  893. count,
  894. book: false,
  895. bookLoading: false,
  896. });
  897. num++;
  898. if (expandedSet.has(item.author)) {
  899. if (authors.length > 1 || item.count > maxItemCount)
  900. this.getBooks(item);//no await
  901. else
  902. await this.getBooks(item);
  903. }
  904. result.push(item);
  905. }
  906. if (result.length == 1 && !this.isExpanded(result[0])) {
  907. this.expandAuthor(result[0]);
  908. }
  909. this.tableData = result;
  910. }
  911. async refresh() {
  912. if (!this.ready)
  913. return;
  914. this.updateRouteQuery();
  915. //оптимизация
  916. if (this.abCacheEnabled && this.search.author && this.search.author[0] == '=') {
  917. const authorSearch = this.search.author.substring(1);
  918. const author = this.cachedAuthors[authorSearch];
  919. if (author) {
  920. const key = `${author.id}-${this.inpxHash}`;
  921. let data = await authorBooksStorage.getData(key);
  922. if (data) {
  923. this.queryFound = 1;
  924. this.totalFound = 1;
  925. this.searchResult = {author: [author]};
  926. await this.updateTableData();
  927. return;
  928. }
  929. }
  930. }
  931. //параметры запроса
  932. const offset = (this.search.page - 1)*this.search.limit;
  933. const newQuery = _.cloneDeep(this.search);
  934. newQuery.offset = offset;
  935. this.queryExecute = newQuery;
  936. if (this.refreshing)
  937. return;
  938. this.refreshing = true;
  939. try {
  940. while (this.queryExecute) {
  941. const query = this.queryExecute;
  942. this.queryExecute = null;
  943. let inSearch = true;
  944. (async() => {
  945. await utils.sleep(500);
  946. if (inSearch)
  947. this.loadingMessage = 'Поиск авторов...';
  948. })();
  949. try {
  950. const result = await this.api.search(query);
  951. this.queryFound = result.author.length;
  952. this.totalFound = result.totalFound;
  953. this.inpxHash = result.inpxHash;
  954. this.searchResult = result;
  955. await utils.sleep(1);
  956. if (!this.queryExecute) {
  957. await this.updateGenreTreeIfNeeded();
  958. await this.updateTableData();
  959. this.scrollToTop();
  960. }
  961. } catch (e) {
  962. this.$root.stdDialog.alert(e.message, 'Ошибка');
  963. } finally {
  964. inSearch = false;
  965. this.loadingMessage = '';
  966. }
  967. }
  968. } finally {
  969. this.refreshing = false;
  970. }
  971. }
  972. }
  973. export default vueComponent(Search);
  974. //-----------------------------------------------------------------------------
  975. </script>
  976. <style scoped>
  977. .root {
  978. }
  979. .tool-panel {
  980. border-bottom: 1px solid black;
  981. }
  982. .header {
  983. min-height: 30px;
  984. }
  985. .clickable {
  986. color: blue;
  987. cursor: pointer;
  988. }
  989. .clickable2 {
  990. cursor: pointer;
  991. }
  992. .odd-author {
  993. background-color: #e8e8e8;
  994. }
  995. .book-row {
  996. margin-left: 70px;
  997. }
  998. </style>