Reader.vue 63 KB

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