1 import { Injectable } from '@angular/core'
2 import { NavigationCancel, NavigationEnd, Router } from '@angular/router'
3 import { ServerService } from '../server'
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
11 private previousUrl: string
12 private currentUrl: string
14 private redirectingToHomepage = false
17 private router: Router,
18 private serverService: ServerService
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
27 this.serverService.getConfig()
28 .subscribe(config => {
29 const defaultRouteConfig = config.instance.defaultClientRoute
31 if (defaultRouteConfig) {
32 RedirectService.DEFAULT_ROUTE = defaultRouteConfig
37 this.currentUrl = this.router.url
38 router.events.subscribe(event => {
39 if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
40 this.previousUrl = this.currentUrl
41 this.currentUrl = event.url
46 redirectToPreviousRoute () {
52 if (this.previousUrl) {
53 const isException = exceptions.find(e => this.previousUrl.startsWith(e))
54 if (!isException) return this.router.navigateByUrl(this.previousUrl)
57 return this.redirectToHomepage()
60 redirectToHomepage (skipLocationChange = false) {
61 if (this.redirectingToHomepage) return
63 this.redirectingToHomepage = true
65 console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE)
67 this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange })
68 .then(() => this.redirectingToHomepage = false)
70 this.redirectingToHomepage = false
73 'Cannot navigate to %s, resetting default route to %s.',
74 RedirectService.DEFAULT_ROUTE,
75 RedirectService.INIT_DEFAULT_ROUTE
78 RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE
79 return this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange })