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