Reader.vue 47 KB

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