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'
11 PeerTubeRouterService,
18 UserLocalStorageService
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'
39 templateUrl: './app.component.html',
40 styleUrls: [ './app.component.scss' ]
42 export class AppComponent implements OnInit, AfterViewInit {
43 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
45 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
46 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
47 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
48 @ViewChild('customModal') customModal: CustomModalComponent
51 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
53 private serverConfig: HTMLServerConfig
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
79 this.ngbConfig.animation = false
83 return this.serverConfig.instance.name
87 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
91 document.getElementById('incompatible-browser').className += ' browser-ok'
95 this.serverConfig = this.serverService.getHTMLConfig()
97 this.hooks.runAction('action:application.init', 'common')
98 this.themeService.initialize()
100 this.authService.loadClientCredentials()
102 if (this.isUserLoggedIn()) {
103 // The service will automatically redirect to the login page if the token is not valid anymore
104 this.authService.refreshUserInformation()
107 this.initRouteEvents()
108 this.scrollService.enableScrollRestoration()
112 this.injectBroadcastMessage()
114 this.serverService.configReloaded
115 .subscribe(config => {
116 this.serverConfig = config
118 this.injectBroadcastMessage()
121 // Don't reinject JS since it could conflict with existing one
126 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
128 this.openModalsIfNeeded()
130 this.document.documentElement.lang = getShortLocale(this.localeId)
131 this.document.documentElement.dir = getLocaleDirection(this.localeId)
135 this.pluginService.initializeCustomModal(this.customModal)
139 if (this.menu.isDisplayed()) return $localize`Close the left menu`
141 return $localize`Open the left menu`
145 return this.authService.isLoggedIn()
148 hideBroadcastMessage () {
149 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
151 this.broadcastMessage = null
152 this.screenService.isBroadcastMessageDisplayed = false
155 getNotificationIcon (message: { severity: 'success' | 'error' | 'info' }): GlobalIconName {
156 switch (message.severity) {
166 private initRouteEvents () {
167 const eventsObs = this.router.events
170 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
171 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
174 // Automatically hide/display the menu
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
180 // Handle lazy loaded module
182 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
183 ).subscribe(() => this.loadingBar.useRef().start())
186 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
187 ).subscribe(() => this.loadingBar.useRef().complete())
190 private async injectBroadcastMessage () {
191 this.broadcastMessage = null
192 this.screenService.isBroadcastMessageDisplayed = false
194 const messageConfig = this.serverConfig.broadcastMessage
196 if (messageConfig.enabled) {
197 // Already dismissed this message?
198 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
202 const classes: { [id in BroadcastMessageLevel]: string } = {
204 warning: 'alert-warning',
205 error: 'alert-danger'
208 this.broadcastMessage = {
209 message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
210 dismissable: messageConfig.dismissable,
211 class: classes[messageConfig.level]
214 this.screenService.isBroadcastMessageDisplayed = true
218 private injectJS () {
220 if (this.serverConfig.instance.customizations.javascript) {
222 /* eslint-disable no-eval */
223 eval(this.serverConfig.instance.customizations.javascript)
225 logger.error('Cannot eval custom JavaScript.', err)
230 private injectCSS () {
231 const headStyle = document.querySelector('style.custom-css-style')
232 if (headStyle) headStyle.parentNode.removeChild(headStyle)
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)
241 private openModalsIfNeeded () {
242 const userSub = this.authService.userInformationLoaded
244 delay(0), // Wait for modals creations
245 map(() => this.authService.getUser())
250 filter(user => user.role.id === UserRole.ADMINISTRATOR)
251 ).subscribe(user => this.openAdminModalsIfNeeded(user))
255 filter(user => user.role.id !== UserRole.ADMINISTRATOR)
256 ).subscribe(user => this.openAccountModalsIfNeeded(user))
259 private openAdminModalsIfNeeded (user: User) {
260 if (this.adminWelcomeModal.shouldOpen(user)) {
261 return this.adminWelcomeModal.show()
264 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
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)
276 private openAccountModalsIfNeeded (user: User) {
277 if (this.accountSetupWarningModal.shouldOpen(user)) {
278 this.accountSetupWarningModal.show(user)
282 private initHotkeys () {
283 this.hotkeysService.add([
284 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
285 document.getElementById('search-video').focus()
287 }, undefined, $localize`Focus the search bar`),
289 new Hotkey('b', (event: KeyboardEvent): boolean => {
290 this.menu.toggleMenu()
292 }, undefined, $localize`Toggle the left menu`),
294 new Hotkey('g o', (event: KeyboardEvent): boolean => {
295 this.router.navigate([ '/videos/overview' ])
297 }, undefined, $localize`Go to the discover videos page`),
299 new Hotkey('g t', (event: KeyboardEvent): boolean => {
300 this.router.navigate([ '/videos/trending' ])
302 }, undefined, $localize`Go to the trending videos page`),
304 new Hotkey('g r', (event: KeyboardEvent): boolean => {
305 this.router.navigate([ '/videos/recently-added' ])
307 }, undefined, $localize`Go to the recently added videos page`),
309 new Hotkey('g l', (event: KeyboardEvent): boolean => {
310 this.router.navigate([ '/videos/local' ])
312 }, undefined, $localize`Go to the local videos page`),
314 new Hotkey('g u', (event: KeyboardEvent): boolean => {
315 this.router.navigate([ '/videos/upload' ])
317 }, undefined, $localize`Go to the videos upload page`)
321 private loadUser () {
322 const tokens = this.userLocalStorage.getTokens()
325 const user = this.userLocalStorage.getLoggedInUser()
329 this.authService.buildAuthUser(user, tokens)