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 { NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { I18n } from '@ngx-translate/i18n-polyfill'
16 import { BroadcastMessageLevel, getShortLocale, is18nPath, ServerConfig, UserRole } from '@shared/models'
17 import { MenuService } from './core/menu/menu.service'
18 import { peertubeLocalStorage, POP_STATE_MODAL_DISMISS } from './helpers'
19 import { InstanceService } from './shared/shared-instance'
23 templateUrl: './app.component.html',
24 styleUrls: [ './app.component.scss' ]
26 export class AppComponent implements OnInit, AfterViewInit {
27 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
29 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
30 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
31 @ViewChild('customModal') customModal: CustomModalComponent
34 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
36 private serverConfig: ServerConfig
39 @Inject(DOCUMENT) private document: Document,
40 @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 public menu: MenuService
61 return this.serverConfig.instance.name
65 return RedirectService.DEFAULT_ROUTE
69 document.getElementById('incompatible-browser').className += ' browser-ok'
71 this.serverConfig = this.serverService.getTmpConfig()
72 this.serverService.getConfig()
73 .subscribe(config => this.serverConfig = config)
76 this.themeService.initialize()
78 this.authService.loadClientCredentials()
80 if (this.isUserLoggedIn()) {
81 // The service will automatically redirect to the login page if the token is not valid anymore
82 this.authService.refreshUserInformation()
85 this.initRouteEvents()
88 this.injectBroadcastMessage()
92 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
94 this.openModalsIfNeeded()
96 this.document.documentElement.lang = getShortLocale(this.localeId)
100 this.pluginService.initializeCustomModal(this.customModal)
104 return this.authService.isLoggedIn()
107 hideBroadcastMessage () {
108 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
110 this.broadcastMessage = null
113 private initRouteEvents () {
114 let resetScroll = true
115 const eventsObs = this.router.events
117 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
119 scrollEvent.subscribe(e => {
121 return this.viewportScroller.scrollToPosition(e.position)
125 return this.viewportScroller.scrollToAnchor(e.anchor)
129 return this.viewportScroller.scrollToPosition([ 0, 0 ])
133 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
135 // When we add the a-state parameter, we don't want to alter the scroll
136 navigationEndEvent.pipe(pairwise())
137 .subscribe(([ e1, e2 ]) => {
141 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
142 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
144 if (previousUrl.pathname !== nextUrl.pathname) {
149 const nextSearchParams = nextUrl.searchParams
150 nextSearchParams.delete('a-state')
152 const previousSearchParams = previousUrl.searchParams
154 nextSearchParams.sort()
155 previousSearchParams.sort()
157 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
161 console.error('Cannot parse URL to check next scroll.', e)
166 navigationEndEvent.pipe(
167 map(() => window.location.pathname),
168 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
169 ).subscribe(() => this.redirectService.redirectToHomepage(true))
171 navigationEndEvent.subscribe(e => {
172 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
176 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
177 filter(() => this.screenService.isInSmallView())
178 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
181 private injectBroadcastMessage () {
183 this.serverService.getConfig().pipe(first()),
184 this.serverService.configReloaded
185 ).subscribe(async config => {
186 this.broadcastMessage = null
188 const messageConfig = config.broadcastMessage
190 if (messageConfig.enabled) {
191 // Already dismissed this message?
192 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
196 const classes: { [id in BroadcastMessageLevel]: string } = {
198 warning: 'alert-warning',
199 error: 'alert-danger'
202 this.broadcastMessage = {
203 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
204 dismissable: messageConfig.dismissable,
205 class: classes[messageConfig.level]
211 private injectJS () {
213 this.serverService.getConfig()
214 .subscribe(config => {
215 if (config.instance.customizations.javascript) {
217 // tslint:disable:no-eval
218 eval(config.instance.customizations.javascript)
220 console.error('Cannot eval custom JavaScript.', err)
226 private injectCSS () {
227 // Inject CSS if modified (admin config settings)
229 this.serverService.getConfig().pipe(first()),
230 this.serverService.configReloaded
231 ).subscribe(config => {
232 const headStyle = document.querySelector('style.custom-css-style')
233 if (headStyle) headStyle.parentNode.removeChild(headStyle)
235 // We test customCSS if the admin removed the css
236 if (this.customCSS || config.instance.customizations.css) {
237 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
238 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
243 private async loadPlugins () {
244 this.pluginService.initializePlugins()
246 this.hooks.runAction('action:application.init', 'common')
249 private async openModalsIfNeeded () {
250 this.authService.userInformationLoaded
252 map(() => this.authService.getUser()),
253 filter(user => user.role === UserRole.ADMINISTRATOR)
254 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
257 private async _openAdminModalsIfNeeded (user: User) {
258 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
260 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
262 this.instanceService.getAbout()
263 .subscribe(about => {
265 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
266 !about.instance.terms ||
267 !about.instance.administrator ||
268 !about.instance.maintenanceLifetime
270 this.instanceConfigWarningModal.show(about)
275 private initHotkeys () {
276 this.hotkeysService.add([
277 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
278 document.getElementById('search-video').focus()
280 }, undefined, this.i18n('Focus the search bar')),
282 new Hotkey('b', (event: KeyboardEvent): boolean => {
283 this.menu.toggleMenu()
285 }, undefined, this.i18n('Toggle the left menu')),
287 new Hotkey('g o', (event: KeyboardEvent): boolean => {
288 this.router.navigate([ '/videos/overview' ])
290 }, undefined, this.i18n('Go to the discover videos page')),
292 new Hotkey('g t', (event: KeyboardEvent): boolean => {
293 this.router.navigate([ '/videos/trending' ])
295 }, undefined, this.i18n('Go to the trending videos page')),
297 new Hotkey('g r', (event: KeyboardEvent): boolean => {
298 this.router.navigate([ '/videos/recently-added' ])
300 }, undefined, this.i18n('Go to the recently added videos page')),
302 new Hotkey('g l', (event: KeyboardEvent): boolean => {
303 this.router.navigate([ '/videos/local' ])
305 }, undefined, this.i18n('Go to the local videos page')),
307 new Hotkey('g u', (event: KeyboardEvent): boolean => {
308 this.router.navigate([ '/videos/upload' ])
310 }, undefined, this.i18n('Go to the videos upload page'))