Reader.vue 63 KB

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