Reader.vue 63 KB

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