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 document.getElementById('incompatible-browser').className += ' browser-ok'
91 this.serverConfig = this.serverService.getHTMLConfig()
93 this.hooks.runAction('action:application.init', 'common')
94 this.themeService.initialize()
96 this.authService.loadClientCredentials()
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()
103 this.initRouteEvents()
104 this.scrollService.enableScrollRestoration()
108 this.injectBroadcastMessage()
110 this.serverService.configReloaded
111 .subscribe(config => {
112 this.serverConfig = config
114 this.injectBroadcastMessage()
117 // Don't reinject JS since it could conflict with existing one
122 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
124 this.openModalsIfNeeded()
126 this.document.documentElement.lang = getShortLocale(this.localeId)
127 this.document.documentElement.dir = getLocaleDirection(this.localeId)
131 this.pluginService.initializeCustomModal(this.customModal)
134 // ---------------------------------------------------------------------------
137 return this.redirectService.getDefaultRoute().split('?')[0]
140 getDefaultRouteQuery () {
141 return this.router.parseUrl(this.redirectService.getDefaultRoute()).queryParams
144 // ---------------------------------------------------------------------------
147 if (this.menu.isDisplayed()) return $localize`Close the left menu`
149 return $localize`Open the left menu`
153 return this.authService.isLoggedIn()
156 hideBroadcastMessage () {
157 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
159 this.broadcastMessage = null
160 this.screenService.isBroadcastMessageDisplayed = false
163 getNotificationIcon (message: { severity: 'success' | 'error' | 'info' }): GlobalIconName {
164 switch (message.severity) {
174 private initRouteEvents () {
175 const eventsObs = this.router.events
178 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
179 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
182 // Automatically hide/display the menu
184 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
185 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
186 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
188 // Handle lazy loaded module
190 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
191 ).subscribe(() => this.loadingBar.useRef().start())
194 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
195 ).subscribe(() => this.loadingBar.useRef().complete())
198 private async injectBroadcastMessage () {
199 this.broadcastMessage = null
200 this.screenService.isBroadcastMessageDisplayed = false
202 const messageConfig = this.serverConfig.broadcastMessage
204 if (messageConfig.enabled) {
205 // Already dismissed this message?
206 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
210 const classes: { [id in BroadcastMessageLevel]: string } = {
212 warning: 'alert-warning',
213 error: 'alert-danger'
216 this.broadcastMessage = {
217 message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
218 dismissable: messageConfig.dismissable,
219 class: classes[messageConfig.level]
222 this.screenService.isBroadcastMessageDisplayed = true
226 private injectJS () {
228 if (this.serverConfig.instance.customizations.javascript) {
230 /* eslint-disable no-eval */
231 eval(this.serverConfig.instance.customizations.javascript)
233 logger.error('Cannot eval custom JavaScript.', err)
238 private injectCSS () {
239 const headStyle = document.querySelector('style.custom-css-style')
240 if (headStyle) headStyle.parentNode.removeChild(headStyle)
242 // We test customCSS if the admin removed the css
243 if (this.customCSS || this.serverConfig.instance.customizations.css) {
244 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
245 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
249 private openModalsIfNeeded () {
250 const userSub = this.authService.userInformationLoaded
252 delay(0), // Wait for modals creations
253 map(() => this.authService.getUser())
258 filter(user => user.role.id === UserRole.ADMINISTRATOR)
259 ).subscribe(user => this.openAdminModalsIfNeeded(user))
263 filter(user => user.role.id !== UserRole.ADMINISTRATOR)
264 ).subscribe(user => this.openAccountModalsIfNeeded(user))
267 private openAdminModalsIfNeeded (user: User) {
268 if (this.adminWelcomeModal.shouldOpen(user)) {
269 return this.adminWelcomeModal.show()
272 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
275 this.serverService.getConfig().pipe(first()),
276 this.instanceService.getAbout().pipe(first())
277 ]).subscribe(([ config, about ]) => {
278 if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
279 this.instanceConfigWarningModal.show(about)
284 private openAccountModalsIfNeeded (user: User) {
285 if (this.accountSetupWarningModal.shouldOpen(user)) {
286 this.accountSetupWarningModal.show(user)
290 private initHotkeys () {
291 this.hotkeysService.add([
292 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
293 document.getElementById('search-video').focus()
295 }, undefined, $localize`Focus the search bar`),
297 new Hotkey('b', (event: KeyboardEvent): boolean => {
298 this.menu.toggleMenu()
300 }, undefined, $localize`Toggle the left menu`),
302 new Hotkey('g o', (event: KeyboardEvent): boolean => {
303 this.router.navigate([ '/videos/overview' ])
305 }, undefined, $localize`Go to the discover videos page`),
307 new Hotkey('g t', (event: KeyboardEvent): boolean => {
308 this.router.navigate([ '/videos/trending' ])
310 }, undefined, $localize`Go to the trending videos page`),
312 new Hotkey('g r', (event: KeyboardEvent): boolean => {
313 this.router.navigate([ '/videos/recently-added' ])
315 }, undefined, $localize`Go to the recently added videos page`),
317 new Hotkey('g l', (event: KeyboardEvent): boolean => {
318 this.router.navigate([ '/videos/local' ])
320 }, undefined, $localize`Go to the local videos page`),
322 new Hotkey('g u', (event: KeyboardEvent): boolean => {
323 this.router.navigate([ '/videos/upload' ])
325 }, undefined, $localize`Go to the videos upload page`)
329 private loadUser () {
330 const tokens = this.userLocalStorage.getTokens()
333 const user = this.userLocalStorage.getLoggedInUser()
337 this.authService.buildAuthUser(user, tokens)