ExternalLibs.vue 22 KB

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