1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { 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,
19 import { HooksService } from '@app/core/plugins/hooks.service'
20 import { PluginService } from '@app/core/plugins/plugin.service'
21 import { AccountSetupWarningModalComponent } from '@app/modal/account-setup-warning-modal.component'
22 import { CustomModalComponent } from '@app/modal/custom-modal.component'
23 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
24 import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
25 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
26 import { LoadingBarService } from '@ngx-loading-bar/core'
27 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
28 import { getShortLocale } from '@shared/core-utils/i18n'
29 import { BroadcastMessageLevel, HTMLServerConfig, UserRole } from '@shared/models'
30 import { MenuService } from './core/menu/menu.service'
31 import { POP_STATE_MODAL_DISMISS } from './helpers'
32 import { InstanceService } from './shared/shared-instance'
36 templateUrl: './app.component.html',
37 styleUrls: [ './app.component.scss' ]
39 export class AppComponent implements OnInit, AfterViewInit {
40 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
42 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
43 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
44 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
45 @ViewChild('customModal') customModal: CustomModalComponent
48 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
50 private serverConfig: HTMLServerConfig
53 @Inject(DOCUMENT) private document: Document,
54 @Inject(LOCALE_ID) private localeId: string,
55 private router: Router,
56 private authService: AuthService,
57 private serverService: ServerService,
58 private peertubeRouter: PeerTubeRouterService,
59 private pluginService: PluginService,
60 private instanceService: InstanceService,
61 private domSanitizer: DomSanitizer,
62 private redirectService: RedirectService,
63 private screenService: ScreenService,
64 private hotkeysService: HotkeysService,
65 private themeService: ThemeService,
66 private hooks: HooksService,
67 private location: PlatformLocation,
68 private modalService: NgbModal,
69 private markdownService: MarkdownService,
70 private ngbConfig: NgbConfig,
71 private loadingBar: LoadingBarService,
72 private scrollService: ScrollService,
73 public menu: MenuService
75 this.ngbConfig.animation = false
79 return this.serverConfig.instance.name
83 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
87 document.getElementById('incompatible-browser').className += ' browser-ok'
89 this.serverConfig = this.serverService.getHTMLConfig()
91 this.hooks.runAction('action:application.init', 'common')
92 this.themeService.initialize()
94 this.authService.loadClientCredentials()
96 if (this.isUserLoggedIn()) {
97 // The service will automatically redirect to the login page if the token is not valid anymore
98 this.authService.refreshUserInformation()
101 this.initRouteEvents()
102 this.scrollService.enableScrollRestoration()
106 this.injectBroadcastMessage()
108 this.serverService.configReloaded
109 .subscribe(config => {
110 this.serverConfig = config
112 this.injectBroadcastMessage()
115 // Don't reinject JS since it could conflict with existing one
120 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
122 this.openModalsIfNeeded()
124 this.document.documentElement.lang = getShortLocale(this.localeId)
125 this.document.documentElement.dir = getLocaleDirection(this.localeId)
129 this.pluginService.initializeCustomModal(this.customModal)
133 if (this.menu.isDisplayed()) return $localize`Close the left menu`
135 return $localize`Open the left menu`
139 return this.authService.isLoggedIn()
142 hideBroadcastMessage () {
143 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
145 this.broadcastMessage = null
146 this.screenService.isBroadcastMessageDisplayed = false
149 private initRouteEvents () {
150 const eventsObs = this.router.events
153 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
154 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
157 // Automatically hide/display the menu
159 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
160 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
161 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
163 // Handle lazy loaded module
165 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
166 ).subscribe(() => this.loadingBar.useRef().start())
169 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
170 ).subscribe(() => this.loadingBar.useRef().complete())
173 private async injectBroadcastMessage () {
174 this.broadcastMessage = null
175 this.screenService.isBroadcastMessageDisplayed = false
177 const messageConfig = this.serverConfig.broadcastMessage
179 if (messageConfig.enabled) {
180 // Already dismissed this message?
181 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
185 const classes: { [id in BroadcastMessageLevel]: string } = {
187 warning: 'alert-warning',
188 error: 'alert-danger'
191 this.broadcastMessage = {
192 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
193 dismissable: messageConfig.dismissable,
194 class: classes[messageConfig.level]
197 this.screenService.isBroadcastMessageDisplayed = true
201 private injectJS () {
203 if (this.serverConfig.instance.customizations.javascript) {
205 /* eslint-disable no-eval */
206 eval(this.serverConfig.instance.customizations.javascript)
208 console.error('Cannot eval custom JavaScript.', err)
213 private injectCSS () {
214 const headStyle = document.querySelector('style.custom-css-style')
215 if (headStyle) headStyle.parentNode.removeChild(headStyle)
217 // We test customCSS if the admin removed the css
218 if (this.customCSS || this.serverConfig.instance.customizations.css) {
219 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
220 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
224 private openModalsIfNeeded () {
225 const userSub = this.authService.userInformationLoaded
226 .pipe(map(() => this.authService.getUser()))
230 filter(user => user.role === UserRole.ADMINISTRATOR)
231 ).subscribe(user => this.openAdminModalsIfNeeded(user))
235 filter(user => user.role !== UserRole.ADMINISTRATOR)
236 ).subscribe(user => this.openAccountModalsIfNeeded(user))
239 private openAdminModalsIfNeeded (user: User) {
240 if (this.adminWelcomeModal.shouldOpen(user)) {
241 return this.adminWelcomeModal.show()
244 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
247 this.serverService.getConfig().pipe(first()),
248 this.instanceService.getAbout().pipe(first())
249 ]).subscribe(([ config, about ]) => {
250 if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
251 this.instanceConfigWarningModal.show(about)
256 private openAccountModalsIfNeeded (user: User) {
257 if (this.accountSetupWarningModal.shouldOpen(user)) {
258 this.accountSetupWarningModal.show(user)
262 private initHotkeys () {
263 this.hotkeysService.add([
264 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
265 document.getElementById('search-video').focus()
267 }, undefined, $localize`Focus the search bar`),
269 new Hotkey('b', (event: KeyboardEvent): boolean => {
270 this.menu.toggleMenu()
272 }, undefined, $localize`Toggle the left menu`),
274 new Hotkey('g o', (event: KeyboardEvent): boolean => {
275 this.router.navigate([ '/videos/overview' ])
277 }, undefined, $localize`Go to the discover videos page`),
279 new Hotkey('g t', (event: KeyboardEvent): boolean => {
280 this.router.navigate([ '/videos/trending' ])
282 }, undefined, $localize`Go to the trending videos page`),
284 new Hotkey('g r', (event: KeyboardEvent): boolean => {
285 this.router.navigate([ '/videos/recently-added' ])
287 }, undefined, $localize`Go to the recently added videos page`),
289 new Hotkey('g l', (event: KeyboardEvent): boolean => {
290 this.router.navigate([ '/videos/local' ])
292 }, undefined, $localize`Go to the local videos page`),
294 new Hotkey('g u', (event: KeyboardEvent): boolean => {
295 this.router.navigate([ '/videos/upload' ])
297 }, undefined, $localize`Go to the videos upload page`)