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