Reader.vue 59 KB

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