ExternalLibs.vue 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. <template>
  2. <Window ref="window" margin="2px" @close="close">
  3. <template #header>
  4. {{ header }}
  5. </template>
  6. <template #buttons>
  7. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="fullScreenToggle">
  8. <q-icon :name="(fullScreenActive ? 'la la-compress-arrows-alt': 'la la-expand-arrows-alt')" size="16px" />
  9. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">На весь экран</q-tooltip>
  10. </span>
  11. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="changeScale(0.1)">
  12. <q-icon name="la la-plus" size="16px" />
  13. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Увеличить масштаб</q-tooltip>
  14. </span>
  15. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="changeScale(-0.1)">
  16. <q-icon name="la la-minus" size="16px" />
  17. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Уменьшить масштаб</q-tooltip>
  18. </span>
  19. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="showHelp">
  20. <q-icon name="la la-question-circle" size="16px" />
  21. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Справка</q-tooltip>
  22. </span>
  23. </template>
  24. <div v-show="ready" class="col column" style="min-width: 600px">
  25. <div class="row items-center q-px-sm" style="height: 50px">
  26. <q-select
  27. ref="rootLink"
  28. v-model="rootLink"
  29. class="q-mr-sm"
  30. :options="rootLinkOptions"
  31. style="width: 230px"
  32. dropdown-icon="la la-angle-down la-sm"
  33. rounded outlined dense emit-value map-options display-value-sanitize options-sanitize
  34. @input="rootLinkInput"
  35. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  36. >
  37. <template #prepend>
  38. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-plus" size="12px" @click.stop="addBookmark">
  39. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  40. Добавить закладку
  41. </q-tooltip>
  42. </q-btn>
  43. <q-btn round dense color="blue" icon="la la-bars" size="12px" @click.stop="bookmarkSettings">
  44. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  45. Настроить закладки
  46. </q-tooltip>
  47. </q-btn>
  48. </template>
  49. <template #selected>
  50. <div style="overflow: hidden; white-space: nowrap;">
  51. {{ rootLinkWithoutProtocol }}
  52. </div>
  53. </template>
  54. </q-select>
  55. <q-select
  56. ref="selectedLink"
  57. v-model="selectedLink"
  58. class="q-mr-sm"
  59. :options="selectedLinkOptions"
  60. style="width: 50px"
  61. dropdown-icon="la la-angle-down la-sm"
  62. rounded outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  63. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  64. @input="selectedLinkInput"
  65. >
  66. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  67. Закладки
  68. </q-tooltip>
  69. </q-select>
  70. <q-input
  71. ref="input"
  72. v-model="bookUrl"
  73. class="col q-mr-sm"
  74. rounded outlined dense
  75. bg-color="white"
  76. placeholder="Скопируйте сюда URL книги"
  77. @focus="selectAllOnFocus" @keydown="bookUrlKeyDown"
  78. >
  79. <template #prepend>
  80. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-home" size="12px" @click="goToLink(selectedLink)">
  81. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  82. Вернуться на стартовую страницу
  83. </q-tooltip>
  84. </q-btn>
  85. <q-btn :disabled="!bookUrl" round dense color="blue" icon="la la-angle-double-down" size="12px" @click="openBookUrlInFrame">
  86. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  87. Загрузить URL во фрейм
  88. </q-tooltip>
  89. </q-btn>
  90. </template>
  91. <template #append>
  92. <q-btn round dense color="blue" icon="la la-cog" size="12px" @click.stop="optionsVisible = true">
  93. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  94. Опции
  95. </q-tooltip>
  96. </q-btn>
  97. </template>
  98. </q-input>
  99. <q-btn :disabled="!bookUrl" rounded color="green-7" no-caps size="14px" @click="submitUrl">
  100. Открыть
  101. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  102. Открыть в читалке
  103. </q-tooltip>
  104. </q-btn>
  105. </div>
  106. <div class="separator"></div>
  107. <div ref="frameBox" class="col fit" style="position: relative;">
  108. <div ref="frameWrap" class="overflow-hidden">
  109. <iframe v-if="frameVisible" ref="frame" :src="frameSrc" frameborder="0"></iframe>
  110. </div>
  111. <div v-show="transparentLayoutVisible" ref="transparentLayout" class="fit transparent-layout" @click="transparentLayoutClick"></div>
  112. </div>
  113. <Dialog ref="dialogAddBookmark" v-model="addBookmarkVisible">
  114. <template #header>
  115. <div class="row items-center">
  116. <q-icon class="q-mr-sm" name="la la-bookmark" size="28px"></q-icon>
  117. <div v-if="addBookmarkMode == 'edit'">
  118. Редактировать закладку
  119. </div>
  120. <div v-else>
  121. Добавить закладку
  122. </div>
  123. </div>
  124. </template>
  125. <div class="q-mx-md row">
  126. <q-input
  127. ref="bookmarkLink"
  128. v-model="bookmarkLink"
  129. class="col q-mr-sm"
  130. outlined dense
  131. bg-color="white"
  132. placeholder="Ссылка для закладки" maxlength="2000" @focus="selectAllOnFocus" @keydown="bookmarkLinkKeyDown"
  133. >
  134. </q-input>
  135. <q-select
  136. ref="defaultRootLink"
  137. v-model="defaultRootLink"
  138. class="q-mr-sm"
  139. :options="defaultRootLinkOptions"
  140. style="width: 50px"
  141. dropdown-icon="la la-angle-down la-sm"
  142. outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  143. @input="defaultRootLinkInput"
  144. >
  145. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">
  146. Предустановленные ссылки
  147. </q-tooltip>
  148. </q-select>
  149. </div>
  150. <div class="q-mx-md q-mt-md">
  151. <q-input
  152. ref="bookmarkDesc"
  153. v-model="bookmarkDesc"
  154. class="col q-mr-sm"
  155. outlined dense
  156. bg-color="white"
  157. placeholder="Описание" style="width: 400px" maxlength="100" @focus="selectAllOnFocus" @keydown="bookmarkDescKeyDown"
  158. >
  159. </q-input>
  160. </div>
  161. <template #footer>
  162. <q-btn v-close-popup class="q-px-md q-ml-sm" dense no-caps>
  163. Отмена
  164. </q-btn>
  165. <q-btn :disabled="!bookmarkLink" class="q-px-md q-ml-sm" color="primary" dense no-caps @click="okAddBookmark">
  166. OK
  167. </q-btn>
  168. </template>
  169. </Dialog>
  170. <Dialog ref="options" v-model="optionsVisible">
  171. <template #header>
  172. <div class="row items-center">
  173. <q-icon class="q-mr-sm" name="la la-cog" size="28px"></q-icon>
  174. Опции
  175. </div>
  176. </template>
  177. <div class="q-mx-md column">
  178. <q-checkbox v-model="closeAfterSubmit" size="36px" label="Закрыть окно при отправке ссылки в читалку" />
  179. <q-checkbox v-model="openInFrameOnEnter" size="36px" label="Открывать ссылку во фрейме при нажатии 'Enter'" />
  180. <q-checkbox v-model="openInFrameOnAdd" size="36px" label="Активировать новую закладку после добавления" />
  181. </div>
  182. <template #footer>
  183. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="optionsVisible = false">
  184. OK
  185. </q-btn>
  186. </template>
  187. </Dialog>
  188. </div>
  189. <BookmarkSettings
  190. v-if="bookmarkSettingsActive"
  191. ref="bookmarkSettings"
  192. :libs="libs"
  193. :add-bookmark-visible="addBookmarkVisible"
  194. @do-action="doAction" @close="closeBookmarkSettings"
  195. >
  196. </BookmarkSettings>
  197. </Window>
  198. </template>
  199. <script>
  200. //-----------------------------------------------------------------------------
  201. import vueComponent from '../vueComponent.js';
  202. import _ from 'lodash';
  203. import Window from '../share/Window.vue';
  204. import Dialog from '../share/Dialog.vue';
  205. import BookmarkSettings from './BookmarkSettings/BookmarkSettings.vue';
  206. import rstore from '../../store/modules/reader';
  207. import * as utils from '../../share/utils';
  208. import * as lu from './linkUtils';
  209. const proxySubst = {
  210. 'http://flibusta.is': 'http://b.liberama.top:23480',
  211. 'http://fantasy-worlds.org': 'http://b.liberama.top:23580',
  212. };
  213. const componentOptions = {
  214. components: {
  215. Window,
  216. Dialog,
  217. BookmarkSettings
  218. },
  219. watch: {
  220. libs: function() {
  221. this.loadLibs();
  222. },
  223. defaultRootLink: function() {
  224. this.updateBookmarkLink();
  225. },
  226. bookUrl: function(newValue) {
  227. const value = lu.addProtocol(newValue);
  228. const subst = this.makeProxySubst(value, true);
  229. if (value != subst) {
  230. this.$nextTick(() => {
  231. this.bookUrl = subst;
  232. });
  233. }
  234. },
  235. bookmarkLink: function(newValue) {
  236. const value = lu.addProtocol(newValue);
  237. const subst = this.makeProxySubst(value, true);
  238. if (value != subst) {
  239. this.$nextTick(() => {
  240. this.bookmarkLink = subst;
  241. });
  242. }
  243. },
  244. closeAfterSubmit: function(newValue) {
  245. this.commitProp('closeAfterSubmit', newValue);
  246. },
  247. openInFrameOnEnter: function(newValue) {
  248. this.commitProp('openInFrameOnEnter', newValue);
  249. },
  250. openInFrameOnAdd: function(newValue) {
  251. this.commitProp('openInFrameOnAdd', newValue);
  252. },
  253. }
  254. };
  255. class ExternalLibs {
  256. _options = componentOptions;
  257. ready = false;
  258. frameVisible = false;
  259. rootLink = '';
  260. selectedLink = '';
  261. frameSrc = '';
  262. bookUrl = '';
  263. libs = {};
  264. fullScreenActive = false;
  265. transparentLayoutVisible = false;
  266. addBookmarkVisible = false;
  267. optionsVisible = false;
  268. addBookmarkMode = '';
  269. bookmarkLink = '';
  270. bookmarkDesc = '';
  271. defaultRootLink = '';
  272. bookmarkSettingsActive = false;
  273. closeAfterSubmit = false;
  274. openInFrameOnEnter = false;
  275. openInFrameOnAdd = false;
  276. frameScale = 1;
  277. created() {
  278. this.oldStartLink = '';
  279. this.justOpened = true;
  280. this.$root.addEventHook('key', this.keyHook);
  281. this.$root.addEventHook('resize', async() => {
  282. await utils.sleep(200);
  283. this.frameResize();
  284. });
  285. document.addEventListener('fullscreenchange', () => {
  286. this.fullScreenActive = (document.fullscreenElement !== null);
  287. });
  288. this.debouncedGoToLink = _.debounce((link) => {
  289. this.goToLink(link);
  290. }, 100, {'maxWait':200});
  291. //this.commit = this.$store.commit;
  292. //this.commit('reader/setLibs', rstore.libsDefaults);
  293. }
  294. mounted() {
  295. //Поправка метода toggleOption компонента select фреймворка quasar, необходимо другое поведение
  296. //$emit('input'.. вызывается всегда
  297. this.toggleOption = function(opt, keepOpen) {
  298. if (this.editable !== true || opt === void 0 || this.isOptionDisabled(opt) === true) {
  299. return;
  300. }
  301. const optValue = this.getOptionValue(opt);
  302. if (this.multiple !== true) {
  303. if (keepOpen !== true) {
  304. this.updateInputValue(this.fillInput === true ? this.getOptionLabel(opt) : '', true, true);
  305. this.hidePopup();
  306. }
  307. this.$refs.target !== void 0 && this.$refs.target.focus();
  308. this.$emit('input', this.emitValue === true ? optValue : opt);
  309. }
  310. };
  311. this.$refs.rootLink.toggleOption = this.toggleOption;
  312. this.$refs.selectedLink.toggleOption = this.toggleOption;
  313. (async() => {
  314. //подождем this.mode
  315. let i = 0;
  316. while(!this.mode && i < 100) {
  317. await utils.sleep(100);
  318. i++;
  319. }
  320. if (this.mode != 'liberama.top') {
  321. this.$router.replace('/404');
  322. return;
  323. }
  324. this.$refs.window.init();
  325. this.opener = null;
  326. const host = window.location.host;
  327. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  328. const openerOrigin1 = `http://${openerHost}`;
  329. const openerOrigin2 = `https://${openerHost}`;
  330. window.addEventListener('message', (event) => {
  331. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  332. return;
  333. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  334. return;
  335. if (event.origin == openerOrigin1)
  336. this.opener = window.opener;
  337. else
  338. this.opener = event.source;
  339. this.openerOrigin = event.origin;
  340. //console.log(event);
  341. this.recvMessage(event.data);
  342. });
  343. //Ожидаем родителя
  344. i = 0;
  345. while(!this.opener) {
  346. await utils.sleep(1000);
  347. i++;
  348. if (i >= 5) {
  349. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  350. window.close();
  351. }
  352. }
  353. //Проверка закрытия родительского окна
  354. while(this.opener) {
  355. await this.checkOpener();
  356. await utils.sleep(1000);
  357. }
  358. })();
  359. }
  360. recvMessage(d) {
  361. if (d.type == 'mes') {
  362. switch(d.data) {
  363. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  364. }
  365. } else if (d.type == 'libs') {
  366. this.ready = true;
  367. this.libs = _.cloneDeep(d.data);
  368. } else if (d.type == 'notify') {
  369. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  370. }
  371. }
  372. sendMessage(d) {
  373. (async() => {
  374. await this.checkOpener();
  375. if (this.opener && this.openerOrigin)
  376. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  377. })();
  378. }
  379. async checkOpener() {
  380. if (this.opener.closed) {
  381. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  382. window.close();
  383. }
  384. }
  385. commitLibs(libs) {
  386. this.sendMessage({type: 'libs', data: libs});
  387. }
  388. commitProp(prop, value) {
  389. let libs = _.cloneDeep(this.libs);
  390. libs[prop] = value;
  391. this.commitLibs(libs);
  392. }
  393. loadLibs() {
  394. const libs = this.libs;
  395. if (!libs.helpShowed) {
  396. this.showHelp();
  397. (async() => {
  398. await utils.sleep(1000);
  399. this.commitProp('helpShowed', true);
  400. })();
  401. }
  402. this.selectedLink = libs.startLink;
  403. this.closeAfterSubmit = libs.closeAfterSubmit || false;
  404. this.openInFrameOnEnter = libs.openInFrameOnEnter || false;
  405. this.openInFrameOnAdd = libs.openInFrameOnAdd || false;
  406. this.frameScale = 1;
  407. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  408. if (index >= 0)
  409. this.frameScale = this.libs.groups[index].frameScale || 1;
  410. this.updateStartLink();
  411. }
  412. doAction(event) {
  413. switch (event.action) {
  414. case 'setLibs': this.commitLibs(event.data); break;
  415. case 'setRootLink': this.rootLink = event.data; this.rootLinkInput(); break;
  416. case 'setSelectedLink': this.selectedLink = event.data; this.selectedLinkInput(); break;
  417. case 'editBookmark': this.addBookmark('edit', event.data.link, event.data.desc); break;
  418. case 'addBookmark': this.addBookmark('add'); break;
  419. }
  420. }
  421. get mode() {
  422. return this.$store.state.config.mode;
  423. }
  424. get header() {
  425. let result = (this.ready ? 'Сетевая библиотека' : 'Загрузка...');
  426. if (this.ready && this.selectedLink) {
  427. result += ` | ${(this.libs.comment ? this.libs.comment + ' ': '') + lu.removeProtocol(this.libs.startLink)}`;
  428. }
  429. this.$root.setAppTitle(result);
  430. return result;
  431. }
  432. get rootLinkWithoutProtocol() {
  433. return lu.removeProtocol(this.rootLink);
  434. }
  435. updateSelectedLinkByRoot() {
  436. if (!this.ready)
  437. return;
  438. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  439. if (index >= 0)
  440. this.selectedLink = this.libs.groups[index].s;
  441. else
  442. this.selectedLink = '';
  443. }
  444. updateStartLink(force) {
  445. if (!this.ready)
  446. return;
  447. let index = -1;
  448. try {
  449. this.rootLink = lu.getOrigin(this.selectedLink);
  450. index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  451. } catch(e) {
  452. //
  453. }
  454. if (index >= 0) {
  455. let libs = _.cloneDeep(this.libs);
  456. const com = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  457. if (libs.groups[index].s != this.selectedLink ||
  458. libs.startLink != this.selectedLink ||
  459. libs.comment != com) {
  460. libs.groups[index].s = this.selectedLink;
  461. libs.startLink = this.selectedLink;
  462. libs.comment = com;
  463. this.commitLibs(libs);
  464. }
  465. if (force || this.oldStartLink != libs.startLink) {
  466. this.oldStartLink = libs.startLink;
  467. this.debouncedGoToLink(this.selectedLink);
  468. }
  469. } else {
  470. this.rootLink = '';
  471. this.selectedLink = '';
  472. this.debouncedGoToLink(this.selectedLink);
  473. }
  474. }
  475. get rootLinkOptions() {
  476. let result = [];
  477. if (!this.ready)
  478. return result;
  479. this.libs.groups.forEach(group => {
  480. result.push({label: lu.removeProtocol(group.r), value: group.r});
  481. });
  482. return result;
  483. }
  484. get defaultRootLinkOptions() {
  485. let result = [];
  486. rstore.libsDefaults.groups.forEach(group => {
  487. result.push({label: lu.removeProtocol(group.r), value: group.r});
  488. });
  489. return result;
  490. }
  491. get selectedLinkOptions() {
  492. let result = [];
  493. if (!this.ready)
  494. return result;
  495. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  496. if (index >= 0) {
  497. this.libs.groups[index].list.forEach(link => {
  498. result.push({label: (link.c ? link.c + ' ': '') + lu.removeOrigin(link.l), value: link.l});
  499. });
  500. }
  501. return result;
  502. }
  503. openBookUrlInFrame() {
  504. if (this.bookUrl) {
  505. this.goToLink(lu.addProtocol(this.bookUrl));
  506. }
  507. }
  508. goToLink(link) {
  509. if (!this.ready || !link)
  510. return;
  511. if (!link) {
  512. this.frameVisible = false;
  513. return;
  514. }
  515. this.frameSrc = this.makeProxySubst(link);
  516. this.frameVisible = false;
  517. this.$nextTick(() => {
  518. this.frameVisible = true;
  519. this.$nextTick(() => {
  520. if (this.$refs.frame) {
  521. this.$refs.frame.contentWindow.focus();
  522. this.frameResize();
  523. }
  524. });
  525. });
  526. }
  527. frameResize() {
  528. this.$refs.frameWrap.style = 'width: 1px; height: 1px;';
  529. this.$nextTick(() => {
  530. if (this.$refs.frame) {
  531. const w = this.$refs.frameBox.offsetWidth;
  532. const h = this.$refs.frameBox.offsetHeight;
  533. const normalSize = `width: ${w}px; height: ${h}px;`;
  534. this.$refs.frameWrap.style = normalSize;
  535. if (this.frameScale != 1) {
  536. const s = this.frameScale;
  537. this.$refs.frame.style = `width: ${w/s}px; height: ${h/s}px; transform: scale(${s}); transform-origin: 0 0;`;
  538. } else {
  539. this.$refs.frame.style = normalSize;
  540. }
  541. }
  542. });
  543. }
  544. changeScale(delta) {
  545. if ((this.frameScale > 0.1 && delta <= 0) || (this.frameScale < 5 && delta >= 0)) {
  546. this.frameScale = _.round(this.frameScale + delta, 1);
  547. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  548. if (index >= 0) {
  549. let libs = _.cloneDeep(this.libs);
  550. libs.groups[index].frameScale = this.frameScale;
  551. this.commitLibs(libs);
  552. }
  553. this.frameResize();
  554. this.$root.notify.success(`Масштаб изменен: ${(this.frameScale*100).toFixed(0)}%`, '', {position: 'bottom-right'});
  555. }
  556. }
  557. getCommentByLink(list, link) {
  558. const item = lu.getListItemByLink(list, link);
  559. return (item ? item.c : '');
  560. }
  561. makeProxySubst(url, reverse = false) {
  562. for (const [key, value] of Object.entries(proxySubst)) {
  563. if (reverse && value == url.substring(0, value.length)) {
  564. return key + url.substring(value.length);
  565. } else if (!reverse && key == url.substring(0, key.length)) {
  566. return value + url.substring(key.length);
  567. }
  568. }
  569. return url;
  570. }
  571. selectAllOnFocus(event) {
  572. if (event.target.select)
  573. event.target.select();
  574. }
  575. rootLinkInput() {
  576. this.updateSelectedLinkByRoot();
  577. this.updateStartLink(true);
  578. }
  579. selectedLinkInput() {
  580. this.updateStartLink(true);
  581. }
  582. submitUrl() {
  583. if (this.bookUrl) {
  584. this.sendMessage({type: 'submitUrl', data: {
  585. url: this.bookUrl,
  586. force: true
  587. }});
  588. this.bookUrl = '';
  589. if (this.closeAfterSubmit)
  590. this.close();
  591. }
  592. }
  593. addBookmark(mode = 'add', link = '', desc = '') {
  594. if (mode == 'edit') {
  595. this.editBookmarkLink = this.bookmarkLink = link;
  596. this.editBookmarkDesc = this.bookmarkDesc = desc;
  597. } else {
  598. this.bookmarkLink = this.bookUrl;
  599. this.bookmarkDesc = '';
  600. }
  601. this.addBookmarkMode = mode;
  602. this.addBookmarkVisible = true;
  603. this.$nextTick(() => {
  604. this.$refs.bookmarkLink.focus();
  605. this.$refs.defaultRootLink.toggleOption = this.toggleOption;
  606. });
  607. }
  608. updateBookmarkLink() {
  609. const index = lu.getSafeRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  610. if (index >= 0) {
  611. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  612. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  613. } else {
  614. this.bookmarkLink = '';
  615. this.bookmarkDesc = '';
  616. }
  617. }
  618. defaultRootLinkInput() {
  619. this.updateBookmarkLink();
  620. }
  621. bookmarkLinkKeyDown(event) {
  622. if (event.key == 'Enter') {
  623. this.$refs.bookmarkDesc.focus();
  624. event.preventDefault();
  625. }
  626. }
  627. bookmarkDescKeyDown(event) {
  628. if (event.key == 'Enter') {
  629. event.stopPropagation();
  630. event.preventDefault();
  631. this.okAddBookmark();
  632. }
  633. }
  634. async okAddBookmark() {
  635. if (!this.bookmarkLink)
  636. return;
  637. const link = (this.addBookmarkMode == 'edit' ? lu.addProtocol(this.editBookmarkLink) : lu.addProtocol(this.bookmarkLink));
  638. let index = -1;
  639. try {
  640. index = lu.getRootIndexByUrl(this.libs.groups, link);
  641. } catch (e) {
  642. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  643. return;
  644. }
  645. let libs = _.cloneDeep(this.libs);
  646. //добавление
  647. //есть группа в закладках
  648. if (index >= 0) {
  649. const item = lu.getListItemByLink(libs.groups[index].list, link);
  650. //редактирование
  651. if (item && this.addBookmarkMode == 'edit') {
  652. if (item) {
  653. //редактируем
  654. item.l = link;
  655. item.c = this.bookmarkDesc;
  656. this.commitLibs(libs);
  657. } else {
  658. await this.$root.stdDialog.alert('Не удалось отредактировать закладку', 'Ошибка');
  659. }
  660. } else if (!item) {
  661. //добавляем
  662. if (libs.groups[index].list.length >= 100) {
  663. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  664. return;
  665. }
  666. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  667. if (this.openInFrameOnAdd) {
  668. libs.startLink = link;
  669. libs.comment = this.bookmarkDesc;
  670. }
  671. this.commitLibs(libs);
  672. } else if (item.c != this.bookmarkDesc) {
  673. if (await this.$root.stdDialog.confirm(`Такая закладка уже существует с другим описанием.<br>` +
  674. `Заменить '${this.$root.sanitize(item.c)}' на '${this.$root.sanitize(this.bookmarkDesc)}'?`, ' ')) {
  675. item.c = this.bookmarkDesc;
  676. this.commitLibs(libs);
  677. } else
  678. return;
  679. } else {
  680. await this.$root.stdDialog.alert('Такая закладка уже существует', ' ');
  681. return;
  682. }
  683. } else {//нет группы в закладках
  684. if (libs.groups.length >= 100) {
  685. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  686. return;
  687. }
  688. //добавляем сначала группу
  689. libs.groups.push({r: lu.getOrigin(link), s: link, list: []});
  690. index = lu.getSafeRootIndexByUrl(libs.groups, link);
  691. if (index >= 0)
  692. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  693. if (this.openInFrameOnAdd) {
  694. libs.startLink = link;
  695. libs.comment = this.bookmarkDesc;
  696. }
  697. this.commitLibs(libs);
  698. }
  699. this.addBookmarkVisible = false;
  700. }
  701. fullScreenToggle() {
  702. this.fullScreenActive = !this.fullScreenActive;
  703. if (this.fullScreenActive) {
  704. this.$q.fullscreen.request();
  705. } else {
  706. this.$q.fullscreen.exit();
  707. }
  708. }
  709. transparentLayoutClick() {
  710. this.transparentLayoutVisible = false;
  711. }
  712. onSelectPopupShow() {
  713. this.transparentLayoutVisible = true;
  714. }
  715. onSelectPopupHide() {
  716. this.transparentLayoutVisible = false;
  717. }
  718. close() {
  719. this.sendMessage({type: 'close'});
  720. }
  721. bookUrlKeyDown(event) {
  722. if (event.key == 'Enter') {
  723. if (!this.openInFrameOnEnter) {
  724. this.submitUrl();
  725. } else {
  726. if (this.bookUrl)
  727. this.goToLink(this.bookUrl);
  728. }
  729. event.preventDefault();
  730. }
  731. }
  732. bookmarkSettings() {
  733. this.bookmarkSettingsActive = true;
  734. this.$nextTick(() => {
  735. this.$refs.bookmarkSettings.init();
  736. });
  737. }
  738. closeBookmarkSettings() {
  739. this.bookmarkSettingsActive = false;
  740. }
  741. showHelp() {
  742. this.$root.stdDialog.alert(`
  743. <p>Окно 'Сетевая библиотека' позволяет открывать ссылки в читалке без переключения между окнами,
  744. что особенно актуально для мобильных устройств. Имеется возможность управлять закладками
  745. на понравившиеся ресурсы, книги или страницы авторов. Открытие ссылок и навигация происходят во фрейме, но,
  746. к сожалению, в нем открываются не все страницы.</p>
  747. <p>Доступ к сайтам <span style="color: blue">http://flibusta.is</span> и <span style="color: blue">http://fantasy-worlds.org</span> работает через прокси.
  748. <br><span style="color: red"><b>ПРЕДУПРЕЖДЕНИЕ!</b></span>
  749. Доступ предназначен только для просмотра и скачивания книг. Авторизоваться на этих сайтах
  750. из фрейма категорически не рекомендуется, т.к. ваше подключение не защищено и данные могут попасть
  751. к третьим лицам.
  752. </p>
  753. <p>Из-за проблем с безопасностью, навигация 'вперед-назад' во фрейме осуществляется с помощью контекстного меню правой кнопкой мыши.
  754. На мобильных устройствах для этого служит системная клавиша 'Назад (стрелка влево)' и опция 'Вперед (стрелка вправо)' в меню браузера.
  755. </p>
  756. <p>Приятного пользования ;-)
  757. </p>
  758. `, 'Справка', {iconName: 'la la-info-circle'});
  759. }
  760. keyHook(event) {
  761. if (this.$root.getRootRoute() == '/external-libs') {
  762. if (this.$root.stdDialog.active)
  763. return false;
  764. if (this.bookmarkSettingsActive && this.$refs.bookmarkSettings.keyHook(event))
  765. return true;
  766. if (this.addBookmarkVisible || this.optionsVisible)
  767. return false;
  768. if (event.type == 'keydown' && event.key == 'F4') {
  769. this.addBookmark();
  770. return true;
  771. }
  772. if (event.type == 'keydown' && event.key == 'Escape' &&
  773. (document.activeElement != this.$refs.rootLink.$refs.target || !this.$refs.rootLink.menu) &&
  774. (document.activeElement != this.$refs.selectedLink.$refs.target || !this.$refs.selectedLink.menu)
  775. ) {
  776. this.close();
  777. return true;
  778. }
  779. }
  780. return false;
  781. }
  782. }
  783. export default vueComponent(ExternalLibs);
  784. //-----------------------------------------------------------------------------
  785. </script>
  786. <style scoped>
  787. .separator {
  788. height: 1px;
  789. background-color: #A0A0A0;
  790. }
  791. .full-screen-button {
  792. width: 30px;
  793. height: 30px;
  794. cursor: pointer;
  795. }
  796. .full-screen-button:hover {
  797. background-color: #69C05F;
  798. }
  799. .transparent-layout {
  800. top: 0;
  801. left: 0;
  802. position: absolute;
  803. }
  804. </style>