Reader.vue 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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 v-show="showToolButton['libs']" class="space"></div>
  89. <button v-show="showToolButton['libs']" ref="libs" v-ripple class="tool-button" :class="buttonActiveClass('libs')" @click="buttonClick('libs')">
  90. <q-icon name="la la-sitemap" size="32px" />
  91. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  92. {{ rstore.readerActions['libs'] }}
  93. </q-tooltip>
  94. </button>
  95. <div class="space"></div>
  96. <button v-show="showToolButton['contents']" ref="contents" v-ripple class="tool-button" :class="buttonActiveClass('contents')" @click="buttonClick('contents')">
  97. <q-icon name="la la-list" size="32px" />
  98. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  99. {{ rstore.readerActions['contents'] }}
  100. </q-tooltip>
  101. </button>
  102. <button v-show="showToolButton['recentBooks']" ref="recentBooks" v-ripple class="tool-button" :class="buttonActiveClass('recentBooks')" @click="buttonClick('recentBooks')">
  103. <div v-show="bothBucEnabled && needBookUpdateCount > 0" style="position: absolute">
  104. <div class="need-book-update-count">
  105. {{ needBookUpdateCount }}
  106. </div>
  107. </div>
  108. <q-icon name="la la-book-open" size="32px" />
  109. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  110. {{ rstore.readerActions['recentBooks'] }}
  111. </q-tooltip>
  112. </button>
  113. <div class="space"></div>
  114. </div>
  115. <div class="row no-wrap">
  116. <button v-show="showToolButton['clickControl']" ref="clickControl" v-ripple class="tool-button" :class="buttonActiveClass('clickControl')" @click="buttonClick('clickControl')">
  117. <q-icon name="la la-mouse" size="32px" />
  118. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  119. {{ rstore.readerActions['clickControl'] }}
  120. </q-tooltip>
  121. </button>
  122. <button v-show="showToolButton['offlineMode']" ref="offlineMode" v-ripple class="tool-button" :class="buttonActiveClass('offlineMode')" @click="buttonClick('offlineMode')">
  123. <q-icon name="la la-unlink" size="32px" />
  124. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  125. {{ rstore.readerActions['offlineMode'] }}
  126. </q-tooltip>
  127. </button>
  128. <button ref="settings" v-ripple class="tool-button" :class="buttonActiveClass('settings')" @click="buttonClick('settings')">
  129. <q-icon name="la la-cog" size="32px" />
  130. <q-tooltip :delay="1500" anchor="bottom left" content-style="font-size: 80%">
  131. {{ rstore.readerActions['settings'] }}
  132. </q-tooltip>
  133. </button>
  134. </div>
  135. </div>
  136. </div>
  137. <div class="main col row relative-position">
  138. <keep-alive>
  139. <component
  140. :is="activePage"
  141. ref="page"
  142. class="col"
  143. @load-book="loadBook"
  144. @load-file="loadFile"
  145. @book-pos-changed="bookPosChanged"
  146. @do-action="doAction"
  147. @hide-tool-bar="hideToolBar"
  148. ></component>
  149. </keep-alive>
  150. <SetPositionPage v-if="setPositionActive" ref="setPositionPage" @set-position-toggle="setPositionToggle" @book-pos-changed="bookPosChanged"></SetPositionPage>
  151. <SearchPage
  152. v-show="searchActive"
  153. ref="searchPage"
  154. @do-action="doAction"
  155. @book-pos-changed="bookPosChanged"
  156. @start-text-search="startTextSearch"
  157. @stop-text-search="stopTextSearch"
  158. ></SearchPage>
  159. <CopyTextPage v-if="copyTextActive" ref="copyTextPage" @do-action="doAction"></CopyTextPage>
  160. <LibsPage v-show="hidden" ref="libsPage" @load-book="loadBook" @libs-close="libsClose" @do-action="doAction"></LibsPage>
  161. <RecentBooksPage v-show="recentBooksActive" ref="recentBooksPage" @load-book="loadBook" @recent-books-close="recentBooksClose" @update-count-changed="updateCountChanged"></RecentBooksPage>
  162. <SettingsPage v-show="settingsActive" ref="settingsPage" @do-action="doAction"></SettingsPage>
  163. <HelpPage v-if="helpActive" ref="helpPage" @do-action="doAction"></HelpPage>
  164. <ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
  165. <ContentsPage v-show="contentsActive" ref="contentsPage" :book-pos="bookPos" :is-visible="contentsActive" @do-action="doAction" @book-pos-changed="bookPosChanged"></ContentsPage>
  166. <ServerStorage v-show="hidden" ref="serverStorage"></ServerStorage>
  167. <ReaderDialogs ref="dialogs" @donate-toggle="donateToggle" @version-history-toggle="versionHistoryToggle" @load-buffer-toggle="loadBufferToggle"></ReaderDialogs>
  168. </div>
  169. </div>
  170. </template>
  171. <script>
  172. //-----------------------------------------------------------------------------
  173. import vueComponent from '../vueComponent.js';
  174. import _ from 'lodash';
  175. import {Buffer} from 'safe-buffer';
  176. import LoaderPage from './LoaderPage/LoaderPage.vue';
  177. import TextPage from './TextPage/TextPage.vue';
  178. import ProgressPage from './ProgressPage/ProgressPage.vue';
  179. import SetPositionPage from './SetPositionPage/SetPositionPage.vue';
  180. import SearchPage from './SearchPage/SearchPage.vue';
  181. import CopyTextPage from './CopyTextPage/CopyTextPage.vue';
  182. import LibsPage from './LibsPage/LibsPage.vue';
  183. import RecentBooksPage from './RecentBooksPage/RecentBooksPage.vue';
  184. import SettingsPage from './SettingsPage/SettingsPage.vue';
  185. import HelpPage from './HelpPage/HelpPage.vue';
  186. import ClickMapPage from './ClickMapPage/ClickMapPage.vue';
  187. import ContentsPage from './ContentsPage/ContentsPage.vue';
  188. import ServerStorage from './ServerStorage/ServerStorage.vue';
  189. import ReaderDialogs from './ReaderDialogs/ReaderDialogs.vue';
  190. import bookManager from './share/bookManager';
  191. import wallpaperStorage from './share/wallpaperStorage';
  192. import coversStorage from './share/coversStorage';
  193. import dynamicCss from '../../share/dynamicCss';
  194. import rstore from '../../store/modules/reader';
  195. import readerApi from '../../api/reader';
  196. import miscApi from '../../api/misc';
  197. import {versionHistory} from './versionHistory';
  198. import * as utils from '../../share/utils';
  199. import LockQueue from '../../share/LockQueue';
  200. const componentOptions = {
  201. components: {
  202. LoaderPage,
  203. TextPage,
  204. ProgressPage,
  205. SetPositionPage,
  206. SearchPage,
  207. CopyTextPage,
  208. LibsPage,
  209. RecentBooksPage,
  210. SettingsPage,
  211. HelpPage,
  212. ClickMapPage,
  213. ContentsPage,
  214. ServerStorage,
  215. ReaderDialogs,
  216. },
  217. watch: {
  218. bookPos: function(newValue) {
  219. if (newValue !== undefined && this.activePage == 'TextPage') {
  220. const textPage = this.$refs.page;
  221. if (textPage.bookPos != newValue) {
  222. textPage.bookPos = newValue;
  223. }
  224. if (!this.scrollingActive)
  225. this.debouncedSetRecentBook(newValue);
  226. else
  227. this.scrollingSetRecentBook(newValue);
  228. }
  229. },
  230. routeParamPos: function(newValue) {
  231. if (!this.paramPosIgnore && newValue !== undefined && newValue != this.bookPos) {
  232. this.bookPos = newValue;
  233. }
  234. },
  235. routeParamUrl: function(newValue) {
  236. if (newValue !== '' && newValue !== this.mostRecentBook().url) {
  237. this.loadBook({url: newValue, bookPos: this.routeParamPos});
  238. }
  239. },
  240. settings: function() {
  241. this.loadSettings();
  242. this.updateRoute();
  243. },
  244. loaderActive: function(newValue) {
  245. (async() => {
  246. const recent = this.mostRecentBook();
  247. if (!newValue && !this.loading && recent && !await bookManager.hasBookParsed(recent)) {
  248. this.loadBook(recent);
  249. }
  250. })();
  251. },
  252. dualPageMode(newValue) {
  253. if (newValue)
  254. this.stopScrolling();
  255. },
  256. },
  257. };
  258. class Reader {
  259. _options = componentOptions;
  260. rstore = {};
  261. loaderActive = false;
  262. loadFileActive = false;
  263. loadBufferActive = false;
  264. fullScreenActive = false;
  265. setPositionActive = false;
  266. searchActive = false;
  267. copyTextActive = false;
  268. convOptionsActive = false;
  269. refreshActive = false;
  270. contentsActive = false;
  271. libsActive = false;
  272. recentBooksActive = false;
  273. clickControlActive = 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. this.commit('reader/setSettings', {});
  483. }
  484. dynamicCss.replace('wallpapers', newCss);
  485. }
  486. }
  487. async checkNewVersionAvailable() {
  488. if (!this.checkingNewVersion && this.showNeedUpdateNotify) {
  489. this.checkingNewVersion = true;
  490. try {
  491. await utils.sleep(15*1000); //подождем 15 секунд, чтобы прогрузился ServiceWorker при выходе новой версии
  492. const config = await miscApi.loadConfig();
  493. this.commit('config/setConfig', config);
  494. let againMes = '';
  495. if (this.isFirstNeedUpdateNotify) {
  496. againMes = ' еще один раз';
  497. }
  498. if (this.version != this.clientVersion)
  499. this.$root.notify.info(`Вышла новая версия (v${this.version}) читалки.<br>Пожалуйста, обновите страницу${againMes}.`, 'Обновление');
  500. } catch(e) {
  501. console.error(e);
  502. } finally {
  503. this.checkingNewVersion = false;
  504. }
  505. this.isFirstNeedUpdateNotify = false;
  506. }
  507. }
  508. async checkBuc() {
  509. if (!this.bothBucEnabled)
  510. return;
  511. try {
  512. const sorted = bookManager.getSortedRecent();
  513. //выберем все кандидиаты на обновление
  514. const updateUrls = new Set();
  515. for (const book of sorted) {
  516. if (!book.deleted && book.checkBuc && book.url && book.url.indexOf('disk://') !== 0)
  517. updateUrls.add(book.url);
  518. }
  519. //теперь по кусочкам запросим сервер
  520. const arr = Array.from(updateUrls);
  521. const bucSize = {};
  522. const chunkSize = 100;
  523. for (let i = 0; i < arr.length; i += chunkSize) {
  524. const chunk = arr.slice(i, i + chunkSize);
  525. const data = await readerApi.checkBuc(chunk);
  526. for (const item of data) {
  527. bucSize[item.id] = item.size;
  528. }
  529. await utils.sleep(1000);//чтобы не ддосить сервер
  530. }
  531. const checkSetTime = {};
  532. //проставим новые размеры у книг
  533. for (const book of sorted) {
  534. if (book.deleted)
  535. continue;
  536. //размер 0 считаем отсутствующим
  537. if (book.url && bucSize[book.url] && bucSize[book.url] !== book.bucSize) {
  538. book.bucSize = bucSize[book.url];
  539. await bookManager.recentSetItem(book);
  540. }
  541. //подготовка к следующему шагу, ищем книгу по url с максимальной датой установки checkBucTime/loadTime
  542. //от этой даты будем потом отсчитывать bucCancelDays
  543. if (updateUrls.has(book.url)) {
  544. let rec = checkSetTime[book.url] || {time: 0, loadTime: 0};
  545. const time = (book.checkBucTime ? book.checkBucTime : (rec.loadTime || 0));
  546. if (time > rec.time || (time == rec.time && (book.loadTime > rec.loadTime)))
  547. rec = {time, loadTime: book.loadTime, key: book.key};
  548. checkSetTime[book.url] = rec;
  549. }
  550. }
  551. //bucCancelEnabled и bucCancelDays
  552. //снимем флаг checkBuc у необновлявшихся bucCancelDays
  553. if (this.bucCancelEnabled) {
  554. for (const rec of Object.values(checkSetTime)) {
  555. if (rec.time && Date.now() - rec.time > this.bucCancelDays*24*3600*1000) {
  556. const book = await bookManager.getRecentBook({key: rec.key});
  557. const needBookUpdate =
  558. book.checkBuc
  559. && book.bucSize
  560. && utils.hasProp(book, 'downloadSize')
  561. && book.bucSize !== book.downloadSize
  562. && (book.bucSize - book.downloadSize >= this.bucSizeDiff)
  563. ;
  564. if (book && !needBookUpdate) {
  565. await bookManager.setCheckBuc(book, undefined);//!!!
  566. }
  567. }
  568. }
  569. }
  570. await this.$refs.recentBooksPage.updateTableData();
  571. } catch (e) {
  572. console.error(e);
  573. }
  574. }
  575. updateCountChanged(event) {
  576. this.needBookUpdateCount = event.needBookUpdateCount;
  577. }
  578. checkSetStorageAccessKey() {
  579. const q = this.$route.query;
  580. if (q['setStorageAccessKey']) {
  581. this.$router.replace(`/reader`);
  582. this.settingsToggle();
  583. this.$nextTick(() => {
  584. this.$refs.settingsPage.enterServerStorageKey(
  585. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  586. );
  587. });
  588. }
  589. }
  590. checkActivateDonateHelpPage() {
  591. const q = this.$route.query;
  592. if (q['donate']) {
  593. this.$router.replace(`/reader`);
  594. this.helpToggle();
  595. this.$nextTick(() => {
  596. this.$refs.helpPage.activateDonateHelpPage();
  597. });
  598. }
  599. }
  600. checkBookPosPercent() {
  601. const q = this.$route.query;
  602. if (q['__pp']) {
  603. let pp = q['__pp'];
  604. if (pp) {
  605. pp = parseFloat(pp) || 0;
  606. const recent = this.mostRecentBook();
  607. (async() => {
  608. await utils.sleep(100);
  609. this.bookPos = Math.floor(recent.textLength*pp/100);
  610. })();
  611. }
  612. }
  613. }
  614. get routeParamPos() {
  615. let result = undefined;
  616. const q = this.$route.query;
  617. if (q['__p']) {
  618. result = q['__p'];
  619. if (Array.isArray(result))
  620. result = result[0];
  621. }
  622. return (result ? parseInt(result, 10) || 0 : result);
  623. }
  624. updateRoute(isNewRoute) {
  625. if (this.loading)
  626. return;
  627. const recent = this.mostRecentBook();
  628. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  629. const url = (recent ? `url=${encodeURIComponent(recent.url)}` : '');
  630. if (isNewRoute)
  631. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  632. else
  633. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  634. }
  635. get mode() {
  636. return this.$store.state.config.mode;
  637. }
  638. get version() {
  639. return this.$store.state.config.version;
  640. }
  641. get clientVersion() {
  642. return versionHistory[0].version;
  643. }
  644. get bothBucEnabled() {
  645. return this.$store.state.config.bucEnabled && this.bucEnabled;
  646. }
  647. get routeParamUrl() {
  648. let result = '';
  649. const path = this.$route.fullPath;
  650. const i = path.indexOf('url=');
  651. if (i >= 0) {
  652. result = path.substr(i + 4);
  653. }
  654. return decodeURIComponent(result);
  655. }
  656. get routeParamRefresh() {
  657. const q = this.$route.query;
  658. return !!q['__refresh'];
  659. }
  660. bookPosChanged(event) {
  661. if (event.bookPosSeen !== undefined)
  662. this.bookPosSeen = event.bookPosSeen;
  663. this.bookPos = event.bookPos;
  664. }
  665. async bookManagerEvent(eventName, value) {
  666. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  667. const oldBook = (this.textPage ? this.textPage.lastBook : null);
  668. const oldPos = (this.textPage ? this.textPage.bookPos : null);
  669. const newBook = bookManager.mostRecentBook();
  670. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  671. this.mostRecentBook();
  672. }
  673. if (oldBook && newBook) {
  674. if (oldBook.key != newBook.key || oldBook.path != newBook.path) {
  675. this.loadingBook = true;
  676. try {
  677. await this.loadBook(newBook);
  678. } finally {
  679. this.loadingBook = false;
  680. }
  681. } else if (oldPos != newBook.bookPos) {
  682. while (this.loadingBook) await utils.sleep(100);
  683. this.bookPosChanged({bookPos: newBook.bookPos});
  684. }
  685. }
  686. }
  687. if (eventName == 'recent-changed') {
  688. this.debouncedRecentBooksPageUpdate();
  689. //сохранение в serverStorage
  690. if (value && this.recentItemKeys.indexOf(value) < 0) {
  691. this.recentItemKeys.push(value);
  692. this.debouncedSaveRecent();
  693. }
  694. }
  695. }
  696. get toolBarActive() {
  697. return this.reader.toolBarActive;
  698. }
  699. get offlineModeActive() {
  700. return this.reader.offlineModeActive;
  701. }
  702. mostRecentBook() {
  703. const result = bookManager.mostRecentBook();
  704. this.mostRecentBookReactive = result;
  705. return result;
  706. }
  707. get settings() {
  708. return this.$store.state.reader.settings;
  709. }
  710. addAction(pos) {
  711. let a = this.actionList;
  712. if (!a.length || a[a.length - 1] != pos) {
  713. a.push(pos);
  714. if (a.length > 20)
  715. a.shift();
  716. this.actionCur = a.length - 1;
  717. }
  718. }
  719. toolBarToggle() {
  720. this.commit('reader/setToolBarActive', !this.toolBarActive);
  721. this.$root.eventHook('resize');
  722. }
  723. hideToolBar(event) {
  724. this.debouncedHideToolBar(event);
  725. }
  726. fullScreenToggle() {
  727. if (!this.$q.fullscreen.isActive) {
  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();//no await
  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.commit('reader/setOfflineModeActive', !this.offlineModeActive);
  885. }
  886. settingsToggle() {
  887. this.settingsActive = !this.settingsActive;
  888. if (this.settingsActive) {
  889. this.closeAllWindows();
  890. this.settingsActive = true;
  891. this.$nextTick(() => {
  892. this.$refs.settingsPage.init();
  893. });
  894. } else {
  895. this.settingsActive = false;
  896. }
  897. }
  898. convOptionsToggle() {
  899. this.settingsToggle();
  900. if (this.settingsActive)
  901. this.$refs.settingsPage.selectedTab = 'convert';
  902. }
  903. helpToggle() {
  904. this.helpActive = !this.helpActive;
  905. if (this.helpActive) {
  906. this.closeAllWindows();
  907. this.helpActive = true;
  908. }
  909. }
  910. donateToggle() {
  911. this.helpToggle();
  912. if (this.helpActive) {
  913. this.$nextTick(() => {
  914. this.$refs.helpPage.activateDonateHelpPage();
  915. });
  916. }
  917. }
  918. versionHistoryToggle() {
  919. this.helpToggle();
  920. if (this.helpActive) {
  921. this.$nextTick(() => {
  922. this.$refs.helpPage.activateVersionHistoryHelpPage();
  923. });
  924. }
  925. }
  926. refreshBook() {
  927. const mrb = this.mostRecentBook();
  928. this.loadBook(Object.assign({}, mrb, {force: true}));
  929. }
  930. undoAction() {
  931. if (this.actionCur > 0) {
  932. this.actionCur--;
  933. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  934. }
  935. }
  936. redoAction() {
  937. if (this.actionCur < this.actionList.length - 1) {
  938. this.actionCur++;
  939. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  940. }
  941. }
  942. buttonClick(action) {
  943. const activeClass = this.buttonActiveClass(action);
  944. this.$refs[action].blur();
  945. if (activeClass['tool-button-disabled'])
  946. return;
  947. this.doAction({action});
  948. }
  949. buttonActiveClass(action) {
  950. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  951. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  952. let classResult = {};
  953. switch (action) {
  954. case 'loader':
  955. case 'loadFile':
  956. case 'loadBuffer':
  957. case 'help':
  958. case 'fullScreen':
  959. case 'setPosition':
  960. case 'search':
  961. case 'copyText':
  962. case 'convOptions':
  963. case 'refresh':
  964. case 'contents':
  965. case 'libs':
  966. case 'recentBooks':
  967. case 'clickControl':
  968. case 'offlineMode':
  969. case 'settings':
  970. if (this.progressActive) {
  971. classResult = classDisabled;
  972. } else if (this[`${action}Active`]) {
  973. classResult = classActive;
  974. }
  975. break;
  976. case 'scrolling':
  977. if (this.progressActive || this.dualPageMode) {
  978. classResult = classDisabled;
  979. } else if (this[`${action}Active`]) {
  980. classResult = classActive;
  981. }
  982. break;
  983. case 'undoAction':
  984. if (this.actionCur <= 0)
  985. classResult = classDisabled;
  986. break;
  987. case 'redoAction':
  988. if (this.actionCur == this.actionList.length - 1)
  989. classResult = classDisabled;
  990. break;
  991. }
  992. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  993. switch (action) {
  994. case 'undoAction':
  995. case 'redoAction':
  996. case 'setPosition':
  997. case 'scrolling':
  998. case 'search':
  999. case 'copyText':
  1000. case 'contents':
  1001. classResult = classDisabled;
  1002. break;
  1003. case 'refresh':
  1004. if (!this.mostRecentBookReactive)
  1005. classResult = classDisabled;
  1006. break;
  1007. }
  1008. }
  1009. return classResult;
  1010. }
  1011. async activateClickMapPage() {
  1012. if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
  1013. this.clickMapActive = true;
  1014. await this.$refs.clickMapPage.slowDisappear();
  1015. this.clickMapActive = false;
  1016. }
  1017. }
  1018. get activePage() {
  1019. let result = undefined;
  1020. if (this.progressActive)
  1021. result = 'ProgressPage';
  1022. else if (this.loaderActive)
  1023. result = 'LoaderPage';
  1024. else if (this.mostRecentBookReactive)
  1025. result = 'TextPage';
  1026. if (!result && !this.loading) {
  1027. this.loaderActive = true;
  1028. result = 'LoaderPage';
  1029. }
  1030. if (result != 'TextPage') {
  1031. this.$root.setAppTitle();
  1032. }
  1033. // на LoaderPage всегда показываем toolBar
  1034. if (result == 'LoaderPage' && !this.toolBarActive) {
  1035. this.toolBarToggle();
  1036. }
  1037. if (this.lastActivePage != result && result == 'TextPage') {
  1038. //акивируем страницу с текстом
  1039. this.$nextTick(async() => {
  1040. const last = this.mostRecentBookReactive;
  1041. const isParsed = await bookManager.hasBookParsed(last);
  1042. if (!isParsed) {
  1043. this.$root.setAppTitle();
  1044. return;
  1045. }
  1046. this.updateRoute();
  1047. const textPage = this.$refs.page;
  1048. if (textPage.showBook) {
  1049. this.textPage = textPage;
  1050. textPage.lastBook = last;
  1051. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  1052. textPage.showBook();
  1053. }
  1054. });
  1055. }
  1056. this.lastActivePage = result;
  1057. return result;
  1058. }
  1059. async _loadBook(opts) {
  1060. if (!opts || !opts.url) {
  1061. this.mostRecentBook();
  1062. return;
  1063. }
  1064. this.closeAllWindows();
  1065. let url = encodeURI(decodeURI(opts.url));
  1066. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  1067. (url.indexOf('disk://') != 0))
  1068. url = 'http://' + url;
  1069. // уже просматривается сейчас
  1070. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  1071. if (!opts.force && lastBook && lastBook.url == url &&
  1072. (!opts.path || opts.path == lastBook.path) &&
  1073. await bookManager.hasBookParsed(lastBook)) {
  1074. this.loaderActive = false;
  1075. return;
  1076. }
  1077. this.progressActive = true;
  1078. await this.$nextTick();
  1079. const progress = this.$refs.page;
  1080. this.actionList = [];
  1081. this.actionCur = -1;
  1082. try {
  1083. progress.show();
  1084. progress.setState({state: 'parse'});
  1085. // есть ли среди загруженных
  1086. let wasOpened = bookManager.findRecentByUrlAndPath(url, opts.path);
  1087. wasOpened = (wasOpened ? _.cloneDeep(wasOpened) : {});
  1088. wasOpened = Object.assign(wasOpened, {
  1089. url: (opts.url !== undefined ? opts.url : wasOpened.url),
  1090. path: (opts.path !== undefined ? opts.path : wasOpened.path),
  1091. bookPos: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos),
  1092. bookPosSeen: (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen),
  1093. uploadFileName: (opts.uploadFileName ? opts.uploadFileName : wasOpened.uploadFileName),
  1094. });
  1095. let book = null;
  1096. if (!opts.force) {
  1097. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  1098. const bookParsed = await bookManager.getBook(wasOpened, (prog) => {
  1099. progress.setState({progress: prog});
  1100. });
  1101. // если есть в локальном кэше
  1102. if (bookParsed) {
  1103. await bookManager.setRecentBook(Object.assign(wasOpened, bookParsed));
  1104. this.mostRecentBook();
  1105. this.addAction(wasOpened.bookPos);
  1106. this.loaderActive = false;
  1107. progress.hide(); this.progressActive = false;
  1108. this.blinkCachedLoadMessage();
  1109. this.checkBookPosPercent();
  1110. this.activateClickMapPage();//no await
  1111. this.$refs.recentBooksPage.updateTableData();//no await
  1112. return;
  1113. }
  1114. // иначе идем на сервер
  1115. // пытаемся загрузить готовый файл с сервера
  1116. if (wasOpened.path) {
  1117. progress.setState({totalSteps: 5});
  1118. try {
  1119. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  1120. progress.setState(state);
  1121. });
  1122. book = Object.assign({}, wasOpened, {data: resp.data});
  1123. } catch (e) {
  1124. this.$root.notify.error('Конвертированный файл не найден на сервере.<br>Пробуем загрузить оригинал.', 'Ошибка загрузки');
  1125. }
  1126. }
  1127. }
  1128. progress.setState({totalSteps: 5});
  1129. // не удалось, скачиваем книгу полностью с конвертацией
  1130. let loadCached = true;
  1131. if (!book) {
  1132. book = await readerApi.loadBook({
  1133. url,
  1134. uploadFileName: wasOpened.uploadFileName,
  1135. enableSitesFilter: this.enableSitesFilter,
  1136. skipHtmlCheck: (this.splitToPara ? true : false),
  1137. isText: (this.splitToPara ? true : false),
  1138. djvuQuality: this.djvuQuality,
  1139. pdfAsText: this.pdfAsText,
  1140. pdfQuality: this.pdfQuality,
  1141. },
  1142. (state) => {
  1143. progress.setState(state);
  1144. }
  1145. );
  1146. loadCached = false;
  1147. }
  1148. // добавляем в bookManager
  1149. progress.setState({state: 'parse', step: 5});
  1150. const addedBook = await bookManager.addBook(book, (prog) => {
  1151. progress.setState({progress: prog});
  1152. });
  1153. // sameBookKey
  1154. if (url.indexOf('disk://') == 0) {
  1155. //ищем такой файл в загруженных
  1156. let found = bookManager.findRecentBySameBookKey(wasOpened.uploadFileName);
  1157. found = (found ? _.cloneDeep(found) : found);
  1158. if (found) {
  1159. if (wasOpened.sameBookKey != found.sameBookKey) {
  1160. //спрашиваем, надо ли объединить файлы
  1161. const askResult = bookManager.keysEqual(found.path, addedBook.path) ||
  1162. await this.$root.stdDialog.askYesNo(`
  1163. Файл с именем "${wasOpened.uploadFileName}" уже есть в загруженных.
  1164. <br>Объединить позицию?`, 'Найдена похожая книга');
  1165. if (askResult) {
  1166. wasOpened.bookPos = found.bookPos;
  1167. wasOpened.bookPosSeen = found.bookPosSeen;
  1168. wasOpened.sameBookKey = found.sameBookKey;
  1169. }
  1170. }
  1171. } else {
  1172. wasOpened.sameBookKey = wasOpened.uploadFileName;
  1173. }
  1174. } else {
  1175. wasOpened.sameBookKey = addedBook.url;
  1176. }
  1177. if (!bookManager.keysEqual(wasOpened.path, addedBook.path))
  1178. delete wasOpened.loadTime;
  1179. // добавляем в историю
  1180. const recentBook = await bookManager.setRecentBook(Object.assign(wasOpened, addedBook));
  1181. if (this.bucSetOnNew) {
  1182. await bookManager.setCheckBuc(recentBook, true);
  1183. }
  1184. this.mostRecentBook();
  1185. this.addAction(recentBook.bookPos);
  1186. this.updateRoute(true);
  1187. this.loaderActive = false;
  1188. progress.hide(); this.progressActive = false;
  1189. if (loadCached) {
  1190. this.blinkCachedLoadMessage();
  1191. } else
  1192. this.stopBlink = true;
  1193. this.checkBookPosPercent();
  1194. this.activateClickMapPage();//no await
  1195. this.$refs.recentBooksPage.updateTableData();//no await
  1196. } catch (e) {
  1197. progress.hide(); this.progressActive = false;
  1198. this.loaderActive = true;
  1199. if (!this.showHelpOnErrorIfNeeded(url)) {
  1200. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1201. }
  1202. } finally {
  1203. this.checkNewVersionAvailable();
  1204. }
  1205. }
  1206. async loadBook(opts) {
  1207. await this.lock.get();
  1208. try {
  1209. await this._loadBook(opts);
  1210. } finally {
  1211. this.lock.ret();
  1212. }
  1213. }
  1214. async _loadFile(opts) {
  1215. this.progressActive = true;
  1216. await this.$nextTick();
  1217. const progress = this.$refs.page;
  1218. try {
  1219. progress.show();
  1220. progress.setState({state: 'upload'});
  1221. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  1222. progress.setState(state);
  1223. });
  1224. progress.hide(); this.progressActive = false;
  1225. await this._loadBook({url, uploadFileName: opts.file.name, force: true});
  1226. } catch (e) {
  1227. progress.hide(); this.progressActive = false;
  1228. this.loaderActive = true;
  1229. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  1230. }
  1231. }
  1232. async loadFile(opts) {
  1233. await this.lock.get();
  1234. try {
  1235. await this._loadFile(opts);
  1236. } finally {
  1237. this.lock.ret();
  1238. }
  1239. }
  1240. blinkCachedLoadMessage() {
  1241. if (!this.blinkCachedLoad)
  1242. return;
  1243. this.blinkCount = 30;
  1244. if (!this.inBlink) {
  1245. this.inBlink = true;
  1246. this.stopBlink = false;
  1247. this.$nextTick(async() => {
  1248. let page = this.$refs.page;
  1249. while (this.blinkCount) {
  1250. this.showRefreshIcon = !this.showRefreshIcon;
  1251. if (page && page.blinkCachedLoadMessage)
  1252. page.blinkCachedLoadMessage(this.showRefreshIcon);
  1253. await utils.sleep(500);
  1254. if (this.stopBlink)
  1255. break;
  1256. this.blinkCount--;
  1257. page = this.$refs.page;
  1258. }
  1259. this.showRefreshIcon = true;
  1260. this.inBlink = false;
  1261. if (page && page.blinkCachedLoadMessage)
  1262. page.blinkCachedLoadMessage('finish');
  1263. });
  1264. }
  1265. }
  1266. doAction(opts) {
  1267. let result = true;
  1268. let {action = '', event = false} = opts;
  1269. switch (action) {
  1270. case 'loader':
  1271. this.loaderToggle();
  1272. break;
  1273. case 'loadFile':
  1274. this.loadFileToggle();
  1275. break;
  1276. case 'loadBuffer':
  1277. this.loadBufferToggle();
  1278. break;
  1279. case 'help':
  1280. this.helpToggle();
  1281. break;
  1282. case 'undoAction':
  1283. this.undoAction();
  1284. break;
  1285. case 'redoAction':
  1286. this.redoAction();
  1287. break;
  1288. case 'fullScreen':
  1289. this.fullScreenToggle();
  1290. break;
  1291. case 'scrolling':
  1292. this.scrollingToggle();
  1293. break;
  1294. case 'stopScrolling':
  1295. this.stopScrolling();
  1296. break;
  1297. case 'setPosition':
  1298. this.setPositionToggle();
  1299. break;
  1300. case 'search':
  1301. this.searchToggle();
  1302. break;
  1303. case 'copyText':
  1304. this.copyTextToggle();
  1305. break;
  1306. case 'convOptions':
  1307. this.convOptionsToggle();
  1308. break;
  1309. case 'refresh':
  1310. this.refreshBook();
  1311. break;
  1312. case 'contents':
  1313. this.contentsPageToggle();
  1314. break;
  1315. case 'libs':
  1316. this.libsToogle();
  1317. break;
  1318. case 'recentBooks':
  1319. this.recentBooksToggle();
  1320. break;
  1321. case 'clickControl':
  1322. this.clickControlToggle();
  1323. break;
  1324. case 'offlineMode':
  1325. this.offlineModeToggle();
  1326. break;
  1327. case 'settings':
  1328. this.settingsToggle();
  1329. break;
  1330. case 'switchToolbar':
  1331. this.toolBarToggle();
  1332. break;
  1333. case 'donate':
  1334. this.donateToggle();
  1335. break;
  1336. default:
  1337. result = false;
  1338. break;
  1339. }
  1340. if (!result && this.activePage == 'TextPage' && this.$refs.page) {
  1341. result = true;
  1342. const textPage = this.$refs.page;
  1343. switch (action) {
  1344. case 'bookBegin':
  1345. textPage.doHome();
  1346. break;
  1347. case 'bookEnd':
  1348. textPage.doEnd();
  1349. break;
  1350. case 'pageBack':
  1351. textPage.doPageUp();
  1352. break;
  1353. case 'pageForward':
  1354. textPage.doPageDown();
  1355. break;
  1356. case 'lineBack':
  1357. textPage.doUp();
  1358. break;
  1359. case 'lineForward':
  1360. textPage.doDown();
  1361. break;
  1362. case 'incFontSize':
  1363. textPage.doFontSizeInc();
  1364. break;
  1365. case 'decFontSize':
  1366. textPage.doFontSizeDec();
  1367. break;
  1368. case 'scrollingSpeedUp':
  1369. textPage.doScrollingSpeedUp();
  1370. break;
  1371. case 'scrollingSpeedDown':
  1372. textPage.doScrollingSpeedDown();
  1373. break;
  1374. default:
  1375. result = false;
  1376. break;
  1377. }
  1378. }
  1379. if (result && event) {
  1380. event.preventDefault();
  1381. event.stopPropagation();
  1382. }
  1383. return result;
  1384. }
  1385. keyHook(event) {
  1386. let result = false;
  1387. if (this.$root.getRootRoute() == '/reader') {
  1388. if (this.$root.stdDialog.active)
  1389. return result;
  1390. if (!result)
  1391. result = this.$refs.dialogs.keyHook(event);
  1392. if (!result && this.helpActive)
  1393. result = this.$refs.helpPage.keyHook(event);
  1394. if (!result && this.settingsActive)
  1395. result = this.$refs.settingsPage.keyHook(event);
  1396. if (!result && this.recentBooksActive)
  1397. result = this.$refs.recentBooksPage.keyHook(event);
  1398. if (!result && this.setPositionActive)
  1399. result = this.$refs.setPositionPage.keyHook(event);
  1400. if (!result && this.searchActive)
  1401. result = this.$refs.searchPage.keyHook(event);
  1402. if (!result && this.copyTextActive)
  1403. result = this.$refs.copyTextPage.keyHook(event);
  1404. if (!result && this.contentsActive)
  1405. result = this.$refs.contentsPage.keyHook(event);
  1406. if (!result && this.$refs.page && this.$refs.page.keyHook)
  1407. result = this.$refs.page.keyHook(event);
  1408. if (!result && event.type == 'keydown') {
  1409. const action = this.$root.readerActionByKeyEvent(event);
  1410. /*if (action == 'loader') {
  1411. result = this.doAction({action, event});
  1412. }
  1413. if (!result && this.activePage == 'TextPage') {
  1414. result = this.doAction({action, event});
  1415. }*/
  1416. result = this.doAction({action, event});
  1417. }
  1418. }
  1419. return result;
  1420. }
  1421. }
  1422. export default vueComponent(Reader);
  1423. //-----------------------------------------------------------------------------
  1424. </script>
  1425. <style scoped>
  1426. .header {
  1427. height: 50px;
  1428. padding-left: 5px;
  1429. padding-right: 5px;
  1430. background-color: #1B695F;
  1431. color: #000;
  1432. overflow-x: auto;
  1433. overflow-y: hidden;
  1434. scrollbar-color: #c4aa60 #e4e4e4;
  1435. }
  1436. .header::-webkit-scrollbar {
  1437. height: 5px;
  1438. }
  1439. .header::-webkit-scrollbar-track {
  1440. background-color: #1B695F;
  1441. border-radius: 1px;
  1442. }
  1443. .header::-webkit-scrollbar-thumb {
  1444. background-color: #c4aa60;
  1445. border-radius: 1px;
  1446. border: 1px solid #1B695F;
  1447. }
  1448. .main {
  1449. background-color: #EBE2C9;
  1450. color: #000;
  1451. }
  1452. .tool-button {
  1453. margin: 0px 2px 0 2px;
  1454. padding: 0;
  1455. color: #3E843E;
  1456. background-color: #E6EDF4;
  1457. margin-top: 5px;
  1458. height: 38px;
  1459. width: 38px;
  1460. border: 0;
  1461. border-radius: 6px;
  1462. box-shadow: 3px 3px 5px black;
  1463. outline: 0;
  1464. }
  1465. .tool-button:hover {
  1466. background-color: white;
  1467. cursor: pointer;
  1468. }
  1469. .tool-button-active {
  1470. box-shadow: 0 0 0;
  1471. color: white;
  1472. background-color: #8AB45F;
  1473. position: relative;
  1474. top: 1px;
  1475. left: 1px;
  1476. }
  1477. .tool-button-active:hover {
  1478. color: white;
  1479. background-color: #81C581;
  1480. cursor: pointer;
  1481. }
  1482. .tool-button-disabled {
  1483. color: lightgray;
  1484. background-color: gray;
  1485. cursor: default;
  1486. }
  1487. .tool-button-disabled:hover {
  1488. color: lightgray;
  1489. background-color: gray;
  1490. cursor: default;
  1491. }
  1492. .space {
  1493. width: 10px;
  1494. display: inline-block;
  1495. }
  1496. .clear {
  1497. color: rgba(0,0,0,0);
  1498. }
  1499. .need-book-update-count {
  1500. position: relative;
  1501. padding: 2px 6px 2px 6px;
  1502. left: 27px;
  1503. top: 22px;
  1504. background-color: blue;
  1505. border-radius: 10px;
  1506. color: white;
  1507. z-index: 10;
  1508. font-size: 80%;
  1509. }
  1510. </style>