]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/routing/redirect.service.ts
198332b00bdd925363b576d541627549b9251e6a
[github/Chocobozzz/PeerTube.git] / client / src / app / core / routing / redirect.service.ts
1 import { Injectable } from '@angular/core'
2 import { NavigationCancel, 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 INIT_DEFAULT_TRENDING_ALGORITHM = 'most-viewed'
10
11 private previousUrl: string
12 private currentUrl: string
13
14 private redirectingToHomepage = false
15 private defaultTrendingAlgorithm = RedirectService.INIT_DEFAULT_TRENDING_ALGORITHM
16 private defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
17
18 constructor (
19 private router: Router,
20 private serverService: ServerService
21 ) {
22 // The config is first loaded from the cache so try to get the default route
23 const config = this.serverService.getHTMLConfig()
24 if (config?.instance?.defaultClientRoute) {
25 this.defaultRoute = config.instance.defaultClientRoute
26 }
27 if (config?.trending?.videos?.algorithms?.default) {
28 this.defaultTrendingAlgorithm = config.trending.videos.algorithms.default
29 }
30
31 // Track previous url
32 this.currentUrl = this.router.url
33 router.events.subscribe(event => {
34 if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
35 this.previousUrl = this.currentUrl
36 this.currentUrl = event.url
37 }
38 })
39 }
40
41 getDefaultRoute () {
42 return this.defaultRoute
43 }
44
45
46 getDefaultTrendingAlgorithm () {
47 return this.defaultTrendingAlgorithm
48 }
49
50 redirectToPreviousRoute () {
51 const exceptions = [
52 '/verify-account',
53 '/reset-password'
54 ]
55
56 if (this.previousUrl) {
57 const isException = exceptions.find(e => this.previousUrl.startsWith(e))
58 if (!isException) return this.router.navigateByUrl(this.previousUrl)
59 }
60
61 return this.redirectToHomepage()
62 }
63
64 redirectToHomepage (skipLocationChange = false) {
65 if (this.redirectingToHomepage) return
66
67 this.redirectingToHomepage = true
68
69 console.log('Redirecting to %s...', this.defaultRoute)
70
71 this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
72 .then(() => this.redirectingToHomepage = false)
73 .catch(() => {
74 this.redirectingToHomepage = false
75
76 console.error(
77 'Cannot navigate to %s, resetting default route to %s.',
78 this.defaultRoute,
79 RedirectService.INIT_DEFAULT_ROUTE
80 )
81
82 this.defaultRoute = RedirectService.INIT_DEFAULT_ROUTE
83 return this.router.navigateByUrl(this.defaultRoute, { skipLocationChange })
84 })
85
86 }
87 }