Reader.vue 46 KB

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