Reader.vue 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. this.nightModeActive = settings.nightMode;
  418. this.clickControlActive = settings.clickControl;
  419. this.blinkCachedLoad = settings.blinkCachedLoad;
  420. this.showToolButton = settings.showToolButton;
  421. this.toolBarHideOnScroll = settings.toolBarHideOnScroll;
  422. this.toolBarMultiLine = settings.toolBarMultiLine;
  423. this.enableSitesFilter = settings.enableSitesFilter;
  424. this.showNeedUpdateNotify = settings.showNeedUpdateNotify;
  425. this.splitToPara = settings.splitToPara;
  426. this.djvuQuality = settings.djvuQuality;
  427. this.pdfAsText = settings.pdfAsText;
  428. this.pdfQuality = settings.pdfQuality;
  429. this.dualPageMode = settings.dualPageMode;
  430. this.userWallpapers = settings.userWallpapers;
  431. this.bucEnabled = settings.bucEnabled;
  432. this.bucSizeDiff = settings.bucSizeDiff;
  433. this.bucSetOnNew = settings.bucSetOnNew;
  434. this.bucCancelEnabled = settings.bucCancelEnabled;
  435. this.bucCancelDays = settings.bucCancelDays;
  436. this.readerActionByKeyCode = utils.userHotKeysObjectSwap(settings.userHotKeys);
  437. this.$root.readerActionByKeyEvent = (event) => {
  438. return this.readerActionByKeyCode[utils.keyEventToCode(event)];
  439. }
  440. this.loadWallpapers();//no await
  441. }
  442. showHelpOnErrorIfNeeded(errorMessage) {
  443. //небольшая эвристика
  444. let i = errorMessage.indexOf('http://');
  445. if (i < 0)
  446. i = errorMessage.indexOf('https://');
  447. errorMessage = errorMessage.substring(i + 7);
  448. const perCount = errorMessage.split('%').length - 1;
  449. if (perCount > errorMessage.length/3.2) {
  450. this.$refs.dialogs.showUrlHelp();
  451. return true;
  452. }
  453. return false;
  454. }
  455. //wallpaper css
  456. async loadWallpapers() {
  457. if (!_.isEqual(this.userWallpapers, this.prevUserWallpapers)) {//оптимизация
  458. this.prevUserWallpapers = _.cloneDeep(this.userWallpapers);
  459. let newCss = '';
  460. let updated = false;
  461. const wallpaperExists = new Set();
  462. for (const wp of this.userWallpapers) {
  463. wallpaperExists.add(wp.cssClass);
  464. let data = await wallpaperStorage.getData(wp.cssClass);
  465. if (!data) {
  466. //здесь будем восстанавливать данные с сервера
  467. const url = `disk://${wp.cssClass.replace('user-paper', '')}`;
  468. try {
  469. data = await readerApi.getUploadedFileBuf(url);
  470. await wallpaperStorage.setData(wp.cssClass, data);
  471. updated = true;
  472. } catch (e) {
  473. console.error(e);
  474. }
  475. }
  476. if (data) {
  477. newCss += `.${wp.cssClass} {background: url(${data}) center; background-size: 100% 100%;}`;
  478. }
  479. }
  480. //почистим wallpaperStorage
  481. for (const key of await wallpaperStorage.getKeys()) {
  482. if (!wallpaperExists.has(key)) {
  483. await wallpaperStorage.removeData(key);
  484. }
  485. }
  486. //обновим settings, если загружали обои из /upload/
  487. if (updated) {
  488. this.commit('reader/setSettings', {});
  489. }
  490. dynamicCss.replace('wallpapers', newCss);
  491. }
  492. }
  493. async checkNewVersionAvailable() {
  494. if (!this.checkingNewVersion && this.showNeedUpdateNotify) {
  495. this.checkingNewVersion = true;
  496. try {
  497. await utils.sleep(15*1000); //подождем 15 секунд, чтобы прогрузился ServiceWorker при выходе новой версии
  498. const config = await miscApi.loadConfig();
  499. this.commit('config/setConfig', config);
  500. let againMes = '';
  501. if (this.isFirstNeedUpdateNotify) {
  502. againMes = ' еще один раз';
  503. }
  504. if (this.version != this.clientVersion)
  505. this.$root.notify.info(`Вышла новая версия (v${this.version}) читалки.<br>Пожалуйста, обновите страницу${againMes}.`, 'Обновление');
  506. } catch(e) {
  507. console.error(e);
  508. } finally {
  509. this.checkingNewVersion = false;
  510. }
  511. this.isFirstNeedUpdateNotify = false;
  512. }
  513. }
  514. async checkBuc() {
  515. if (!this.bothBucEnabled)
  516. return;
  517. try {
  518. const sorted = bookManager.getSortedRecent();
  519. //выберем все кандидиаты на обновление
  520. const updateUrls = new Set();
  521. for (const book of sorted) {
  522. if (!book.deleted && book.checkBuc && book.url && book.url.indexOf('disk://') !== 0)
  523. updateUrls.add(book.url);
  524. }
  525. //теперь по кусочкам запросим сервер
  526. const arr = Array.from(updateUrls);
  527. const bucSize = {};
  528. const chunkSize = 100;
  529. for (let i = 0; i < arr.length; i += chunkSize) {
  530. const chunk = arr.slice(i, i + chunkSize);
  531. const data = await readerApi.checkBuc(chunk);
  532. for (const item of data) {
  533. bucSize[item.id] = item.size;
  534. }
  535. await utils.sleep(1000);//чтобы не ддосить сервер
  536. }
  537. const checkSetTime = {};
  538. //проставим новые размеры у книг
  539. for (const book of sorted) {
  540. if (book.deleted)
  541. continue;
  542. //размер 0 считаем отсутствующим
  543. if (book.url && bucSize[book.url] && bucSize[book.url] !== book.bucSize) {
  544. book.bucSize = bucSize[book.url];
  545. await bookManager.recentSetItem(book);
  546. }
  547. //подготовка к следующему шагу, ищем книгу по url с максимальной датой установки checkBucTime/loadTime
  548. //от этой даты будем потом отсчитывать bucCancelDays
  549. if (updateUrls.has(book.url)) {
  550. let rec = checkSetTime[book.url] || {time: 0, loadTime: 0};
  551. const time = (book.checkBucTime ? book.checkBucTime : (rec.loadTime || 0));
  552. if (time > rec.time || (time == rec.time && (book.loadTime > rec.loadTime)))
  553. rec = {time, loadTime: book.loadTime, key: book.key};
  554. checkSetTime[book.url] = rec;
  555. }
  556. }
  557. //bucCancelEnabled и bucCancelDays
  558. //снимем флаг checkBuc у необновлявшихся bucCancelDays
  559. if (this.bucCancelEnabled) {
  560. for (const rec of Object.values(checkSetTime)) {
  561. if (rec.time && Date.now() - rec.time > this.bucCancelDays*24*3600*1000) {
  562. const book = await bookManager.getRecentBook({key: rec.key});
  563. const needBookUpdate =
  564. book.checkBuc
  565. && book.bucSize
  566. && utils.hasProp(book, 'downloadSize')
  567. && book.bucSize !== book.downloadSize
  568. && (book.bucSize - book.downloadSize >= this.bucSizeDiff)
  569. ;
  570. if (book && !needBookUpdate) {
  571. await bookManager.setCheckBuc(book, undefined);//!!!
  572. }
  573. }
  574. }
  575. }
  576. await this.$refs.recentBooksPage.updateTableData();
  577. } catch (e) {
  578. console.error(e);
  579. }
  580. }
  581. updateCountChanged(event) {
  582. this.needBookUpdateCount = event.needBookUpdateCount;
  583. }
  584. checkSetStorageAccessKey() {
  585. const q = this.$route.query;
  586. if (q['setStorageAccessKey']) {
  587. this.$router.replace(`/reader`);
  588. this.settingsToggle();
  589. this.$nextTick(() => {
  590. this.$refs.settingsPage.enterServerStorageKey(
  591. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  592. );
  593. });
  594. }
  595. }
  596. checkActivateDonateHelpPage() {
  597. const q = this.$route.query;
  598. if (q['donate']) {
  599. this.$router.replace(`/reader`);
  600. this.helpToggle();
  601. this.$nextTick(() => {
  602. this.$refs.helpPage.activateDonateHelpPage();
  603. });
  604. }
  605. }
  606. checkBookPosPercent() {
  607. const q = this.$route.query;
  608. if (q['__pp']) {
  609. let pp = q['__pp'];
  610. if (pp) {
  611. pp = parseFloat(pp) || 0;
  612. const recent = this.mostRecentBook();
  613. (async() => {
  614. await utils.sleep(100);
  615. this.bookPos = Math.floor(recent.textLength*pp/100);
  616. })();
  617. }
  618. }
  619. }
  620. get routeParamPos() {
  621. let result = undefined;
  622. const q = this.$route.query;
  623. if (q['__p']) {
  624. result = q['__p'];
  625. if (Array.isArray(result))
  626. result = result[0];
  627. }
  628. return (result ? parseInt(result, 10) || 0 : result);
  629. }
  630. updateRoute(isNewRoute) {
  631. if (this.loading)
  632. return;
  633. const recent = this.mostRecentBook();
  634. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  635. const url = (recent ? `url=${encodeURIComponent(recent.url)}` : '');
  636. if (isNewRoute)
  637. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  638. else
  639. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  640. }
  641. get mode() {
  642. return this.$store.state.config.mode;
  643. }
  644. get version() {
  645. return this.$store.state.config.version;
  646. }
  647. get clientVersion() {
  648. return versionHistory[0].version;
  649. }
  650. get bothBucEnabled() {
  651. return this.$store.state.config.bucEnabled && this.bucEnabled;
  652. }
  653. get routeParamUrl() {
  654. let result = '';
  655. const path = this.$route.fullPath;
  656. const i = path.indexOf('url=');
  657. if (i >= 0) {
  658. result = path.substr(i + 4);
  659. }
  660. return decodeURIComponent(result);
  661. }
  662. get routeParamRefresh() {
  663. const q = this.$route.query;
  664. return !!q['__refresh'];
  665. }
  666. bookPosChanged(event) {
  667. if (event.bookPosSeen !== undefined)
  668. this.bookPosSeen = event.bookPosSeen;
  669. this.bookPos = event.bookPos;
  670. }
  671. async bookManagerEvent(eventName, value) {
  672. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  673. const oldBook = (this.textPage ? this.textPage.lastBook : null);
  674. const oldPos = (this.textPage ? this.textPage.bookPos : null);
  675. const newBook = bookManager.mostRecentBook();
  676. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  677. this.mostRecentBook();
  678. }
  679. if (oldBook && newBook) {
  680. if (oldBook.key != newBook.key || oldBook.path != newBook.path) {
  681. this.loadingBook = true;
  682. try {
  683. await this.loadBook(newBook);
  684. } finally {
  685. this.loadingBook = false;
  686. }
  687. } else if (oldPos != newBook.bookPos) {
  688. while (this.loadingBook) await utils.sleep(100);
  689. this.bookPosChanged({bookPos: newBook.bookPos});
  690. }
  691. }
  692. }
  693. if (eventName == 'recent-changed') {
  694. this.debouncedRecentBooksPageUpdate();
  695. //сохранение в serverStorage
  696. if (value && this.recentItemKeys.indexOf(value) < 0) {
  697. this.recentItemKeys.push(value);
  698. this.debouncedSaveRecent();
  699. }
  700. }
  701. }
  702. get toolBarActive() {
  703. return this.reader.toolBarActive;
  704. }
  705. get offlineModeActive() {
  706. return this.reader.offlineModeActive;
  707. }
  708. mostRecentBook() {
  709. const result = bookManager.mostRecentBook();
  710. this.mostRecentBookReactive = result;
  711. return result;
  712. }
  713. get settings() {
  714. return this.$store.state.reader.settings;
  715. }
  716. addAction(pos) {
  717. let a = this.actionList;
  718. if (!a.length || a[a.length - 1] != pos) {
  719. a.push(pos);
  720. if (a.length > 20)
  721. a.shift();
  722. this.actionCur = a.length - 1;
  723. }
  724. }
  725. toolBarToggle() {
  726. this.commit('reader/setToolBarActive', !this.toolBarActive);
  727. this.$root.eventHook('resize');
  728. }
  729. hideToolBar(event) {
  730. this.debouncedHideToolBar(event);
  731. }
  732. fullScreenToggle() {
  733. if (!this.$q.fullscreen.isActive) {
  734. this.$q.fullscreen.request();
  735. } else {
  736. this.$q.fullscreen.exit();
  737. }
  738. }
  739. closeAllWindows() {
  740. this.setPositionActive = false;
  741. this.copyTextActive = false;
  742. this.recentBooksActive = false;
  743. this.settingsActive = false;
  744. this.stopScrolling();
  745. this.stopSearch();
  746. this.helpActive = false;
  747. this.contentsActive = false;
  748. }
  749. loaderToggle() {
  750. this.loaderActive = !this.loaderActive;
  751. if (this.loaderActive) {
  752. this.closeAllWindows();
  753. }
  754. }
  755. loadFileToggle() {
  756. if (!this.loaderActive)
  757. this.loaderToggle();
  758. this.$nextTick(() => {
  759. const page = this.$refs.page;
  760. if (this.activePage == 'LoaderPage' && page.loadFileClick) {
  761. page.loadFileClick();
  762. }
  763. });
  764. }
  765. loadBufferToggle() {
  766. if (!this.loaderActive)
  767. this.loaderToggle();
  768. this.$nextTick(() => {
  769. const page = this.$refs.page;
  770. if (this.activePage == 'LoaderPage' && page.showPasteText) {
  771. page.showPasteText();
  772. }
  773. });
  774. }
  775. setPositionToggle() {
  776. this.setPositionActive = !this.setPositionActive;
  777. const page = this.$refs.page;
  778. if (this.setPositionActive && this.activePage == 'TextPage' && page.parsed) {
  779. this.closeAllWindows();
  780. this.setPositionActive = true;
  781. this.$nextTick(() => {
  782. const recent = this.mostRecentBook();
  783. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  784. });
  785. } else {
  786. this.setPositionActive = false;
  787. }
  788. }
  789. stopScrolling() {
  790. if (this.scrollingActive)
  791. this.scrollingToggle();
  792. }
  793. scrollingToggle() {
  794. this.scrollingActive = !this.scrollingActive;
  795. if (this.activePage == 'TextPage') {
  796. const page = this.$refs.page;
  797. if (this.scrollingActive) {
  798. page.startTextScrolling();
  799. } else {
  800. page.stopTextScrolling();
  801. }
  802. }
  803. if (!this.scrollingActive) {
  804. this.scrollingSetRecentBook.flush();
  805. }
  806. }
  807. stopSearch() {
  808. if (this.searchActive)
  809. this.searchToggle();
  810. }
  811. startTextSearch(opts) {
  812. if (this.activePage == 'TextPage')
  813. this.$refs.page.startSearch(opts.needle);
  814. }
  815. stopTextSearch() {
  816. if (this.activePage == 'TextPage')
  817. this.$refs.page.stopSearch();
  818. }
  819. searchToggle() {
  820. this.searchActive = !this.searchActive;
  821. const page = this.$refs.page;
  822. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  823. this.closeAllWindows();
  824. this.searchActive = true;
  825. this.$nextTick(() => {
  826. this.$refs.searchPage.init(page.parsed);
  827. });
  828. } else {
  829. this.stopTextSearch();
  830. this.searchActive = false;
  831. }
  832. }
  833. copyTextToggle() {
  834. this.copyTextActive = !this.copyTextActive;
  835. const page = this.$refs.page;
  836. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  837. this.closeAllWindows();
  838. this.copyTextActive = true;
  839. this.$nextTick(() => {
  840. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  841. });
  842. } else {
  843. this.copyTextActive = false;
  844. }
  845. }
  846. recentBooksClose() {
  847. this.recentBooksActive = false;
  848. }
  849. recentBooksToggle() {
  850. this.recentBooksActive = !this.recentBooksActive;
  851. if (this.recentBooksActive) {
  852. this.closeAllWindows();
  853. this.$refs.recentBooksPage.init();
  854. this.recentBooksActive = true;
  855. } else {
  856. this.recentBooksActive = false;
  857. }
  858. }
  859. contentsPageToggle() {
  860. this.contentsActive = !this.contentsActive;
  861. const page = this.$refs.page;
  862. if (this.contentsActive && this.activePage == 'TextPage' && page.parsed) {
  863. this.closeAllWindows();
  864. this.contentsActive = true;
  865. this.$nextTick(() => {
  866. this.$refs.contentsPage.init(this.mostRecentBook(), page.parsed);
  867. });
  868. } else {
  869. this.contentsActive = false;
  870. }
  871. }
  872. libsClose() {
  873. if (this.libsActive)
  874. this.libsToogle();
  875. }
  876. libsToogle() {
  877. this.libsActive = !this.libsActive;
  878. if (this.libsActive) {
  879. this.$refs.libsPage.init();//no await
  880. } else {
  881. this.$refs.libsPage.done();
  882. }
  883. }
  884. nightModeToggle() {
  885. if (!this.nightModeActive && !utils.hasProp(this.settings.nightColorSets, 'textColor')) {
  886. this.$root.notify.warning(`Ночной режим активирован впервые. Цвета заданы по умолчанию.`);
  887. }
  888. this.commit('reader/nightModeToggle');
  889. }
  890. clickControlToggle() {
  891. this.commit('reader/setSettings', {clickControl: !this.clickControlActive});
  892. }
  893. offlineModeToggle() {
  894. this.commit('reader/setOfflineModeActive', !this.offlineModeActive);
  895. }
  896. settingsToggle() {
  897. this.settingsActive = !this.settingsActive;
  898. if (this.settingsActive) {
  899. this.closeAllWindows();
  900. this.settingsActive = true;
  901. this.$nextTick(() => {
  902. this.$refs.settingsPage.init();
  903. });
  904. } else {
  905. this.settingsActive = false;
  906. }
  907. }
  908. convOptionsToggle() {
  909. this.settingsToggle();
  910. if (this.settingsActive)
  911. this.$refs.settingsPage.selectedTab = 'convert';
  912. }
  913. helpToggle() {
  914. this.helpActive = !this.helpActive;
  915. if (this.helpActive) {
  916. this.closeAllWindows();
  917. this.helpActive = true;
  918. }
  919. }
  920. donateToggle() {
  921. this.helpToggle();
  922. if (this.helpActive) {
  923. this.$nextTick(() => {
  924. this.$refs.helpPage.activateDonateHelpPage();
  925. });
  926. }
  927. }
  928. versionHistoryToggle() {
  929. this.helpToggle();
  930. if (this.helpActive) {
  931. this.$nextTick(() => {
  932. this.$refs.helpPage.activateVersionHistoryHelpPage();
  933. });
  934. }
  935. }
  936. refreshBook() {
  937. const mrb = this.mostRecentBook();
  938. this.loadBook(Object.assign({}, mrb, {force: true}));
  939. }
  940. undoAction() {
  941. if (this.actionCur > 0) {
  942. this.actionCur--;
  943. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  944. }
  945. }
  946. redoAction() {
  947. if (this.actionCur < this.actionList.length - 1) {
  948. this.actionCur++;
  949. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  950. }
  951. }
  952. buttonClick(action) {
  953. const activeClass = this.buttonActiveClass(action);
  954. this.$refs[action].blur();
  955. if (activeClass['tool-button-disabled'])
  956. return;
  957. this.doAction({action});
  958. }
  959. buttonActiveClass(action) {
  960. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  961. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  962. let classResult = {};
  963. switch (action) {
  964. case 'loader':
  965. case 'loadFile':
  966. case 'loadBuffer':
  967. case 'help':
  968. case 'fullScreen':
  969. case 'setPosition':
  970. case 'search':
  971. case 'copyText':
  972. case 'convOptions':
  973. case 'refresh':
  974. case 'contents':
  975. case 'libs':
  976. case 'recentBooks':
  977. case 'nightMode':
  978. case 'clickControl':
  979. case 'offlineMode':
  980. case 'settings':
  981. if (this.progressActive) {
  982. classResult = classDisabled;
  983. } else if (this[`${action}Active`]) {
  984. classResult = classActive;
  985. }
  986. break;
  987. case 'scrolling':
  988. if (this.progressActive || this.dualPageMode) {
  989. classResult = classDisabled;
  990. } else if (this[`${action}Active`]) {
  991. classResult = classActive;
  992. }
  993. break;
  994. case 'undoAction':
  995. if (this.actionCur <= 0)
  996. classResult = classDisabled;
  997. break;
  998. case 'redoAction':
  999. if (this.actionCur == this.actionList.length - 1)
  1000. classResult = classDisabled;
  1001. break;
  1002. }
  1003. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  1004. switch (action) {
  1005. case 'undoAction':
  1006. case 'redoAction':
  1007. case 'setPosition':
  1008. case 'scrolling':
  1009. case 'search':
  1010. case 'copyText':
  1011. case 'contents':
  1012. classResult = classDisabled;
  1013. break;
  1014. case 'refresh':
  1015. if (!this.mostRecentBookReactive)
  1016. classResult = classDisabled;
  1017. break;
  1018. }
  1019. }
  1020. return classResult;
  1021. }
  1022. async activateClickMapPage() {
  1023. if (this.clickControlActive && this.showClickMapPage && !this.clickMapActive) {
  1024. this.clickMapActive = true;
  1025. await this.$refs.clickMapPage.slowDisappear();
  1026. this.clickMapActive = false;
  1027. }
  1028. }
  1029. get activePage() {
  1030. let result = undefined;
  1031. if (this.progressActive)
  1032. result = 'ProgressPage';
  1033. else if (this.loaderActive)
  1034. result = 'LoaderPage';
  1035. else if (this.mostRecentBookReactive)
  1036. result = 'TextPage';
  1037. if (!result && !this.loading) {
  1038. this.loaderActive = true;
  1039. result = 'LoaderPage';
  1040. }
  1041. if (result != 'TextPage') {
  1042. this.$root.setAppTitle();
  1043. }
  1044. // на LoaderPage всегда показываем toolBar
  1045. if (result == 'LoaderPage' && !this.toolBarActive) {
  1046. this.toolBarToggle();
  1047. }
  1048. if (this.lastActivePage != result && result == 'TextPage') {
  1049. //акивируем страницу с текстом
  1050. this.$nextTick(async() => {
  1051. const last = this.mostRecentBookReactive;
  1052. const isParsed = await bookManager.hasBookParsed(last);
  1053. if (!isParsed) {
  1054. this.$root.setAppTitle();
  1055. return;
  1056. }
  1057. this.updateRoute();
  1058. const textPage = this.$refs.page;
  1059. if (textPage.showBook) {
  1060. this.textPage = textPage;
  1061. textPage.lastBook = last;
  1062. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  1063. textPage.showBook();
  1064. }
  1065. });
  1066. }
  1067. this.lastActivePage = result;
  1068. return result;
  1069. }
  1070. async _loadBook(opts) {
  1071. if (!opts || !opts.url) {
  1072. this.mostRecentBook();
  1073. return;
  1074. }
  1075. this.closeAllWindows();
  1076. let url = encodeURI(decodeURI(opts.url));
  1077. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  1078. (url.indexOf('disk://') != 0))
  1079. url = 'http://' + url;
  1080. // уже просматривается сейчас
  1081. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  1082. if (!opts.force && lastBook && lastBook.url == url &&
  1083. (!opts.path || opts.path == lastBook.path) &&
  1084. await bookManager.hasBookParsed(lastBook)) {
  1085. this.loaderActive = false;
  1086. return;
  1087. }
  1088. this.progressActive = true;
  1089. await this.$nextTick();
  1090. const progress = this.$refs.page;
  1091. this.actionList = [];
  1092. this.actionCur = -1;
  1093. try {
  1094. progress.show();
  1095. progress.setState({state: 'parse'});
  1096. // есть ли среди загруженных
  1097. let wasOpened = bookManager.findRecentByUrlAndPath(url, opts.path);
  1098. wasOpened = (wasOpened ? _.cloneDeep(wasOpened) : {});
  1099. wasOpened = Object.assign(wasOpened, {
  1100. url: (opts.url !== undefined ? opts.url : wasOpened.url),
  1101. path: (opts.path !== undefined ? opts.path : wasOpened.path),
  1102. bookPos: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos),
  1103. bookPosSeen: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen),
  1104. uploadFileName: (opts.uploadFileName ? opts.uploadFileName : wasOpened.uploadFileName),
  1105. });
  1106. let book = null;
  1107. if (!opts.force) {
  1108. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  1109. const bookParsed = await bookManager.getBook(wasOpened, (prog) => {
  1110. progress.setState({progress: prog});
  1111. });
  1112. // если есть в локальном кэше
  1113. if (bookParsed) {
  1114. await bookManager.setRecentBook(Object.assign(wasOpened, bookParsed));
  1115. this.mostRecentBook();
  1116. this.addAction(wasOpened.bookPos);
  1117. this.loaderActive = false;
  1118. progress.hide(); this.progressActive = false;
  1119. this.blinkCachedLoadMessage();
  1120. this.checkBookPosPercent();
  1121. this.activateClickMapPage();//no await
  1122. this.$refs.recentBooksPage.updateTableData();//no await
  1123. return;
  1124. }
  1125. // иначе идем на сервер
  1126. // пытаемся загрузить готовый файл с сервера
  1127. if (wasOpened.path) {
  1128. progress.setState({totalSteps: 5});
  1129. try {
  1130. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  1131. progress.setState(state);
  1132. });
  1133. book = Object.assign({}, wasOpened, {data: resp.data});
  1134. } catch (e) {
  1135. this.$root.notify.error('Конвертированный файл не найден на сервере.<br>Пробуем загрузить оригинал.', 'Ошибка загрузки');
  1136. }
  1137. }
  1138. }
  1139. progress.setState({totalSteps: 5});
  1140. // не удалось, скачиваем книгу полностью с конвертацией
  1141. let loadCached = true;
  1142. if (!book) {
  1143. book = await readerApi.loadBook({
  1144. url,
  1145. uploadFileName: wasOpened.uploadFileName,
  1146. enableSitesFilter: this.enableSitesFilter,
  1147. skipHtmlCheck: (this.splitToPara ? true : false),
  1148. isText: (this.splitToPara ? true : false),
  1149. djvuQuality: this.djvuQuality,
  1150. pdfAsText: this.pdfAsText,
  1151. pdfQuality: this.pdfQuality,
  1152. },
  1153. (state) => {
  1154. progress.setState(state);
  1155. }
  1156. );
  1157. loadCached = false;
  1158. }
  1159. // добавляем в bookManager
  1160. progress.setState({state: 'parse', step: 5});
  1161. const addedBook = await bookManager.addBook(book, (prog) => {
  1162. progress.setState({progress: prog});
  1163. });
  1164. // sameBookKey
  1165. if (url.indexOf('disk://') == 0) {
  1166. //ищем такой файл в загруженных
  1167. let found = bookManager.findRecentBySameBookKey(wasOpened.uploadFileName);
  1168. found = (found ? _.cloneDeep(found) : found);
  1169. if (found) {
  1170. if (wasOpened.sameBookKey != found.sameBookKey) {
  1171. //спрашиваем, надо ли объединить файлы
  1172. const askResult = bookManager.keysEqual(found.path, addedBook.path) ||
  1173. await this.$root.stdDialog.askYesNo(`
  1174. Файл с именем "${wasOpened.uploadFileName}" уже есть в загруженных.
  1175. <br>Объединить позицию?`, 'Найдена похожая книга');
  1176. if (askResult) {
  1177. wasOpened.bookPos = found.bookPos;
  1178. wasOpened.bookPosSeen = found.bookPosSeen;
  1179. wasOpened.sameBookKey = found.sameBookKey;
  1180. }
  1181. }
  1182. } else {
  1183. wasOpened.sameBookKey = wasOpened.uploadFileName;
  1184. }
  1185. } else {
  1186. wasOpened.sameBookKey = addedBook.url;
  1187. }
  1188. if (!bookManager.keysEqual(wasOpened.path, addedBook.path))
  1189. delete wasOpened.loadTime;
  1190. // добавляем в историю
  1191. const recentBook = await bookManager.setRecentBook(Object.assign(wasOpened, addedBook));
  1192. if (this.bucSetOnNew) {
  1193. await bookManager.setCheckBuc(recentBook, true);
  1194. }
  1195. this.mostRecentBook();
  1196. this.addAction(recentBook.bookPos);
  1197. this.updateRoute(true);
  1198. this.loaderActive = false;
  1199. progress.hide(); this.progressActive = false;
  1200. if (loadCached) {
  1201. this.blinkCachedLoadMessage();
  1202. } else
  1203. this.stopBlink = true;
  1204. this.checkBookPosPercent();
  1205. this.activateClickMapPage();//no await
  1206. this.$refs.recentBooksPage.updateTableData();//no await
  1207. } catch (e) {
  1208. progress.hide(); this.progressActive = false;
  1209. this.loaderActive = true;
  1210. if (!this.showHelpOnErrorIfNeeded(url)) {
  1211. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1212. }
  1213. } finally {
  1214. this.checkNewVersionAvailable();
  1215. }
  1216. }
  1217. async loadBook(opts) {
  1218. await this.lock.get();
  1219. try {
  1220. await this._loadBook(opts);
  1221. } finally {
  1222. this.lock.ret();
  1223. }
  1224. }
  1225. async _loadFile(opts) {
  1226. this.progressActive = true;
  1227. await this.$nextTick();
  1228. const progress = this.$refs.page;
  1229. try {
  1230. progress.show();
  1231. progress.setState({state: 'upload'});
  1232. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  1233. progress.setState(state);
  1234. });
  1235. progress.hide(); this.progressActive = false;
  1236. await this._loadBook({url, uploadFileName: opts.file.name, force: true});
  1237. } catch (e) {
  1238. progress.hide(); this.progressActive = false;
  1239. this.loaderActive = true;
  1240. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1241. }
  1242. }
  1243. async loadFile(opts) {
  1244. await this.lock.get();
  1245. try {
  1246. await this._loadFile(opts);
  1247. } finally {
  1248. this.lock.ret();
  1249. }
  1250. }
  1251. blinkCachedLoadMessage() {
  1252. if (!this.blinkCachedLoad)
  1253. return;
  1254. this.blinkCount = 30;
  1255. if (!this.inBlink) {
  1256. this.inBlink = true;
  1257. this.stopBlink = false;
  1258. this.$nextTick(async() => {
  1259. let page = this.$refs.page;
  1260. while (this.blinkCount) {
  1261. this.showRefreshIcon = !this.showRefreshIcon;
  1262. if (page && page.blinkCachedLoadMessage)
  1263. page.blinkCachedLoadMessage(this.showRefreshIcon);
  1264. await utils.sleep(500);
  1265. if (this.stopBlink)
  1266. break;
  1267. this.blinkCount--;
  1268. page = this.$refs.page;
  1269. }
  1270. this.showRefreshIcon = true;
  1271. this.inBlink = false;
  1272. if (page && page.blinkCachedLoadMessage)
  1273. page.blinkCachedLoadMessage('finish');
  1274. });
  1275. }
  1276. }
  1277. doAction(opts) {
  1278. let result = true;
  1279. let {action = '', event = false} = opts;
  1280. switch (action) {
  1281. case 'loader':
  1282. this.loaderToggle();
  1283. break;
  1284. case 'loadFile':
  1285. this.loadFileToggle();
  1286. break;
  1287. case 'loadBuffer':
  1288. this.loadBufferToggle();
  1289. break;
  1290. case 'help':
  1291. this.helpToggle();
  1292. break;
  1293. case 'undoAction':
  1294. this.undoAction();
  1295. break;
  1296. case 'redoAction':
  1297. this.redoAction();
  1298. break;
  1299. case 'fullScreen':
  1300. this.fullScreenToggle();
  1301. break;
  1302. case 'scrolling':
  1303. this.scrollingToggle();
  1304. break;
  1305. case 'stopScrolling':
  1306. this.stopScrolling();
  1307. break;
  1308. case 'setPosition':
  1309. this.setPositionToggle();
  1310. break;
  1311. case 'search':
  1312. this.searchToggle();
  1313. break;
  1314. case 'copyText':
  1315. this.copyTextToggle();
  1316. break;
  1317. case 'convOptions':
  1318. this.convOptionsToggle();
  1319. break;
  1320. case 'refresh':
  1321. this.refreshBook();
  1322. break;
  1323. case 'contents':
  1324. this.contentsPageToggle();
  1325. break;
  1326. case 'libs':
  1327. this.libsToogle();
  1328. break;
  1329. case 'recentBooks':
  1330. this.recentBooksToggle();
  1331. break;
  1332. case 'nightMode':
  1333. this.nightModeToggle();
  1334. break;
  1335. case 'clickControl':
  1336. this.clickControlToggle();
  1337. break;
  1338. case 'offlineMode':
  1339. this.offlineModeToggle();
  1340. break;
  1341. case 'settings':
  1342. this.settingsToggle();
  1343. break;
  1344. case 'switchToolbar':
  1345. this.toolBarToggle();
  1346. break;
  1347. case 'donate':
  1348. this.donateToggle();
  1349. break;
  1350. default:
  1351. result = false;
  1352. break;
  1353. }
  1354. if (!result && this.activePage == 'TextPage' && this.$refs.page) {
  1355. result = true;
  1356. const textPage = this.$refs.page;
  1357. switch (action) {
  1358. case 'bookBegin':
  1359. textPage.doHome();
  1360. break;
  1361. case 'bookEnd':
  1362. textPage.doEnd();
  1363. break;
  1364. case 'pageBack':
  1365. textPage.doPageUp();
  1366. break;
  1367. case 'pageForward':
  1368. textPage.doPageDown();
  1369. break;
  1370. case 'lineBack':
  1371. textPage.doUp();
  1372. break;
  1373. case 'lineForward':
  1374. textPage.doDown();
  1375. break;
  1376. case 'incFontSize':
  1377. textPage.doFontSizeInc();
  1378. break;
  1379. case 'decFontSize':
  1380. textPage.doFontSizeDec();
  1381. break;
  1382. case 'scrollingSpeedUp':
  1383. textPage.doScrollingSpeedUp();
  1384. break;
  1385. case 'scrollingSpeedDown':
  1386. textPage.doScrollingSpeedDown();
  1387. break;
  1388. default:
  1389. result = false;
  1390. break;
  1391. }
  1392. }
  1393. if (result && event) {
  1394. event.preventDefault();
  1395. event.stopPropagation();
  1396. }
  1397. return result;
  1398. }
  1399. keyHook(event) {
  1400. let result = false;
  1401. if (this.$root.getRootRoute() == '/reader') {
  1402. if (this.$root.stdDialog.active)
  1403. return result;
  1404. if (!result)
  1405. result = this.$refs.dialogs.keyHook(event);
  1406. if (!result && this.helpActive)
  1407. result = this.$refs.helpPage.keyHook(event);
  1408. if (!result && this.settingsActive)
  1409. result = this.$refs.settingsPage.keyHook(event);
  1410. if (!result && this.recentBooksActive)
  1411. result = this.$refs.recentBooksPage.keyHook(event);
  1412. if (!result && this.setPositionActive)
  1413. result = this.$refs.setPositionPage.keyHook(event);
  1414. if (!result && this.searchActive)
  1415. result = this.$refs.searchPage.keyHook(event);
  1416. if (!result && this.copyTextActive)
  1417. result = this.$refs.copyTextPage.keyHook(event);
  1418. if (!result && this.contentsActive)
  1419. result = this.$refs.contentsPage.keyHook(event);
  1420. if (!result && this.$refs.page && this.$refs.page.keyHook)
  1421. result = this.$refs.page.keyHook(event);
  1422. if (!result && event.type == 'keydown') {
  1423. const action = this.$root.readerActionByKeyEvent(event);
  1424. /*if (action == 'loader') {
  1425. result = this.doAction({action, event});
  1426. }
  1427. if (!result && this.activePage == 'TextPage') {
  1428. result = this.doAction({action, event});
  1429. }*/
  1430. result = this.doAction({action, event});
  1431. }
  1432. }
  1433. return result;
  1434. }
  1435. }
  1436. export default vueComponent(Reader);
  1437. //-----------------------------------------------------------------------------
  1438. </script>
  1439. <style scoped>
  1440. .header {
  1441. padding: 5px 5px 0px 5px;
  1442. background-color: #1B695F;
  1443. color: #000;
  1444. overflow-x: auto;
  1445. overflow-y: hidden;
  1446. scrollbar-color: #c4aa60 #e4e4e4;
  1447. }
  1448. .header::-webkit-scrollbar {
  1449. height: 5px;
  1450. }
  1451. .header::-webkit-scrollbar-track {
  1452. background-color: #1B695F;
  1453. border-radius: 1px;
  1454. }
  1455. .header::-webkit-scrollbar-thumb {
  1456. background-color: #c4aa60;
  1457. border-radius: 1px;
  1458. border: 1px solid #1B695F;
  1459. }
  1460. .main {
  1461. background-color: var(--bg-loader-color);
  1462. color: var(--text-app-color);
  1463. }
  1464. .tool-button {
  1465. margin: 0px 2px 7px 2px;
  1466. padding: 0;
  1467. color: var(--text-tb-normal);
  1468. background-color: var(--bg-tb-normal);
  1469. min-height: 38px;
  1470. min-width: 38px;
  1471. height: 38px;
  1472. width: 38px;
  1473. border: 0;
  1474. border-radius: 6px;
  1475. box-shadow: 3px 3px 5px black;
  1476. outline: 0;
  1477. }
  1478. .tool-button:hover {
  1479. background-color: var(--bg-tb-hover);
  1480. cursor: pointer;
  1481. }
  1482. .tool-button-active {
  1483. box-shadow: 0 0 0;
  1484. color: var(--text-tb-active);
  1485. background-color: var(--bg-tb-active);
  1486. position: relative;
  1487. top: 1px;
  1488. left: 1px;
  1489. }
  1490. .tool-button-active:hover {
  1491. background-color: var(--bg-tb-active-hover);
  1492. cursor: pointer;
  1493. }
  1494. .tool-button-disabled {
  1495. color: var(--text-tb-disabled);
  1496. background-color: var(--bg-tb-disabled);
  1497. cursor: default;
  1498. }
  1499. .tool-button-disabled:hover {
  1500. color: var(--text-tb-disabled);
  1501. background-color: var(--bg-tb-disabled);
  1502. cursor: default;
  1503. }
  1504. .space {
  1505. width: 10px;
  1506. display: inline-block;
  1507. }
  1508. .clear {
  1509. color: rgba(0,0,0,0);
  1510. }
  1511. .need-book-update-count {
  1512. position: relative;
  1513. padding: 2px 6px 2px 6px;
  1514. left: 27px;
  1515. top: 22px;
  1516. background-color: blue;
  1517. border-radius: 10px;
  1518. color: white;
  1519. z-index: 10;
  1520. font-size: 80%;
  1521. }
  1522. </style>