1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, delay } 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 { CustomModalComponent } from '@app/modal/custom-modal.component'
24 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
25 import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
26 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
27 import { LoadingBarService } from '@ngx-loading-bar/core'
28 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
29 import { getShortLocale } from '@shared/core-utils/i18n'
30 import { BroadcastMessageLevel, HTMLServerConfig, UserRole } from '@shared/models'
31 import { MenuService } from './core/menu/menu.service'
32 import { POP_STATE_MODAL_DISMISS } from './helpers'
33 import { InstanceService } from './shared/shared-instance'
37 templateUrl: './app.component.html',
38 styleUrls: [ './app.component.scss' ]
40 export class AppComponent implements OnInit, AfterViewInit {
41 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
43 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
44 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
45 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
46 @ViewChild('customModal') customModal: CustomModalComponent
49 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
51 private serverConfig: HTMLServerConfig
54 @Inject(DOCUMENT) private document: Document,
55 @Inject(LOCALE_ID) private localeId: string,
56 private router: Router,
57 private authService: AuthService,
58 private serverService: ServerService,
59 private peertubeRouter: PeerTubeRouterService,
60 private pluginService: PluginService,
61 private instanceService: InstanceService,
62 private domSanitizer: DomSanitizer,
63 private redirectService: RedirectService,
64 private screenService: ScreenService,
65 private hotkeysService: HotkeysService,
66 private themeService: ThemeService,
67 private hooks: HooksService,
68 private location: PlatformLocation,
69 private modalService: NgbModal,
70 private markdownService: MarkdownService,
71 private ngbConfig: NgbConfig,
72 private loadingBar: LoadingBarService,
73 private scrollService: ScrollService,
74 private userLocalStorage: UserLocalStorageService,
75 public menu: MenuService
77 this.ngbConfig.animation = false
81 return this.serverConfig.instance.name
85 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
89 document.getElementById('incompatible-browser').className += ' browser-ok'
93 this.serverConfig = this.serverService.getHTMLConfig()
95 this.hooks.runAction('action:application.init', 'common')
96 this.themeService.initialize()
98 this.authService.loadClientCredentials()
100 if (this.isUserLoggedIn()) {
101 // The service will automatically redirect to the login page if the token is not valid anymore
102 this.authService.refreshUserInformation()
105 this.initRouteEvents()
106 this.scrollService.enableScrollRestoration()
110 this.injectBroadcastMessage()
112 this.serverService.configReloaded
113 .subscribe(config => {
114 this.serverConfig = config
116 this.injectBroadcastMessage()
119 // Don't reinject JS since it could conflict with existing one
124 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
126 this.openModalsIfNeeded()
128 this.document.documentElement.lang = getShortLocale(this.localeId)
129 this.document.documentElement.dir = getLocaleDirection(this.localeId)
133 this.pluginService.initializeCustomModal(this.customModal)
137 if (this.menu.isDisplayed()) return $localize`Close the left menu`
139 return $localize`Open the left menu`
143 return this.authService.isLoggedIn()
146 hideBroadcastMessage () {
147 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
149 this.broadcastMessage = null
150 this.screenService.isBroadcastMessageDisplayed = false
153 private initRouteEvents () {
154 const eventsObs = this.router.events
157 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
158 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
161 // Automatically hide/display the menu
163 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
164 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
165 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
167 // Handle lazy loaded module
169 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
170 ).subscribe(() => this.loadingBar.useRef().start())
173 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
174 ).subscribe(() => this.loadingBar.useRef().complete())
177 private async injectBroadcastMessage () {
178 this.broadcastMessage = null
179 this.screenService.isBroadcastMessageDisplayed = false
181 const messageConfig = this.serverConfig.broadcastMessage
183 if (messageConfig.enabled) {
184 // Already dismissed this message?
185 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
189 const classes: { [id in BroadcastMessageLevel]: string } = {
191 warning: 'alert-warning',
192 error: 'alert-danger'
195 this.broadcastMessage = {
196 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
197 dismissable: messageConfig.dismissable,
198 class: classes[messageConfig.level]
201 this.screenService.isBroadcastMessageDisplayed = true
205 private injectJS () {
207 if (this.serverConfig.instance.customizations.javascript) {
209 /* eslint-disable no-eval */
210 eval(this.serverConfig.instance.customizations.javascript)
212 console.error('Cannot eval custom JavaScript.', err)
217 private injectCSS () {
218 const headStyle = document.querySelector('style.custom-css-style')
219 if (headStyle) headStyle.parentNode.removeChild(headStyle)
221 // We test customCSS if the admin removed the css
222 if (this.customCSS || this.serverConfig.instance.customizations.css) {
223 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
224 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
228 private openModalsIfNeeded () {
229 const userSub = this.authService.userInformationLoaded
231 delay(0), // Wait for modals creations
232 map(() => this.authService.getUser())
237 filter(user => user.role === UserRole.ADMINISTRATOR)
238 ).subscribe(user => this.openAdminModalsIfNeeded(user))
242 filter(user => user.role !== UserRole.ADMINISTRATOR)
243 ).subscribe(user => this.openAccountModalsIfNeeded(user))
246 private openAdminModalsIfNeeded (user: User) {
247 if (this.adminWelcomeModal.shouldOpen(user)) {
248 return this.adminWelcomeModal.show()
251 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
254 this.serverService.getConfig().pipe(first()),
255 this.instanceService.getAbout().pipe(first())
256 ]).subscribe(([ config, about ]) => {
257 if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
258 this.instanceConfigWarningModal.show(about)
263 private openAccountModalsIfNeeded (user: User) {
264 if (this.accountSetupWarningModal.shouldOpen(user)) {
265 this.accountSetupWarningModal.show(user)
269 private initHotkeys () {
270 this.hotkeysService.add([
271 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
272 document.getElementById('search-video').focus()
274 }, undefined, $localize`Focus the search bar`),
276 new Hotkey('b', (event: KeyboardEvent): boolean => {
277 this.menu.toggleMenu()
279 }, undefined, $localize`Toggle the left menu`),
281 new Hotkey('g o', (event: KeyboardEvent): boolean => {
282 this.router.navigate([ '/videos/overview' ])
284 }, undefined, $localize`Go to the discover videos page`),
286 new Hotkey('g t', (event: KeyboardEvent): boolean => {
287 this.router.navigate([ '/videos/trending' ])
289 }, undefined, $localize`Go to the trending videos page`),
291 new Hotkey('g r', (event: KeyboardEvent): boolean => {
292 this.router.navigate([ '/videos/recently-added' ])
294 }, undefined, $localize`Go to the recently added videos page`),
296 new Hotkey('g l', (event: KeyboardEvent): boolean => {
297 this.router.navigate([ '/videos/local' ])
299 }, undefined, $localize`Go to the local videos page`),
301 new Hotkey('g u', (event: KeyboardEvent): boolean => {
302 this.router.navigate([ '/videos/upload' ])
304 }, undefined, $localize`Go to the videos upload page`)
308 private loadUser () {
309 const tokens = this.userLocalStorage.getTokens()
312 const user = this.userLocalStorage.getLoggedInUser()
316 this.authService.buildAuthUser(user, tokens)