Reader.vue 46 KB

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