]>
Commit | Line | Data |
---|---|---|
1 | import { Component } from '@angular/core' | |
2 | import { Router } from '@angular/router' | |
3 | import { NotificationsService } from 'angular2-notifications' | |
4 | import { ConfirmService } from '../../../core' | |
5 | import { validateHost } from '../../../shared' | |
6 | import { FollowService } from '../shared' | |
7 | ||
8 | @Component({ | |
9 | selector: 'my-following-add', | |
10 | templateUrl: './following-add.component.html', | |
11 | styleUrls: [ './following-add.component.scss' ] | |
12 | }) | |
13 | export class FollowingAddComponent { | |
14 | hostsString = '' | |
15 | hostsError: string = null | |
16 | error: string = null | |
17 | ||
18 | constructor ( | |
19 | private router: Router, | |
20 | private notificationsService: NotificationsService, | |
21 | private confirmService: ConfirmService, | |
22 | private followService: FollowService | |
23 | ) {} | |
24 | ||
25 | httpEnabled () { | |
26 | return window.location.protocol === 'https:' | |
27 | } | |
28 | ||
29 | onHostsChanged () { | |
30 | this.hostsError = null | |
31 | ||
32 | const newHostsErrors = [] | |
33 | const hosts = this.getNotEmptyHosts() | |
34 | ||
35 | for (const host of hosts) { | |
36 | if (validateHost(host) === false) { | |
37 | newHostsErrors.push(`${host} is not valid`) | |
38 | } | |
39 | } | |
40 | ||
41 | if (newHostsErrors.length !== 0) { | |
42 | this.hostsError = newHostsErrors.join('. ') | |
43 | } | |
44 | } | |
45 | ||
46 | async addFollowing () { | |
47 | this.error = '' | |
48 | ||
49 | const hosts = this.getNotEmptyHosts() | |
50 | if (hosts.length === 0) { | |
51 | this.error = 'You need to specify hosts to follow.' | |
52 | } | |
53 | ||
54 | if (!this.isHostsUnique(hosts)) { | |
55 | this.error = 'Hosts need to be unique.' | |
56 | return | |
57 | } | |
58 | ||
59 | const confirmMessage = 'If you confirm, you will send a follow request to:<br /> - ' + hosts.join('<br /> - ') | |
60 | const res = await this.confirmService.confirm(confirmMessage, 'Follow new server(s)') | |
61 | if (res === false) return | |
62 | ||
63 | this.followService.follow(hosts).subscribe( | |
64 | () => { | |
65 | this.notificationsService.success('Success', 'Follow request(s) sent!') | |
66 | ||
67 | setTimeout(() => this.router.navigate([ '/admin/follows/following-list' ]), 500) | |
68 | }, | |
69 | ||
70 | err => this.notificationsService.error('Error', err.message) | |
71 | ) | |
72 | } | |
73 | ||
74 | private isHostsUnique (hosts: string[]) { | |
75 | return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host)) | |
76 | } | |
77 | ||
78 | private getNotEmptyHosts () { | |
79 | const hosts = this.hostsString | |
80 | .split('\n') | |
81 | .filter(host => host && host.length !== 0) // Eject empty hosts | |
82 | ||
83 | return hosts | |
84 | } | |
85 | } |