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
10 static INIT_DEFAULT_TRENDING_ALGORITHM = 'most-viewed'
11 static DEFAULT_TRENDING_ALGORITHM = RedirectService.INIT_DEFAULT_TRENDING_ALGORITHM
13 private previousUrl: string
14 private currentUrl: string
16 private redirectingToHomepage = false
19 private router: Router,
20 private serverService: ServerService
22 // The config is first loaded from the cache so try to get the default route
23 const tmpConfig = this.serverService.getTmpConfig()
24 if (tmpConfig?.instance?.defaultClientRoute) {
25 RedirectService.DEFAULT_ROUTE = tmpConfig.instance.defaultClientRoute
27 if (tmpConfig?.trending?.videos?.algorithms?.default) {
28 RedirectService.DEFAULT_TRENDING_ALGORITHM = tmpConfig.trending.videos.algorithms.default
32 this.serverService.getConfig()
33 .subscribe(config => {
34 const defaultRouteConfig = config.instance.defaultClientRoute
35 const defaultTrendingConfig = config.trending.videos.algorithms.default
37 if (defaultRouteConfig) {
38 RedirectService.DEFAULT_ROUTE = defaultRouteConfig
41 if (defaultTrendingConfig) {
42 RedirectService.DEFAULT_TRENDING_ALGORITHM = defaultTrendingConfig
47 this.currentUrl = this.router.url
48 router.events.subscribe(event => {
49 if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
50 this.previousUrl = this.currentUrl
51 this.currentUrl = event.url
56 redirectToPreviousRoute () {
62 if (this.previousUrl) {
63 const isException = exceptions.find(e => this.previousUrl.startsWith(e))
64 if (!isException) return this.router.navigateByUrl(this.previousUrl)
67 return this.redirectToHomepage()
70 redirectToHomepage (skipLocationChange = false) {
71 if (this.redirectingToHomepage) return
73 this.redirectingToHomepage = true
75 console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE)
77 this.router.navigateByUrl(RedirectService.DEFAULT_ROUTE, { skipLocationChange })
78 .then(() => this.redirectingToHomepage = false)
80 this.redirectingToHomepage = false
83 'Cannot navigate to %s, resetting default route to %s.',
84 RedirectService.DEFAULT_ROUTE,
85 RedirectService.INIT_DEFAULT_ROUTE
88 RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE
89 return this.router.navigateByUrl(RedirectService.DEFAULT_ROUTE, { skipLocationChange })