Reader.vue 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. <template>
  2. <div class="column no-wrap">
  3. <div v-show="toolBarActive" ref="header" class="header">
  4. <div ref="buttons" class="row" :class="{'no-wrap': !toolBarMultiLine}">
  5. <button ref="loader" v-ripple class="tool-button" :class="buttonActiveClass('loader')" @click="buttonClick('loader')">
  6. <q-icon name="la la-arrow-left" size="32px" />
  7. <q-tooltip :delay="1500" anchor="bottom right" content-style="font-size: 80%">
  8. {{ rstore.readerActions['loader'] }}
  9. </q-tooltip>
  10. </button>
  11. <button v-show="showToolButton['loadFile']" ref="loadFile" v-ripple class="tool-button" :class="buttonActiveClass('loadFile')" @click="buttonClick('loadFile')">
  12. <q-icon name="la la-caret-square-up" size="32px" />
  13. <q-tooltip :delay="1500" anchor="bottom right" content-style="font-size: 80%">
  14. {{ rstore.readerActions['loadFile'] }}
  15. </q-tooltip>
  16. </button>
  17. <button v-show="showToolButton['loadBuffer']" ref="loadBuffer" v-ripple class="tool-button" :class="buttonActiveClass('loadBuffer')" @click="buttonClick('loadBuffer')">
  18. <q-icon name="la la-comment" size="32px" />
  19. <q-tooltip :delay="1500" anchor="bottom right" content-style="font-size: 80%">
  20. {{ rstore.readerActions['loadBuffer'] }}
  21. </q-tooltip>
  22. </button>
  23. <button v-show="showToolButton['help']" ref="help" v-ripple class="tool-button" :class="buttonActiveClass('help')" @click="buttonClick('help')">
  24. <q-icon name="la la-question" size="32px" />
  25. <q-tooltip :delay="1500" anchor="bottom right" content-style="font-size: 80%">
  26. {{ rstore.readerActions['help'] }}
  27. </q-tooltip>
  28. </button>
  29. <div class="col"></div>
  30. <div class="space"></div>
  31. <button v-show="showToolButton['undoAction']" ref="undoAction" v-ripple class="tool-button" :class="buttonActiveClass('undoAction')" @click="buttonClick('undoAction')">
  32. <q-icon name="la la-angle-left" size="32px" />
  33. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  34. {{ rstore.readerActions['undoAction'] }}
  35. </q-tooltip>
  36. </button>
  37. <button v-show="showToolButton['redoAction']" ref="redoAction" v-ripple class="tool-button" :class="buttonActiveClass('redoAction')" @click="buttonClick('redoAction')">
  38. <q-icon name="la la-angle-right" size="32px" />
  39. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  40. {{ rstore.readerActions['redoAction'] }}
  41. </q-tooltip>
  42. </button>
  43. <div class="space"></div>
  44. <button v-show="showToolButton['fullScreen']" ref="fullScreen" v-ripple class="tool-button" :class="buttonActiveClass('fullScreen')" @click="buttonClick('fullScreen')">
  45. <q-icon :name="(fullScreenActive ? 'la la-compress-arrows-alt': 'la la-expand-arrows-alt')" size="32px" />
  46. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  47. {{ rstore.readerActions['fullScreen'] }}
  48. </q-tooltip>
  49. </button>
  50. <button v-show="showToolButton['scrolling']" ref="scrolling" v-ripple class="tool-button" :class="buttonActiveClass('scrolling')" @click="buttonClick('scrolling')">
  51. <q-icon name="la la-film" size="32px" />
  52. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  53. {{ rstore.readerActions['scrolling'] }}
  54. </q-tooltip>
  55. </button>
  56. <button v-show="showToolButton['setPosition']" ref="setPosition" v-ripple class="tool-button" :class="buttonActiveClass('setPosition')" @click="buttonClick('setPosition')">
  57. <q-icon name="la la-angle-double-right" size="32px" />
  58. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  59. {{ rstore.readerActions['setPosition'] }}
  60. </q-tooltip>
  61. </button>
  62. <button v-show="showToolButton['search']" ref="search" v-ripple class="tool-button" :class="buttonActiveClass('search')" @click="buttonClick('search')">
  63. <q-icon name="la la-search" size="32px" />
  64. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  65. {{ rstore.readerActions['search'] }}
  66. </q-tooltip>
  67. </button>
  68. <button v-show="showToolButton['copyText']" ref="copyText" v-ripple class="tool-button" :class="buttonActiveClass('copyText')" @click="buttonClick('copyText')">
  69. <q-icon name="la la-copy" size="32px" />
  70. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  71. {{ rstore.readerActions['copyText'] }}
  72. </q-tooltip>
  73. </button>
  74. <button v-show="showToolButton['convOptions']" ref="convOptions" v-ripple class="tool-button" :class="buttonActiveClass('convOptions')" @click="buttonClick('convOptions')">
  75. <q-icon name="la la-magic" size="32px" />
  76. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  77. {{ rstore.readerActions['convOptions'] }}
  78. </q-tooltip>
  79. </button>
  80. <button v-show="showToolButton['refresh']" ref="refresh" v-ripple class="tool-button" :class="buttonActiveClass('refresh')" @click="buttonClick('refresh')">
  81. <q-icon name="la la-sync" size="32px" :class="{clear: !showRefreshIcon}" />
  82. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  83. {{ rstore.readerActions['refresh'] }}
  84. </q-tooltip>
  85. </button>
  86. <div v-show="showToolButton['libs']" class="space"></div>
  87. <button v-show="showToolButton['libs']" ref="libs" v-ripple class="tool-button" :class="buttonActiveClass('libs')" @click="buttonClick('libs')">
  88. <q-icon name="la la-sitemap" size="32px" />
  89. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  90. {{ rstore.readerActions['libs'] }}
  91. </q-tooltip>
  92. </button>
  93. <div class="space"></div>
  94. <button v-show="showToolButton['contents']" ref="contents" v-ripple class="tool-button" :class="buttonActiveClass('contents')" @click="buttonClick('contents')">
  95. <q-icon name="la la-list" size="32px" />
  96. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  97. {{ rstore.readerActions['contents'] }}
  98. </q-tooltip>
  99. </button>
  100. <button v-show="showToolButton['recentBooks']" ref="recentBooks" v-ripple class="tool-button" :class="buttonActiveClass('recentBooks')" @click="buttonClick('recentBooks')">
  101. <div v-show="bothBucEnabled && needBookUpdateCount > 0" style="position: absolute">
  102. <div class="need-book-update-count">
  103. {{ needBookUpdateCount }}
  104. </div>
  105. </div>
  106. <q-icon name="la la-book-open" size="32px" />
  107. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  108. {{ rstore.readerActions['recentBooks'] }}
  109. </q-tooltip>
  110. </button>
  111. <div class="space"></div>
  112. <div class="col"></div>
  113. <button v-show="showToolButton['nightMode']" ref="nightMode" v-ripple class="tool-button" :class="buttonActiveClass('nightMode')" @click="buttonClick('nightMode')">
  114. <q-icon name="la la-moon" size="32px" />
  115. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  116. {{ rstore.readerActions['nightMode'] }}
  117. </q-tooltip>
  118. </button>
  119. <button v-show="showToolButton['clickControl']" ref="clickControl" v-ripple class="tool-button" :class="buttonActiveClass('clickControl')" @click="buttonClick('clickControl')">
  120. <q-icon name="la la-mouse" size="32px" />
  121. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  122. {{ rstore.readerActions['clickControl'] }}
  123. </q-tooltip>
  124. </button>
  125. <button v-show="showToolButton['offlineMode']" ref="offlineMode" v-ripple class="tool-button" :class="buttonActiveClass('offlineMode')" @click="buttonClick('offlineMode')">
  126. <q-icon name="la la-unlink" size="32px" />
  127. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  128. {{ rstore.readerActions['offlineMode'] }}
  129. </q-tooltip>
  130. </button>
  131. <button ref="settings" v-ripple class="tool-button" :class="buttonActiveClass('settings')" @click="buttonClick('settings')">
  132. <q-icon name="la la-cog" size="32px" />
  133. <q-tooltip :delay="1500" anchor="bottom left" content-style="font-size: 80%">
  134. {{ rstore.readerActions['settings'] }}
  135. </q-tooltip>
  136. </button>
  137. </div>
  138. </div>
  139. <div class="col row relative-position main">
  140. <keep-alive>
  141. <component
  142. :is="activePage"
  143. ref="page"
  144. class="col"
  145. @load-book="loadBook"
  146. @load-file="loadFile"
  147. @book-pos-changed="bookPosChanged"
  148. @do-action="doAction"
  149. @hide-tool-bar="hideToolBar"
  150. ></component>
  151. </keep-alive>
  152. <SetPositionPage v-if="setPositionActive" ref="setPositionPage" @set-position-toggle="setPositionToggle" @book-pos-changed="bookPosChanged"></SetPositionPage>
  153. <SearchPage
  154. v-show="searchActive"
  155. ref="searchPage"
  156. @do-action="doAction"
  157. @book-pos-changed="bookPosChanged"
  158. @start-text-search="startTextSearch"
  159. @stop-text-search="stopTextSearch"
  160. ></SearchPage>
  161. <CopyTextPage v-if="copyTextActive" ref="copyTextPage" @do-action="doAction"></CopyTextPage>
  162. <LibsPage v-show="hidden" ref="libsPage" @load-book="loadBook" @libs-close="libsClose" @do-action="doAction"></LibsPage>
  163. <RecentBooksPage v-show="recentBooksActive" ref="recentBooksPage" @load-book="loadBook" @recent-books-close="recentBooksClose" @update-count-changed="updateCountChanged"></RecentBooksPage>
  164. <SettingsPage v-show="settingsActive" ref="settingsPage" @do-action="doAction"></SettingsPage>
  165. <HelpPage v-if="helpActive" ref="helpPage" @do-action="doAction"></HelpPage>
  166. <ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
  167. <ContentsPage v-show="contentsActive" ref="contentsPage" :book-pos="bookPos" :is-visible="contentsActive" @do-action="doAction" @book-pos-changed="bookPosChanged"></ContentsPage>
  168. <ServerStorage v-show="hidden" ref="serverStorage"></ServerStorage>
  169. <ReaderDialogs ref="dialogs" @donate-toggle="donateToggle" @version-history-toggle="versionHistoryToggle" @load-buffer-toggle="loadBufferToggle"></ReaderDialogs>
  170. </div>
  171. </div>
  172. </template>
  173. <script>
  174. //-----------------------------------------------------------------------------
  175. import vueComponent from '../vueComponent.js';
  176. import _ from 'lodash';
  177. import {Buffer} from 'safe-buffer';
  178. import LoaderPage from './LoaderPage/LoaderPage.vue';
  179. import TextPage from './TextPage/TextPage.vue';
  180. import ProgressPage from './ProgressPage/ProgressPage.vue';
  181. import SetPositionPage from './SetPositionPage/SetPositionPage.vue';
  182. import SearchPage from './SearchPage/SearchPage.vue';
  183. import CopyTextPage from './CopyTextPage/CopyTextPage.vue';
  184. import LibsPage from './LibsPage/LibsPage.vue';
  185. import RecentBooksPage from './RecentBooksPage/RecentBooksPage.vue';
  186. import SettingsPage from './SettingsPage/SettingsPage.vue';
  187. import HelpPage from './HelpPage/HelpPage.vue';
  188. import ClickMapPage from './ClickMapPage/ClickMapPage.vue';
  189. import ContentsPage from './ContentsPage/ContentsPage.vue';
  190. import ServerStorage from './ServerStorage/ServerStorage.vue';
  191. import ReaderDialogs from './ReaderDialogs/ReaderDialogs.vue';
  192. import bookManager from './share/bookManager';
  193. import wallpaperStorage from './share/wallpaperStorage';
  194. import coversStorage from './share/coversStorage';
  195. import dynamicCss from '../../share/dynamicCss';
  196. import rstore from '../../store/modules/reader';
  197. import readerApi from '../../api/reader';
  198. import miscApi from '../../api/misc';
  199. import {versionHistory} from './versionHistory';
  200. import * as utils from '../../share/utils';
  201. import LockQueue from '../../share/LockQueue';
  202. const componentOptions = {
  203. components: {
  204. LoaderPage,
  205. TextPage,
  206. ProgressPage,
  207. SetPositionPage,
  208. SearchPage,
  209. CopyTextPage,
  210. LibsPage,
  211. RecentBooksPage,
  212. SettingsPage,
  213. HelpPage,
  214. ClickMapPage,
  215. ContentsPage,
  216. ServerStorage,
  217. ReaderDialogs,
  218. },
  219. watch: {
  220. bookPos: function(newValue) {
  221. if (newValue !== undefined && this.activePage == 'TextPage') {
  222. const textPage = this.$refs.page;
  223. if (textPage.bookPos != newValue) {
  224. textPage.bookPos = newValue;
  225. }
  226. if (!this.scrollingActive)
  227. this.debouncedSetRecentBook(newValue);
  228. else
  229. this.scrollingSetRecentBook(newValue);
  230. }
  231. },
  232. routeParamPos: function(newValue) {
  233. if (!this.paramPosIgnore && newValue !== undefined && newValue != this.bookPos) {
  234. this.bookPos = newValue;
  235. }
  236. },
  237. routeParamUrl: function(newValue) {
  238. if (newValue !== '' && newValue !== this.mostRecentBook().url) {
  239. this.loadBook({url: newValue, bookPos: this.routeParamPos});
  240. }
  241. },
  242. settings: function() {
  243. this.loadSettings();
  244. this.updateRoute();
  245. },
  246. loaderActive: function(newValue) {
  247. (async() => {
  248. const recent = this.mostRecentBook();
  249. if (!newValue && !this.loading && recent && !await bookManager.hasBookParsed(recent)) {
  250. this.loadBook(recent);
  251. }
  252. })();
  253. },
  254. dualPageMode(newValue) {
  255. if (newValue)
  256. this.stopScrolling();
  257. },
  258. },
  259. };
  260. class Reader {
  261. _options = componentOptions;
  262. rstore = {};
  263. loaderActive = false;
  264. loadFileActive = false;
  265. loadBufferActive = false;
  266. fullScreenActive = false;
  267. setPositionActive = false;
  268. searchActive = false;
  269. copyTextActive = false;
  270. convOptionsActive = false;
  271. refreshActive = false;
  272. contentsActive = false;
  273. libsActive = false;
  274. recentBooksActive = false;
  275. nightModeActive = false;
  276. clickControlActive = false;
  277. settingsActive = false;
  278. clickMapActive = false;
  279. helpActive = false;
  280. scrollingActive = false;
  281. progressActive = false;
  282. bookPos = null;
  283. allowUrlParamBookPos = false;
  284. showRefreshIcon = true;
  285. mostRecentBookReactive = null;
  286. showToolButton = {};
  287. toolBarHideOnScroll = false;
  288. toolBarMultiLine = false;
  289. actionList = [];
  290. actionCur = -1;
  291. hidden = false;
  292. whatsNewVisible = false;
  293. whatsNewContent = '';
  294. donationVisible = false;
  295. dualPageMode = false;
  296. bucEnabled = false;
  297. bucSetOnNew = false;
  298. needBookUpdateCount = 0;
  299. created() {
  300. this.rstore = rstore;
  301. this.loading = true;
  302. this.commit = this.$store.commit;
  303. this.reader = this.$store.state.reader;
  304. this.config = this.$store.state.config;
  305. this.lock = new LockQueue(100);
  306. this.$root.addEventHook('key', this.keyHook);
  307. this.lastActivePage = false;
  308. this.$watch(
  309. () => this.$route.path,
  310. (newValue) => {
  311. if (newValue == '/reader') {
  312. this.updateRoute();
  313. }
  314. }
  315. );
  316. this.debouncedSetRecentBook = _.debounce(async(newValue) => {
  317. const recent = this.mostRecentBook();
  318. if (recent && (recent.bookPos != newValue || recent.bookPosSeen !== this.bookPosSeen)) {
  319. await bookManager.setRecentBook(Object.assign({}, recent, {bookPos: newValue, bookPosSeen: this.bookPosSeen}));
  320. if (this.actionCur < 0 || (this.actionCur >= 0 && this.actionList[this.actionCur] != newValue))
  321. this.addAction(newValue);
  322. this.paramPosIgnore = true;
  323. this.updateRoute();
  324. await this.$nextTick();
  325. this.paramPosIgnore = false;
  326. }
  327. }, 250, {maxWait: 5000});
  328. this.scrollingSetRecentBook = _.debounce((newValue) => {
  329. this.debouncedSetRecentBook(newValue);
  330. }, 15000, {maxWait: 20000});
  331. this.debouncedHideToolBar = _.debounce((event) => {
  332. if (this.toolBarHideOnScroll && this.toolBarActive !== !!event.show) {
  333. this.commit('reader/setToolBarActive', !!event.show);
  334. this.$root.eventHook('resize');
  335. }
  336. }, 200);
  337. this.debouncedRecentBooksPageUpdate = _.debounce(async() => {
  338. if (this.recentBooksActive) {
  339. await this.$refs.recentBooksPage.updateTableData();
  340. }
  341. }, 100);
  342. this.recentItemKeys = [];
  343. this.debouncedSaveRecent = _.debounce(async() => {
  344. let timer = setTimeout(() => {
  345. if (!this.offlineModeActive)
  346. this.$root.notify.error('Таймаут соединения');
  347. }, 10000);
  348. try {
  349. const itemKeys = this.recentItemKeys;
  350. this.recentItemKeys = [];
  351. //сохранение в удаленном хранилище
  352. await this.$refs.serverStorage.saveRecent(itemKeys);
  353. } catch (e) {
  354. if (!this.offlineModeActive)
  355. this.$root.notify.error(e.message);
  356. } finally {
  357. clearTimeout(timer);
  358. }
  359. }, 500, {maxWait: 1000});
  360. document.addEventListener('fullscreenchange', () => {
  361. this.fullScreenActive = (document.fullscreenElement !== null);
  362. });
  363. this.loadSettings();
  364. }
  365. mounted() {
  366. (async() => {
  367. await wallpaperStorage.init();
  368. await coversStorage.init();
  369. await bookManager.init(this.settings);
  370. bookManager.addEventListener(this.bookManagerEvent);
  371. if (this.$root.getRootRoute() == '/reader') {
  372. if (this.routeParamUrl) {
  373. await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos, force: this.routeParamRefresh});
  374. } else {
  375. this.loaderActive = true;
  376. }
  377. }
  378. await this.$refs.serverStorage.init();
  379. this.checkSetStorageAccessKey();
  380. this.checkActivateDonateHelpPage();
  381. this.loading = false;
  382. //проверим состояние Settings, и обновим, если надо
  383. const newSettings = rstore.addDefaultsToSettings(this.settings);
  384. if (newSettings) {
  385. this.commit('reader/setSettings', newSettings);
  386. }
  387. this.updateRoute();
  388. await this.$refs.dialogs.init();
  389. this.$refs.recentBooksPage.init();
  390. })();
  391. //проверки обновлений читалки
  392. (async() => {
  393. this.isFirstNeedUpdateNotify = true;
  394. //вечный цикл, запрашиваем периодически конфиг для проверки выхода новой версии читалки
  395. while (1) {// eslint-disable-line no-constant-condition
  396. await this.checkNewVersionAvailable();
  397. await utils.sleep(60*60*1000); //каждый час
  398. }
  399. //дальше хода нет
  400. })();
  401. //проверки обновлений книг
  402. (async() => {
  403. await utils.sleep(15*1000); //подождем неск. секунд перед первым запросом
  404. //вечный цикл, запрашиваем периодически обновления
  405. while (1) {// eslint-disable-line no-constant-condition
  406. await this.checkBuc();
  407. await utils.sleep(70*60*1000); //каждые 70 минут
  408. }
  409. //дальше хода нет
  410. })();
  411. }
  412. loadSettings() {
  413. const settings = this.settings;
  414. this.allowUrlParamBookPos = settings.allowUrlParamBookPos;
  415. this.copyFullText = settings.copyFullText;
  416. this.showClickMapPage = settings.showClickMapPage;
  417. //dark mode
  418. this.nightModeActive = settings.nightMode;
  419. this.$root.setDarkMode(this.nightModeActive);
  420. this.$q.dark.set(this.nightModeActive);
  421. this.clickControlActive = settings.clickControl;
  422. this.blinkCachedLoad = settings.blinkCachedLoad;
  423. this.showToolButton = settings.showToolButton;
  424. this.toolBarHideOnScroll = settings.toolBarHideOnScroll;
  425. this.toolBarMultiLine = settings.toolBarMultiLine;
  426. this.enableSitesFilter = settings.enableSitesFilter;
  427. this.showNeedUpdateNotify = settings.showNeedUpdateNotify;
  428. this.splitToPara = settings.splitToPara;
  429. this.djvuQuality = settings.djvuQuality;
  430. this.pdfAsText = settings.pdfAsText;
  431. this.pdfQuality = settings.pdfQuality;
  432. this.dualPageMode = settings.dualPageMode;
  433. this.userWallpapers = settings.userWallpapers;
  434. this.bucEnabled = settings.bucEnabled;
  435. this.bucSizeDiff = settings.bucSizeDiff;
  436. this.bucSetOnNew = settings.bucSetOnNew;
  437. this.bucCancelEnabled = settings.bucCancelEnabled;
  438. this.bucCancelDays = settings.bucCancelDays;
  439. this.readerActionByKeyCode = utils.userHotKeysObjectSwap(settings.userHotKeys);
  440. this.$root.readerActionByKeyEvent = (event) => {
  441. return this.readerActionByKeyCode[utils.keyEventToCode(event)];
  442. }
  443. this.loadWallpapers();//no await
  444. }
  445. showHelpOnErrorIfNeeded(errorMessage) {
  446. //небольшая эвристика
  447. let i = errorMessage.indexOf('http://');
  448. if (i < 0)
  449. i = errorMessage.indexOf('https://');
  450. errorMessage = errorMessage.substring(i + 7);
  451. const perCount = errorMessage.split('%').length - 1;
  452. if (perCount > errorMessage.length/3.2) {
  453. this.$refs.dialogs.showUrlHelp();
  454. return true;
  455. }
  456. return false;
  457. }
  458. //wallpaper css
  459. async loadWallpapers() {
  460. if (!_.isEqual(this.userWallpapers, this.prevUserWallpapers)) {//оптимизация
  461. this.prevUserWallpapers = _.cloneDeep(this.userWallpapers);
  462. let newCss = '';
  463. let updated = false;
  464. const wallpaperExists = new Set();
  465. for (const wp of this.userWallpapers) {
  466. wallpaperExists.add(wp.cssClass);
  467. let data = await wallpaperStorage.getData(wp.cssClass);
  468. if (!data) {
  469. //здесь будем восстанавливать данные с сервера
  470. const url = `disk://${wp.cssClass.replace('user-paper', '')}`;
  471. try {
  472. data = await readerApi.getUploadedFileBuf(url);
  473. await wallpaperStorage.setData(wp.cssClass, data);
  474. updated = true;
  475. } catch (e) {
  476. console.error(e);
  477. }
  478. }
  479. if (data) {
  480. newCss += `.${wp.cssClass} {background: url(${data}) center; background-size: 100% 100%;}`;
  481. }
  482. }
  483. //почистим wallpaperStorage
  484. for (const key of await wallpaperStorage.getKeys()) {
  485. if (!wallpaperExists.has(key)) {
  486. await wallpaperStorage.removeData(key);
  487. }
  488. }
  489. //обновим settings, если загружали обои из /upload/
  490. if (updated) {
  491. this.commit('reader/setSettings', {});
  492. }
  493. dynamicCss.replace('wallpapers', newCss);
  494. }
  495. }
  496. async checkNewVersionAvailable() {
  497. if (!this.checkingNewVersion && this.showNeedUpdateNotify) {
  498. this.checkingNewVersion = true;
  499. try {
  500. await utils.sleep(15*1000); //подождем 15 секунд, чтобы прогрузился ServiceWorker при выходе новой версии
  501. const config = await miscApi.loadConfig();
  502. this.commit('config/setConfig', config);
  503. let againMes = '';
  504. if (this.isFirstNeedUpdateNotify) {
  505. againMes = ' еще один раз';
  506. }
  507. if (this.version != this.clientVersion)
  508. this.$root.notify.info(`Вышла новая версия (v${this.version}) читалки.<br>Пожалуйста, обновите страницу${againMes}.`, 'Обновление');
  509. } catch(e) {
  510. console.error(e);
  511. } finally {
  512. this.checkingNewVersion = false;
  513. }
  514. this.isFirstNeedUpdateNotify = false;
  515. }
  516. }
  517. async checkBuc() {
  518. if (!this.bothBucEnabled)
  519. return;
  520. try {
  521. const sorted = bookManager.getSortedRecent();
  522. //выберем все кандидиаты на обновление
  523. const updateUrls = new Set();
  524. for (const book of sorted) {
  525. if (!book.deleted && book.checkBuc && book.url && book.url.indexOf('disk://') !== 0)
  526. updateUrls.add(book.url);
  527. }
  528. //теперь по кусочкам запросим сервер
  529. const arr = Array.from(updateUrls);
  530. const bucSize = {};
  531. const chunkSize = 100;
  532. for (let i = 0; i < arr.length; i += chunkSize) {
  533. const chunk = arr.slice(i, i + chunkSize);
  534. const data = await readerApi.checkBuc(chunk);
  535. for (const item of data) {
  536. bucSize[item.id] = item.size;
  537. }
  538. await utils.sleep(1000);//чтобы не ддосить сервер
  539. }
  540. const checkSetTime = {};
  541. //проставим новые размеры у книг
  542. for (const book of sorted) {
  543. if (book.deleted)
  544. continue;
  545. //размер 0 считаем отсутствующим
  546. if (book.url && bucSize[book.url] && bucSize[book.url] !== book.bucSize) {
  547. book.bucSize = bucSize[book.url];
  548. await bookManager.recentSetItem(book);
  549. }
  550. //подготовка к следующему шагу, ищем книгу по url с максимальной датой установки checkBucTime/loadTime
  551. //от этой даты будем потом отсчитывать bucCancelDays
  552. if (updateUrls.has(book.url)) {
  553. let rec = checkSetTime[book.url] || {time: 0, loadTime: 0};
  554. const time = (book.checkBucTime ? book.checkBucTime : (rec.loadTime || 0));
  555. if (time > rec.time || (time == rec.time && (book.loadTime > rec.loadTime)))
  556. rec = {time, loadTime: book.loadTime, key: book.key};
  557. checkSetTime[book.url] = rec;
  558. }
  559. }
  560. //bucCancelEnabled и bucCancelDays
  561. //снимем флаг checkBuc у необновлявшихся bucCancelDays
  562. if (this.bucCancelEnabled) {
  563. for (const rec of Object.values(checkSetTime)) {
  564. if (rec.time && Date.now() - rec.time > this.bucCancelDays*24*3600*1000) {
  565. const book = await bookManager.getRecentBook({key: rec.key});
  566. const needBookUpdate =
  567. book.checkBuc
  568. && book.bucSize
  569. && utils.hasProp(book, 'downloadSize')
  570. && book.bucSize !== book.downloadSize
  571. && (book.bucSize - book.downloadSize >= this.bucSizeDiff)
  572. ;
  573. if (book && !needBookUpdate) {
  574. await bookManager.setCheckBuc(book, undefined);//!!!
  575. }
  576. }
  577. }
  578. }
  579. await this.$refs.recentBooksPage.updateTableData();
  580. } catch (e) {
  581. console.error(e);
  582. }
  583. }
  584. updateCountChanged(event) {
  585. this.needBookUpdateCount = event.needBookUpdateCount;
  586. }
  587. checkSetStorageAccessKey() {
  588. const q = this.$route.query;
  589. if (q['setStorageAccessKey']) {
  590. this.$router.replace(`/reader`);
  591. this.settingsToggle();
  592. this.$nextTick(() => {
  593. this.$refs.settingsPage.enterServerStorageKey(
  594. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  595. );
  596. });
  597. }
  598. }
  599. checkActivateDonateHelpPage() {
  600. const q = this.$route.query;
  601. if (q['donate']) {
  602. this.$router.replace(`/reader`);
  603. this.helpToggle();
  604. this.$nextTick(() => {
  605. this.$refs.helpPage.activateDonateHelpPage();
  606. });
  607. }
  608. }
  609. checkBookPosPercent() {
  610. const q = this.$route.query;
  611. if (q['__pp']) {
  612. let pp = q['__pp'];
  613. if (pp) {
  614. pp = parseFloat(pp) || 0;
  615. const recent = this.mostRecentBook();
  616. (async() => {
  617. await utils.sleep(100);
  618. this.bookPos = Math.floor(recent.textLength*pp/100);
  619. })();
  620. }
  621. }
  622. }
  623. get routeParamPos() {
  624. let result = undefined;
  625. const q = this.$route.query;
  626. if (q['__p']) {
  627. result = q['__p'];
  628. if (Array.isArray(result))
  629. result = result[0];
  630. }
  631. return (result ? parseInt(result, 10) || 0 : result);
  632. }
  633. updateRoute(isNewRoute) {
  634. if (this.loading)
  635. return;
  636. const recent = this.mostRecentBook();
  637. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  638. const url = (recent ? `url=${encodeURIComponent(recent.url)}` : '');
  639. if (isNewRoute)
  640. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  641. else
  642. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  643. }
  644. get mode() {
  645. return this.$store.state.config.mode;
  646. }
  647. get version() {
  648. return this.$store.state.config.version;
  649. }
  650. get clientVersion() {
  651. return versionHistory[0].version;
  652. }
  653. get bothBucEnabled() {
  654. return this.$store.state.config.bucEnabled && this.bucEnabled;
  655. }
  656. get routeParamUrl() {
  657. let result = '';
  658. const path = this.$route.fullPath;
  659. const i = path.indexOf('url=');
  660. if (i >= 0) {
  661. result = path.substr(i + 4);
  662. }
  663. return decodeURIComponent(result);
  664. }
  665. get routeParamRefresh() {
  666. const q = this.$route.query;
  667. return !!q['__refresh'];
  668. }
  669. bookPosChanged(event) {
  670. if (event.bookPosSeen !== undefined)
  671. this.bookPosSeen = event.bookPosSeen;
  672. this.bookPos = event.bookPos;
  673. }
  674. async bookManagerEvent(eventName, value) {
  675. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  676. const oldBook = (this.textPage ? this.textPage.lastBook : null);
  677. const oldPos = (this.textPage ? this.textPage.bookPos : null);
  678. const newBook = bookManager.mostRecentBook();
  679. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  680. this.mostRecentBook();
  681. }
  682. if (oldBook && newBook) {
  683. if (oldBook.key != newBook.key || oldBook.path != newBook.path) {
  684. this.loadingBook = true;
  685. try {
  686. await this.loadBook(newBook);
  687. } finally {
  688. this.loadingBook = false;
  689. }
  690. } else if (oldPos != newBook.bookPos) {
  691. while (this.loadingBook) await utils.sleep(100);
  692. this.bookPosChanged({bookPos: newBook.bookPos});
  693. }
  694. }
  695. }
  696. if (eventName == 'recent-changed') {
  697. this.debouncedRecentBooksPageUpdate();
  698. //сохранение в serverStorage
  699. if (value && this.recentItemKeys.indexOf(value) < 0) {
  700. this.recentItemKeys.push(value);
  701. this.debouncedSaveRecent();
  702. }
  703. }
  704. }
  705. get toolBarActive() {
  706. return this.reader.toolBarActive;
  707. }
  708. get offlineModeActive() {
  709. return this.reader.offlineModeActive;
  710. }
  711. mostRecentBook() {
  712. const result = bookManager.mostRecentBook();
  713. this.mostRecentBookReactive = result;
  714. return result;
  715. }
  716. get settings() {
  717. return this.$store.state.reader.settings;
  718. }
  719. addAction(pos) {
  720. let a = this.actionList;
  721. if (!a.length || a[a.length - 1] != pos) {
  722. a.push(pos);
  723. if (a.length > 20)
  724. a.shift();
  725. this.actionCur = a.length - 1;
  726. }
  727. }
  728. toolBarToggle() {
  729. this.commit('reader/setToolBarActive', !this.toolBarActive);
  730. this.$root.eventHook('resize');
  731. }
  732. hideToolBar(event) {
  733. this.debouncedHideToolBar(event);
  734. }
  735. fullScreenToggle() {
  736. if (!this.$q.fullscreen.isActive) {
  737. this.$q.fullscreen.request();
  738. } else {
  739. this.$q.fullscreen.exit();
  740. }
  741. }
  742. closeAllWindows() {
  743. this.setPositionActive = false;
  744. this.copyTextActive = false;
  745. this.recentBooksActive = false;
  746. this.settingsActive = false;
  747. this.stopScrolling();
  748. this.stopSearch();
  749. this.helpActive = false;
  750. this.contentsActive = false;
  751. }
  752. loaderToggle() {
  753. this.loaderActive = !this.loaderActive;
  754. if (this.loaderActive) {
  755. this.closeAllWindows();
  756. }
  757. }
  758. loadFileToggle() {
  759. if (!this.loaderActive)
  760. this.loaderToggle();
  761. this.$nextTick(() => {
  762. const page = this.$refs.page;
  763. if (this.activePage == 'LoaderPage' && page.loadFileClick) {
  764. page.loadFileClick();
  765. }
  766. });
  767. }
  768. loadBufferToggle() {
  769. if (!this.loaderActive)
  770. this.loaderToggle();
  771. this.$nextTick(() => {
  772. const page = this.$refs.page;
  773. if (this.activePage == 'LoaderPage' && page.showPasteText) {
  774. page.showPasteText();
  775. }
  776. });
  777. }
  778. setPositionToggle() {
  779. this.setPositionActive = !this.setPositionActive;
  780. const page = this.$refs.page;
  781. if (this.setPositionActive && this.activePage == 'TextPage' && page.parsed) {
  782. this.closeAllWindows();
  783. this.setPositionActive = true;
  784. this.$nextTick(() => {
  785. const recent = this.mostRecentBook();
  786. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  787. });
  788. } else {
  789. this.setPositionActive = false;
  790. }
  791. }
  792. stopScrolling() {
  793. if (this.scrollingActive)
  794. this.scrollingToggle();
  795. }
  796. scrollingToggle() {
  797. this.scrollingActive = !this.scrollingActive;
  798. if (this.activePage == 'TextPage') {
  799. const page = this.$refs.page;
  800. if (this.scrollingActive) {
  801. page.startTextScrolling();
  802. } else {
  803. page.stopTextScrolling();
  804. }
  805. }
  806. if (!this.scrollingActive) {
  807. this.scrollingSetRecentBook.flush();
  808. }
  809. }
  810. stopSearch() {
  811. if (this.searchActive)
  812. this.searchToggle();
  813. }
  814. startTextSearch(opts) {
  815. if (this.activePage == 'TextPage')
  816. this.$refs.page.startSearch(opts.needle);
  817. }
  818. stopTextSearch() {
  819. if (this.activePage == 'TextPage')
  820. this.$refs.page.stopSearch();
  821. }
  822. searchToggle() {
  823. this.searchActive = !this.searchActive;
  824. const page = this.$refs.page;
  825. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  826. this.closeAllWindows();
  827. this.searchActive = true;
  828. this.$nextTick(() => {
  829. this.$refs.searchPage.init(page.parsed);
  830. });
  831. } else {
  832. this.stopTextSearch();
  833. this.searchActive = false;
  834. }
  835. }
  836. copyTextToggle() {
  837. this.copyTextActive = !this.copyTextActive;
  838. const page = this.$refs.page;
  839. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  840. this.closeAllWindows();
  841. this.copyTextActive = true;
  842. this.$nextTick(() => {
  843. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  844. });
  845. } else {
  846. this.copyTextActive = false;
  847. }
  848. }
  849. recentBooksClose() {
  850. this.recentBooksActive = false;
  851. }
  852. recentBooksToggle() {
  853. this.recentBooksActive = !this.recentBooksActive;
  854. if (this.recentBooksActive) {
  855. this.closeAllWindows();
  856. this.$refs.recentBooksPage.init();
  857. this.recentBooksActive = true;
  858. } else {
  859. this.recentBooksActive = false;
  860. }
  861. }
  862. contentsPageToggle() {
  863. this.contentsActive = !this.contentsActive;
  864. const page = this.$refs.page;
  865. if (this.contentsActive && this.activePage == 'TextPage' && page.parsed) {
  866. this.closeAllWindows();
  867. this.contentsActive = true;
  868. this.$nextTick(() => {
  869. this.$refs.contentsPage.init(this.mostRecentBook(), page.parsed);
  870. });
  871. } else {
  872. this.contentsActive = false;
  873. }
  874. }
  875. libsClose() {
  876. if (this.libsActive)
  877. this.libsToogle();
  878. }
  879. libsToogle() {
  880. this.libsActive = !this.libsActive;
  881. if (this.libsActive) {
  882. this.$refs.libsPage.init();//no await
  883. } else {
  884. this.$refs.libsPage.done();
  885. }
  886. }
  887. nightModeToggle() {
  888. if (!this.nightModeActive && !utils.hasProp(this.settings.nightColorSets, 'textColor')) {
  889. this.$root.notify.warning(`Ночной режим активирован впервые. Цвета заданы по умолчанию.`);
  890. }
  891. this.commit('reader/nightModeToggle');
  892. }
  893. clickControlToggle() {
  894. this.commit('reader/setSettings', {clickControl: !this.clickControlActive});
  895. }
  896. offlineModeToggle() {
  897. this.commit('reader/setOfflineModeActive', !this.offlineModeActive);
  898. }
  899. settingsToggle() {
  900. this.settingsActive = !this.settingsActive;
  901. if (this.settingsActive) {
  902. this.closeAllWindows();
  903. this.settingsActive = true;
  904. this.$nextTick(() => {
  905. this.$refs.settingsPage.init();
  906. });
  907. } else {
  908. this.settingsActive = false;
  909. }
  910. }
  911. convOptionsToggle() {
  912. this.settingsToggle();
  913. if (this.settingsActive)
  914. this.$refs.settingsPage.selectedTab = 'convert';
  915. }
  916. helpToggle() {
  917. this.helpActive = !this.helpActive;
  918. if (this.helpActive) {
  919. this.closeAllWindows();
  920. this.helpActive = true;
  921. }
  922. }
  923. donateToggle() {
  924. this.helpToggle();
  925. if (this.helpActive) {
  926. this.$nextTick(() => {
  927. this.$refs.helpPage.activateDonateHelpPage();
  928. });
  929. }
  930. }
  931. versionHistoryToggle() {
  932. this.helpToggle();
  933. if (this.helpActive) {
  934. this.$nextTick(() => {
  935. this.$refs.helpPage.activateVersionHistoryHelpPage();
  936. });
  937. }
  938. }
  939. refreshBook() {
  940. const mrb = this.mostRecentBook();
  941. this.loadBook(Object.assign({}, mrb, {force: true}));
  942. }
  943. undoAction() {
  944. if (this.actionCur > 0) {
  945. this.actionCur--;
  946. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  947. }
  948. }
  949. redoAction() {
  950. if (this.actionCur < this.actionList.length - 1) {
  951. this.actionCur++;
  952. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  953. }
  954. }
  955. buttonClick(action) {
  956. const activeClass = this.buttonActiveClass(action);
  957. this.$refs[action].blur();
  958. if (activeClass['tool-button-disabled'])
  959. return;
  960. this.doAction({action});
  961. }
  962. buttonActiveClass(action) {
  963. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  964. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  965. let classResult = {};
  966. switch (action) {
  967. case 'loader':
  968. case 'loadFile':
  969. case 'loadBuffer':
  970. case 'help':
  971. case 'fullScreen':
  972. case 'setPosition':
  973. case 'search':
  974. case 'copyText':
  975. case 'convOptions':
  976. case 'refresh':
  977. case 'contents':
  978. case 'libs':
  979. case 'recentBooks':
  980. case 'nightMode':
  981. case 'clickControl':
  982. case 'offlineMode':
  983. case 'settings':
  984. if (this.progressActive) {
  985. classResult = classDisabled;
  986. } else if (this[`${action}Active`]) {
  987. classResult = classActive;
  988. }
  989. break;
  990. case 'scrolling':
  991. if (this.progressActive || this.dualPageMode) {
  992. classResult = classDisabled;
  993. } else if (this[`${action}Active`]) {
  994. classResult = classActive;
  995. }
  996. break;
  997. case 'undoAction':
  998. if (this.actionCur <= 0)
  999. classResult = classDisabled;
  1000. break;
  1001. case 'redoAction':
  1002. if (this.actionCur == this.actionList.length - 1)
  1003. classResult = classDisabled;
  1004. break;
  1005. }
  1006. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  1007. switch (action) {
  1008. case 'undoAction':
  1009. case 'redoAction':
  1010. case 'setPosition':
  1011. case 'scrolling':
  1012. case 'search':
  1013. case 'copyText':
  1014. case 'contents':
  1015. classResult = classDisabled;
  1016. break;
  1017. case 'refresh':
  1018. if (!this.mostRecentBookReactive)
  1019. classResult = classDisabled;
  1020. break;
  1021. }
  1022. }
  1023. return classResult;
  1024. }
  1025. async activateClickMapPage() {
  1026. if (this.clickControlActive && this.showClickMapPage && !this.clickMapActive) {
  1027. this.clickMapActive = true;
  1028. await this.$refs.clickMapPage.slowDisappear();
  1029. this.clickMapActive = false;
  1030. }
  1031. }
  1032. get activePage() {
  1033. let result = undefined;
  1034. if (this.progressActive)
  1035. result = 'ProgressPage';
  1036. else if (this.loaderActive)
  1037. result = 'LoaderPage';
  1038. else if (this.mostRecentBookReactive)
  1039. result = 'TextPage';
  1040. if (!result && !this.loading) {
  1041. this.loaderActive = true;
  1042. result = 'LoaderPage';
  1043. }
  1044. if (result != 'TextPage') {
  1045. this.$root.setAppTitle();
  1046. }
  1047. // на LoaderPage всегда показываем toolBar
  1048. if (result == 'LoaderPage' && !this.toolBarActive) {
  1049. this.toolBarToggle();
  1050. }
  1051. if (this.lastActivePage != result && result == 'TextPage') {
  1052. //акивируем страницу с текстом
  1053. this.$nextTick(async() => {
  1054. const last = this.mostRecentBookReactive;
  1055. const isParsed = await bookManager.hasBookParsed(last);
  1056. if (!isParsed) {
  1057. this.$root.setAppTitle();
  1058. return;
  1059. }
  1060. this.updateRoute();
  1061. const textPage = this.$refs.page;
  1062. if (textPage.showBook) {
  1063. this.textPage = textPage;
  1064. textPage.lastBook = last;
  1065. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  1066. textPage.showBook();
  1067. }
  1068. });
  1069. }
  1070. this.lastActivePage = result;
  1071. return result;
  1072. }
  1073. async _loadBook(opts) {
  1074. if (!opts || !opts.url) {
  1075. this.mostRecentBook();
  1076. return;
  1077. }
  1078. this.closeAllWindows();
  1079. let url = encodeURI(decodeURI(opts.url));
  1080. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  1081. (url.indexOf('disk://') != 0))
  1082. url = 'http://' + url;
  1083. // уже просматривается сейчас
  1084. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  1085. if (!opts.force && lastBook && lastBook.url == url &&
  1086. (!opts.path || opts.path == lastBook.path) &&
  1087. await bookManager.hasBookParsed(lastBook)) {
  1088. this.loaderActive = false;
  1089. return;
  1090. }
  1091. this.progressActive = true;
  1092. await this.$nextTick();
  1093. const progress = this.$refs.page;
  1094. this.actionList = [];
  1095. this.actionCur = -1;
  1096. try {
  1097. progress.show();
  1098. progress.setState({state: 'parse'});
  1099. // есть ли среди загруженных
  1100. let wasOpened = bookManager.findRecentByUrlAndPath(url, opts.path);
  1101. wasOpened = (wasOpened ? _.cloneDeep(wasOpened) : {});
  1102. wasOpened = Object.assign(wasOpened, {
  1103. url: (opts.url !== undefined ? opts.url : wasOpened.url),
  1104. path: (opts.path !== undefined ? opts.path : wasOpened.path),
  1105. bookPos: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos),
  1106. bookPosSeen: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen),
  1107. uploadFileName: (opts.uploadFileName ? opts.uploadFileName : wasOpened.uploadFileName),
  1108. });
  1109. let book = null;
  1110. if (!opts.force) {
  1111. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  1112. const bookParsed = await bookManager.getBook(wasOpened, (prog) => {
  1113. progress.setState({progress: prog});
  1114. });
  1115. // если есть в локальном кэше
  1116. if (bookParsed) {
  1117. await bookManager.setRecentBook(Object.assign(wasOpened, bookParsed));
  1118. this.mostRecentBook();
  1119. this.addAction(wasOpened.bookPos);
  1120. this.loaderActive = false;
  1121. progress.hide(); this.progressActive = false;
  1122. this.blinkCachedLoadMessage();
  1123. this.checkBookPosPercent();
  1124. this.activateClickMapPage();//no await
  1125. this.$refs.recentBooksPage.updateTableData();//no await
  1126. return;
  1127. }
  1128. // иначе идем на сервер
  1129. // пытаемся загрузить готовый файл с сервера
  1130. if (wasOpened.path) {
  1131. progress.setState({totalSteps: 5});
  1132. try {
  1133. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  1134. progress.setState(state);
  1135. });
  1136. book = Object.assign({}, wasOpened, {data: resp.data});
  1137. } catch (e) {
  1138. this.$root.notify.error('Конвертированный файл не найден на сервере.<br>Пробуем загрузить оригинал.', 'Ошибка загрузки');
  1139. }
  1140. }
  1141. }
  1142. progress.setState({totalSteps: 5});
  1143. // не удалось, скачиваем книгу полностью с конвертацией
  1144. let loadCached = true;
  1145. if (!book) {
  1146. book = await readerApi.loadBook({
  1147. url,
  1148. uploadFileName: wasOpened.uploadFileName,
  1149. enableSitesFilter: this.enableSitesFilter,
  1150. skipHtmlCheck: (this.splitToPara ? true : false),
  1151. isText: (this.splitToPara ? true : false),
  1152. djvuQuality: this.djvuQuality,
  1153. pdfAsText: this.pdfAsText,
  1154. pdfQuality: this.pdfQuality,
  1155. },
  1156. (state) => {
  1157. progress.setState(state);
  1158. }
  1159. );
  1160. loadCached = false;
  1161. }
  1162. // добавляем в bookManager
  1163. progress.setState({state: 'parse', step: 5});
  1164. const addedBook = await bookManager.addBook(book, (prog) => {
  1165. progress.setState({progress: prog});
  1166. });
  1167. // sameBookKey
  1168. if (url.indexOf('disk://') == 0) {
  1169. //ищем такой файл в загруженных
  1170. let found = bookManager.findRecentBySameBookKey(wasOpened.uploadFileName);
  1171. found = (found ? _.cloneDeep(found) : found);
  1172. if (found) {
  1173. if (wasOpened.sameBookKey != found.sameBookKey) {
  1174. //спрашиваем, надо ли объединить файлы
  1175. const askResult = bookManager.keysEqual(found.path, addedBook.path) ||
  1176. await this.$root.stdDialog.askYesNo(`
  1177. Файл с именем "${wasOpened.uploadFileName}" уже есть в загруженных.
  1178. <br>Объединить позицию?`, 'Найдена похожая книга');
  1179. if (askResult) {
  1180. wasOpened.bookPos = found.bookPos;
  1181. wasOpened.bookPosSeen = found.bookPosSeen;
  1182. wasOpened.sameBookKey = found.sameBookKey;
  1183. }
  1184. }
  1185. } else {
  1186. wasOpened.sameBookKey = wasOpened.uploadFileName;
  1187. }
  1188. } else {
  1189. wasOpened.sameBookKey = addedBook.url;
  1190. }
  1191. if (!bookManager.keysEqual(wasOpened.path, addedBook.path))
  1192. delete wasOpened.loadTime;
  1193. // добавляем в историю
  1194. const recentBook = await bookManager.setRecentBook(Object.assign(wasOpened, addedBook));
  1195. if (this.bucSetOnNew) {
  1196. await bookManager.setCheckBuc(recentBook, true);
  1197. }
  1198. this.mostRecentBook();
  1199. this.addAction(recentBook.bookPos);
  1200. this.updateRoute(true);
  1201. this.loaderActive = false;
  1202. progress.hide(); this.progressActive = false;
  1203. if (loadCached) {
  1204. this.blinkCachedLoadMessage();
  1205. } else
  1206. this.stopBlink = true;
  1207. this.checkBookPosPercent();
  1208. this.activateClickMapPage();//no await
  1209. this.$refs.recentBooksPage.updateTableData();//no await
  1210. } catch (e) {
  1211. progress.hide(); this.progressActive = false;
  1212. this.loaderActive = true;
  1213. if (!this.showHelpOnErrorIfNeeded(url)) {
  1214. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1215. }
  1216. } finally {
  1217. this.checkNewVersionAvailable();
  1218. }
  1219. }
  1220. async loadBook(opts) {
  1221. await this.lock.get();
  1222. try {
  1223. await this._loadBook(opts);
  1224. } finally {
  1225. this.lock.ret();
  1226. }
  1227. }
  1228. async _loadFile(opts) {
  1229. this.progressActive = true;
  1230. await this.$nextTick();
  1231. const progress = this.$refs.page;
  1232. try {
  1233. progress.show();
  1234. progress.setState({state: 'upload'});
  1235. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  1236. progress.setState(state);
  1237. });
  1238. progress.hide(); this.progressActive = false;
  1239. await this._loadBook({url, uploadFileName: opts.file.name, force: true});
  1240. } catch (e) {
  1241. progress.hide(); this.progressActive = false;
  1242. this.loaderActive = true;
  1243. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1244. }
  1245. }
  1246. async loadFile(opts) {
  1247. await this.lock.get();
  1248. try {
  1249. await this._loadFile(opts);
  1250. } finally {
  1251. this.lock.ret();
  1252. }
  1253. }
  1254. blinkCachedLoadMessage() {
  1255. if (!this.blinkCachedLoad)
  1256. return;
  1257. this.blinkCount = 30;
  1258. if (!this.inBlink) {
  1259. this.inBlink = true;
  1260. this.stopBlink = false;
  1261. this.$nextTick(async() => {
  1262. let page = this.$refs.page;
  1263. while (this.blinkCount) {
  1264. this.showRefreshIcon = !this.showRefreshIcon;
  1265. if (page && page.blinkCachedLoadMessage)
  1266. page.blinkCachedLoadMessage(this.showRefreshIcon);
  1267. await utils.sleep(500);
  1268. if (this.stopBlink)
  1269. break;
  1270. this.blinkCount--;
  1271. page = this.$refs.page;
  1272. }
  1273. this.showRefreshIcon = true;
  1274. this.inBlink = false;
  1275. if (page && page.blinkCachedLoadMessage)
  1276. page.blinkCachedLoadMessage('finish');
  1277. });
  1278. }
  1279. }
  1280. doAction(opts) {
  1281. let result = true;
  1282. let {action = '', event = false} = opts;
  1283. switch (action) {
  1284. case 'loader':
  1285. this.loaderToggle();
  1286. break;
  1287. case 'loadFile':
  1288. this.loadFileToggle();
  1289. break;
  1290. case 'loadBuffer':
  1291. this.loadBufferToggle();
  1292. break;
  1293. case 'help':
  1294. this.helpToggle();
  1295. break;
  1296. case 'undoAction':
  1297. this.undoAction();
  1298. break;
  1299. case 'redoAction':
  1300. this.redoAction();
  1301. break;
  1302. case 'fullScreen':
  1303. this.fullScreenToggle();
  1304. break;
  1305. case 'scrolling':
  1306. this.scrollingToggle();
  1307. break;
  1308. case 'stopScrolling':
  1309. this.stopScrolling();
  1310. break;
  1311. case 'setPosition':
  1312. this.setPositionToggle();
  1313. break;
  1314. case 'search':
  1315. this.searchToggle();
  1316. break;
  1317. case 'copyText':
  1318. this.copyTextToggle();
  1319. break;
  1320. case 'convOptions':
  1321. this.convOptionsToggle();
  1322. break;
  1323. case 'refresh':
  1324. this.refreshBook();
  1325. break;
  1326. case 'contents':
  1327. this.contentsPageToggle();
  1328. break;
  1329. case 'libs':
  1330. this.libsToogle();
  1331. break;
  1332. case 'recentBooks':
  1333. this.recentBooksToggle();
  1334. break;
  1335. case 'nightMode':
  1336. this.nightModeToggle();
  1337. break;
  1338. case 'clickControl':
  1339. this.clickControlToggle();
  1340. break;
  1341. case 'offlineMode':
  1342. this.offlineModeToggle();
  1343. break;
  1344. case 'settings':
  1345. this.settingsToggle();
  1346. break;
  1347. case 'switchToolbar':
  1348. this.toolBarToggle();
  1349. break;
  1350. case 'donate':
  1351. this.donateToggle();
  1352. break;
  1353. default:
  1354. result = false;
  1355. break;
  1356. }
  1357. if (!result && this.activePage == 'TextPage' && this.$refs.page) {
  1358. result = true;
  1359. const textPage = this.$refs.page;
  1360. switch (action) {
  1361. case 'bookBegin':
  1362. textPage.doHome();
  1363. break;
  1364. case 'bookEnd':
  1365. textPage.doEnd();
  1366. break;
  1367. case 'pageBack':
  1368. textPage.doPageUp();
  1369. break;
  1370. case 'pageForward':
  1371. textPage.doPageDown();
  1372. break;
  1373. case 'lineBack':
  1374. textPage.doUp();
  1375. break;
  1376. case 'lineForward':
  1377. textPage.doDown();
  1378. break;
  1379. case 'incFontSize':
  1380. textPage.doFontSizeInc();
  1381. break;
  1382. case 'decFontSize':
  1383. textPage.doFontSizeDec();
  1384. break;
  1385. case 'scrollingSpeedUp':
  1386. textPage.doScrollingSpeedUp();
  1387. break;
  1388. case 'scrollingSpeedDown':
  1389. textPage.doScrollingSpeedDown();
  1390. break;
  1391. default:
  1392. result = false;
  1393. break;
  1394. }
  1395. }
  1396. if (result && event) {
  1397. event.preventDefault();
  1398. event.stopPropagation();
  1399. }
  1400. return result;
  1401. }
  1402. keyHook(event) {
  1403. let result = false;
  1404. if (this.$root.getRootRoute() == '/reader') {
  1405. if (this.$root.stdDialog.active)
  1406. return result;
  1407. if (!result)
  1408. result = this.$refs.dialogs.keyHook(event);
  1409. if (!result && this.helpActive)
  1410. result = this.$refs.helpPage.keyHook(event);
  1411. if (!result && this.settingsActive)
  1412. result = this.$refs.settingsPage.keyHook(event);
  1413. if (!result && this.recentBooksActive)
  1414. result = this.$refs.recentBooksPage.keyHook(event);
  1415. if (!result && this.setPositionActive)
  1416. result = this.$refs.setPositionPage.keyHook(event);
  1417. if (!result && this.searchActive)
  1418. result = this.$refs.searchPage.keyHook(event);
  1419. if (!result && this.copyTextActive)
  1420. result = this.$refs.copyTextPage.keyHook(event);
  1421. if (!result && this.contentsActive)
  1422. result = this.$refs.contentsPage.keyHook(event);
  1423. if (!result && this.$refs.page && this.$refs.page.keyHook)
  1424. result = this.$refs.page.keyHook(event);
  1425. if (!result && event.type == 'keydown') {
  1426. const action = this.$root.readerActionByKeyEvent(event);
  1427. /*if (action == 'loader') {
  1428. result = this.doAction({action, event});
  1429. }
  1430. if (!result && this.activePage == 'TextPage') {
  1431. result = this.doAction({action, event});
  1432. }*/
  1433. result = this.doAction({action, event});
  1434. }
  1435. }
  1436. return result;
  1437. }
  1438. }
  1439. export default vueComponent(Reader);
  1440. //-----------------------------------------------------------------------------
  1441. </script>
  1442. <style scoped>
  1443. .header {
  1444. padding: 5px 5px 0px 5px;
  1445. background-color: #1B695F;
  1446. color: #000;
  1447. overflow-x: auto;
  1448. overflow-y: hidden;
  1449. scrollbar-color: #c4aa60 #e4e4e4;
  1450. }
  1451. .header::-webkit-scrollbar {
  1452. height: 5px;
  1453. }
  1454. .header::-webkit-scrollbar-track {
  1455. background-color: #1B695F;
  1456. border-radius: 1px;
  1457. }
  1458. .header::-webkit-scrollbar-thumb {
  1459. background-color: #c4aa60;
  1460. border-radius: 1px;
  1461. border: 1px solid #1B695F;
  1462. }
  1463. .main {
  1464. background-color: var(--bg-loader-color);
  1465. color: var(--text-app-color);
  1466. }
  1467. .tool-button {
  1468. margin: 0px 2px 7px 2px;
  1469. padding: 0;
  1470. color: #3E843E;
  1471. background-color: #E6EDF4;
  1472. min-height: 38px;
  1473. min-width: 38px;
  1474. height: 38px;
  1475. width: 38px;
  1476. border: 0;
  1477. border-radius: 6px;
  1478. box-shadow: 3px 3px 5px black;
  1479. outline: 0;
  1480. }
  1481. .tool-button:hover {
  1482. background-color: white;
  1483. cursor: pointer;
  1484. }
  1485. .tool-button-active {
  1486. box-shadow: 0 0 0;
  1487. color: white;
  1488. background-color: #8AB45F;
  1489. position: relative;
  1490. top: 1px;
  1491. left: 1px;
  1492. }
  1493. .tool-button-active:hover {
  1494. color: white;
  1495. background-color: #81C581;
  1496. cursor: pointer;
  1497. }
  1498. .tool-button-disabled {
  1499. color: lightgray;
  1500. background-color: gray;
  1501. cursor: default;
  1502. }
  1503. .tool-button-disabled:hover {
  1504. color: lightgray;
  1505. background-color: gray;
  1506. cursor: default;
  1507. }
  1508. .space {
  1509. width: 10px;
  1510. display: inline-block;
  1511. }
  1512. .clear {
  1513. color: rgba(0,0,0,0);
  1514. }
  1515. .need-book-update-count {
  1516. position: relative;
  1517. padding: 2px 6px 2px 6px;
  1518. left: 27px;
  1519. top: 22px;
  1520. background-color: blue;
  1521. border-radius: 10px;
  1522. color: white;
  1523. z-index: 10;
  1524. font-size: 80%;
  1525. }
  1526. </style>