Reader.vue 48 KB

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