]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Merge branch 'release/5.1.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { delay, forkJoin } from 'rxjs'
3 import { filter, first, map } from 'rxjs/operators'
4 import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
5 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
6 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
7 import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
8 import {
9 AuthService,
10 MarkdownService,
11 PeerTubeRouterService,
12 RedirectService,
13 ScreenService,
14 ScrollService,
15 ServerService,
16 ThemeService,
17 User,
18 UserLocalStorageService
19 } from '@app/core'
20 import { HooksService } from '@app/core/plugins/hooks.service'
21 import { PluginService } from '@app/core/plugins/plugin.service'
22 import { AccountSetupWarningModalComponent } from '@app/modal/account-setup-warning-modal.component'
23 import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
24 import { CustomModalComponent } from '@app/modal/custom-modal.component'
25 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
26 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
27 import { LoadingBarService } from '@ngx-loading-bar/core'
28 import { logger } from '@root-helpers/logger'
29 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
30 import { getShortLocale } from '@shared/core-utils/i18n'
31 import { BroadcastMessageLevel, HTMLServerConfig, UserRole } from '@shared/models'
32 import { MenuService } from './core/menu/menu.service'
33 import { POP_STATE_MODAL_DISMISS } from './helpers'
34 import { GlobalIconName } from './shared/shared-icons'
35 import { InstanceService } from './shared/shared-instance'
36
37 @Component({
38 selector: 'my-app',
39 templateUrl: './app.component.html',
40 styleUrls: [ './app.component.scss' ]
41 })
42 export class AppComponent implements OnInit, AfterViewInit {
43 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
44
45 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
46 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
47 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
48 @ViewChild('customModal') customModal: CustomModalComponent
49
50 customCSS: SafeHtml
51 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
52
53 private serverConfig: HTMLServerConfig
54
55 constructor (
56 @Inject(DOCUMENT) private document: Document,
57 @Inject(LOCALE_ID) private localeId: string,
58 private router: Router,
59 private authService: AuthService,
60 private serverService: ServerService,
61 private peertubeRouter: PeerTubeRouterService,
62 private pluginService: PluginService,
63 private instanceService: InstanceService,
64 private domSanitizer: DomSanitizer,
65 private redirectService: RedirectService,
66 private screenService: ScreenService,
67 private hotkeysService: HotkeysService,
68 private themeService: ThemeService,
69 private hooks: HooksService,
70 private location: PlatformLocation,
71 private modalService: NgbModal,
72 private markdownService: MarkdownService,
73 private ngbConfig: NgbConfig,
74 private loadingBar: LoadingBarService,
75 private scrollService: ScrollService,
76 private userLocalStorage: UserLocalStorageService,
77 public menu: MenuService
78 ) {
79 this.ngbConfig.animation = false
80 }
81
82 get instanceName () {
83 return this.serverConfig.instance.name
84 }
85
86 ngOnInit () {
87 document.getElementById('incompatible-browser').className += ' browser-ok'
88
89 this.loadUser()
90
91 this.serverConfig = this.serverService.getHTMLConfig()
92
93 this.hooks.runAction('action:application.init', 'common')
94 this.themeService.initialize()
95
96 this.authService.loadClientCredentials()
97
98 if (this.isUserLoggedIn()) {
99 // The service will automatically redirect to the login page if the token is not valid anymore
100 this.authService.refreshUserInformation()
101 }
102
103 this.initRouteEvents()
104 this.scrollService.enableScrollRestoration()
105
106 this.injectJS()
107 this.injectCSS()
108 this.injectBroadcastMessage()
109
110 this.serverService.configReloaded
111 .subscribe(config => {
112 this.serverConfig = config
113
114 this.injectBroadcastMessage()
115 this.injectCSS()
116
117 // Don't reinject JS since it could conflict with existing one
118 })
119
120 this.initHotkeys()
121
122 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
123
124 this.openModalsIfNeeded()
125
126 this.document.documentElement.lang = getShortLocale(this.localeId)
127 this.document.documentElement.dir = getLocaleDirection(this.localeId)
128 }
129
130 ngAfterViewInit () {
131 this.pluginService.initializeCustomModal(this.customModal)
132 }
133
134 getDefaultRoute () {
135 return this.redirectService.getDefaultRoute()
136 }
137
138 getToggleTitle () {
139 if (this.menu.isDisplayed()) return $localize`Close the left menu`
140
141 return $localize`Open the left menu`
142 }
143
144 isUserLoggedIn () {
145 return this.authService.isLoggedIn()
146 }
147
148 hideBroadcastMessage () {
149 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
150
151 this.broadcastMessage = null
152 this.screenService.isBroadcastMessageDisplayed = false
153 }
154
155 getNotificationIcon (message: { severity: 'success' | 'error' | 'info' }): GlobalIconName {
156 switch (message.severity) {
157 case 'error':
158 return 'cross'
159 case 'success':
160 return 'tick'
161 case 'info':
162 return 'help'
163 }
164 }
165
166 private initRouteEvents () {
167 const eventsObs = this.router.events
168
169 // Plugin hooks
170 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
171 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
172 })
173
174 // Automatically hide/display the menu
175 eventsObs.pipe(
176 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
177 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
178 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
179
180 // Handle lazy loaded module
181 eventsObs.pipe(
182 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
183 ).subscribe(() => this.loadingBar.useRef().start())
184
185 eventsObs.pipe(
186 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
187 ).subscribe(() => this.loadingBar.useRef().complete())
188 }
189
190 private async injectBroadcastMessage () {
191 this.broadcastMessage = null
192 this.screenService.isBroadcastMessageDisplayed = false
193
194 const messageConfig = this.serverConfig.broadcastMessage
195
196 if (messageConfig.enabled) {
197 // Already dismissed this message?
198 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
199 return
200 }
201
202 const classes: { [id in BroadcastMessageLevel]: string } = {
203 info: 'alert-info',
204 warning: 'alert-warning',
205 error: 'alert-danger'
206 }
207
208 this.broadcastMessage = {
209 message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
210 dismissable: messageConfig.dismissable,
211 class: classes[messageConfig.level]
212 }
213
214 this.screenService.isBroadcastMessageDisplayed = true
215 }
216 }
217
218 private injectJS () {
219 // Inject JS
220 if (this.serverConfig.instance.customizations.javascript) {
221 try {
222 /* eslint-disable no-eval */
223 eval(this.serverConfig.instance.customizations.javascript)
224 } catch (err) {
225 logger.error('Cannot eval custom JavaScript.', err)
226 }
227 }
228 }
229
230 private injectCSS () {
231 const headStyle = document.querySelector('style.custom-css-style')
232 if (headStyle) headStyle.parentNode.removeChild(headStyle)
233
234 // We test customCSS if the admin removed the css
235 if (this.customCSS || this.serverConfig.instance.customizations.css) {
236 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
237 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
238 }
239 }
240
241 private openModalsIfNeeded () {
242 const userSub = this.authService.userInformationLoaded
243 .pipe(
244 delay(0), // Wait for modals creations
245 map(() => this.authService.getUser())
246 )
247
248 // Admin modal
249 userSub.pipe(
250 filter(user => user.role.id === UserRole.ADMINISTRATOR)
251 ).subscribe(user => this.openAdminModalsIfNeeded(user))
252
253 // Account modal
254 userSub.pipe(
255 filter(user => user.role.id !== UserRole.ADMINISTRATOR)
256 ).subscribe(user => this.openAccountModalsIfNeeded(user))
257 }
258
259 private openAdminModalsIfNeeded (user: User) {
260 if (this.adminWelcomeModal.shouldOpen(user)) {
261 return this.adminWelcomeModal.show()
262 }
263
264 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
265
266 forkJoin([
267 this.serverService.getConfig().pipe(first()),
268 this.instanceService.getAbout().pipe(first())
269 ]).subscribe(([ config, about ]) => {
270 if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
271 this.instanceConfigWarningModal.show(about)
272 }
273 })
274 }
275
276 private openAccountModalsIfNeeded (user: User) {
277 if (this.accountSetupWarningModal.shouldOpen(user)) {
278 this.accountSetupWarningModal.show(user)
279 }
280 }
281
282 private initHotkeys () {
283 this.hotkeysService.add([
284 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
285 document.getElementById('search-video').focus()
286 return false
287 }, undefined, $localize`Focus the search bar`),
288
289 new Hotkey('b', (event: KeyboardEvent): boolean => {
290 this.menu.toggleMenu()
291 return false
292 }, undefined, $localize`Toggle the left menu`),
293
294 new Hotkey('g o', (event: KeyboardEvent): boolean => {
295 this.router.navigate([ '/videos/overview' ])
296 return false
297 }, undefined, $localize`Go to the discover videos page`),
298
299 new Hotkey('g t', (event: KeyboardEvent): boolean => {
300 this.router.navigate([ '/videos/trending' ])
301 return false
302 }, undefined, $localize`Go to the trending videos page`),
303
304 new Hotkey('g r', (event: KeyboardEvent): boolean => {
305 this.router.navigate([ '/videos/recently-added' ])
306 return false
307 }, undefined, $localize`Go to the recently added videos page`),
308
309 new Hotkey('g l', (event: KeyboardEvent): boolean => {
310 this.router.navigate([ '/videos/local' ])
311 return false
312 }, undefined, $localize`Go to the local videos page`),
313
314 new Hotkey('g u', (event: KeyboardEvent): boolean => {
315 this.router.navigate([ '/videos/upload' ])
316 return false
317 }, undefined, $localize`Go to the videos upload page`)
318 ])
319 }
320
321 private loadUser () {
322 const tokens = this.userLocalStorage.getTokens()
323 if (!tokens) return
324
325 const user = this.userLocalStorage.getLoggedInUser()
326 if (!user) return
327
328 // Initialize user
329 this.authService.buildAuthUser(user, tokens)
330 }
331 }