Reader.vue 47 KB

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