ExternalLibs.vue 18 KB

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