Reader.vue 62 KB

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