Reader.vue 46 KB

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