Reader.vue 48 KB

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