Go back when cancel NSFW modal
[oweals/peertube.git] / client / src / app / app.component.ts
1 import { Component, OnInit } from '@angular/core'
2 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
3 import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
4 import { AuthService, RedirectService, ServerService, ThemeService } from '@app/core'
5 import { is18nPath } from '../../../shared/models/i18n'
6 import { ScreenService } from '@app/shared/misc/screen.service'
7 import { debounceTime, filter, map, pairwise, skip } from 'rxjs/operators'
8 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
10 import { fromEvent } from 'rxjs'
11 import { PlatformLocation, ViewportScroller } from '@angular/common'
12 import { PluginService } from '@app/core/plugins/plugin.service'
13 import { HooksService } from '@app/core/plugins/hooks.service'
14 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { POP_STATE_MODAL_DISMISS } from '@app/shared/misc/constants'
16
17 @Component({
18   selector: 'my-app',
19   templateUrl: './app.component.html',
20   styleUrls: [ './app.component.scss' ]
21 })
22 export class AppComponent implements OnInit {
23   isMenuDisplayed = true
24   isMenuChangedByUser = false
25
26   customCSS: SafeHtml
27
28   constructor (
29     private i18n: I18n,
30     private viewportScroller: ViewportScroller,
31     private router: Router,
32     private authService: AuthService,
33     private serverService: ServerService,
34     private pluginService: PluginService,
35     private domSanitizer: DomSanitizer,
36     private redirectService: RedirectService,
37     private screenService: ScreenService,
38     private hotkeysService: HotkeysService,
39     private themeService: ThemeService,
40     private hooks: HooksService,
41     private location: PlatformLocation,
42     private modalService: NgbModal
43   ) { }
44
45   get serverVersion () {
46     return this.serverService.getConfig().serverVersion
47   }
48
49   get serverCommit () {
50     const commit = this.serverService.getConfig().serverCommit || ''
51     return (commit !== '') ? '...' + commit : commit
52   }
53
54   get instanceName () {
55     return this.serverService.getConfig().instance.name
56   }
57
58   get defaultRoute () {
59     return RedirectService.DEFAULT_ROUTE
60   }
61
62   ngOnInit () {
63     document.getElementById('incompatible-browser').className += ' browser-ok'
64
65     this.authService.loadClientCredentials()
66
67     if (this.isUserLoggedIn()) {
68       // The service will automatically redirect to the login page if the token is not valid anymore
69       this.authService.refreshUserInformation()
70     }
71
72     // Load custom data from server
73     this.serverService.loadConfig()
74     this.serverService.loadVideoCategories()
75     this.serverService.loadVideoLanguages()
76     this.serverService.loadVideoLicences()
77     this.serverService.loadVideoPrivacies()
78     this.serverService.loadVideoPlaylistPrivacies()
79
80     this.loadPlugins()
81     this.themeService.initialize()
82
83     // Do not display menu on small screens
84     if (this.screenService.isInSmallView()) {
85       this.isMenuDisplayed = false
86     }
87
88     this.initRouteEvents()
89     this.injectJS()
90     this.injectCSS()
91
92     this.initHotkeys()
93
94     fromEvent(window, 'resize')
95       .pipe(debounceTime(200))
96       .subscribe(() => this.onResize())
97
98     this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
99   }
100
101   isUserLoggedIn () {
102     return this.authService.isLoggedIn()
103   }
104
105   toggleMenu () {
106     this.isMenuDisplayed = !this.isMenuDisplayed
107     this.isMenuChangedByUser = true
108   }
109
110   onResize () {
111     this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
112   }
113
114   private initRouteEvents () {
115     let resetScroll = true
116     const eventsObs = this.router.events
117
118     const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
119
120     scrollEvent.subscribe(e => {
121       if (e.position) {
122         return this.viewportScroller.scrollToPosition(e.position)
123       }
124
125       if (e.anchor) {
126         return this.viewportScroller.scrollToAnchor(e.anchor)
127       }
128
129       if (resetScroll) {
130         return this.viewportScroller.scrollToPosition([ 0, 0 ])
131       }
132     })
133
134     const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
135
136     // When we add the a-state parameter, we don't want to alter the scroll
137     navigationEndEvent.pipe(pairwise())
138                       .subscribe(([ e1, e2 ]) => {
139                         try {
140                           resetScroll = false
141
142                           const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
143                           const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
144
145                           if (previousUrl.pathname !== nextUrl.pathname) {
146                             resetScroll = true
147                             return
148                           }
149
150                           const nextSearchParams = nextUrl.searchParams
151                           nextSearchParams.delete('a-state')
152
153                           const previousSearchParams = previousUrl.searchParams
154
155                           nextSearchParams.sort()
156                           previousSearchParams.sort()
157
158                           if (nextSearchParams.toString() !== previousSearchParams.toString()) {
159                             resetScroll = true
160                           }
161                         } catch (e) {
162                           console.error('Cannot parse URL to check next scroll.', e)
163                           resetScroll = true
164                         }
165                       })
166
167     navigationEndEvent.pipe(
168       map(() => window.location.pathname),
169       filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
170     ).subscribe(() => this.redirectService.redirectToHomepage(true))
171
172     navigationEndEvent.subscribe(e => {
173       this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
174     })
175
176     eventsObs.pipe(
177       filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
178       filter(() => this.screenService.isInSmallView())
179     ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
180   }
181
182   private injectJS () {
183     // Inject JS
184     this.serverService.configLoaded
185         .subscribe(() => {
186           const config = this.serverService.getConfig()
187
188           if (config.instance.customizations.javascript) {
189             try {
190               // tslint:disable:no-eval
191               eval(config.instance.customizations.javascript)
192             } catch (err) {
193               console.error('Cannot eval custom JavaScript.', err)
194             }
195           }
196         })
197   }
198
199   private injectCSS () {
200     // Inject CSS if modified (admin config settings)
201     this.serverService.configLoaded
202         .pipe(skip(1)) // We only want to subscribe to reloads, because the CSS is already injected by the server
203         .subscribe(() => {
204           const headStyle = document.querySelector('style.custom-css-style')
205           if (headStyle) headStyle.parentNode.removeChild(headStyle)
206
207           const config = this.serverService.getConfig()
208
209           // We test customCSS if the admin removed the css
210           if (this.customCSS || config.instance.customizations.css) {
211             const styleTag = '<style>' + config.instance.customizations.css + '</style>'
212             this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
213           }
214         })
215   }
216
217   private async loadPlugins () {
218     this.pluginService.initializePlugins()
219
220     this.hooks.runAction('action:application.init', 'common')
221   }
222
223   private initHotkeys () {
224     this.hotkeysService.add([
225       new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
226         document.getElementById('search-video').focus()
227         return false
228       }, undefined, this.i18n('Focus the search bar')),
229       new Hotkey('b', (event: KeyboardEvent): boolean => {
230         this.toggleMenu()
231         return false
232       }, undefined, this.i18n('Toggle the left menu')),
233       new Hotkey('g o', (event: KeyboardEvent): boolean => {
234         this.router.navigate([ '/videos/overview' ])
235         return false
236       }, undefined, this.i18n('Go to the discover videos page')),
237       new Hotkey('g t', (event: KeyboardEvent): boolean => {
238         this.router.navigate([ '/videos/trending' ])
239         return false
240       }, undefined, this.i18n('Go to the trending videos page')),
241       new Hotkey('g r', (event: KeyboardEvent): boolean => {
242         this.router.navigate([ '/videos/recently-added' ])
243         return false
244       }, undefined, this.i18n('Go to the recently added videos page')),
245       new Hotkey('g l', (event: KeyboardEvent): boolean => {
246         this.router.navigate([ '/videos/local' ])
247         return false
248       }, undefined, this.i18n('Go to the local videos page')),
249       new Hotkey('g u', (event: KeyboardEvent): boolean => {
250         this.router.navigate([ '/videos/upload' ])
251         return false
252       }, undefined, this.i18n('Go to the videos upload page'))
253     ])
254   }
255 }