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 { POP_STATE_MODAL_DISMISS } from './helpers'
19 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
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,
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 public menu: MenuService
62 return this.serverConfig.instance.name
66 return RedirectService.DEFAULT_ROUTE
70 document.getElementById('incompatible-browser').className += ' browser-ok'
72 this.serverConfig = this.serverService.getTmpConfig()
73 this.serverService.getConfig()
74 .subscribe(config => this.serverConfig = config)
77 this.themeService.initialize()
79 this.authService.loadClientCredentials()
81 if (this.isUserLoggedIn()) {
82 // The service will automatically redirect to the login page if the token is not valid anymore
83 this.authService.refreshUserInformation()
86 this.initRouteEvents()
89 this.injectBroadcastMessage()
93 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
95 this.openModalsIfNeeded()
97 this.document.documentElement.lang = getShortLocale(this.localeId)
101 this.pluginService.initializeCustomModal(this.customModal)
105 return this.authService.isLoggedIn()
108 hideBroadcastMessage () {
109 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
111 this.broadcastMessage = null
114 private initRouteEvents () {
115 let resetScroll = true
116 const eventsObs = this.router.events
118 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
120 scrollEvent.subscribe(e => {
122 return this.viewportScroller.scrollToPosition(e.position)
126 return this.viewportScroller.scrollToAnchor(e.anchor)
130 return this.viewportScroller.scrollToPosition([ 0, 0 ])
134 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
136 // When we add the a-state parameter, we don't want to alter the scroll
137 navigationEndEvent.pipe(pairwise())
138 .subscribe(([ e1, e2 ]) => {
142 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
143 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
145 if (previousUrl.pathname !== nextUrl.pathname) {
150 const nextSearchParams = nextUrl.searchParams
151 nextSearchParams.delete('a-state')
153 const previousSearchParams = previousUrl.searchParams
155 nextSearchParams.sort()
156 previousSearchParams.sort()
158 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
162 console.error('Cannot parse URL to check next scroll.', e)
167 navigationEndEvent.pipe(
168 map(() => window.location.pathname),
169 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
170 ).subscribe(() => this.redirectService.redirectToHomepage(true))
172 navigationEndEvent.subscribe(e => {
173 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
177 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
178 filter(() => this.screenService.isInSmallView())
179 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
182 private injectBroadcastMessage () {
184 this.serverService.getConfig().pipe(first()),
185 this.serverService.configReloaded
186 ).subscribe(async config => {
187 this.broadcastMessage = null
189 const messageConfig = config.broadcastMessage
191 if (messageConfig.enabled) {
192 // Already dismissed this message?
193 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
197 const classes: { [id in BroadcastMessageLevel]: string } = {
199 warning: 'alert-warning',
200 error: 'alert-danger'
203 this.broadcastMessage = {
204 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
205 dismissable: messageConfig.dismissable,
206 class: classes[messageConfig.level]
212 private injectJS () {
214 this.serverService.getConfig()
215 .subscribe(config => {
216 if (config.instance.customizations.javascript) {
218 // tslint:disable:no-eval
219 eval(config.instance.customizations.javascript)
221 console.error('Cannot eval custom JavaScript.', err)
227 private injectCSS () {
228 // Inject CSS if modified (admin config settings)
230 this.serverService.getConfig().pipe(first()),
231 this.serverService.configReloaded
232 ).subscribe(config => {
233 const headStyle = document.querySelector('style.custom-css-style')
234 if (headStyle) headStyle.parentNode.removeChild(headStyle)
236 // We test customCSS if the admin removed the css
237 if (this.customCSS || config.instance.customizations.css) {
238 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
239 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
244 private async loadPlugins () {
245 this.pluginService.initializePlugins()
247 this.hooks.runAction('action:application.init', 'common')
250 private async openModalsIfNeeded () {
251 this.authService.userInformationLoaded
253 map(() => this.authService.getUser()),
254 filter(user => user.role === UserRole.ADMINISTRATOR)
255 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
258 private async _openAdminModalsIfNeeded (user: User) {
259 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
261 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
263 this.instanceService.getAbout()
264 .subscribe(about => {
266 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
267 !about.instance.terms ||
268 !about.instance.administrator ||
269 !about.instance.maintenanceLifetime
271 this.instanceConfigWarningModal.show(about)
276 private initHotkeys () {
277 this.hotkeysService.add([
278 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
279 document.getElementById('search-video').focus()
281 }, undefined, this.i18n('Focus the search bar')),
283 new Hotkey('b', (event: KeyboardEvent): boolean => {
284 this.menu.toggleMenu()
286 }, undefined, this.i18n('Toggle the left menu')),
288 new Hotkey('g o', (event: KeyboardEvent): boolean => {
289 this.router.navigate([ '/videos/overview' ])
291 }, undefined, this.i18n('Go to the discover videos page')),
293 new Hotkey('g t', (event: KeyboardEvent): boolean => {
294 this.router.navigate([ '/videos/trending' ])
296 }, undefined, this.i18n('Go to the trending videos page')),
298 new Hotkey('g r', (event: KeyboardEvent): boolean => {
299 this.router.navigate([ '/videos/recently-added' ])
301 }, undefined, this.i18n('Go to the recently added videos page')),
303 new Hotkey('g l', (event: KeyboardEvent): boolean => {
304 this.router.navigate([ '/videos/local' ])
306 }, undefined, this.i18n('Go to the local videos page')),
308 new Hotkey('g u', (event: KeyboardEvent): boolean => {
309 this.router.navigate([ '/videos/upload' ])
311 }, undefined, this.i18n('Go to the videos upload page'))