ExternalLibs.vue 20 KB

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