Reader.vue 59 KB

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