Reader.vue 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. <template>
  2. <el-container>
  3. <el-header v-show="toolBarActive" height='50px'>
  4. <div ref="header" class="header">
  5. <el-tooltip content="Загрузить книгу" :open-delay="1000" effect="light">
  6. <el-button ref="loader" class="tool-button" :class="buttonActiveClass('loader')" @click="buttonClick('loader')"><i class="el-icon-back"></i></el-button>
  7. </el-tooltip>
  8. <div>
  9. <el-tooltip v-show="showToolButton['undoAction']" content="Действие назад" :open-delay="1000" effect="light">
  10. <el-button ref="undoAction" class="tool-button" :class="buttonActiveClass('undoAction')" @click="buttonClick('undoAction')" ><i class="el-icon-arrow-left"></i></el-button>
  11. </el-tooltip>
  12. <el-tooltip v-show="showToolButton['redoAction']" content="Действие вперед" :open-delay="1000" effect="light">
  13. <el-button ref="redoAction" class="tool-button" :class="buttonActiveClass('redoAction')" @click="buttonClick('redoAction')" ><i class="el-icon-arrow-right"></i></el-button>
  14. </el-tooltip>
  15. <div class="space"></div>
  16. <el-tooltip v-show="showToolButton['fullScreen']" content="На весь экран" :open-delay="1000" effect="light">
  17. <el-button ref="fullScreen" class="tool-button" :class="buttonActiveClass('fullScreen')" @click="buttonClick('fullScreen')"><i class="el-icon-rank"></i></el-button>
  18. </el-tooltip>
  19. <el-tooltip v-show="showToolButton['scrolling']" content="Плавный скроллинг" :open-delay="1000" effect="light">
  20. <el-button ref="scrolling" class="tool-button" :class="buttonActiveClass('scrolling')" @click="buttonClick('scrolling')"><i class="el-icon-sort"></i></el-button>
  21. </el-tooltip>
  22. <el-tooltip v-show="showToolButton['setPosition']" content="На страницу" :open-delay="1000" effect="light">
  23. <el-button ref="setPosition" class="tool-button" :class="buttonActiveClass('setPosition')" @click="buttonClick('setPosition')"><i class="el-icon-d-arrow-right"></i></el-button>
  24. </el-tooltip>
  25. <el-tooltip v-show="showToolButton['search']" content="Найти в тексте" :open-delay="1000" effect="light">
  26. <el-button ref="search" class="tool-button" :class="buttonActiveClass('search')" @click="buttonClick('search')"><i class="el-icon-search"></i></el-button>
  27. </el-tooltip>
  28. <el-tooltip v-show="showToolButton['copyText']" content="Скопировать текст со страницы" :open-delay="1000" effect="light">
  29. <el-button ref="copyText" class="tool-button" :class="buttonActiveClass('copyText')" @click="buttonClick('copyText')"><i class="el-icon-edit-outline"></i></el-button>
  30. </el-tooltip>
  31. <el-tooltip v-show="showToolButton['refresh']" content="Принудительно обновить книгу в обход кэша" :open-delay="1000" effect="light">
  32. <el-button ref="refresh" class="tool-button" :class="buttonActiveClass('refresh')" @click="buttonClick('refresh')">
  33. <i class="el-icon-refresh" :class="{clear: !showRefreshIcon}"></i>
  34. </el-button>
  35. </el-tooltip>
  36. <div class="space"></div>
  37. <el-tooltip v-show="showToolButton['offlineMode']" content="Автономный режим (без интернета)" :open-delay="1000" effect="light">
  38. <el-button ref="offlineMode" class="tool-button" :class="buttonActiveClass('offlineMode')" @click="buttonClick('offlineMode')"><i class="el-icon-connection"></i></el-button>
  39. </el-tooltip>
  40. <el-tooltip v-show="showToolButton['recentBooks']" content="Открыть недавние" :open-delay="1000" effect="light">
  41. <el-button ref="recentBooks" class="tool-button" :class="buttonActiveClass('recentBooks')" @click="buttonClick('recentBooks')"><i class="el-icon-document"></i></el-button>
  42. </el-tooltip>
  43. </div>
  44. <el-tooltip content="Настроить" :open-delay="1000" effect="light">
  45. <el-button ref="settings" class="tool-button" :class="buttonActiveClass('settings')" @click="buttonClick('settings')"><i class="el-icon-setting"></i></el-button>
  46. </el-tooltip>
  47. </div>
  48. </el-header>
  49. <el-main>
  50. <keep-alive>
  51. <component ref="page" :is="activePage"
  52. @load-book="loadBook"
  53. @load-file="loadFile"
  54. @book-pos-changed="bookPosChanged"
  55. @tool-bar-toggle="toolBarToggle"
  56. @full-screen-toogle="fullScreenToggle"
  57. @stop-scrolling="stopScrolling"
  58. @scrolling-toggle="scrollingToggle"
  59. @help-toggle="helpToggle"
  60. @donate-toggle="donateToggle"
  61. ></component>
  62. </keep-alive>
  63. <SetPositionPage v-if="setPositionActive" ref="setPositionPage" @set-position-toggle="setPositionToggle" @book-pos-changed="bookPosChanged"></SetPositionPage>
  64. <SearchPage v-show="searchActive" ref="searchPage"
  65. @search-toggle="searchToggle"
  66. @book-pos-changed="bookPosChanged"
  67. @start-text-search="startTextSearch"
  68. @stop-text-search="stopTextSearch">
  69. </SearchPage>
  70. <CopyTextPage v-if="copyTextActive" ref="copyTextPage" @copy-text-toggle="copyTextToggle"></CopyTextPage>
  71. <RecentBooksPage v-show="recentBooksActive" ref="recentBooksPage" @load-book="loadBook" @recent-books-toggle="recentBooksToggle"></RecentBooksPage>
  72. <SettingsPage v-if="settingsActive" ref="settingsPage" @settings-toggle="settingsToggle"></SettingsPage>
  73. <HelpPage v-if="helpActive" ref="helpPage" @help-toggle="helpToggle"></HelpPage>
  74. <ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
  75. <ServerStorage v-show="hidden" ref="serverStorage"></ServerStorage>
  76. <el-dialog
  77. title="Что нового:"
  78. :visible.sync="whatsNewVisible"
  79. width="80%">
  80. <div style="line-height: 20px" v-html="whatsNewContent"></div>
  81. <span class="clickable" @click="openVersionHistory">Посмотреть историю версий</span>
  82. <span slot="footer" class="dialog-footer">
  83. <el-button @click="whatsNewDisable">Больше не показывать</el-button>
  84. </span>
  85. </el-dialog>
  86. <el-dialog
  87. title="Внимание!"
  88. :visible.sync="migrationVisible1"
  89. width="90%">
  90. <div>
  91. Появилась httpS-версия сайта по адресу <a href="https://omnireader.ru" target="_blank">https://omnireader.ru</a><br>
  92. Работа по httpS-протоколу, помимо безопасности соединения, позволяет воспользоваться всеми возможностями
  93. современных браузеров, а именно, применительно к нашему ресурсу:
  94. <ul>
  95. <li>возможность автономной работы с читалкой (без доступа к интернету), кеширование сайта через appcache</li>
  96. <li>безопасная передача на сервер данных о настройках и читаемых книгах при включенной синхронизации; все данные шифруются на стороне
  97. браузера ключом доступа и никто (в т.ч. администратор) не имеет возможности их прочитать
  98. <li>использование встроенных в JS функций шифрования и других</li>
  99. </ul>
  100. Для того, чтобы перейти на новую версию с сохранением настроек и читаемых книг необходимо синхронизировать обе читалки:
  101. <ul>
  102. <li>зайти в "Настройки"->"Профили" и поставить галочку "Включить синхронизацию с сервером"</li>
  103. <li>там же добавить профиль устройства с любым именем для синхронизации настроек<br>
  104. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  105. после этого все данные будут автоматически сохранены на сервер
  106. </span>
  107. </li>
  108. <li>далее нажать на кнопку "Показать ключ доступа" и кликнуть по ссылке "Ссылка для ввода ключа"<br>
  109. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  110. произойдет переход на https-версию читалки и откроется окно для ввода ключа
  111. </span><br>
  112. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  113. подтвердив ввод ключа нажатием "OK", включив синхронизацию с сервером и выбрав профиль устройства, вы восстановите все ваши настройки в новой версии
  114. </span>
  115. </li>
  116. </ul>
  117. Старая http-версия сайта будет доступна до конца 2019 года.<br>
  118. Приносим извинения за доставленные неудобства.
  119. </div>
  120. <span slot="footer" class="dialog-footer">
  121. <el-button @click="migrationDialogDisable">Больше не показывать</el-button>
  122. <el-button @click="migrationDialogRemind">Напомнить позже</el-button>
  123. </span>
  124. </el-dialog>
  125. <el-dialog
  126. title="Внимание!"
  127. :visible.sync="migrationVisible2"
  128. width="90%">
  129. <div>
  130. Информация для пользователей старой версии читалки по адресу <a href="http://omnireader.ru" target="_blank">http://omnireader.ru</a><br>
  131. Для того, чтобы перейти на новую httpS-версию с сохранением настроек и читаемых книг необходимо синхронизировать обе читалки:
  132. <ul>
  133. <li>перейти на старую версию ресурса <a href="http://omnireader.ru" target="_blank">http://omnireader.ru</a></li>
  134. <li>зайти в "Настройки"->"Профили" и поставить галочку "Включить синхронизацию с сервером"</li>
  135. <li>там же добавить профиль устройства с любым именем для синхронизации настроек<br>
  136. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  137. после этого все данные будут автоматически сохранены на сервер
  138. </span>
  139. </li>
  140. <li>далее нажать на кнопку "Показать ключ доступа" и кликнуть по ссылке "Ссылка для ввода ключа"<br>
  141. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  142. произойдет переход на https-версию читалки и откроется окно для ввода ключа
  143. </span><br>
  144. <span style="margin-left: 20px"><i style="font-size: 90%" class="el-icon-info"></i>
  145. подтвердив ввод ключа нажатием "OK", включив синхронизацию с сервером и выбрав профиль устройства, вы восстановите все ваши настройки в новой версии
  146. </span>
  147. </li>
  148. </ul>
  149. Старая http-версия сайта будет доступна до конца 2019 года.<br>
  150. Приносим извинения за доставленные неудобства.
  151. </div>
  152. <span slot="footer" class="dialog-footer">
  153. <el-button @click="migrationDialogDisable">Больше не показывать</el-button>
  154. <el-button @click="migrationDialogRemind">Напомнить позже</el-button>
  155. </span>
  156. </el-dialog>
  157. </el-main>
  158. </el-container>
  159. </template>
  160. <script>
  161. //-----------------------------------------------------------------------------
  162. import Vue from 'vue';
  163. import Component from 'vue-class-component';
  164. import _ from 'lodash';
  165. import {Buffer} from 'safe-buffer';
  166. import LoaderPage from './LoaderPage/LoaderPage.vue';
  167. import TextPage from './TextPage/TextPage.vue';
  168. import ProgressPage from './ProgressPage/ProgressPage.vue';
  169. import SetPositionPage from './SetPositionPage/SetPositionPage.vue';
  170. import SearchPage from './SearchPage/SearchPage.vue';
  171. import CopyTextPage from './CopyTextPage/CopyTextPage.vue';
  172. import RecentBooksPage from './RecentBooksPage/RecentBooksPage.vue';
  173. import SettingsPage from './SettingsPage/SettingsPage.vue';
  174. import HelpPage from './HelpPage/HelpPage.vue';
  175. import ClickMapPage from './ClickMapPage/ClickMapPage.vue';
  176. import ServerStorage from './ServerStorage/ServerStorage.vue';
  177. import bookManager from './share/bookManager';
  178. import readerApi from '../../api/reader';
  179. import * as utils from '../../share/utils';
  180. import {versionHistory} from './versionHistory';
  181. export default @Component({
  182. components: {
  183. LoaderPage,
  184. TextPage,
  185. ProgressPage,
  186. SetPositionPage,
  187. SearchPage,
  188. CopyTextPage,
  189. RecentBooksPage,
  190. SettingsPage,
  191. HelpPage,
  192. ClickMapPage,
  193. ServerStorage,
  194. },
  195. watch: {
  196. bookPos: function(newValue) {
  197. if (newValue !== undefined && this.activePage == 'TextPage') {
  198. const textPage = this.$refs.page;
  199. if (textPage.bookPos != newValue) {
  200. textPage.bookPos = newValue;
  201. }
  202. this.debouncedSetRecentBook(newValue);
  203. }
  204. },
  205. routeParamPos: function(newValue) {
  206. if (newValue !== undefined && newValue != this.bookPos) {
  207. this.bookPos = newValue;
  208. }
  209. },
  210. routeParamUrl: function(newValue) {
  211. if (newValue !== '' && newValue !== this.mostRecentBook().url) {
  212. this.loadBook({url: newValue, bookPos: this.routeParamPos});
  213. }
  214. },
  215. settings: function() {
  216. this.loadSettings();
  217. this.updateRoute();
  218. },
  219. loaderActive: function(newValue) {
  220. (async() => {
  221. const recent = this.mostRecentBook();
  222. if (!newValue && !this.loading && recent && !await bookManager.hasBookParsed(recent)) {
  223. this.loadBook(recent);
  224. }
  225. })();
  226. },
  227. },
  228. })
  229. class Reader extends Vue {
  230. loaderActive = false;
  231. progressActive = false;
  232. fullScreenActive = false;
  233. scrollingActive = false;
  234. setPositionActive = false;
  235. searchActive = false;
  236. copyTextActive = false;
  237. recentBooksActive = false;
  238. offlineModeActive = false;
  239. settingsActive = false;
  240. helpActive = false;
  241. clickMapActive = false;
  242. bookPos = null;
  243. allowUrlParamBookPos = false;
  244. showRefreshIcon = true;
  245. mostRecentBookReactive = null;
  246. showToolButton = {};
  247. actionList = [];
  248. actionCur = -1;
  249. hidden = false;
  250. whatsNewVisible = false;
  251. whatsNewContent = '';
  252. migrationVisible1 = false;
  253. migrationVisible2 = false;
  254. created() {
  255. this.loading = true;
  256. this.commit = this.$store.commit;
  257. this.dispatch = this.$store.dispatch;
  258. this.reader = this.$store.state.reader;
  259. this.config = this.$store.state.config;
  260. this.$root.addKeyHook(this.keyHook);
  261. this.lastActivePage = false;
  262. this.debouncedUpdateRoute = _.debounce(() => {
  263. this.updateRoute();
  264. }, 1000);
  265. this.debouncedSetRecentBook = _.debounce(async(newValue) => {
  266. const recent = this.mostRecentBook();
  267. if (recent && (recent.bookPos != newValue || recent.bookPosSeen !== this.bookPosSeen)) {
  268. await bookManager.setRecentBook(Object.assign({}, recent, {bookPos: newValue, bookPosSeen: this.bookPosSeen}));
  269. if (this.actionCur < 0 || (this.actionCur >= 0 && this.actionList[this.actionCur] != newValue))
  270. this.addAction(newValue);
  271. }
  272. }, 500);
  273. document.addEventListener('fullscreenchange', () => {
  274. this.fullScreenActive = (document.fullscreenElement !== null);
  275. });
  276. this.loadSettings();
  277. //TODO: убрать в будущем
  278. if (this.showToolButton['history']) {
  279. const newShowToolButton = Object.assign({}, this.showToolButton);
  280. newShowToolButton['recentBooks'] = true;
  281. delete newShowToolButton['history'];
  282. const newSettings = Object.assign({}, this.settings, { showToolButton: newShowToolButton });
  283. this.commit('reader/setSettings', newSettings);
  284. }
  285. }
  286. mounted() {
  287. this.updateHeaderMinWidth();
  288. (async() => {
  289. await bookManager.init(this.settings);
  290. bookManager.addEventListener(this.bookManagerEvent);
  291. if (this.$root.rootRoute == '/reader') {
  292. if (this.routeParamUrl) {
  293. await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos, force: this.routeParamRefresh});
  294. } else {
  295. this.loaderActive = true;
  296. }
  297. }
  298. await this.$refs.serverStorage.init();
  299. this.checkSetStorageAccessKey();
  300. this.checkActivateDonateHelpPage();
  301. this.loading = false;
  302. await this.showWhatsNew();
  303. await this.showMigration();
  304. })();
  305. }
  306. loadSettings() {
  307. const settings = this.settings;
  308. this.allowUrlParamBookPos = settings.allowUrlParamBookPos;
  309. this.copyFullText = settings.copyFullText;
  310. this.showClickMapPage = settings.showClickMapPage;
  311. this.clickControl = settings.clickControl;
  312. this.blinkCachedLoad = settings.blinkCachedLoad;
  313. this.showWhatsNewDialog = settings.showWhatsNewDialog;
  314. this.showMigrationDialog = settings.showMigrationDialog;
  315. this.showToolButton = settings.showToolButton;
  316. this.enableSitesFilter = settings.enableSitesFilter;
  317. this.updateHeaderMinWidth();
  318. }
  319. updateHeaderMinWidth() {
  320. const showButtonCount = Object.values(this.showToolButton).reduce((a, b) => a + (b ? 1 : 0), 0);
  321. if (this.$refs.header)
  322. this.$refs.header.style.minWidth = 65*showButtonCount + 'px';
  323. }
  324. checkSetStorageAccessKey() {
  325. const q = this.$route.query;
  326. if (q['setStorageAccessKey']) {
  327. this.$router.replace(`/reader`);
  328. this.settingsToggle();
  329. this.$nextTick(() => {
  330. this.$refs.settingsPage.enterServerStorageKey(
  331. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  332. );
  333. });
  334. }
  335. }
  336. checkActivateDonateHelpPage() {
  337. const q = this.$route.query;
  338. if (q['donate']) {
  339. this.$router.replace(`/reader`);
  340. this.helpToggle();
  341. this.$nextTick(() => {
  342. this.$refs.helpPage.activateDonateHelpPage();
  343. });
  344. }
  345. }
  346. checkBookPosPercent() {
  347. const q = this.$route.query;
  348. if (q['__pp']) {
  349. let pp = q['__pp'];
  350. if (pp) {
  351. pp = parseFloat(pp) || 0;
  352. const recent = this.mostRecentBook();
  353. (async() => {
  354. await utils.sleep(100);
  355. this.bookPos = Math.floor(recent.textLength*pp/100);
  356. })();
  357. }
  358. }
  359. }
  360. async showWhatsNew() {
  361. await utils.sleep(2000);
  362. const whatsNew = versionHistory[0];
  363. if (this.showWhatsNewDialog &&
  364. whatsNew.showUntil >= utils.formatDate(new Date(), 'coDate') &&
  365. whatsNew.header != this.whatsNewContentHash) {
  366. this.whatsNewContent = 'Версия ' + whatsNew.header + whatsNew.content;
  367. this.whatsNewVisible = true;
  368. }
  369. }
  370. async showMigration() {
  371. await utils.sleep(3000);
  372. if (!this.settingsActive &&
  373. this.mode == 'omnireader' && this.showMigrationDialog && this.migrationRemindDate != utils.formatDate(new Date(), 'coDate')) {
  374. if (window.location.protocol == 'http:') {
  375. this.migrationVisible1 = true;
  376. } else if (window.location.protocol == 'https:') {
  377. this.migrationVisible2 = true;
  378. }
  379. }
  380. }
  381. migrationDialogDisable() {
  382. this.migrationVisible1 = false;
  383. this.migrationVisible2 = false;
  384. if (this.showMigrationDialog) {
  385. const newSettings = Object.assign({}, this.settings, { showMigrationDialog: false });
  386. this.commit('reader/setSettings', newSettings);
  387. }
  388. }
  389. migrationDialogRemind() {
  390. this.migrationVisible1 = false;
  391. this.migrationVisible2 = false;
  392. this.commit('reader/setMigrationRemindDate', utils.formatDate(new Date(), 'coDate'));
  393. }
  394. openVersionHistory() {
  395. this.whatsNewVisible = false;
  396. this.versionHistoryToggle();
  397. }
  398. whatsNewDisable() {
  399. this.whatsNewVisible = false;
  400. const whatsNew = versionHistory[0];
  401. this.commit('reader/setWhatsNewContentHash', whatsNew.header);
  402. }
  403. get routeParamPos() {
  404. let result = undefined;
  405. const q = this.$route.query;
  406. if (q['__p']) {
  407. result = q['__p'];
  408. if (Array.isArray(result))
  409. result = result[0];
  410. }
  411. return (result ? parseInt(result, 10) || 0 : result);
  412. }
  413. updateRoute(isNewRoute) {
  414. if (this.loading)
  415. return;
  416. const recent = this.mostRecentBook();
  417. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  418. const url = (recent ? `url=${recent.url}` : '');
  419. if (isNewRoute)
  420. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  421. else
  422. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  423. }
  424. get mode() {
  425. return this.$store.state.config.mode;
  426. }
  427. get routeParamUrl() {
  428. let result = '';
  429. const path = this.$route.fullPath;
  430. const i = path.indexOf('url=');
  431. if (i >= 0) {
  432. result = path.substr(i + 4);
  433. }
  434. return decodeURIComponent(result);
  435. }
  436. get routeParamRefresh() {
  437. const q = this.$route.query;
  438. return !!q['__refresh'];
  439. }
  440. bookPosChanged(event) {
  441. if (event.bookPosSeen !== undefined)
  442. this.bookPosSeen = event.bookPosSeen;
  443. this.bookPos = event.bookPos;
  444. this.debouncedUpdateRoute();
  445. }
  446. async bookManagerEvent(eventName, value) {
  447. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  448. const oldBook = (this.textPage ? this.textPage.lastBook : null);
  449. const oldPos = (this.textPage ? this.textPage.bookPos : null);
  450. const newBook = bookManager.mostRecentBook();
  451. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  452. this.mostRecentBook();
  453. }
  454. if (oldBook && newBook) {
  455. if (oldBook.key != newBook.key || oldBook.path != newBook.path) {
  456. this.loadingBook = true;
  457. try {
  458. await this.loadBook(newBook);
  459. } finally {
  460. this.loadingBook = false;
  461. }
  462. } else if (oldPos != newBook.bookPos) {
  463. while (this.loadingBook) await utils.sleep(100);
  464. this.bookPosChanged({bookPos: newBook.bookPos});
  465. }
  466. }
  467. }
  468. if (eventName == 'recent-changed') {
  469. if (this.recentBooksActive) {
  470. await this.$refs.recentBooksPage.updateTableData();
  471. }
  472. if (value) {
  473. await utils.sleep(500);
  474. while (!this.$refs.serverStorage.inited ||
  475. !bookManager.loaded ||
  476. this.$refs.serverStorage.savingRecent)
  477. await utils.sleep(100);
  478. await this.$refs.serverStorage.saveRecent(value);
  479. }
  480. }
  481. }
  482. get toolBarActive() {
  483. return this.reader.toolBarActive;
  484. }
  485. mostRecentBook() {
  486. const result = bookManager.mostRecentBook();
  487. this.mostRecentBookReactive = result;
  488. return result;
  489. }
  490. get settings() {
  491. return this.$store.state.reader.settings;
  492. }
  493. get whatsNewContentHash() {
  494. return this.$store.state.reader.whatsNewContentHash;
  495. }
  496. get migrationRemindDate() {
  497. return this.$store.state.reader.migrationRemindDate;
  498. }
  499. addAction(pos) {
  500. let a = this.actionList;
  501. if (!a.length || a[a.length - 1] != pos) {
  502. a.push(pos);
  503. if (a.length > 20)
  504. a.shift();
  505. this.actionCur = a.length - 1;
  506. }
  507. }
  508. toolBarToggle() {
  509. this.commit('reader/setToolBarActive', !this.toolBarActive);
  510. this.$root.$emit('resize');
  511. }
  512. fullScreenToggle() {
  513. this.fullScreenActive = !this.fullScreenActive;
  514. if (this.fullScreenActive) {
  515. const element = document.documentElement;
  516. if (element.requestFullscreen) {
  517. element.requestFullscreen();
  518. } else if (element.webkitrequestFullscreen) {
  519. element.webkitRequestFullscreen();
  520. } else if (element.mozRequestFullscreen) {
  521. element.mozRequestFullScreen();
  522. }
  523. } else {
  524. if (document.cancelFullScreen) {
  525. document.cancelFullScreen();
  526. } else if (document.mozCancelFullScreen) {
  527. document.mozCancelFullScreen();
  528. } else if (document.webkitCancelFullScreen) {
  529. document.webkitCancelFullScreen();
  530. }
  531. }
  532. }
  533. closeAllTextPages() {
  534. this.setPositionActive = false;
  535. this.copyTextActive = false;
  536. this.recentBooksActive = false;
  537. this.settingsActive = false;
  538. this.stopScrolling();
  539. this.stopSearch();
  540. this.helpActive = false;
  541. }
  542. loaderToggle() {
  543. this.loaderActive = !this.loaderActive;
  544. if (this.loaderActive) {
  545. this.closeAllTextPages();
  546. }
  547. }
  548. setPositionToggle() {
  549. this.setPositionActive = !this.setPositionActive;
  550. if (this.setPositionActive && this.activePage == 'TextPage' && this.mostRecentBook()) {
  551. this.closeAllTextPages();
  552. this.setPositionActive = true;
  553. this.$nextTick(() => {
  554. const recent = this.mostRecentBook();
  555. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  556. });
  557. } else {
  558. this.setPositionActive = false;
  559. }
  560. }
  561. stopScrolling() {
  562. if (this.scrollingActive)
  563. this.scrollingToggle();
  564. }
  565. scrollingToggle() {
  566. this.scrollingActive = !this.scrollingActive;
  567. if (this.activePage == 'TextPage') {
  568. const page = this.$refs.page;
  569. if (this.scrollingActive) {
  570. page.startTextScrolling();
  571. } else {
  572. page.stopTextScrolling();
  573. }
  574. }
  575. }
  576. stopSearch() {
  577. if (this.searchActive)
  578. this.searchToggle();
  579. }
  580. startTextSearch(opts) {
  581. if (this.activePage == 'TextPage')
  582. this.$refs.page.startSearch(opts.needle);
  583. }
  584. stopTextSearch() {
  585. if (this.activePage == 'TextPage')
  586. this.$refs.page.stopSearch();
  587. }
  588. searchToggle() {
  589. this.searchActive = !this.searchActive;
  590. const page = this.$refs.page;
  591. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  592. this.closeAllTextPages();
  593. this.searchActive = true;
  594. this.$nextTick(() => {
  595. this.$refs.searchPage.init(page.parsed);
  596. });
  597. } else {
  598. this.stopTextSearch();
  599. this.searchActive = false;
  600. }
  601. }
  602. copyTextToggle() {
  603. this.copyTextActive = !this.copyTextActive;
  604. const page = this.$refs.page;
  605. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  606. this.closeAllTextPages();
  607. this.copyTextActive = true;
  608. this.$nextTick(() => {
  609. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  610. });
  611. } else {
  612. this.copyTextActive = false;
  613. }
  614. }
  615. recentBooksToggle() {
  616. this.recentBooksActive = !this.recentBooksActive;
  617. if (this.recentBooksActive) {
  618. this.closeAllTextPages();
  619. this.$refs.recentBooksPage.init();
  620. this.recentBooksActive = true;
  621. } else {
  622. this.recentBooksActive = false;
  623. }
  624. }
  625. offlineModeToggle() {
  626. this.offlineModeActive = !this.offlineModeActive;
  627. this.$refs.serverStorage.offlineModeActive = this.offlineModeActive;
  628. }
  629. settingsToggle() {
  630. this.settingsActive = !this.settingsActive;
  631. if (this.settingsActive) {
  632. this.closeAllTextPages();
  633. this.settingsActive = true;
  634. this.$nextTick(() => {
  635. this.$refs.settingsPage.init();
  636. });
  637. } else {
  638. this.settingsActive = false;
  639. }
  640. }
  641. helpToggle() {
  642. this.helpActive = !this.helpActive;
  643. if (this.helpActive) {
  644. this.closeAllTextPages();
  645. this.helpActive = true;
  646. }
  647. }
  648. donateToggle() {
  649. this.helpToggle();
  650. if (this.helpActive) {
  651. this.$nextTick(() => {
  652. this.$refs.helpPage.activateDonateHelpPage();
  653. });
  654. }
  655. }
  656. versionHistoryToggle() {
  657. this.helpToggle();
  658. if (this.helpActive) {
  659. this.$nextTick(() => {
  660. this.$refs.helpPage.activateVersionHistoryHelpPage();
  661. });
  662. }
  663. }
  664. refreshBook() {
  665. if (this.mostRecentBook()) {
  666. this.loadBook({url: this.mostRecentBook().url, force: true});
  667. }
  668. }
  669. buttonClick(button) {
  670. const activeClass = this.buttonActiveClass(button);
  671. this.$refs[button].$el.blur();
  672. if (activeClass['tool-button-disabled'])
  673. return;
  674. switch (button) {
  675. case 'loader':
  676. this.loaderToggle();
  677. break;
  678. case 'undoAction':
  679. if (this.actionCur > 0) {
  680. this.actionCur--;
  681. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  682. }
  683. break;
  684. case 'redoAction':
  685. if (this.actionCur < this.actionList.length - 1) {
  686. this.actionCur++;
  687. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  688. }
  689. break;
  690. case 'fullScreen':
  691. this.fullScreenToggle();
  692. break;
  693. case 'setPosition':
  694. this.setPositionToggle();
  695. break;
  696. case 'scrolling':
  697. this.scrollingToggle();
  698. break;
  699. case 'search':
  700. this.searchToggle();
  701. break;
  702. case 'copyText':
  703. this.copyTextToggle();
  704. break;
  705. case 'refresh':
  706. this.refreshBook();
  707. break;
  708. case 'recentBooks':
  709. this.recentBooksToggle();
  710. break;
  711. case 'offlineMode':
  712. this.offlineModeToggle();
  713. break;
  714. case 'settings':
  715. this.settingsToggle();
  716. break;
  717. }
  718. }
  719. buttonActiveClass(button) {
  720. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  721. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  722. let classResult = {};
  723. switch (button) {
  724. case 'loader':
  725. case 'fullScreen':
  726. case 'setPosition':
  727. case 'scrolling':
  728. case 'search':
  729. case 'copyText':
  730. case 'recentBooks':
  731. case 'offlineMode':
  732. case 'settings':
  733. if (this[`${button}Active`])
  734. classResult = classActive;
  735. break;
  736. }
  737. switch (button) {
  738. case 'undoAction':
  739. if (this.actionCur <= 0)
  740. classResult = classDisabled;
  741. break;
  742. case 'redoAction':
  743. if (this.actionCur == this.actionList.length - 1)
  744. classResult = classDisabled;
  745. break;
  746. }
  747. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  748. switch (button) {
  749. case 'undoAction':
  750. case 'redoAction':
  751. case 'setPosition':
  752. case 'scrolling':
  753. case 'search':
  754. case 'copyText':
  755. classResult = classDisabled;
  756. break;
  757. case 'recentBooks':
  758. case 'refresh':
  759. if (!this.mostRecentBookReactive)
  760. classResult = classDisabled;
  761. break;
  762. }
  763. }
  764. return classResult;
  765. }
  766. async activateClickMapPage() {
  767. if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
  768. this.clickMapActive = true;
  769. await this.$refs.clickMapPage.slowDisappear();
  770. this.clickMapActive = false;
  771. }
  772. }
  773. get activePage() {
  774. let result = '';
  775. if (this.progressActive)
  776. result = 'ProgressPage';
  777. else if (this.loaderActive)
  778. result = 'LoaderPage';
  779. else if (this.mostRecentBookReactive)
  780. result = 'TextPage';
  781. if (!result && !this.loading) {
  782. this.loaderActive = true;
  783. result = 'LoaderPage';
  784. }
  785. if (result != 'TextPage') {
  786. this.$root.$emit('set-app-title');
  787. }
  788. // на LoaderPage всегда показываем toolBar
  789. if (result == 'LoaderPage' && !this.toolBarActive) {
  790. this.toolBarToggle();
  791. }
  792. if (this.lastActivePage != result && result == 'TextPage') {
  793. //акивируем страницу с текстом
  794. this.$nextTick(async() => {
  795. const last = this.mostRecentBookReactive;
  796. const isParsed = await bookManager.hasBookParsed(last);
  797. if (!isParsed) {
  798. this.$root.$emit('set-app-title');
  799. return;
  800. }
  801. this.updateRoute();
  802. const textPage = this.$refs.page;
  803. if (textPage.showBook) {
  804. this.textPage = textPage;
  805. textPage.lastBook = last;
  806. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  807. textPage.showBook();
  808. }
  809. });
  810. }
  811. this.lastActivePage = result;
  812. return result;
  813. }
  814. async loadBook(opts) {
  815. if (!opts || !opts.url) {
  816. this.mostRecentBook();
  817. return;
  818. }
  819. let url = opts.url;
  820. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  821. (url.indexOf('file://') != 0))
  822. url = 'http://' + url;
  823. // уже просматривается сейчас
  824. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  825. if (!opts.force && lastBook && lastBook.url == url &&
  826. (!opts.path || opts.path == lastBook.path) &&
  827. await bookManager.hasBookParsed(lastBook)) {
  828. this.loaderActive = false;
  829. return;
  830. }
  831. this.progressActive = true;
  832. await this.$nextTick();
  833. const progress = this.$refs.page;
  834. this.actionList = [];
  835. this.actionCur = -1;
  836. try {
  837. progress.show();
  838. progress.setState({state: 'parse'});
  839. // есть ли среди недавних
  840. const key = bookManager.keyFromUrl(url);
  841. let wasOpened = await bookManager.getRecentBook({key});
  842. wasOpened = (wasOpened ? wasOpened : {});
  843. const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
  844. const bookPosSeen = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen);
  845. let book = null;
  846. if (!opts.force) {
  847. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  848. const bookParsed = await bookManager.getBook({url, path: opts.path}, (prog) => {
  849. progress.setState({progress: prog});
  850. });
  851. // если есть в локальном кэше
  852. if (bookParsed) {
  853. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, bookParsed));
  854. this.mostRecentBook();
  855. this.addAction(bookPos);
  856. this.loaderActive = false;
  857. progress.hide(); this.progressActive = false;
  858. this.blinkCachedLoadMessage();
  859. this.checkBookPosPercent();
  860. await this.activateClickMapPage();
  861. return;
  862. }
  863. // иначе идем на сервер
  864. // пытаемся загрузить готовый файл с сервера
  865. if (wasOpened.path) {
  866. progress.setState({totalSteps: 5});
  867. try {
  868. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  869. progress.setState(state);
  870. });
  871. book = Object.assign({}, wasOpened, {data: resp.data});
  872. } catch (e) {
  873. //молчим
  874. }
  875. }
  876. }
  877. progress.setState({totalSteps: 5});
  878. // не удалось, скачиваем книгу полностью с конвертацией
  879. let loadCached = true;
  880. if (!book) {
  881. book = await readerApi.loadBook({url, enableSitesFilter: this.enableSitesFilter}, (state) => {
  882. progress.setState(state);
  883. });
  884. loadCached = false;
  885. }
  886. // добавляем в bookManager
  887. progress.setState({state: 'parse', step: 5});
  888. const addedBook = await bookManager.addBook(book, (prog) => {
  889. progress.setState({progress: prog});
  890. });
  891. // добавляем в историю
  892. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, addedBook));
  893. this.mostRecentBook();
  894. this.addAction(bookPos);
  895. this.updateRoute(true);
  896. this.loaderActive = false;
  897. progress.hide(); this.progressActive = false;
  898. if (loadCached) {
  899. this.blinkCachedLoadMessage();
  900. } else
  901. this.stopBlink = true;
  902. this.checkBookPosPercent();
  903. await this.activateClickMapPage();
  904. } catch (e) {
  905. progress.hide(); this.progressActive = false;
  906. this.loaderActive = true;
  907. this.$alert(e.message, 'Ошибка', {type: 'error'});
  908. }
  909. }
  910. async loadFile(opts) {
  911. this.progressActive = true;
  912. await this.$nextTick();
  913. const progress = this.$refs.page;
  914. try {
  915. progress.show();
  916. progress.setState({state: 'upload'});
  917. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  918. progress.setState(state);
  919. });
  920. progress.hide(); this.progressActive = false;
  921. await this.loadBook({url});
  922. } catch (e) {
  923. progress.hide(); this.progressActive = false;
  924. this.loaderActive = true;
  925. this.$alert(e.message, 'Ошибка', {type: 'error'});
  926. }
  927. }
  928. blinkCachedLoadMessage() {
  929. if (!this.blinkCachedLoad)
  930. return;
  931. this.blinkCount = 30;
  932. if (!this.inBlink) {
  933. this.inBlink = true;
  934. this.stopBlink = false;
  935. this.$nextTick(async() => {
  936. let page = this.$refs.page;
  937. while (this.blinkCount) {
  938. this.showRefreshIcon = !this.showRefreshIcon;
  939. if (page && page.blinkCachedLoadMessage)
  940. page.blinkCachedLoadMessage(this.showRefreshIcon);
  941. await utils.sleep(500);
  942. if (this.stopBlink)
  943. break;
  944. this.blinkCount--;
  945. page = this.$refs.page;
  946. }
  947. this.showRefreshIcon = true;
  948. this.inBlink = false;
  949. if (page && page.blinkCachedLoadMessage)
  950. page.blinkCachedLoadMessage('finish');
  951. });
  952. }
  953. }
  954. keyHook(event) {
  955. if (this.$root.rootRoute == '/reader') {
  956. let handled = false;
  957. if (!handled && this.helpActive)
  958. handled = this.$refs.helpPage.keyHook(event);
  959. if (!handled && this.settingsActive)
  960. handled = this.$refs.settingsPage.keyHook(event);
  961. if (!handled && this.recentBooksActive)
  962. handled = this.$refs.recentBooksPage.keyHook(event);
  963. if (!handled && this.setPositionActive)
  964. handled = this.$refs.setPositionPage.keyHook(event);
  965. if (!handled && this.searchActive)
  966. handled = this.$refs.searchPage.keyHook(event);
  967. if (!handled && this.copyTextActive)
  968. handled = this.$refs.copyTextPage.keyHook(event);
  969. if (!handled && this.$refs.page && this.$refs.page.keyHook)
  970. handled = this.$refs.page.keyHook(event);
  971. if (!handled && event.type == 'keydown') {
  972. if (event.code == 'Escape')
  973. this.loaderToggle();
  974. if (this.activePage == 'TextPage') {
  975. switch (event.code) {
  976. case 'KeyH':
  977. case 'F1':
  978. this.helpToggle();
  979. event.preventDefault();
  980. event.stopPropagation();
  981. break;
  982. case 'KeyZ':
  983. this.scrollingToggle();
  984. break;
  985. case 'KeyP':
  986. this.setPositionToggle();
  987. break;
  988. case 'KeyF':
  989. if (event.ctrlKey) {
  990. this.searchToggle();
  991. event.preventDefault();
  992. event.stopPropagation();
  993. }
  994. break;
  995. case 'KeyC':
  996. if (event.ctrlKey) {
  997. this.copyTextToggle();
  998. event.preventDefault();
  999. event.stopPropagation();
  1000. }
  1001. break;
  1002. case 'KeyR':
  1003. this.refreshBook();
  1004. break;
  1005. case 'KeyX':
  1006. this.recentBooksToggle();
  1007. event.preventDefault();
  1008. event.stopPropagation();
  1009. break;
  1010. case 'KeyO':
  1011. this.offlineModeToggle();
  1012. break;
  1013. case 'KeyS':
  1014. this.settingsToggle();
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. //-----------------------------------------------------------------------------
  1023. </script>
  1024. <style scoped>
  1025. .el-container {
  1026. padding: 0;
  1027. margin: 0;
  1028. height: 100%;
  1029. }
  1030. .el-header {
  1031. padding-left: 5px;
  1032. padding-right: 5px;
  1033. background-color: #1B695F;
  1034. color: #000;
  1035. overflow-x: auto;
  1036. overflow-y: hidden;
  1037. }
  1038. .header {
  1039. display: flex;
  1040. justify-content: space-between;
  1041. }
  1042. .el-main {
  1043. position: relative;
  1044. display: flex;
  1045. padding: 0;
  1046. margin: 0;
  1047. background-color: #EBE2C9;
  1048. color: #000;
  1049. }
  1050. .tool-button {
  1051. margin: 0 2px 0 2px;
  1052. padding: 0;
  1053. color: #3E843E;
  1054. background-color: #E6EDF4;
  1055. margin-top: 5px;
  1056. height: 38px;
  1057. width: 38px;
  1058. border: 0;
  1059. box-shadow: 3px 3px 5px black;
  1060. }
  1061. .tool-button + .tool-button {
  1062. margin: 0 2px 0 2px;
  1063. }
  1064. .tool-button:hover {
  1065. background-color: white;
  1066. }
  1067. .tool-button-active {
  1068. box-shadow: 0 0 0;
  1069. color: white;
  1070. background-color: #8AB45F;
  1071. position: relative;
  1072. top: 1px;
  1073. left: 1px;
  1074. }
  1075. .tool-button-active:hover {
  1076. color: white;
  1077. background-color: #81C581;
  1078. }
  1079. .tool-button-disabled {
  1080. color: lightgray;
  1081. background-color: gray;
  1082. }
  1083. .tool-button-disabled:hover {
  1084. color: lightgray;
  1085. background-color: gray;
  1086. }
  1087. i {
  1088. font-size: 200%;
  1089. }
  1090. .space {
  1091. width: 10px;
  1092. display: inline-block;
  1093. }
  1094. .clear {
  1095. color: rgba(0,0,0,0);
  1096. }
  1097. .clickable {
  1098. color: blue;
  1099. text-decoration: underline;
  1100. cursor: pointer;
  1101. }
  1102. </style>