1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { concat } from 'rxjs'
3 import { filter, first, map, pairwise } from 'rxjs/operators'
4 import { DOCUMENT, PlatformLocation, ViewportScroller } 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, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, Router, Scroll } from '@angular/router'
8 import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
9 import { HooksService } from '@app/core/plugins/hooks.service'
10 import { PluginService } from '@app/core/plugins/plugin.service'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
13 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
14 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { LoadingBarService } from '@ngx-loading-bar/core'
16 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
17 import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
18 import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
19 import { MenuService } from './core/menu/menu.service'
20 import { POP_STATE_MODAL_DISMISS } from './helpers'
21 import { InstanceService } from './shared/shared-instance'
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
28 export class AppComponent implements OnInit, AfterViewInit {
29 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
31 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
32 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
33 @ViewChild('customModal') customModal: CustomModalComponent
36 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
38 private serverConfig: ServerConfig
41 @Inject(DOCUMENT) private document: Document,
42 @Inject(LOCALE_ID) private localeId: string,
43 private viewportScroller: ViewportScroller,
44 private router: Router,
45 private authService: AuthService,
46 private serverService: ServerService,
47 private pluginService: PluginService,
48 private instanceService: InstanceService,
49 private domSanitizer: DomSanitizer,
50 private redirectService: RedirectService,
51 private screenService: ScreenService,
52 private hotkeysService: HotkeysService,
53 private themeService: ThemeService,
54 private hooks: HooksService,
55 private location: PlatformLocation,
56 private modalService: NgbModal,
57 private markdownService: MarkdownService,
58 private ngbConfig: NgbConfig,
59 private loadingBar: LoadingBarService,
60 public menu: MenuService
62 this.ngbConfig.animation = false
66 return this.serverConfig.instance.name
70 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
74 document.getElementById('incompatible-browser').className += ' browser-ok'
76 this.serverConfig = this.serverService.getTmpConfig()
77 this.serverService.getConfig()
78 .subscribe(config => this.serverConfig = config)
81 this.themeService.initialize()
83 this.authService.loadClientCredentials()
85 if (this.isUserLoggedIn()) {
86 // The service will automatically redirect to the login page if the token is not valid anymore
87 this.authService.refreshUserInformation()
90 this.initRouteEvents()
93 this.injectBroadcastMessage()
97 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
99 this.openModalsIfNeeded()
101 this.document.documentElement.lang = getShortLocale(this.localeId)
105 this.pluginService.initializeCustomModal(this.customModal)
109 if (this.menu.isDisplayed()) return $localize`Close the left menu`
111 return $localize`Open the left menu`
115 return this.authService.isLoggedIn()
118 hideBroadcastMessage () {
119 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
121 this.broadcastMessage = null
122 this.screenService.isBroadcastMessageDisplayed = false
125 private initRouteEvents () {
126 let resetScroll = true
127 const eventsObs = this.router.events
129 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
131 // Handle anchors/restore position
132 scrollEvent.subscribe(e => {
133 // scrollToAnchor first to preserve anchor position when using history navigation
136 this.viewportScroller.scrollToAnchor(e.anchor)
143 return this.viewportScroller.scrollToPosition(e.position)
147 return this.viewportScroller.scrollToPosition([ 0, 0 ])
151 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
153 // When we add the a-state parameter, we don't want to alter the scroll
154 navigationEndEvent.pipe(pairwise())
155 .subscribe(([ e1, e2 ]) => {
159 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
160 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
162 if (previousUrl.pathname !== nextUrl.pathname) {
167 const nextSearchParams = nextUrl.searchParams
168 nextSearchParams.delete('a-state')
170 const previousSearchParams = previousUrl.searchParams
172 nextSearchParams.sort()
173 previousSearchParams.sort()
175 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
179 console.error('Cannot parse URL to check next scroll.', e)
184 // Homepage redirection
185 navigationEndEvent.pipe(
186 map(() => window.location.pathname),
187 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
188 ).subscribe(() => this.redirectService.redirectToHomepage(true))
191 navigationEndEvent.subscribe(e => {
192 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
195 // Automatically hide/display the menu
197 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
198 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
199 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
201 // Handle lazy loaded module
203 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
204 ).subscribe(() => this.loadingBar.useRef().start())
207 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
208 ).subscribe(() => this.loadingBar.useRef().complete())
211 private injectBroadcastMessage () {
213 this.serverService.getConfig().pipe(first()),
214 this.serverService.configReloaded
215 ).subscribe(async config => {
216 this.broadcastMessage = null
217 this.screenService.isBroadcastMessageDisplayed = false
219 const messageConfig = config.broadcastMessage
221 if (messageConfig.enabled) {
222 // Already dismissed this message?
223 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
227 const classes: { [id in BroadcastMessageLevel]: string } = {
229 warning: 'alert-warning',
230 error: 'alert-danger'
233 this.broadcastMessage = {
234 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
235 dismissable: messageConfig.dismissable,
236 class: classes[messageConfig.level]
239 this.screenService.isBroadcastMessageDisplayed = true
244 private injectJS () {
246 this.serverService.getConfig()
247 .subscribe(config => {
248 if (config.instance.customizations.javascript) {
250 // tslint:disable:no-eval
251 eval(config.instance.customizations.javascript)
253 console.error('Cannot eval custom JavaScript.', err)
259 private injectCSS () {
260 // Inject CSS if modified (admin config settings)
262 this.serverService.getConfig().pipe(first()),
263 this.serverService.configReloaded
264 ).subscribe(config => {
265 const headStyle = document.querySelector('style.custom-css-style')
266 if (headStyle) headStyle.parentNode.removeChild(headStyle)
268 // We test customCSS if the admin removed the css
269 if (this.customCSS || config.instance.customizations.css) {
270 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
271 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
276 private async loadPlugins () {
277 this.pluginService.initializePlugins()
279 this.hooks.runAction('action:application.init', 'common')
282 private async openModalsIfNeeded () {
283 this.authService.userInformationLoaded
285 map(() => this.authService.getUser()),
286 filter(user => user.role === UserRole.ADMINISTRATOR)
287 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
290 private async _openAdminModalsIfNeeded (user: User) {
291 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
293 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
295 this.instanceService.getAbout()
296 .subscribe(about => {
298 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
299 !about.instance.terms ||
300 !about.instance.administrator ||
301 !about.instance.maintenanceLifetime
303 this.instanceConfigWarningModal.show(about)
308 private initHotkeys () {
309 this.hotkeysService.add([
310 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
311 document.getElementById('search-video').focus()
313 }, undefined, $localize`Focus the search bar`),
315 new Hotkey('b', (event: KeyboardEvent): boolean => {
316 this.menu.toggleMenu()
318 }, undefined, $localize`Toggle the left menu`),
320 new Hotkey('g o', (event: KeyboardEvent): boolean => {
321 this.router.navigate([ '/videos/overview' ])
323 }, undefined, $localize`Go to the discover videos page`),
325 new Hotkey('g t', (event: KeyboardEvent): boolean => {
326 this.router.navigate([ '/videos/trending' ])
328 }, undefined, $localize`Go to the trending videos page`),
330 new Hotkey('g r', (event: KeyboardEvent): boolean => {
331 this.router.navigate([ '/videos/recently-added' ])
333 }, undefined, $localize`Go to the recently added videos page`),
335 new Hotkey('g l', (event: KeyboardEvent): boolean => {
336 this.router.navigate([ '/videos/local' ])
338 }, undefined, $localize`Go to the local videos page`),
340 new Hotkey('g u', (event: KeyboardEvent): boolean => {
341 this.router.navigate([ '/videos/upload' ])
343 }, undefined, $localize`Go to the videos upload page`)