Reader.vue 62 KB

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