Reader.vue 63 KB

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