ExternalLibs.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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;">{{ removeProtocol(rootLink) }}</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">
  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" @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. const proxySubst = {
  103. 'http://flibusta.is': 'http://b.liberama.top:23480',
  104. };
  105. export default @Component({
  106. components: {
  107. Window,
  108. Dialog,
  109. BookmarkSettings
  110. },
  111. watch: {
  112. libs: function() {
  113. this.loadLibs();
  114. },
  115. rootLink: function() {
  116. this.updateSelectedLink();
  117. this.updateStartLink();
  118. },
  119. selectedLink: function() {
  120. this.updateStartLink();
  121. },
  122. defaultRootLink: function() {
  123. this.updateBookmarkLink();
  124. }
  125. }
  126. })
  127. class ExternalLibs extends Vue {
  128. ready = false;
  129. frameVisible = false;
  130. startLink = '';
  131. rootLink = '';
  132. selectedLink = '';
  133. frameSrc = '';
  134. bookUrl = '';
  135. libs = {};
  136. fullScreenActive = false;
  137. addBookmarkVisible = false;
  138. transparentLayoutVisible = false;
  139. bookmarkLink = '';
  140. bookmarkDesc = '';
  141. defaultRootLink = '';
  142. bookmarkSettingsActive = false;
  143. created() {
  144. this.$root.addKeyHook(this.keyHook);
  145. document.addEventListener('fullscreenchange', () => {
  146. this.fullScreenActive = (document.fullscreenElement !== null);
  147. });
  148. //this.commit = this.$store.commit;
  149. //this.commit('reader/setLibs', rstore.libsDefaults);
  150. }
  151. mounted() {
  152. //Поправка метода toggleOption компонента select фреймворка quasar, необходимо другое поведение
  153. //$emit('input'.. вызывается всегда
  154. this.toggleOption = function(opt, keepOpen) {
  155. if (this.editable !== true || opt === void 0 || this.isOptionDisabled(opt) === true) {
  156. return;
  157. }
  158. const optValue = this.getOptionValue(opt);
  159. if (this.multiple !== true) {
  160. if (keepOpen !== true) {
  161. this.updateInputValue(this.fillInput === true ? this.getOptionLabel(opt) : '', true, true);
  162. this.hidePopup();
  163. }
  164. this.$refs.target !== void 0 && this.$refs.target.focus();
  165. this.$emit('input', this.emitValue === true ? optValue : opt);
  166. }
  167. };
  168. this.$refs.rootLink.toggleOption = this.toggleOption;
  169. this.$refs.selectedLink.toggleOption = this.toggleOption;
  170. (async() => {
  171. //подождем this.mode
  172. let i = 0;
  173. while(!this.mode && i < 100) {
  174. await utils.sleep(100);
  175. i++;
  176. }
  177. if (this.mode != 'liberama.top') {
  178. this.$router.replace('/404');
  179. return;
  180. }
  181. this.$refs.window.init();
  182. this.opener = null;
  183. const host = window.location.host;
  184. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  185. const openerOrigin1 = `http://${openerHost}`;
  186. const openerOrigin2 = `https://${openerHost}`;
  187. window.addEventListener('message', (event) => {
  188. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  189. return;
  190. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  191. return;
  192. if (event.origin == openerOrigin1)
  193. this.opener = window.opener;
  194. else
  195. this.opener = event.source;
  196. this.openerOrigin = event.origin;
  197. //console.log(event);
  198. this.recvMessage(event.data);
  199. });
  200. //Ожидаем родителя
  201. i = 0;
  202. while(!this.opener) {
  203. await utils.sleep(1000);
  204. i++;
  205. if (i >= 5) {
  206. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  207. window.close();
  208. }
  209. }
  210. //Проверка закрытия родительского окна
  211. while(this.opener) {
  212. await this.checkOpener();
  213. await utils.sleep(1000);
  214. }
  215. })();
  216. }
  217. recvMessage(d) {
  218. if (d.type == 'mes') {
  219. switch(d.data) {
  220. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  221. }
  222. } else if (d.type == 'libs') {
  223. this.ready = true;
  224. this.libs = _.cloneDeep(d.data);
  225. if (!this.frameSrc)
  226. this.goToLink(this.libs.startLink);
  227. } else if (d.type == 'notify') {
  228. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  229. }
  230. }
  231. sendMessage(d) {
  232. (async() => {
  233. await this.checkOpener();
  234. if (this.opener && this.openerOrigin)
  235. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  236. })();
  237. }
  238. async checkOpener() {
  239. if (this.opener.closed) {
  240. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  241. window.close();
  242. }
  243. }
  244. commitLibs(libs) {
  245. this.sendMessage({type: 'libs', data: libs});
  246. }
  247. loadLibs() {
  248. const libs = this.libs;
  249. this.startLink = (libs.comment ? libs.comment + ' ': '') + this.removeProtocol(libs.startLink);
  250. this.rootLink = this.getOrigin(libs.startLink);
  251. this.updateSelectedLink();
  252. }
  253. get mode() {
  254. return this.$store.state.config.mode;
  255. }
  256. get header() {
  257. let result = (this.ready ? 'Библиотека' : 'Загрузка...');
  258. if (this.ready && this.startLink) {
  259. result += ` | ${this.startLink}`;
  260. }
  261. this.$root.$emit('set-app-title', result);
  262. return result;
  263. }
  264. updateSelectedLink() {
  265. if (!this.ready)
  266. return;
  267. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  268. if (index >= 0)
  269. this.selectedLink = this.libs.groups[index].s;
  270. }
  271. updateStartLink() {
  272. if (!this.ready)
  273. return;
  274. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  275. if (index >= 0) {
  276. let libs = _.cloneDeep(this.libs);
  277. libs.groups[index].s = this.selectedLink;
  278. libs.startLink = this.selectedLink;
  279. libs.comment = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  280. this.goToLink(this.selectedLink);
  281. this.commitLibs(libs);
  282. }
  283. }
  284. get rootLinkOptions() {
  285. let result = [];
  286. if (!this.ready)
  287. return result;
  288. this.libs.groups.forEach(group => {
  289. result.push({label: this.removeProtocol(group.r), value: group.r});
  290. });
  291. return result;
  292. }
  293. get defaultRootLinkOptions() {
  294. let result = [];
  295. rstore.libsDefaults.groups.forEach(group => {
  296. result.push({label: this.removeProtocol(group.r), value: group.r});
  297. });
  298. return result;
  299. }
  300. get selectedLinkOptions() {
  301. let result = [];
  302. if (!this.ready)
  303. return result;
  304. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  305. if (index >= 0) {
  306. this.libs.groups[index].list.forEach(link => {
  307. result.push({label: (link.c ? link.c + ' ': '') + this.removeOrigin(link.l), value: link.l});
  308. });
  309. }
  310. return result;
  311. }
  312. openBookUrlInFrame() {
  313. if (this.bookUrl) {
  314. this.goToLink(this.addProtocol(this.bookUrl));
  315. }
  316. }
  317. goToLink(link) {
  318. if (!this.ready)
  319. return;
  320. this.frameSrc = this.makeProxySubst(link);
  321. this.frameVisible = false;
  322. this.$nextTick(() => {
  323. this.frameVisible = true;
  324. this.$nextTick(() => {
  325. this.$refs.frame.contentWindow.focus();
  326. });
  327. });
  328. }
  329. addProtocol(url) {
  330. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0))
  331. return 'http://' + url;
  332. return url;
  333. }
  334. removeProtocol(url) {
  335. return url.replace(/(^\w+:|^)\/\//, '');
  336. }
  337. getOrigin(url) {
  338. const parsed = new URL(url);
  339. return parsed.origin;
  340. }
  341. removeOrigin(url) {
  342. const parsed = new URL(url);
  343. const result = url.substring(parsed.origin.length);
  344. return (result ? result : '/');
  345. }
  346. getRootIndexByUrl(groups, url) {
  347. if (!this.ready)
  348. return -1;
  349. const origin = this.getOrigin(url);
  350. for (let i = 0; i < groups.length; i++) {
  351. if (groups[i].r == origin)
  352. return i;
  353. }
  354. return -1;
  355. }
  356. getListItemByLink(list, link) {
  357. for (const item of list) {
  358. if (item.l == link)
  359. return item;
  360. }
  361. return null;
  362. }
  363. getCommentByLink(list, link) {
  364. const item = this.getListItemByLink(list, link);
  365. return (item ? item.c : '');
  366. }
  367. makeProxySubst(url, reverse = false) {
  368. for (const [key, value] of Object.entries(proxySubst)) {
  369. if (reverse && value == url.substring(0, value.length)) {
  370. return key + url.substring(value.length);
  371. } else if (key == url.substring(0, key.length)) {
  372. return value + url.substring(key.length);
  373. }
  374. }
  375. return url;
  376. }
  377. selectAllOnFocus(event) {
  378. if (event.target.select)
  379. event.target.select();
  380. }
  381. rootLinkInput() {
  382. this.updateSelectedLink();
  383. this.updateStartLink();
  384. }
  385. selectedLinkInput() {
  386. this.updateStartLink();
  387. }
  388. submitUrl() {
  389. if (this.bookUrl) {
  390. this.sendMessage({type: 'submitUrl', data: {
  391. url: this.makeProxySubst(this.addProtocol(this.bookUrl), true),
  392. force: true
  393. }});
  394. this.bookUrl = '';
  395. if (this.libs.closeAfterSubmit)
  396. this.close();
  397. }
  398. }
  399. addBookmark() {
  400. this.bookmarkLink = (this.bookUrl ? this.makeProxySubst(this.addProtocol(this.bookUrl), true) : '');
  401. this.bookmarkDesc = '';
  402. this.addBookmarkVisible = true;
  403. this.$nextTick(() => {
  404. this.$refs.bookmarkLink.focus();
  405. this.$refs.defaultRootLink.toggleOption = this.toggleOption;
  406. });
  407. }
  408. updateBookmarkLink() {
  409. const index = this.getRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  410. if (index >= 0) {
  411. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  412. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  413. } else {
  414. this.bookmarkLink = '';
  415. this.bookmarkDesc = '';
  416. }
  417. }
  418. defaultRootLinkInput() {
  419. this.updateBookmarkLink();
  420. }
  421. bookmarkLinkKeyDown(event) {
  422. if (event.key == 'Enter') {
  423. this.$refs.bookmarkDesc.focus();
  424. event.preventDefault();
  425. }
  426. }
  427. bookmarkDescKeyDown(event) {
  428. if (event.key == 'Enter') {
  429. this.okAddBookmark();
  430. event.preventDefault();
  431. }
  432. }
  433. async okAddBookmark() {
  434. if (!this.bookmarkLink)
  435. return;
  436. const link = this.addProtocol(this.bookmarkLink);
  437. let index = -1;
  438. try {
  439. index = this.getRootIndexByUrl(this.libs.groups, link);
  440. } catch (e) {
  441. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  442. return;
  443. }
  444. //есть группа в закладках
  445. if (index >= 0) {
  446. const item = this.getListItemByLink(this.libs.groups[index].list, link);
  447. if (!item || item.c != this.bookmarkDesc) {
  448. //добавляем
  449. let libs = _.cloneDeep(this.libs);
  450. if (libs.groups[index].list.length >= 100) {
  451. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  452. return;
  453. }
  454. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  455. this.commitLibs(libs);
  456. }
  457. } else {//нет группы в закладках
  458. let libs = _.cloneDeep(this.libs);
  459. if (libs.groups.length >= 100) {
  460. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  461. return;
  462. }
  463. //добавляем сначала группу
  464. libs.groups.push({r: this.getOrigin(link), s: link, list: []});
  465. index = this.getRootIndexByUrl(libs.groups, link);
  466. if (index >= 0)
  467. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  468. this.commitLibs(libs);
  469. }
  470. this.addBookmarkVisible = false;
  471. }
  472. fullScreenToggle() {
  473. this.fullScreenActive = !this.fullScreenActive;
  474. if (this.fullScreenActive) {
  475. this.$q.fullscreen.request();
  476. } else {
  477. this.$q.fullscreen.exit();
  478. }
  479. }
  480. transparentLayoutClick() {
  481. this.transparentLayoutVisible = false;
  482. }
  483. onSelectPopupShow() {
  484. this.transparentLayoutVisible = true;
  485. }
  486. onSelectPopupHide() {
  487. this.transparentLayoutVisible = false;
  488. }
  489. close() {
  490. this.sendMessage({type: 'close'});
  491. }
  492. bookUrlKeyDown(event) {
  493. if (event.key == 'Enter') {
  494. this.submitUrl();
  495. event.preventDefault();
  496. }
  497. }
  498. bookmarkSettings() {
  499. this.bookmarkSettingsActive = true;
  500. this.$nextTick(() => {
  501. this.$refs.bookmarkSettings.init();
  502. });
  503. }
  504. closeBookmarkSettings() {
  505. this.bookmarkSettingsActive = false;
  506. }
  507. keyHook(event) {
  508. if (this.$root.rootRoute() == '/external-libs') {
  509. if (this.bookmarkSettingsActive && this.$refs.bookmarkSettings.keyHook(event))
  510. return true;
  511. if (this.$refs.dialogAddBookmark.active)
  512. return false;
  513. if (event.type == 'keydown' && event.key == 'F4') {
  514. this.addBookmark();
  515. return true;
  516. }
  517. if (event.type == 'keydown' && event.key == 'Escape' &&
  518. (document.activeElement != this.$refs.rootLink.$refs.target || !this.$refs.rootLink.menu) &&
  519. (document.activeElement != this.$refs.selectedLink.$refs.target || !this.$refs.selectedLink.menu)
  520. ) {
  521. this.close();
  522. return true;
  523. }
  524. }
  525. return false;
  526. }
  527. }
  528. //-----------------------------------------------------------------------------
  529. </script>
  530. <style scoped>
  531. .separator {
  532. height: 1px;
  533. background-color: #A0A0A0;
  534. }
  535. .full-screen-button {
  536. width: 30px;
  537. height: 30px;
  538. cursor: pointer;
  539. }
  540. .full-screen-button:hover {
  541. background-color: #69C05F;
  542. }
  543. .transparent-layout {
  544. top: 0;
  545. left: 0;
  546. position: absolute;
  547. }
  548. </style>