ExternalLibs.vue 21 KB

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