Reader.vue 60 KB

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