Reader.vue 48 KB

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