Add user moderation in the account page
[oweals/peertube.git] / client / src / app / +accounts / accounts.component.ts
1 import { Component, OnDestroy, OnInit } from '@angular/core'
2 import { ActivatedRoute } from '@angular/router'
3 import { AccountService } from '@app/shared/account/account.service'
4 import { Account } from '@app/shared/account/account.model'
5 import { RestExtractor, UserService } from '@app/shared'
6 import { catchError, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators'
7 import { Subscription } from 'rxjs'
8 import { NotificationsService } from 'angular2-notifications'
9 import { User, UserRight } from '../../../../shared'
10 import { I18n } from '@ngx-translate/i18n-polyfill'
11 import { AuthService, RedirectService } from '@app/core'
12
13 @Component({
14   templateUrl: './accounts.component.html',
15   styleUrls: [ './accounts.component.scss' ]
16 })
17 export class AccountsComponent implements OnInit, OnDestroy {
18   account: Account
19   user: User
20
21   private routeSub: Subscription
22
23   constructor (
24     private route: ActivatedRoute,
25     private userService: UserService,
26     private accountService: AccountService,
27     private notificationsService: NotificationsService,
28     private restExtractor: RestExtractor,
29     private redirectService: RedirectService,
30     private authService: AuthService,
31     private i18n: I18n
32   ) {}
33
34   ngOnInit () {
35     this.routeSub = this.route.params
36       .pipe(
37         map(params => params[ 'accountId' ]),
38         distinctUntilChanged(),
39         switchMap(accountId => this.accountService.getAccount(accountId)),
40         tap(account => this.getUserIfNeeded(account)),
41         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
42       )
43       .subscribe(
44         account => this.account = account,
45
46         err => this.notificationsService.error(this.i18n('Error'), err.message)
47       )
48   }
49
50   ngOnDestroy () {
51     if (this.routeSub) this.routeSub.unsubscribe()
52   }
53
54   onUserChanged () {
55     this.getUserIfNeeded(this.account)
56   }
57
58   onUserDeleted () {
59     this.redirectService.redirectToHomepage()
60   }
61
62   private getUserIfNeeded (account: Account) {
63     if (!account.userId) return
64     if (!this.authService.isLoggedIn()) return
65
66     const user = this.authService.getUser()
67     if (user.hasRight(UserRight.MANAGE_USERS)) {
68       this.userService.getUser(account.userId)
69           .subscribe(
70             user => this.user = user,
71
72             err => this.notificationsService.error(this.i18n('Error'), err.message)
73           )
74     }
75   }
76 }