Reader.vue 63 KB

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