Reader.vue 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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. this.checkSetStorageAccessKey();
  299. this.checkActivateDonateHelpPage();
  300. this.loading = false;
  301. await this.$refs.serverStorage.init();
  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.updateHeaderMinWidth();
  317. }
  318. updateHeaderMinWidth() {
  319. const showButtonCount = Object.values(this.showToolButton).reduce((a, b) => a + (b ? 1 : 0), 0);
  320. if (this.$refs.header)
  321. this.$refs.header.style.minWidth = 65*showButtonCount + 'px';
  322. }
  323. checkSetStorageAccessKey() {
  324. const q = this.$route.query;
  325. if (q['setStorageAccessKey']) {
  326. this.$router.replace(`/reader`);
  327. this.settingsToggle();
  328. this.$nextTick(() => {
  329. this.$refs.settingsPage.enterServerStorageKey(
  330. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  331. );
  332. });
  333. }
  334. }
  335. checkActivateDonateHelpPage() {
  336. const q = this.$route.query;
  337. if (q['donate']) {
  338. this.$router.replace(`/reader`);
  339. this.helpToggle();
  340. this.$nextTick(() => {
  341. this.$refs.helpPage.activateDonateHelpPage();
  342. });
  343. }
  344. }
  345. checkBookPosPercent() {
  346. const q = this.$route.query;
  347. if (q['__pp']) {
  348. let pp = q['__pp'];
  349. if (pp) {
  350. pp = parseFloat(pp) || 0;
  351. const recent = this.mostRecentBook();
  352. (async() => {
  353. await utils.sleep(100);
  354. this.bookPos = Math.floor(recent.textLength*pp/100);
  355. })();
  356. }
  357. }
  358. }
  359. async showWhatsNew() {
  360. await utils.sleep(2000);
  361. const whatsNew = versionHistory[0];
  362. if (this.showWhatsNewDialog &&
  363. whatsNew.showUntil >= utils.formatDate(new Date(), 'coDate') &&
  364. whatsNew.header != this.whatsNewContentHash) {
  365. this.whatsNewContent = 'Версия ' + whatsNew.header + whatsNew.content;
  366. this.whatsNewVisible = true;
  367. }
  368. }
  369. async showMigration() {
  370. await utils.sleep(3000);
  371. if (!this.settingsActive &&
  372. this.mode == 'omnireader' && this.showMigrationDialog && this.migrationRemindDate != utils.formatDate(new Date(), 'coDate')) {
  373. if (window.location.protocol == 'http:') {
  374. this.migrationVisible1 = true;
  375. } else if (window.location.protocol == 'https:') {
  376. this.migrationVisible2 = true;
  377. }
  378. }
  379. }
  380. migrationDialogDisable() {
  381. this.migrationVisible1 = false;
  382. this.migrationVisible2 = false;
  383. if (this.showMigrationDialog) {
  384. const newSettings = Object.assign({}, this.settings, { showMigrationDialog: false });
  385. this.commit('reader/setSettings', newSettings);
  386. }
  387. }
  388. migrationDialogRemind() {
  389. this.migrationVisible1 = false;
  390. this.migrationVisible2 = false;
  391. this.commit('reader/setMigrationRemindDate', utils.formatDate(new Date(), 'coDate'));
  392. }
  393. openVersionHistory() {
  394. this.whatsNewVisible = false;
  395. this.versionHistoryToggle();
  396. }
  397. whatsNewDisable() {
  398. this.whatsNewVisible = false;
  399. const whatsNew = versionHistory[0];
  400. this.commit('reader/setWhatsNewContentHash', whatsNew.header);
  401. }
  402. get routeParamPos() {
  403. let result = undefined;
  404. const q = this.$route.query;
  405. if (q['__p']) {
  406. result = q['__p'];
  407. if (Array.isArray(result))
  408. result = result[0];
  409. }
  410. return (result ? parseInt(result, 10) || 0 : result);
  411. }
  412. updateRoute(isNewRoute) {
  413. if (this.loading)
  414. return;
  415. const recent = this.mostRecentBook();
  416. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  417. const url = (recent ? `url=${recent.url}` : '');
  418. if (isNewRoute)
  419. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  420. else
  421. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  422. }
  423. get mode() {
  424. return this.$store.state.config.mode;
  425. }
  426. get routeParamUrl() {
  427. let result = '';
  428. const path = this.$route.fullPath;
  429. const i = path.indexOf('url=');
  430. if (i >= 0) {
  431. result = path.substr(i + 4);
  432. }
  433. return decodeURIComponent(result);
  434. }
  435. get routeParamRefresh() {
  436. const q = this.$route.query;
  437. return !!q['__refresh'];
  438. }
  439. bookPosChanged(event) {
  440. if (event.bookPosSeen !== undefined)
  441. this.bookPosSeen = event.bookPosSeen;
  442. this.bookPos = event.bookPos;
  443. this.debouncedUpdateRoute();
  444. }
  445. async bookManagerEvent(eventName) {
  446. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  447. const oldBook = this.mostRecentBookReactive;
  448. const newBook = bookManager.mostRecentBook();
  449. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  450. this.mostRecentBook();
  451. }
  452. if (oldBook && newBook) {
  453. if (oldBook.key != newBook.key) {
  454. this.loadingBook = true;
  455. try {
  456. await this.loadBook(newBook);
  457. } finally {
  458. this.loadingBook = false;
  459. }
  460. } else if (oldBook.bookPos != newBook.bookPos) {
  461. while (this.loadingBook) await utils.sleep(100);
  462. this.bookPosChanged({bookPos: newBook.bookPos});
  463. }
  464. }
  465. }
  466. if (eventName == 'recent-changed') {
  467. if (this.recentBooksActive) {
  468. await this.$refs.recentBooksPage.updateTableData();
  469. }
  470. }
  471. }
  472. get toolBarActive() {
  473. return this.reader.toolBarActive;
  474. }
  475. mostRecentBook() {
  476. const result = bookManager.mostRecentBook();
  477. this.mostRecentBookReactive = result;
  478. return result;
  479. }
  480. get settings() {
  481. return this.$store.state.reader.settings;
  482. }
  483. get whatsNewContentHash() {
  484. return this.$store.state.reader.whatsNewContentHash;
  485. }
  486. get migrationRemindDate() {
  487. return this.$store.state.reader.migrationRemindDate;
  488. }
  489. addAction(pos) {
  490. let a = this.actionList;
  491. if (!a.length || a[a.length - 1] != pos) {
  492. a.push(pos);
  493. if (a.length > 20)
  494. a.shift();
  495. this.actionCur = a.length - 1;
  496. }
  497. }
  498. toolBarToggle() {
  499. this.commit('reader/setToolBarActive', !this.toolBarActive);
  500. this.$root.$emit('resize');
  501. }
  502. fullScreenToggle() {
  503. this.fullScreenActive = !this.fullScreenActive;
  504. if (this.fullScreenActive) {
  505. const element = document.documentElement;
  506. if (element.requestFullscreen) {
  507. element.requestFullscreen();
  508. } else if (element.webkitrequestFullscreen) {
  509. element.webkitRequestFullscreen();
  510. } else if (element.mozRequestFullscreen) {
  511. element.mozRequestFullScreen();
  512. }
  513. } else {
  514. if (document.cancelFullScreen) {
  515. document.cancelFullScreen();
  516. } else if (document.mozCancelFullScreen) {
  517. document.mozCancelFullScreen();
  518. } else if (document.webkitCancelFullScreen) {
  519. document.webkitCancelFullScreen();
  520. }
  521. }
  522. }
  523. closeAllTextPages() {
  524. this.setPositionActive = false;
  525. this.copyTextActive = false;
  526. this.recentBooksActive = false;
  527. this.settingsActive = false;
  528. this.stopScrolling();
  529. this.stopSearch();
  530. this.helpActive = false;
  531. }
  532. loaderToggle() {
  533. this.loaderActive = !this.loaderActive;
  534. if (this.loaderActive) {
  535. this.closeAllTextPages();
  536. }
  537. }
  538. setPositionToggle() {
  539. this.setPositionActive = !this.setPositionActive;
  540. if (this.setPositionActive && this.activePage == 'TextPage' && this.mostRecentBook()) {
  541. this.closeAllTextPages();
  542. this.setPositionActive = true;
  543. this.$nextTick(() => {
  544. const recent = this.mostRecentBook();
  545. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  546. });
  547. } else {
  548. this.setPositionActive = false;
  549. }
  550. }
  551. stopScrolling() {
  552. if (this.scrollingActive)
  553. this.scrollingToggle();
  554. }
  555. scrollingToggle() {
  556. this.scrollingActive = !this.scrollingActive;
  557. if (this.activePage == 'TextPage') {
  558. const page = this.$refs.page;
  559. if (this.scrollingActive) {
  560. page.startTextScrolling();
  561. } else {
  562. page.stopTextScrolling();
  563. }
  564. }
  565. }
  566. stopSearch() {
  567. if (this.searchActive)
  568. this.searchToggle();
  569. }
  570. startTextSearch(opts) {
  571. if (this.activePage == 'TextPage')
  572. this.$refs.page.startSearch(opts.needle);
  573. }
  574. stopTextSearch() {
  575. if (this.activePage == 'TextPage')
  576. this.$refs.page.stopSearch();
  577. }
  578. searchToggle() {
  579. this.searchActive = !this.searchActive;
  580. const page = this.$refs.page;
  581. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  582. this.closeAllTextPages();
  583. this.searchActive = true;
  584. this.$nextTick(() => {
  585. this.$refs.searchPage.init(page.parsed);
  586. });
  587. } else {
  588. this.stopTextSearch();
  589. this.searchActive = false;
  590. }
  591. }
  592. copyTextToggle() {
  593. this.copyTextActive = !this.copyTextActive;
  594. const page = this.$refs.page;
  595. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  596. this.closeAllTextPages();
  597. this.copyTextActive = true;
  598. this.$nextTick(() => {
  599. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  600. });
  601. } else {
  602. this.copyTextActive = false;
  603. }
  604. }
  605. recentBooksToggle() {
  606. this.recentBooksActive = !this.recentBooksActive;
  607. if (this.recentBooksActive) {
  608. this.closeAllTextPages();
  609. this.$refs.recentBooksPage.init();
  610. this.recentBooksActive = true;
  611. } else {
  612. this.recentBooksActive = false;
  613. }
  614. }
  615. offlineModeToggle() {
  616. this.offlineModeActive = !this.offlineModeActive;
  617. this.$refs.serverStorage.offlineModeActive = this.offlineModeActive;
  618. }
  619. settingsToggle() {
  620. this.settingsActive = !this.settingsActive;
  621. if (this.settingsActive) {
  622. this.closeAllTextPages();
  623. this.settingsActive = true;
  624. this.$nextTick(() => {
  625. this.$refs.settingsPage.init();
  626. });
  627. } else {
  628. this.settingsActive = false;
  629. }
  630. }
  631. helpToggle() {
  632. this.helpActive = !this.helpActive;
  633. if (this.helpActive) {
  634. this.closeAllTextPages();
  635. this.helpActive = true;
  636. }
  637. }
  638. donateToggle() {
  639. this.helpToggle();
  640. if (this.helpActive) {
  641. this.$nextTick(() => {
  642. this.$refs.helpPage.activateDonateHelpPage();
  643. });
  644. }
  645. }
  646. versionHistoryToggle() {
  647. this.helpToggle();
  648. if (this.helpActive) {
  649. this.$nextTick(() => {
  650. this.$refs.helpPage.activateVersionHistoryHelpPage();
  651. });
  652. }
  653. }
  654. refreshBook() {
  655. if (this.mostRecentBook()) {
  656. this.loadBook({url: this.mostRecentBook().url, force: true});
  657. }
  658. }
  659. buttonClick(button) {
  660. const activeClass = this.buttonActiveClass(button);
  661. this.$refs[button].$el.blur();
  662. if (activeClass['tool-button-disabled'])
  663. return;
  664. switch (button) {
  665. case 'loader':
  666. this.loaderToggle();
  667. break;
  668. case 'undoAction':
  669. if (this.actionCur > 0) {
  670. this.actionCur--;
  671. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  672. }
  673. break;
  674. case 'redoAction':
  675. if (this.actionCur < this.actionList.length - 1) {
  676. this.actionCur++;
  677. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  678. }
  679. break;
  680. case 'fullScreen':
  681. this.fullScreenToggle();
  682. break;
  683. case 'setPosition':
  684. this.setPositionToggle();
  685. break;
  686. case 'scrolling':
  687. this.scrollingToggle();
  688. break;
  689. case 'search':
  690. this.searchToggle();
  691. break;
  692. case 'copyText':
  693. this.copyTextToggle();
  694. break;
  695. case 'refresh':
  696. this.refreshBook();
  697. break;
  698. case 'recentBooks':
  699. this.recentBooksToggle();
  700. break;
  701. case 'offlineMode':
  702. this.offlineModeToggle();
  703. break;
  704. case 'settings':
  705. this.settingsToggle();
  706. break;
  707. }
  708. }
  709. buttonActiveClass(button) {
  710. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  711. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  712. let classResult = {};
  713. switch (button) {
  714. case 'loader':
  715. case 'fullScreen':
  716. case 'setPosition':
  717. case 'scrolling':
  718. case 'search':
  719. case 'copyText':
  720. case 'recentBooks':
  721. case 'offlineMode':
  722. case 'settings':
  723. if (this[`${button}Active`])
  724. classResult = classActive;
  725. break;
  726. }
  727. switch (button) {
  728. case 'undoAction':
  729. if (this.actionCur <= 0)
  730. classResult = classDisabled;
  731. break;
  732. case 'redoAction':
  733. if (this.actionCur == this.actionList.length - 1)
  734. classResult = classDisabled;
  735. break;
  736. }
  737. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  738. switch (button) {
  739. case 'undoAction':
  740. case 'redoAction':
  741. case 'setPosition':
  742. case 'scrolling':
  743. case 'search':
  744. case 'copyText':
  745. classResult = classDisabled;
  746. break;
  747. case 'recentBooks':
  748. case 'refresh':
  749. if (!this.mostRecentBookReactive)
  750. classResult = classDisabled;
  751. break;
  752. }
  753. }
  754. return classResult;
  755. }
  756. async activateClickMapPage() {
  757. if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
  758. this.clickMapActive = true;
  759. await this.$refs.clickMapPage.slowDisappear();
  760. this.clickMapActive = false;
  761. }
  762. }
  763. get activePage() {
  764. let result = '';
  765. if (this.progressActive)
  766. result = 'ProgressPage';
  767. else if (this.loaderActive)
  768. result = 'LoaderPage';
  769. else if (this.mostRecentBookReactive)
  770. result = 'TextPage';
  771. if (!result && !this.loading) {
  772. this.loaderActive = true;
  773. result = 'LoaderPage';
  774. }
  775. if (result != 'TextPage') {
  776. this.$root.$emit('set-app-title');
  777. }
  778. // на LoaderPage всегда показываем toolBar
  779. if (result == 'LoaderPage' && !this.toolBarActive) {
  780. this.toolBarToggle();
  781. }
  782. if (this.lastActivePage != result && result == 'TextPage') {
  783. //акивируем страницу с текстом
  784. this.$nextTick(async() => {
  785. const last = this.mostRecentBookReactive;
  786. const isParsed = await bookManager.hasBookParsed(last);
  787. if (!isParsed) {
  788. this.$root.$emit('set-app-title');
  789. return;
  790. }
  791. this.updateRoute();
  792. const textPage = this.$refs.page;
  793. if (textPage.showBook) {
  794. textPage.lastBook = last;
  795. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  796. textPage.showBook();
  797. }
  798. });
  799. }
  800. this.lastActivePage = result;
  801. return result;
  802. }
  803. async loadBook(opts) {
  804. if (!opts || !opts.url) {
  805. this.mostRecentBook();
  806. return;
  807. }
  808. let url = opts.url;
  809. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  810. (url.indexOf('file://') != 0))
  811. url = 'http://' + url;
  812. // уже просматривается сейчас
  813. const lastBook = (this.$refs.page ? this.$refs.page.lastBook : null);
  814. if (!opts.force && lastBook && lastBook.url == url && await bookManager.hasBookParsed(lastBook)) {
  815. this.loaderActive = false;
  816. return;
  817. }
  818. this.progressActive = true;
  819. await this.$nextTick();
  820. const progress = this.$refs.page;
  821. this.actionList = [];
  822. this.actionCur = -1;
  823. try {
  824. progress.show();
  825. progress.setState({state: 'parse'});
  826. // есть ли среди недавних
  827. const key = bookManager.keyFromUrl(url);
  828. let wasOpened = await bookManager.getRecentBook({key});
  829. wasOpened = (wasOpened ? wasOpened : {});
  830. const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
  831. const bookPosSeen = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen);
  832. let book = null;
  833. if (!opts.force) {
  834. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  835. const bookParsed = await bookManager.getBook({url}, (prog) => {
  836. progress.setState({progress: prog});
  837. });
  838. // если есть в локальном кэше
  839. if (bookParsed) {
  840. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, bookParsed));
  841. this.mostRecentBook();
  842. this.addAction(bookPos);
  843. this.loaderActive = false;
  844. progress.hide(); this.progressActive = false;
  845. this.blinkCachedLoadMessage();
  846. this.checkBookPosPercent();
  847. await this.activateClickMapPage();
  848. return;
  849. }
  850. // иначе идем на сервер
  851. // пытаемся загрузить готовый файл с сервера
  852. if (wasOpened.path) {
  853. try {
  854. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  855. progress.setState(state);
  856. });
  857. book = Object.assign({}, wasOpened, {data: resp.data});
  858. } catch (e) {
  859. //молчим
  860. }
  861. }
  862. }
  863. progress.setState({totalSteps: 5});
  864. // не удалось, скачиваем книгу полностью с конвертацией
  865. let loadCached = true;
  866. if (!book) {
  867. book = await readerApi.loadBook(url, (state) => {
  868. progress.setState(state);
  869. });
  870. loadCached = false;
  871. }
  872. // добавляем в bookManager
  873. progress.setState({state: 'parse', step: 5});
  874. const addedBook = await bookManager.addBook(book, (prog) => {
  875. progress.setState({progress: prog});
  876. });
  877. // добавляем в историю
  878. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, addedBook));
  879. this.mostRecentBook();
  880. this.addAction(bookPos);
  881. this.updateRoute(true);
  882. this.loaderActive = false;
  883. progress.hide(); this.progressActive = false;
  884. if (loadCached) {
  885. this.blinkCachedLoadMessage();
  886. } else
  887. this.stopBlink = true;
  888. this.checkBookPosPercent();
  889. await this.activateClickMapPage();
  890. } catch (e) {
  891. progress.hide(); this.progressActive = false;
  892. this.loaderActive = true;
  893. this.$alert(e.message, 'Ошибка', {type: 'error'});
  894. }
  895. }
  896. async loadFile(opts) {
  897. this.progressActive = true;
  898. await this.$nextTick();
  899. const progress = this.$refs.page;
  900. try {
  901. progress.show();
  902. progress.setState({state: 'upload'});
  903. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  904. progress.setState(state);
  905. });
  906. progress.hide(); this.progressActive = false;
  907. await this.loadBook({url});
  908. } catch (e) {
  909. progress.hide(); this.progressActive = false;
  910. this.loaderActive = true;
  911. this.$alert(e.message, 'Ошибка', {type: 'error'});
  912. }
  913. }
  914. blinkCachedLoadMessage() {
  915. if (!this.blinkCachedLoad)
  916. return;
  917. this.blinkCount = 30;
  918. if (!this.inBlink) {
  919. this.inBlink = true;
  920. this.stopBlink = false;
  921. this.$nextTick(async() => {
  922. let page = this.$refs.page;
  923. while (this.blinkCount) {
  924. this.showRefreshIcon = !this.showRefreshIcon;
  925. if (page && page.blinkCachedLoadMessage)
  926. page.blinkCachedLoadMessage(this.showRefreshIcon);
  927. await utils.sleep(500);
  928. if (this.stopBlink)
  929. break;
  930. this.blinkCount--;
  931. page = this.$refs.page;
  932. }
  933. this.showRefreshIcon = true;
  934. this.inBlink = false;
  935. if (page && page.blinkCachedLoadMessage)
  936. page.blinkCachedLoadMessage('finish');
  937. });
  938. }
  939. }
  940. keyHook(event) {
  941. if (this.$root.rootRoute == '/reader') {
  942. let handled = false;
  943. if (!handled && this.helpActive)
  944. handled = this.$refs.helpPage.keyHook(event);
  945. if (!handled && this.settingsActive)
  946. handled = this.$refs.settingsPage.keyHook(event);
  947. if (!handled && this.recentBooksActive)
  948. handled = this.$refs.recentBooksPage.keyHook(event);
  949. if (!handled && this.setPositionActive)
  950. handled = this.$refs.setPositionPage.keyHook(event);
  951. if (!handled && this.searchActive)
  952. handled = this.$refs.searchPage.keyHook(event);
  953. if (!handled && this.copyTextActive)
  954. handled = this.$refs.copyTextPage.keyHook(event);
  955. if (!handled && this.$refs.page && this.$refs.page.keyHook)
  956. handled = this.$refs.page.keyHook(event);
  957. if (!handled && event.type == 'keydown') {
  958. if (event.code == 'Escape')
  959. this.loaderToggle();
  960. if (this.activePage == 'TextPage') {
  961. switch (event.code) {
  962. case 'KeyH':
  963. case 'F1':
  964. this.helpToggle();
  965. event.preventDefault();
  966. event.stopPropagation();
  967. break;
  968. case 'KeyZ':
  969. this.scrollingToggle();
  970. break;
  971. case 'KeyP':
  972. this.setPositionToggle();
  973. break;
  974. case 'KeyF':
  975. if (event.ctrlKey) {
  976. this.searchToggle();
  977. event.preventDefault();
  978. event.stopPropagation();
  979. }
  980. break;
  981. case 'KeyC':
  982. if (event.ctrlKey) {
  983. this.copyTextToggle();
  984. event.preventDefault();
  985. event.stopPropagation();
  986. }
  987. break;
  988. case 'KeyR':
  989. this.refreshBook();
  990. break;
  991. case 'KeyX':
  992. this.recentBooksToggle();
  993. event.preventDefault();
  994. event.stopPropagation();
  995. break;
  996. case 'KeyO':
  997. this.offlineModeToggle();
  998. break;
  999. case 'KeyS':
  1000. this.settingsToggle();
  1001. break;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. }
  1007. }
  1008. //-----------------------------------------------------------------------------
  1009. </script>
  1010. <style scoped>
  1011. .el-container {
  1012. padding: 0;
  1013. margin: 0;
  1014. height: 100%;
  1015. }
  1016. .el-header {
  1017. padding-left: 5px;
  1018. padding-right: 5px;
  1019. background-color: #1B695F;
  1020. color: #000;
  1021. overflow-x: auto;
  1022. overflow-y: hidden;
  1023. }
  1024. .header {
  1025. display: flex;
  1026. justify-content: space-between;
  1027. }
  1028. .el-main {
  1029. position: relative;
  1030. display: flex;
  1031. padding: 0;
  1032. margin: 0;
  1033. background-color: #EBE2C9;
  1034. color: #000;
  1035. }
  1036. .tool-button {
  1037. margin: 0 2px 0 2px;
  1038. padding: 0;
  1039. color: #3E843E;
  1040. background-color: #E6EDF4;
  1041. margin-top: 5px;
  1042. height: 38px;
  1043. width: 38px;
  1044. border: 0;
  1045. box-shadow: 3px 3px 5px black;
  1046. }
  1047. .tool-button + .tool-button {
  1048. margin: 0 2px 0 2px;
  1049. }
  1050. .tool-button:hover {
  1051. background-color: white;
  1052. }
  1053. .tool-button-active {
  1054. box-shadow: 0 0 0;
  1055. color: white;
  1056. background-color: #8AB45F;
  1057. position: relative;
  1058. top: 1px;
  1059. left: 1px;
  1060. }
  1061. .tool-button-active:hover {
  1062. color: white;
  1063. background-color: #81C581;
  1064. }
  1065. .tool-button-disabled {
  1066. color: lightgray;
  1067. background-color: gray;
  1068. }
  1069. .tool-button-disabled:hover {
  1070. color: lightgray;
  1071. background-color: gray;
  1072. }
  1073. i {
  1074. font-size: 200%;
  1075. }
  1076. .space {
  1077. width: 10px;
  1078. display: inline-block;
  1079. }
  1080. .clear {
  1081. color: rgba(0,0,0,0);
  1082. }
  1083. .clickable {
  1084. color: blue;
  1085. text-decoration: underline;
  1086. cursor: pointer;
  1087. }
  1088. </style>