aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts
blob: 49d61f9451b577f8b400ae4df19a192d81b88ba7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { forkJoin, of } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
import { Injectable } from '@angular/core'
import { ActivatedRouteSnapshot, CanActivate, Router } from '@angular/router'
import { AccountService } from '../account'
import { VideoChannelService } from '../video-channel'

@Injectable()
export class ActorRedirectGuard implements CanActivate {

  constructor (
    private router: Router,
    private accountService: AccountService,
    private channelService: VideoChannelService
  ) {}

  canActivate (route: ActivatedRouteSnapshot) {
    const actorName = route.params.actorName

    return forkJoin([
      this.accountService.getAccount(actorName).pipe(this.orUndefined()),
      this.channelService.getVideoChannel(actorName).pipe(this.orUndefined())
    ]).pipe(
      map(([ account, channel ]) => {
        if (!account && !channel) {
          this.router.navigate([ '/404' ])
          return false
        }

        if (account) {
          this.router.navigate([ `/a/${actorName}` ], { skipLocationChange: true })
        }

        if (channel) {
          this.router.navigate([ `/c/${actorName}` ], { skipLocationChange: true })
        }

        return true
      })
    )
  }

  private orUndefined () {
    return catchError(() => of(undefined))
  }
}