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 INIT_DEFAULT_TRENDING_ALGORITHM = 'most-viewed'
11 private previousUrl: string
12 private currentUrl: string
14 private redirectingToHomepage = false
15 private defaultTrendingAlgorithm = RedirectService.INIT_DEFAULT_TRENDING_ALGORITHM
16 private defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
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 this.defaultRoute = tmpConfig.instance.defaultClientRoute
27 if (tmpConfig?.trending?.videos?.algorithms?.default) {
28 this.defaultTrendingAlgorithm = 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) this.defaultRoute = defaultRouteConfig
38 if (defaultTrendingConfig) this.defaultTrendingAlgorithm = defaultTrendingConfig
42 this.currentUrl = this.router.url
43 router.events.subscribe(event => {
44 if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
45 this.previousUrl = this.currentUrl
46 this.currentUrl = event.url
52 return this.defaultRoute
55 getDefaultTrendingAlgorithm () {
56 return this.defaultTrendingAlgorithm
59 redirectToPreviousRoute () {
65 if (this.previousUrl) {
66 const isException = exceptions.find(e => this.previousUrl.startsWith(e))
67 if (!isException) return this.router.navigateByUrl(this.previousUrl)
70 return this.redirectToHomepage()
73 redirectToHomepage (skipLocationChange = false) {
74 if (this.redirectingToHomepage) return
76 this.redirectingToHomepage = true
78 console.log('Redirecting to %s...', this.defaultRoute)
80 this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
81 .then(() => this.redirectingToHomepage = false)
83 this.redirectingToHomepage = false
86 'Cannot navigate to %s, resetting default route to %s.',
88 RedirectService.INIT_DEFAULT_ROUTE
91 this.defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
92 return this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })