1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { filter, map, switchMap } from 'rxjs/operators'
3 import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
4 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
5 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
6 import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
10 PeerTubeRouterService,
18 import { HooksService } from '@app/core/plugins/hooks.service'
19 import { PluginService } from '@app/core/plugins/plugin.service'
20 import { CustomModalComponent } from '@app/modal/custom-modal.component'
21 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
22 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
23 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
24 import { LoadingBarService } from '@ngx-loading-bar/core'
25 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
26 import { getShortLocale } from '@shared/core-utils/i18n'
27 import { BroadcastMessageLevel, HTMLServerConfig, ServerConfig, UserRole } from '@shared/models'
28 import { MenuService } from './core/menu/menu.service'
29 import { POP_STATE_MODAL_DISMISS } from './helpers'
30 import { InstanceService } from './shared/shared-instance'
34 templateUrl: './app.component.html',
35 styleUrls: [ './app.component.scss' ]
37 export class AppComponent implements OnInit, AfterViewInit {
38 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
40 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
41 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
42 @ViewChild('customModal') customModal: CustomModalComponent
45 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
47 private serverConfig: HTMLServerConfig
50 @Inject(DOCUMENT) private document: Document,
51 @Inject(LOCALE_ID) private localeId: string,
52 private router: Router,
53 private authService: AuthService,
54 private serverService: ServerService,
55 private peertubeRouter: PeerTubeRouterService,
56 private pluginService: PluginService,
57 private instanceService: InstanceService,
58 private domSanitizer: DomSanitizer,
59 private redirectService: RedirectService,
60 private screenService: ScreenService,
61 private hotkeysService: HotkeysService,
62 private themeService: ThemeService,
63 private hooks: HooksService,
64 private location: PlatformLocation,
65 private modalService: NgbModal,
66 private markdownService: MarkdownService,
67 private ngbConfig: NgbConfig,
68 private loadingBar: LoadingBarService,
69 private scrollService: ScrollService,
70 public menu: MenuService
72 this.ngbConfig.animation = false
76 return this.serverConfig.instance.name
80 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
84 document.getElementById('incompatible-browser').className += ' browser-ok'
86 this.serverConfig = this.serverService.getHTMLConfig()
88 this.hooks.runAction('action:application.init', 'common')
89 this.themeService.initialize()
91 this.authService.loadClientCredentials()
93 if (this.isUserLoggedIn()) {
94 // The service will automatically redirect to the login page if the token is not valid anymore
95 this.authService.refreshUserInformation()
98 this.initRouteEvents()
99 this.scrollService.enableScrollRestoration()
103 this.injectBroadcastMessage()
105 this.serverService.configReloaded
106 .subscribe(config => {
107 this.serverConfig = config
109 this.injectBroadcastMessage()
112 // Don't reinject JS since it could conflict with existing one
117 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
119 this.openModalsIfNeeded()
121 this.document.documentElement.lang = getShortLocale(this.localeId)
122 this.document.documentElement.dir = getLocaleDirection(this.localeId)
126 this.pluginService.initializeCustomModal(this.customModal)
130 if (this.menu.isDisplayed()) return $localize`Close the left menu`
132 return $localize`Open the left menu`
136 return this.authService.isLoggedIn()
139 hideBroadcastMessage () {
140 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
142 this.broadcastMessage = null
143 this.screenService.isBroadcastMessageDisplayed = false
146 private initRouteEvents () {
147 const eventsObs = this.router.events
150 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
151 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
154 // Automatically hide/display the menu
156 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
157 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
158 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
160 // Handle lazy loaded module
162 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
163 ).subscribe(() => this.loadingBar.useRef().start())
166 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
167 ).subscribe(() => this.loadingBar.useRef().complete())
170 private async injectBroadcastMessage () {
171 this.broadcastMessage = null
172 this.screenService.isBroadcastMessageDisplayed = false
174 const messageConfig = this.serverConfig.broadcastMessage
176 if (messageConfig.enabled) {
177 // Already dismissed this message?
178 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
182 const classes: { [id in BroadcastMessageLevel]: string } = {
184 warning: 'alert-warning',
185 error: 'alert-danger'
188 this.broadcastMessage = {
189 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
190 dismissable: messageConfig.dismissable,
191 class: classes[messageConfig.level]
194 this.screenService.isBroadcastMessageDisplayed = true
198 private injectJS () {
200 if (this.serverConfig.instance.customizations.javascript) {
202 /* eslint-disable no-eval */
203 eval(this.serverConfig.instance.customizations.javascript)
205 console.error('Cannot eval custom JavaScript.', err)
210 private injectCSS () {
211 const headStyle = document.querySelector('style.custom-css-style')
212 if (headStyle) headStyle.parentNode.removeChild(headStyle)
214 // We test customCSS if the admin removed the css
215 if (this.customCSS || this.serverConfig.instance.customizations.css) {
216 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
217 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
221 private async openModalsIfNeeded () {
222 this.authService.userInformationLoaded
224 map(() => this.authService.getUser()),
225 filter(user => user.role === UserRole.ADMINISTRATOR),
227 return this.serverService.getConfig()
228 .pipe(map(serverConfig => ({ serverConfig, user })))
230 ).subscribe(({ serverConfig, user }) => this._openAdminModalsIfNeeded(serverConfig, user))
233 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
234 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
236 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
238 this.instanceService.getAbout()
239 .subscribe(about => {
241 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
242 !about.instance.terms ||
243 !about.instance.administrator ||
244 !about.instance.maintenanceLifetime
246 this.instanceConfigWarningModal.show(about)
251 private initHotkeys () {
252 this.hotkeysService.add([
253 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
254 document.getElementById('search-video').focus()
256 }, undefined, $localize`Focus the search bar`),
258 new Hotkey('b', (event: KeyboardEvent): boolean => {
259 this.menu.toggleMenu()
261 }, undefined, $localize`Toggle the left menu`),
263 new Hotkey('g o', (event: KeyboardEvent): boolean => {
264 this.router.navigate([ '/videos/overview' ])
266 }, undefined, $localize`Go to the discover videos page`),
268 new Hotkey('g t', (event: KeyboardEvent): boolean => {
269 this.router.navigate([ '/videos/trending' ])
271 }, undefined, $localize`Go to the trending videos page`),
273 new Hotkey('g r', (event: KeyboardEvent): boolean => {
274 this.router.navigate([ '/videos/recently-added' ])
276 }, undefined, $localize`Go to the recently added videos page`),
278 new Hotkey('g l', (event: KeyboardEvent): boolean => {
279 this.router.navigate([ '/videos/local' ])
281 }, undefined, $localize`Go to the local videos page`),
283 new Hotkey('g u', (event: KeyboardEvent): boolean => {
284 this.router.navigate([ '/videos/upload' ])
286 }, undefined, $localize`Go to the videos upload page`)