ExternalLibs.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <template>
  2. <Window ref="window" @close="close">
  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" v-model="rootLink" :options="rootLinkOptions"
  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" v-model="selectedLink" :options="selectedLinkOptions" 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" v-model="defaultRootLink" :options="defaultRootLinkOptions" 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. //this.commit = this.$store.commit;
  134. //this.commit('reader/setLibs', rstore.libsDefaults);
  135. }
  136. mounted() {
  137. if (this.mode != 'liberama.top') {
  138. this.$router.replace('/404');
  139. return;
  140. }
  141. this.$refs.window.init();
  142. this.opener = null;
  143. const host = window.location.host;
  144. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  145. const openerOrigin1 = `http://${openerHost}`;
  146. const openerOrigin2 = `https://${openerHost}`;
  147. window.addEventListener('message', (event) => {
  148. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  149. return;
  150. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  151. return;
  152. if (event.origin == openerOrigin1)
  153. this.opener = window.opener;
  154. else
  155. this.opener = event.source;
  156. this.openerOrigin = event.origin;
  157. //console.log(event);
  158. this.recvMessage(event.data);
  159. });
  160. //Проверка закрытия родительского окна
  161. (async() => {
  162. let i = 0;
  163. while(!this.opener && i < 10) {
  164. await utils.sleep(1000);
  165. i++;
  166. }
  167. if (i >= 10) {
  168. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  169. window.close();
  170. }
  171. while(this.opener) {
  172. await this.checkOpener();
  173. await utils.sleep(1000);
  174. }
  175. })();
  176. }
  177. recvMessage(d) {
  178. if (d.type == 'mes') {
  179. switch(d.data) {
  180. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  181. }
  182. } else if (d.type == 'libs') {
  183. this.ready = true;
  184. this.libs = _.cloneDeep(d.data);
  185. if (!this.frameSrc)
  186. this.goToLink(this.libs.startLink);
  187. } else if (d.type == 'notify') {
  188. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  189. }
  190. }
  191. sendMessage(d) {
  192. (async() => {
  193. await this.checkOpener();
  194. if (this.opener && this.openerOrigin)
  195. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  196. })();
  197. }
  198. async checkOpener() {
  199. if (this.opener.closed) {
  200. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  201. window.close();
  202. }
  203. }
  204. commitLibs(libs) {
  205. this.sendMessage({type: 'libs', data: libs});
  206. }
  207. loadLibs() {
  208. const libs = this.libs;
  209. this.startLink = (libs.comment ? libs.comment + ' ': '') + this.removeProtocol(libs.startLink);
  210. this.rootLink = this.getOrigin(libs.startLink);
  211. this.updateSelectedLink();
  212. }
  213. get mode() {
  214. return this.$store.state.config.mode;
  215. }
  216. get header() {
  217. let result = (this.ready ? 'Библиотека' : 'Загрузка...');
  218. if (this.ready && this.startLink) {
  219. result += ` | ${this.startLink}`;
  220. }
  221. this.$root.$emit('set-app-title', result);
  222. return result;
  223. }
  224. updateSelectedLink() {
  225. if (!this.ready)
  226. return;
  227. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  228. if (index >= 0)
  229. this.selectedLink = this.libs.groups[index].s;
  230. }
  231. updateStartLink() {
  232. if (!this.ready)
  233. return;
  234. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  235. if (index >= 0) {
  236. let libs = _.cloneDeep(this.libs);
  237. libs.groups[index].s = this.selectedLink;
  238. libs.startLink = this.selectedLink;
  239. libs.comment = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  240. this.goToLink(this.selectedLink);
  241. this.commitLibs(libs);
  242. }
  243. }
  244. get rootLinkOptions() {
  245. let result = [];
  246. if (!this.ready)
  247. return result;
  248. this.libs.groups.forEach(group => {
  249. result.push({label: this.removeProtocol(group.r), value: group.r});
  250. });
  251. return result;
  252. }
  253. get defaultRootLinkOptions() {
  254. let result = [];
  255. rstore.libsDefaults.groups.forEach(group => {
  256. result.push({label: this.removeProtocol(group.r), value: group.r});
  257. });
  258. return result;
  259. }
  260. get selectedLinkOptions() {
  261. let result = [];
  262. if (!this.ready)
  263. return result;
  264. const index = this.getRootIndexByUrl(this.libs.groups, this.rootLink);
  265. if (index >= 0) {
  266. this.libs.groups[index].list.forEach(link => {
  267. result.push({label: (link.c ? link.c + ' ': '') + this.removeOrigin(link.l), value: link.l});
  268. });
  269. }
  270. return result;
  271. }
  272. openBookUrlInFrame() {
  273. if (this.bookUrl)
  274. this.goToLink(this.addProtocol(this.bookUrl));
  275. }
  276. goToLink(link) {
  277. if (!this.ready)
  278. return;
  279. this.frameSrc = this.makeProxySubst(link);
  280. this.frameVisible = false;
  281. this.$nextTick(() => {
  282. this.frameVisible = true;
  283. });
  284. }
  285. addProtocol(url) {
  286. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0))
  287. return 'http://' + url;
  288. return url;
  289. }
  290. removeProtocol(url) {
  291. return url.replace(/(^\w+:|^)\/\//, '');
  292. }
  293. getOrigin(url) {
  294. const parsed = new URL(url);
  295. return parsed.origin;
  296. }
  297. removeOrigin(url) {
  298. const parsed = new URL(url);
  299. const result = url.substring(parsed.origin.length);
  300. return (result ? result : '/');
  301. }
  302. getRootIndexByUrl(groups, url) {
  303. if (!this.ready)
  304. return -1;
  305. const origin = this.getOrigin(url);
  306. for (let i = 0; i < groups.length; i++) {
  307. if (groups[i].r == origin)
  308. return i;
  309. }
  310. return -1;
  311. }
  312. getListItemByLink(list, link) {
  313. for (const item of list) {
  314. if (item.l == link)
  315. return item;
  316. }
  317. return null;
  318. }
  319. getCommentByLink(list, link) {
  320. const item = this.getListItemByLink(list, link);
  321. return (item ? item.c : '');
  322. }
  323. makeProxySubst(url, reverse = false) {
  324. for (const [key, value] of Object.entries(proxySubst)) {
  325. if (reverse && value == url.substring(0, value.length)) {
  326. return key + url.substring(value.length);
  327. } else if (key == url.substring(0, key.length)) {
  328. return value + url.substring(key.length);
  329. }
  330. }
  331. return url;
  332. }
  333. onInputFocus(event) {
  334. event.target.select();
  335. }
  336. submitUrl() {
  337. if (this.bookUrl) {
  338. this.sendMessage({type: 'submitUrl', data: {
  339. url: this.makeProxySubst(this.addProtocol(this.bookUrl), true),
  340. force: true
  341. }});
  342. this.bookUrl = '';
  343. if (this.libs.closeAfterSubmit)
  344. this.close();
  345. }
  346. }
  347. addBookmark() {
  348. this.bookmarkLink = (this.bookUrl ? this.makeProxySubst(this.addProtocol(this.bookUrl), true) : '');
  349. this.bookmarkDesc = '';
  350. this.addBookmarkVisible = true;
  351. this.$nextTick(() => {
  352. this.$refs.bookmarkLink.focus();
  353. });
  354. }
  355. updateBookmarkLink() {
  356. const index = this.getRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  357. if (index >= 0) {
  358. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  359. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  360. } else {
  361. this.bookmarkLink = '';
  362. this.bookmarkDesc = '';
  363. }
  364. }
  365. async okAddBookmark() {
  366. const link = this.addProtocol(this.bookmarkLink);
  367. let index = -1;
  368. try {
  369. index = this.getRootIndexByUrl(this.libs.groups, link);
  370. } catch (e) {
  371. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  372. return;
  373. }
  374. //есть группа в закладках
  375. if (index >= 0) {
  376. const item = this.getListItemByLink(this.libs.groups[index].list, link);
  377. if (!item || item.c != this.bookmarkDesc) {
  378. //добавляем
  379. let libs = _.cloneDeep(this.libs);
  380. if (libs.groups[index].list.length >= 100) {
  381. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  382. return;
  383. }
  384. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  385. this.commitLibs(libs);
  386. }
  387. } else {//нет группы в закладках
  388. let libs = _.cloneDeep(this.libs);
  389. if (libs.groups.length >= 100) {
  390. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  391. return;
  392. }
  393. //добавляем сначала группу
  394. libs.groups.push({r: this.getOrigin(link), s: link, list: []});
  395. index = this.getRootIndexByUrl(libs.groups, link);
  396. if (index >= 0)
  397. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  398. this.commitLibs(libs);
  399. }
  400. this.addBookmarkVisible = false;
  401. }
  402. bookmarkSettings() {
  403. }
  404. fullScreenToggle() {
  405. this.fullScreenActive = !this.fullScreenActive;
  406. if (this.fullScreenActive) {
  407. this.$q.fullscreen.request();
  408. } else {
  409. this.$q.fullscreen.exit();
  410. }
  411. }
  412. close() {
  413. this.sendMessage({type: 'close'});
  414. }
  415. keyHook() {
  416. if (this.$root.rootRoute() == '/external-libs') {
  417. if (this.$refs.dialogAddBookmark.active)
  418. return false;
  419. //недостатки сторонних ui
  420. const input = this.$refs.input.$refs.input;
  421. if (document.activeElement === input && event.type == 'keydown' && event.code == 'Enter') {
  422. this.submitUrl();
  423. return true;
  424. }
  425. if (event.type == 'keydown' && (event.code == 'Escape')) {
  426. this.close();
  427. }
  428. return true;
  429. }
  430. return false;
  431. }
  432. }
  433. //-----------------------------------------------------------------------------
  434. </script>
  435. <style scoped>
  436. .separator {
  437. height: 1px;
  438. background-color: #A0A0A0;
  439. }
  440. .full-screen-button {
  441. width: 30px;
  442. height: 30px;
  443. cursor: pointer;
  444. }
  445. .full-screen-button:hover {
  446. background-color: #69C05F;
  447. }
  448. </style>