Lazy load static objects
[oweals/peertube.git] / client / src / app / app.component.ts
1 import { Component, OnInit, ViewChild } 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, first, map, pairwise, skip, switchMap } 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 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
17 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
18 import { ServerConfig, UserRole } from '@shared/models'
19 import { User } from '@app/shared'
20 import { InstanceService } from '@app/shared/instance/instance.service'
21
22 @Component({
23   selector: 'my-app',
24   templateUrl: './app.component.html',
25   styleUrls: [ './app.component.scss' ]
26 })
27 export class AppComponent implements OnInit {
28   @ViewChild('welcomeModal', { static: false }) welcomeModal: WelcomeModalComponent
29   @ViewChild('instanceConfigWarningModal', { static: false }) instanceConfigWarningModal: InstanceConfigWarningModalComponent
30
31   isMenuDisplayed = true
32   isMenuChangedByUser = false
33
34   customCSS: SafeHtml
35
36   private serverConfig: ServerConfig
37
38   constructor (
39     private i18n: I18n,
40     private viewportScroller: ViewportScroller,
41     private router: Router,
42     private authService: AuthService,
43     private serverService: ServerService,
44     private pluginService: PluginService,
45     private instanceService: InstanceService,
46     private domSanitizer: DomSanitizer,
47     private redirectService: RedirectService,
48     private screenService: ScreenService,
49     private hotkeysService: HotkeysService,
50     private themeService: ThemeService,
51     private hooks: HooksService,
52     private location: PlatformLocation,
53     private modalService: NgbModal
54   ) { }
55
56   get instanceName () {
57     return this.serverConfig.instance.name
58   }
59
60   get defaultRoute () {
61     return RedirectService.DEFAULT_ROUTE
62   }
63
64   ngOnInit () {
65     document.getElementById('incompatible-browser').className += ' browser-ok'
66
67     this.serverConfig = this.serverService.getTmpConfig()
68     this.serverService.getConfig()
69         .subscribe(config => this.serverConfig = config)
70
71     this.loadPlugins()
72     this.themeService.initialize()
73
74     this.authService.loadClientCredentials()
75
76     if (this.isUserLoggedIn()) {
77       // The service will automatically redirect to the login page if the token is not valid anymore
78       this.authService.refreshUserInformation()
79     }
80
81     // Do not display menu on small screens
82     if (this.screenService.isInSmallView()) {
83       this.isMenuDisplayed = false
84     }
85
86     this.initRouteEvents()
87     this.injectJS()
88     this.injectCSS()
89
90     this.initHotkeys()
91
92     fromEvent(window, 'resize')
93       .pipe(debounceTime(200))
94       .subscribe(() => this.onResize())
95
96     this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
97
98     this.openModalsIfNeeded()
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   getServerVersionAndCommit () {
115     return this.serverService.getServerVersionAndCommit()
116   }
117
118   private initRouteEvents () {
119     let resetScroll = true
120     const eventsObs = this.router.events
121
122     const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
123
124     scrollEvent.subscribe(e => {
125       if (e.position) {
126         return this.viewportScroller.scrollToPosition(e.position)
127       }
128
129       if (e.anchor) {
130         return this.viewportScroller.scrollToAnchor(e.anchor)
131       }
132
133       if (resetScroll) {
134         return this.viewportScroller.scrollToPosition([ 0, 0 ])
135       }
136     })
137
138     const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
139
140     // When we add the a-state parameter, we don't want to alter the scroll
141     navigationEndEvent.pipe(pairwise())
142                       .subscribe(([ e1, e2 ]) => {
143                         try {
144                           resetScroll = false
145
146                           const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
147                           const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
148
149                           if (previousUrl.pathname !== nextUrl.pathname) {
150                             resetScroll = true
151                             return
152                           }
153
154                           const nextSearchParams = nextUrl.searchParams
155                           nextSearchParams.delete('a-state')
156
157                           const previousSearchParams = previousUrl.searchParams
158
159                           nextSearchParams.sort()
160                           previousSearchParams.sort()
161
162                           if (nextSearchParams.toString() !== previousSearchParams.toString()) {
163                             resetScroll = true
164                           }
165                         } catch (e) {
166                           console.error('Cannot parse URL to check next scroll.', e)
167                           resetScroll = true
168                         }
169                       })
170
171     navigationEndEvent.pipe(
172       map(() => window.location.pathname),
173       filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
174     ).subscribe(() => this.redirectService.redirectToHomepage(true))
175
176     navigationEndEvent.subscribe(e => {
177       this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
178     })
179
180     eventsObs.pipe(
181       filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
182       filter(() => this.screenService.isInSmallView())
183     ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
184   }
185
186   private injectJS () {
187     // Inject JS
188     this.serverService.getConfig()
189         .subscribe(config => {
190           if (config.instance.customizations.javascript) {
191             try {
192               // tslint:disable:no-eval
193               eval(config.instance.customizations.javascript)
194             } catch (err) {
195               console.error('Cannot eval custom JavaScript.', err)
196             }
197           }
198         })
199   }
200
201   private injectCSS () {
202     // Inject CSS if modified (admin config settings)
203     this.serverService.configReloaded
204         .subscribe(() => {
205           const headStyle = document.querySelector('style.custom-css-style')
206           if (headStyle) headStyle.parentNode.removeChild(headStyle)
207
208           // We test customCSS if the admin removed the css
209           if (this.customCSS || this.serverConfig.instance.customizations.css) {
210             const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
211             this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
212           }
213         })
214   }
215
216   private async loadPlugins () {
217     this.pluginService.initializePlugins()
218
219     this.hooks.runAction('action:application.init', 'common')
220   }
221
222   private async openModalsIfNeeded () {
223     this.authService.userInformationLoaded
224         .pipe(
225           map(() => this.authService.getUser()),
226           filter(user => user.role === UserRole.ADMINISTRATOR)
227         ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
228   }
229
230   private async _openAdminModalsIfNeeded (user: User) {
231     if (user.noWelcomeModal !== true) return this.welcomeModal.show()
232
233     if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
234
235     this.instanceService.getAbout()
236       .subscribe(about => {
237         if (
238           this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
239           !about.instance.terms ||
240           !about.instance.administrator ||
241           !about.instance.maintenanceLifetime
242         ) {
243           this.instanceConfigWarningModal.show(about)
244         }
245       })
246   }
247
248   private initHotkeys () {
249     this.hotkeysService.add([
250       new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
251         document.getElementById('search-video').focus()
252         return false
253       }, undefined, this.i18n('Focus the search bar')),
254
255       new Hotkey('b', (event: KeyboardEvent): boolean => {
256         this.toggleMenu()
257         return false
258       }, undefined, this.i18n('Toggle the left menu')),
259
260       new Hotkey('g o', (event: KeyboardEvent): boolean => {
261         this.router.navigate([ '/videos/overview' ])
262         return false
263       }, undefined, this.i18n('Go to the discover videos page')),
264
265       new Hotkey('g t', (event: KeyboardEvent): boolean => {
266         this.router.navigate([ '/videos/trending' ])
267         return false
268       }, undefined, this.i18n('Go to the trending videos page')),
269
270       new Hotkey('g r', (event: KeyboardEvent): boolean => {
271         this.router.navigate([ '/videos/recently-added' ])
272         return false
273       }, undefined, this.i18n('Go to the recently added videos page')),
274
275       new Hotkey('g l', (event: KeyboardEvent): boolean => {
276         this.router.navigate([ '/videos/local' ])
277         return false
278       }, undefined, this.i18n('Go to the local videos page')),
279
280       new Hotkey('g u', (event: KeyboardEvent): boolean => {
281         this.router.navigate([ '/videos/upload' ])
282         return false
283       }, undefined, this.i18n('Go to the videos upload page'))
284     ])
285   }
286 }