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, 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 { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
16 import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
17 import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
18 import { MenuService } from './core/menu/menu.service'
19 import { POP_STATE_MODAL_DISMISS } from './helpers'
20 import { InstanceService } from './shared/shared-instance'
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
27 export class AppComponent implements OnInit, AfterViewInit {
28 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
30 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
31 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
32 @ViewChild('customModal') customModal: CustomModalComponent
35 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
37 private serverConfig: ServerConfig
40 @Inject(DOCUMENT) private document: Document,
41 @Inject(LOCALE_ID) private localeId: string,
42 private viewportScroller: ViewportScroller,
43 private router: Router,
44 private authService: AuthService,
45 private serverService: ServerService,
46 private pluginService: PluginService,
47 private instanceService: InstanceService,
48 private domSanitizer: DomSanitizer,
49 private redirectService: RedirectService,
50 private screenService: ScreenService,
51 private hotkeysService: HotkeysService,
52 private themeService: ThemeService,
53 private hooks: HooksService,
54 private location: PlatformLocation,
55 private modalService: NgbModal,
56 private markdownService: MarkdownService,
57 private ngbConfig: NgbConfig,
58 public menu: MenuService
60 this.ngbConfig.animation = false
64 return this.serverConfig.instance.name
68 return RedirectService.DEFAULT_ROUTE
72 document.getElementById('incompatible-browser').className += ' browser-ok'
74 this.serverConfig = this.serverService.getTmpConfig()
75 this.serverService.getConfig()
76 .subscribe(config => this.serverConfig = config)
79 this.themeService.initialize()
81 this.authService.loadClientCredentials()
83 if (this.isUserLoggedIn()) {
84 // The service will automatically redirect to the login page if the token is not valid anymore
85 this.authService.refreshUserInformation()
88 this.initRouteEvents()
91 this.injectBroadcastMessage()
95 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
97 this.openModalsIfNeeded()
99 this.document.documentElement.lang = getShortLocale(this.localeId)
103 this.pluginService.initializeCustomModal(this.customModal)
107 if (this.menu.isDisplayed()) return $localize`Close the left menu`
109 return $localize`Open the left menu`
113 return this.authService.isLoggedIn()
116 hideBroadcastMessage () {
117 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
119 this.broadcastMessage = null
120 this.screenService.isBroadcastMessageDisplayed = false
123 private initRouteEvents () {
124 let resetScroll = true
125 const eventsObs = this.router.events
127 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
129 scrollEvent.subscribe(e => {
130 // scrollToAnchor first to preserve anchor position when using history navigation
133 this.viewportScroller.scrollToAnchor(e.anchor)
140 return this.viewportScroller.scrollToPosition(e.position)
144 return this.viewportScroller.scrollToPosition([ 0, 0 ])
148 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
150 // When we add the a-state parameter, we don't want to alter the scroll
151 navigationEndEvent.pipe(pairwise())
152 .subscribe(([ e1, e2 ]) => {
156 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
157 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
159 if (previousUrl.pathname !== nextUrl.pathname) {
164 const nextSearchParams = nextUrl.searchParams
165 nextSearchParams.delete('a-state')
167 const previousSearchParams = previousUrl.searchParams
169 nextSearchParams.sort()
170 previousSearchParams.sort()
172 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
176 console.error('Cannot parse URL to check next scroll.', e)
181 navigationEndEvent.pipe(
182 map(() => window.location.pathname),
183 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
184 ).subscribe(() => this.redirectService.redirectToHomepage(true))
186 navigationEndEvent.subscribe(e => {
187 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
191 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
192 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
193 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
196 private injectBroadcastMessage () {
198 this.serverService.getConfig().pipe(first()),
199 this.serverService.configReloaded
200 ).subscribe(async config => {
201 this.broadcastMessage = null
202 this.screenService.isBroadcastMessageDisplayed = false
204 const messageConfig = config.broadcastMessage
206 if (messageConfig.enabled) {
207 // Already dismissed this message?
208 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
212 const classes: { [id in BroadcastMessageLevel]: string } = {
214 warning: 'alert-warning',
215 error: 'alert-danger'
218 this.broadcastMessage = {
219 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
220 dismissable: messageConfig.dismissable,
221 class: classes[messageConfig.level]
224 this.screenService.isBroadcastMessageDisplayed = true
229 private injectJS () {
231 this.serverService.getConfig()
232 .subscribe(config => {
233 if (config.instance.customizations.javascript) {
235 // tslint:disable:no-eval
236 eval(config.instance.customizations.javascript)
238 console.error('Cannot eval custom JavaScript.', err)
244 private injectCSS () {
245 // Inject CSS if modified (admin config settings)
247 this.serverService.getConfig().pipe(first()),
248 this.serverService.configReloaded
249 ).subscribe(config => {
250 const headStyle = document.querySelector('style.custom-css-style')
251 if (headStyle) headStyle.parentNode.removeChild(headStyle)
253 // We test customCSS if the admin removed the css
254 if (this.customCSS || config.instance.customizations.css) {
255 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
256 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
261 private async loadPlugins () {
262 this.pluginService.initializePlugins()
264 this.hooks.runAction('action:application.init', 'common')
267 private async openModalsIfNeeded () {
268 this.authService.userInformationLoaded
270 map(() => this.authService.getUser()),
271 filter(user => user.role === UserRole.ADMINISTRATOR)
272 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
275 private async _openAdminModalsIfNeeded (user: User) {
276 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
278 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
280 this.instanceService.getAbout()
281 .subscribe(about => {
283 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
284 !about.instance.terms ||
285 !about.instance.administrator ||
286 !about.instance.maintenanceLifetime
288 this.instanceConfigWarningModal.show(about)
293 private initHotkeys () {
294 this.hotkeysService.add([
295 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
296 document.getElementById('search-video').focus()
298 }, undefined, $localize`Focus the search bar`),
300 new Hotkey('b', (event: KeyboardEvent): boolean => {
301 this.menu.toggleMenu()
303 }, undefined, $localize`Toggle the left menu`),
305 new Hotkey('g o', (event: KeyboardEvent): boolean => {
306 this.router.navigate([ '/videos/overview' ])
308 }, undefined, $localize`Go to the discover videos page`),
310 new Hotkey('g t', (event: KeyboardEvent): boolean => {
311 this.router.navigate([ '/videos/trending' ])
313 }, undefined, $localize`Go to the trending videos page`),
315 new Hotkey('g r', (event: KeyboardEvent): boolean => {
316 this.router.navigate([ '/videos/recently-added' ])
318 }, undefined, $localize`Go to the recently added videos page`),
320 new Hotkey('g l', (event: KeyboardEvent): boolean => {
321 this.router.navigate([ '/videos/local' ])
323 }, undefined, $localize`Go to the local videos page`),
325 new Hotkey('g u', (event: KeyboardEvent): boolean => {
326 this.router.navigate([ '/videos/upload' ])
328 }, undefined, $localize`Go to the videos upload page`)