Reader.vue 62 KB

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