ExternalLibs.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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" 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. }
  287. goToLink(link) {
  288. if (!this.ready)
  289. return;
  290. this.frameSrc = this.makeProxySubst(link);
  291. this.frameVisible = false;
  292. this.$nextTick(() => {
  293. this.frameVisible = true;
  294. this.$nextTick(() => {
  295. this.$refs.frame.contentWindow.focus();
  296. });
  297. });
  298. }
  299. addProtocol(url) {
  300. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0))
  301. return 'http://' + url;
  302. return url;
  303. }
  304. removeProtocol(url) {
  305. return url.replace(/(^\w+:|^)\/\//, '');
  306. }
  307. getOrigin(url) {
  308. const parsed = new URL(url);
  309. return parsed.origin;
  310. }
  311. removeOrigin(url) {
  312. const parsed = new URL(url);
  313. const result = url.substring(parsed.origin.length);
  314. return (result ? result : '/');
  315. }
  316. getRootIndexByUrl(groups, url) {
  317. if (!this.ready)
  318. return -1;
  319. const origin = this.getOrigin(url);
  320. for (let i = 0; i < groups.length; i++) {
  321. if (groups[i].r == origin)
  322. return i;
  323. }
  324. return -1;
  325. }
  326. getListItemByLink(list, link) {
  327. for (const item of list) {
  328. if (item.l == link)
  329. return item;
  330. }
  331. return null;
  332. }
  333. getCommentByLink(list, link) {
  334. const item = this.getListItemByLink(list, link);
  335. return (item ? item.c : '');
  336. }
  337. makeProxySubst(url, reverse = false) {
  338. for (const [key, value] of Object.entries(proxySubst)) {
  339. if (reverse && value == url.substring(0, value.length)) {
  340. return key + url.substring(value.length);
  341. } else if (key == url.substring(0, key.length)) {
  342. return value + url.substring(key.length);
  343. }
  344. }
  345. return url;
  346. }
  347. onInputFocus(event) {
  348. if (event.target.select)
  349. event.target.select();
  350. }
  351. submitUrl() {
  352. if (this.bookUrl) {
  353. this.sendMessage({type: 'submitUrl', data: {
  354. url: this.makeProxySubst(this.addProtocol(this.bookUrl), true),
  355. force: true
  356. }});
  357. this.bookUrl = '';
  358. if (this.libs.closeAfterSubmit)
  359. this.close();
  360. }
  361. }
  362. addBookmark() {
  363. this.bookmarkLink = (this.bookUrl ? this.makeProxySubst(this.addProtocol(this.bookUrl), true) : '');
  364. this.bookmarkDesc = '';
  365. this.addBookmarkVisible = true;
  366. this.$nextTick(() => {
  367. this.$refs.bookmarkLink.focus();
  368. });
  369. }
  370. updateBookmarkLink() {
  371. const index = this.getRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  372. if (index >= 0) {
  373. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  374. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  375. } else {
  376. this.bookmarkLink = '';
  377. this.bookmarkDesc = '';
  378. }
  379. }
  380. async okAddBookmark() {
  381. const link = this.addProtocol(this.bookmarkLink);
  382. let index = -1;
  383. try {
  384. index = this.getRootIndexByUrl(this.libs.groups, link);
  385. } catch (e) {
  386. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  387. return;
  388. }
  389. //есть группа в закладках
  390. if (index >= 0) {
  391. const item = this.getListItemByLink(this.libs.groups[index].list, link);
  392. if (!item || item.c != this.bookmarkDesc) {
  393. //добавляем
  394. let libs = _.cloneDeep(this.libs);
  395. if (libs.groups[index].list.length >= 100) {
  396. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  397. return;
  398. }
  399. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  400. this.commitLibs(libs);
  401. }
  402. } else {//нет группы в закладках
  403. let libs = _.cloneDeep(this.libs);
  404. if (libs.groups.length >= 100) {
  405. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  406. return;
  407. }
  408. //добавляем сначала группу
  409. libs.groups.push({r: this.getOrigin(link), s: link, list: []});
  410. index = this.getRootIndexByUrl(libs.groups, link);
  411. if (index >= 0)
  412. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  413. this.commitLibs(libs);
  414. }
  415. this.addBookmarkVisible = false;
  416. }
  417. bookmarkSettings() {
  418. }
  419. fullScreenToggle() {
  420. this.fullScreenActive = !this.fullScreenActive;
  421. if (this.fullScreenActive) {
  422. this.$q.fullscreen.request();
  423. } else {
  424. this.$q.fullscreen.exit();
  425. }
  426. }
  427. close() {
  428. this.sendMessage({type: 'close'});
  429. }
  430. keyHook() {
  431. if (this.$root.rootRoute() == '/external-libs') {
  432. if (this.$refs.dialogAddBookmark.active)
  433. return false;
  434. //недостатки сторонних ui
  435. const input = this.$refs.input.$refs.input;
  436. if (document.activeElement === input && event.type == 'keydown' && event.key == 'Enter') {
  437. this.submitUrl();
  438. return true;
  439. }
  440. if (event.type == 'keydown' && event.key == 'Escape') {
  441. this.close();
  442. }
  443. return true;
  444. }
  445. return false;
  446. }
  447. }
  448. //-----------------------------------------------------------------------------
  449. </script>
  450. <style scoped>
  451. .separator {
  452. height: 1px;
  453. background-color: #A0A0A0;
  454. }
  455. .full-screen-button {
  456. width: 30px;
  457. height: 30px;
  458. cursor: pointer;
  459. }
  460. .full-screen-button:hover {
  461. background-color: #69C05F;
  462. }
  463. </style>