Merge branch 'release/v1.2.0'
[oweals/peertube.git] / client / src / app / shared / user-subscription / remote-subscribe.component.ts
1 import { Component, Input, OnInit } from '@angular/core'
2 import { FormReactive } from '@app/shared/forms/form-reactive'
3 import {
4   FormValidatorService,
5   UserValidatorsService
6 } from '@app/shared/forms/form-validators'
7
8 @Component({
9   selector: 'my-remote-subscribe',
10   templateUrl: './remote-subscribe.component.html',
11   styleUrls: ['./remote-subscribe.component.scss']
12 })
13 export class RemoteSubscribeComponent extends FormReactive implements OnInit {
14   @Input() account: string
15   @Input() interact = false
16   @Input() showHelp = false
17
18   constructor (
19     protected formValidatorService: FormValidatorService,
20     private userValidatorsService: UserValidatorsService
21   ) {
22     super()
23   }
24
25   ngOnInit () {
26     this.buildForm({
27       text: this.userValidatorsService.USER_EMAIL
28     })
29   }
30
31   onValidKey () {
32     this.check()
33     if (!this.form.valid) return
34
35     this.formValidated()
36   }
37
38   formValidated () {
39     const address = this.form.value['text']
40     const [ username, hostname ] = address.split('@')
41
42     fetch(`https://${hostname}/.well-known/webfinger?resource=acct:${username}@${hostname}`)
43       .then(response => response.json())
44       .then(data => new Promise((resolve, reject) => {
45         if (data && Array.isArray(data.links)) {
46           const link: {
47             template: string
48           } = data.links.find((link: any) =>
49             link && typeof link.template === 'string' && link.rel === 'http://ostatus.org/schema/1.0/subscribe')
50
51           if (link && link.template.includes('{uri}')) {
52             resolve(link.template.replace('{uri}', `acct:${this.account}`))
53           }
54         }
55         reject()
56       }))
57       .then(window.open)
58       .catch(() => window.open(`https://${hostname}/authorize_interaction?acct=${this.account}`))
59   }
60 }