]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/routing/redirect.service.ts
emit more specific status codes on video upload (#3423)
[github/Chocobozzz/PeerTube.git] / client / src / app / core / routing / redirect.service.ts
1 import { Injectable } from '@angular/core'
2 import { NavigationEnd, Router } from '@angular/router'
3 import { ServerService } from '../server'
4
5 @Injectable()
6 export class RedirectService {
7 // Default route could change according to the instance configuration
8 static INIT_DEFAULT_ROUTE = '/videos/trending'
9 static DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE
10
11 private previousUrl: string
12 private currentUrl: string
13
14 private redirectingToHomepage = false
15
16 constructor (
17 private router: Router,
18 private serverService: ServerService
19 ) {
20 // The config is first loaded from the cache so try to get the default route
21 const tmpConfig = this.serverService.getTmpConfig()
22 if (tmpConfig && tmpConfig.instance && tmpConfig.instance.defaultClientRoute) {
23 RedirectService.DEFAULT_ROUTE = tmpConfig.instance.defaultClientRoute
24 }
25
26 // Load default route
27 this.serverService.getConfig()
28 .subscribe(config => {
29 const defaultRouteConfig = config.instance.defaultClientRoute
30
31 if (defaultRouteConfig) {
32 RedirectService.DEFAULT_ROUTE = defaultRouteConfig
33 }
34 })
35
36 // Track previous url
37 this.currentUrl = this.router.url
38 router.events.subscribe(event => {
39 if (event instanceof NavigationEnd) {
40 this.previousUrl = this.currentUrl
41 this.currentUrl = event.url
42 }
43 })
44 }
45
46 redirectToPreviousRoute () {
47 const exceptions = [
48 '/verify-account',
49 '/reset-password'
50 ]
51
52 if (this.previousUrl) {
53 const isException = exceptions.find(e => this.previousUrl.startsWith(e))
54 if (!isException) return this.router.navigateByUrl(this.previousUrl)
55 }
56
57 return this.redirectToHomepage()
58 }
59
60 redirectToHomepage (skipLocationChange = false) {
61 if (this.redirectingToHomepage) return
62
63 this.redirectingToHomepage = true
64
65 console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE)
66
67 this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange })
68 .then(() => this.redirectingToHomepage = false)
69 .catch(() => {
70 this.redirectingToHomepage = false
71
72 console.error(
73 'Cannot navigate to %s, resetting default route to %s.',
74 RedirectService.DEFAULT_ROUTE,
75 RedirectService.INIT_DEFAULT_ROUTE
76 )
77
78 RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE
79 return this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange })
80 })
81
82 }
83 }