ExternalLibs.vue 18 KB

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