ExternalLibs.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. <template>
  2. <Window ref="window" @close="close" margin="2px">
  3. <template slot="header">
  4. {{ header }}
  5. </template>
  6. <template slot="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. </template>
  12. <div v-show="ready" class="col column" style="min-width: 600px">
  13. <div class="row items-center q-px-sm" style="height: 50px">
  14. <q-select class="q-mr-sm" ref="rootLink" v-model="rootLink" :options="rootLinkOptions" @input="rootLinkInput"
  15. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  16. style="width: 230px"
  17. dropdown-icon="la la-angle-down la-sm"
  18. rounded outlined dense emit-value map-options display-value-sanitize options-sanitize
  19. >
  20. <template v-slot:prepend>
  21. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-plus" @click.stop="addBookmark" size="12px">
  22. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Добавить закладку</q-tooltip>
  23. </q-btn>
  24. <q-btn round dense color="blue" icon="la la-bars" @click.stop="bookmarkSettings" size="12px">
  25. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Настроить закладки</q-tooltip>
  26. </q-btn>
  27. </template>
  28. <template v-slot:selected>
  29. <div style="overflow: hidden; white-space: nowrap;">{{ rootLinkWithoutProtocol }}</div>
  30. </template>
  31. </q-select>
  32. <q-select class="q-mr-sm" ref="selectedLink" v-model="selectedLink" :options="selectedLinkOptions" @input="selectedLinkInput" style="width: 50px"
  33. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  34. dropdown-icon="la la-angle-down la-sm"
  35. rounded outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  36. >
  37. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Закладки</q-tooltip>
  38. </q-select>
  39. <q-input class="col q-mr-sm" ref="input" rounded outlined dense bg-color="white" v-model="bookUrl" placeholder="Скопируйте сюда URL книги"
  40. @focus="selectAllOnFocus" @keydown="bookUrlKeyDown"
  41. >
  42. <template v-slot:prepend>
  43. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-home" @click="goToLink(libs.startLink)" size="12px">
  44. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Вернуться на стартовую страницу</q-tooltip>
  45. </q-btn>
  46. <q-btn round dense color="blue" icon="la la-angle-double-down" @click="openBookUrlInFrame" size="12px" :disabled="!bookUrl">
  47. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Загрузить URL во фрейм</q-tooltip>
  48. </q-btn>
  49. </template>
  50. </q-input>
  51. <q-btn rounded color="green-7" no-caps size="14px" @click="submitUrl">Открыть
  52. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Открыть в читалке</q-tooltip>
  53. </q-btn>
  54. </div>
  55. <div class="separator"></div>
  56. <div class="col fit" style="position: relative;">
  57. <iframe v-if="frameVisible" class="fit" ref="frame" :src="frameSrc" frameborder="0"></iframe>
  58. <div v-show="transparentLayoutVisible" ref="transparentLayout" class="fit transparent-layout" @click="transparentLayoutClick"></div>
  59. </div>
  60. <Dialog ref="dialogAddBookmark" v-model="addBookmarkVisible">
  61. <template slot="header">
  62. <div class="row items-center">
  63. <q-icon class="q-mr-sm" name="la la-bookmark" size="28px"></q-icon>
  64. Добавить закладку
  65. </div>
  66. </template>
  67. <div class="q-mx-md row">
  68. <q-input ref="bookmarkLink" class="col q-mr-sm" outlined dense bg-color="white" v-model="bookmarkLink" @keydown="bookmarkLinkKeyDown"
  69. placeholder="Ссылка для закладки" maxlength="2000" @focus="selectAllOnFocus">
  70. </q-input>
  71. <q-select class="q-mr-sm" ref="defaultRootLink" v-model="defaultRootLink" :options="defaultRootLinkOptions" @input="defaultRootLinkInput" style="width: 50px"
  72. dropdown-icon="la la-angle-down la-sm"
  73. outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  74. >
  75. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Предустановленные ссылки</q-tooltip>
  76. </q-select>
  77. </div>
  78. <div class="q-mx-md q-mt-md">
  79. <q-input class="col q-mr-sm" ref="bookmarkDesc" outlined dense bg-color="white" v-model="bookmarkDesc" @keydown="bookmarkDescKeyDown"
  80. placeholder="Описание" style="width: 400px" maxlength="100" @focus="selectAllOnFocus">
  81. </q-input>
  82. </div>
  83. <template slot="footer">
  84. <q-btn class="q-px-md q-ml-sm" dense no-caps v-close-popup>Отмена</q-btn>
  85. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="okAddBookmark" :disabled="!bookmarkLink">OK</q-btn>
  86. </template>
  87. </Dialog>
  88. </div>
  89. <BookmarkSettings v-if="bookmarkSettingsActive" ref="bookmarkSettings" :libs="libs" @do-action="doAction" @close="closeBookmarkSettings"></BookmarkSettings>
  90. </Window>
  91. </template>
  92. <script>
  93. //-----------------------------------------------------------------------------
  94. import Vue from 'vue';
  95. import Component from 'vue-class-component';
  96. import _ from 'lodash';
  97. import Window from '../share/Window.vue';
  98. import Dialog from '../share/Dialog.vue';
  99. import BookmarkSettings from './BookmarkSettings/BookmarkSettings.vue';
  100. import rstore from '../../store/modules/reader';
  101. import * as utils from '../../share/utils';
  102. import * as lu from './linkUtils';
  103. const proxySubst = {
  104. 'http://flibusta.is': 'http://b.liberama.top:23480',
  105. };
  106. export default @Component({
  107. components: {
  108. Window,
  109. Dialog,
  110. BookmarkSettings
  111. },
  112. watch: {
  113. libs: function() {
  114. this.loadLibs();
  115. },
  116. rootLink: function() {
  117. this.updateSelectedLink();
  118. this.updateStartLink();
  119. },
  120. selectedLink: function() {
  121. this.updateStartLink();
  122. },
  123. defaultRootLink: function() {
  124. this.updateBookmarkLink();
  125. }
  126. }
  127. })
  128. class ExternalLibs extends Vue {
  129. ready = false;
  130. frameVisible = false;
  131. startLink = '';
  132. rootLink = '';
  133. selectedLink = '';
  134. frameSrc = '';
  135. bookUrl = '';
  136. libs = {};
  137. fullScreenActive = false;
  138. addBookmarkVisible = false;
  139. transparentLayoutVisible = false;
  140. bookmarkLink = '';
  141. bookmarkDesc = '';
  142. defaultRootLink = '';
  143. bookmarkSettingsActive = false;
  144. created() {
  145. this.$root.addKeyHook(this.keyHook);
  146. document.addEventListener('fullscreenchange', () => {
  147. this.fullScreenActive = (document.fullscreenElement !== null);
  148. });
  149. //this.commit = this.$store.commit;
  150. //this.commit('reader/setLibs', rstore.libsDefaults);
  151. }
  152. mounted() {
  153. //Поправка метода toggleOption компонента select фреймворка quasar, необходимо другое поведение
  154. //$emit('input'.. вызывается всегда
  155. this.toggleOption = function(opt, keepOpen) {
  156. if (this.editable !== true || opt === void 0 || this.isOptionDisabled(opt) === true) {
  157. return;
  158. }
  159. const optValue = this.getOptionValue(opt);
  160. if (this.multiple !== true) {
  161. if (keepOpen !== true) {
  162. this.updateInputValue(this.fillInput === true ? this.getOptionLabel(opt) : '', true, true);
  163. this.hidePopup();
  164. }
  165. this.$refs.target !== void 0 && this.$refs.target.focus();
  166. this.$emit('input', this.emitValue === true ? optValue : opt);
  167. }
  168. };
  169. this.$refs.rootLink.toggleOption = this.toggleOption;
  170. this.$refs.selectedLink.toggleOption = this.toggleOption;
  171. (async() => {
  172. //подождем this.mode
  173. let i = 0;
  174. while(!this.mode && i < 100) {
  175. await utils.sleep(100);
  176. i++;
  177. }
  178. if (this.mode != 'liberama.top') {
  179. this.$router.replace('/404');
  180. return;
  181. }
  182. this.$refs.window.init();
  183. this.opener = null;
  184. const host = window.location.host;
  185. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  186. const openerOrigin1 = `http://${openerHost}`;
  187. const openerOrigin2 = `https://${openerHost}`;
  188. window.addEventListener('message', (event) => {
  189. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  190. return;
  191. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  192. return;
  193. if (event.origin == openerOrigin1)
  194. this.opener = window.opener;
  195. else
  196. this.opener = event.source;
  197. this.openerOrigin = event.origin;
  198. //console.log(event);
  199. this.recvMessage(event.data);
  200. });
  201. //Ожидаем родителя
  202. i = 0;
  203. while(!this.opener) {
  204. await utils.sleep(1000);
  205. i++;
  206. if (i >= 5) {
  207. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  208. window.close();
  209. }
  210. }
  211. //Проверка закрытия родительского окна
  212. while(this.opener) {
  213. await this.checkOpener();
  214. await utils.sleep(1000);
  215. }
  216. })();
  217. }
  218. recvMessage(d) {
  219. if (d.type == 'mes') {
  220. switch(d.data) {
  221. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  222. }
  223. } else if (d.type == 'libs') {
  224. this.ready = true;
  225. this.libs = _.cloneDeep(d.data);
  226. if (!this.frameSrc)
  227. this.goToLink(this.libs.startLink);
  228. } else if (d.type == 'notify') {
  229. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  230. }
  231. }
  232. sendMessage(d) {
  233. (async() => {
  234. await this.checkOpener();
  235. if (this.opener && this.openerOrigin)
  236. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  237. })();
  238. }
  239. async checkOpener() {
  240. if (this.opener.closed) {
  241. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  242. window.close();
  243. }
  244. }
  245. commitLibs(libs) {
  246. this.sendMessage({type: 'libs', data: libs});
  247. }
  248. loadLibs() {
  249. const libs = this.libs;
  250. this.startLink = (libs.comment ? libs.comment + ' ': '') + lu.removeProtocol(libs.startLink);
  251. this.rootLink = lu.getOrigin(libs.startLink);
  252. this.updateSelectedLink();
  253. }
  254. doAction(event) {
  255. switch (event.action) {
  256. case 'setLibs': this.commitLibs(event.data); break;
  257. case 'setRootLink': this.rootLink = event.data; this.rootLinkInput(); break;
  258. case 'setSelectedLink': this.selectedLink = event.data; this.selectedLinkInput(); break;
  259. }
  260. }
  261. get mode() {
  262. return this.$store.state.config.mode;
  263. }
  264. get header() {
  265. let result = (this.ready ? 'Библиотека' : 'Загрузка...');
  266. if (this.ready && this.startLink) {
  267. result += ` | ${this.startLink}`;
  268. }
  269. this.$root.$emit('set-app-title', result);
  270. return result;
  271. }
  272. get rootLinkWithoutProtocol() {
  273. return lu.removeProtocol(this.rootLink);
  274. }
  275. updateSelectedLink() {
  276. if (!this.ready)
  277. return;
  278. const index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  279. if (index >= 0)
  280. this.selectedLink = this.libs.groups[index].s;
  281. }
  282. updateStartLink() {
  283. if (!this.ready)
  284. return;
  285. const index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  286. if (index >= 0) {
  287. let libs = _.cloneDeep(this.libs);
  288. libs.groups[index].s = this.selectedLink;
  289. libs.startLink = this.selectedLink;
  290. libs.comment = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  291. this.goToLink(this.selectedLink);
  292. this.commitLibs(libs);
  293. }
  294. }
  295. get rootLinkOptions() {
  296. let result = [];
  297. if (!this.ready)
  298. return result;
  299. this.libs.groups.forEach(group => {
  300. result.push({label: lu.removeProtocol(group.r), value: group.r});
  301. });
  302. return result;
  303. }
  304. get defaultRootLinkOptions() {
  305. let result = [];
  306. rstore.libsDefaults.groups.forEach(group => {
  307. result.push({label: lu.removeProtocol(group.r), value: group.r});
  308. });
  309. return result;
  310. }
  311. get selectedLinkOptions() {
  312. let result = [];
  313. if (!this.ready)
  314. return result;
  315. const index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  316. if (index >= 0) {
  317. this.libs.groups[index].list.forEach(link => {
  318. result.push({label: (link.c ? link.c + ' ': '') + lu.removeOrigin(link.l), value: link.l});
  319. });
  320. }
  321. return result;
  322. }
  323. openBookUrlInFrame() {
  324. if (this.bookUrl) {
  325. this.goToLink(lu.addProtocol(this.bookUrl));
  326. }
  327. }
  328. goToLink(link) {
  329. if (!this.ready)
  330. return;
  331. this.frameSrc = this.makeProxySubst(link);
  332. this.frameVisible = false;
  333. this.$nextTick(() => {
  334. this.frameVisible = true;
  335. this.$nextTick(() => {
  336. this.$refs.frame.contentWindow.focus();
  337. });
  338. });
  339. }
  340. getCommentByLink(list, link) {
  341. const item = lu.getListItemByLink(list, link);
  342. return (item ? item.c : '');
  343. }
  344. makeProxySubst(url, reverse = false) {
  345. for (const [key, value] of Object.entries(proxySubst)) {
  346. if (reverse && value == url.substring(0, value.length)) {
  347. return key + url.substring(value.length);
  348. } else if (key == url.substring(0, key.length)) {
  349. return value + url.substring(key.length);
  350. }
  351. }
  352. return url;
  353. }
  354. selectAllOnFocus(event) {
  355. if (event.target.select)
  356. event.target.select();
  357. }
  358. rootLinkInput() {
  359. this.updateSelectedLink();
  360. this.updateStartLink();
  361. }
  362. selectedLinkInput() {
  363. this.updateStartLink();
  364. }
  365. submitUrl() {
  366. if (this.bookUrl) {
  367. this.sendMessage({type: 'submitUrl', data: {
  368. url: this.makeProxySubst(lu.addProtocol(this.bookUrl), true),
  369. force: true
  370. }});
  371. this.bookUrl = '';
  372. if (this.libs.closeAfterSubmit)
  373. this.close();
  374. }
  375. }
  376. addBookmark() {
  377. this.bookmarkLink = (this.bookUrl ? this.makeProxySubst(lu.addProtocol(this.bookUrl), true) : '');
  378. this.bookmarkDesc = '';
  379. this.addBookmarkVisible = true;
  380. this.$nextTick(() => {
  381. this.$refs.bookmarkLink.focus();
  382. this.$refs.defaultRootLink.toggleOption = this.toggleOption;
  383. });
  384. }
  385. updateBookmarkLink() {
  386. const index = lu.getRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  387. if (index >= 0) {
  388. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  389. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  390. } else {
  391. this.bookmarkLink = '';
  392. this.bookmarkDesc = '';
  393. }
  394. }
  395. defaultRootLinkInput() {
  396. this.updateBookmarkLink();
  397. }
  398. bookmarkLinkKeyDown(event) {
  399. if (event.key == 'Enter') {
  400. this.$refs.bookmarkDesc.focus();
  401. event.preventDefault();
  402. }
  403. }
  404. bookmarkDescKeyDown(event) {
  405. if (event.key == 'Enter') {
  406. this.okAddBookmark();
  407. event.preventDefault();
  408. }
  409. }
  410. async okAddBookmark() {
  411. if (!this.bookmarkLink)
  412. return;
  413. const link = lu.addProtocol(this.bookmarkLink);
  414. let index = -1;
  415. try {
  416. index = lu.getRootIndexByUrl(this.libs.groups, link);
  417. } catch (e) {
  418. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  419. return;
  420. }
  421. //есть группа в закладках
  422. if (index >= 0) {
  423. const item = lu.getListItemByLink(this.libs.groups[index].list, link);
  424. if (!item || item.c != this.bookmarkDesc) {
  425. //добавляем
  426. let libs = _.cloneDeep(this.libs);
  427. if (libs.groups[index].list.length >= 100) {
  428. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  429. return;
  430. }
  431. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  432. this.commitLibs(libs);
  433. }
  434. } else {//нет группы в закладках
  435. let libs = _.cloneDeep(this.libs);
  436. if (libs.groups.length >= 100) {
  437. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  438. return;
  439. }
  440. //добавляем сначала группу
  441. libs.groups.push({r: lu.getOrigin(link), s: link, list: []});
  442. index = lu.getRootIndexByUrl(libs.groups, link);
  443. if (index >= 0)
  444. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  445. this.commitLibs(libs);
  446. }
  447. this.addBookmarkVisible = false;
  448. }
  449. fullScreenToggle() {
  450. this.fullScreenActive = !this.fullScreenActive;
  451. if (this.fullScreenActive) {
  452. this.$q.fullscreen.request();
  453. } else {
  454. this.$q.fullscreen.exit();
  455. }
  456. }
  457. transparentLayoutClick() {
  458. this.transparentLayoutVisible = false;
  459. }
  460. onSelectPopupShow() {
  461. this.transparentLayoutVisible = true;
  462. }
  463. onSelectPopupHide() {
  464. this.transparentLayoutVisible = false;
  465. }
  466. close() {
  467. this.sendMessage({type: 'close'});
  468. }
  469. bookUrlKeyDown(event) {
  470. if (event.key == 'Enter') {
  471. this.submitUrl();
  472. event.preventDefault();
  473. }
  474. }
  475. bookmarkSettings() {
  476. this.bookmarkSettingsActive = true;
  477. this.$nextTick(() => {
  478. this.$refs.bookmarkSettings.init();
  479. });
  480. }
  481. closeBookmarkSettings() {
  482. this.bookmarkSettingsActive = false;
  483. }
  484. keyHook(event) {
  485. if (this.$root.rootRoute() == '/external-libs') {
  486. if (this.bookmarkSettingsActive && this.$refs.bookmarkSettings.keyHook(event))
  487. return true;
  488. if (this.$refs.dialogAddBookmark.active)
  489. return false;
  490. if (event.type == 'keydown' && event.key == 'F4') {
  491. this.addBookmark();
  492. return true;
  493. }
  494. if (event.type == 'keydown' && event.key == 'Escape' &&
  495. (document.activeElement != this.$refs.rootLink.$refs.target || !this.$refs.rootLink.menu) &&
  496. (document.activeElement != this.$refs.selectedLink.$refs.target || !this.$refs.selectedLink.menu)
  497. ) {
  498. this.close();
  499. return true;
  500. }
  501. }
  502. return false;
  503. }
  504. }
  505. //-----------------------------------------------------------------------------
  506. </script>
  507. <style scoped>
  508. .separator {
  509. height: 1px;
  510. background-color: #A0A0A0;
  511. }
  512. .full-screen-button {
  513. width: 30px;
  514. height: 30px;
  515. cursor: pointer;
  516. }
  517. .full-screen-button:hover {
  518. background-color: #69C05F;
  519. }
  520. .transparent-layout {
  521. top: 0;
  522. left: 0;
  523. position: absolute;
  524. }
  525. </style>