Reader.vue 62 KB

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