1 import { Component, OnInit, ViewChild, AfterViewInit, Inject, LOCALE_ID } from '@angular/core'
2 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
3 import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
4 import { AuthService, RedirectService, ServerService, ThemeService } from '@app/core'
5 import { is18nPath, getShortLocale } from '../../../shared/models/i18n'
6 import { ScreenService } from '@app/shared/misc/screen.service'
7 import { filter, map, pairwise, first } from 'rxjs/operators'
8 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
10 import { PlatformLocation, ViewportScroller, DOCUMENT } from '@angular/common'
11 import { PluginService } from '@app/core/plugins/plugin.service'
12 import { HooksService } from '@app/core/plugins/hooks.service'
13 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
14 import { POP_STATE_MODAL_DISMISS } from '@app/shared/misc/constants'
15 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
16 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
17 import { CustomModalComponent } from '@app/modal/custom-modal.component'
18 import { ServerConfig, UserRole } from '@shared/models'
19 import { User } from '@app/shared'
20 import { InstanceService } from '@app/shared/instance/instance.service'
21 import { MenuService } from './core/menu/menu.service'
22 import { BroadcastMessageLevel } from '@shared/models/server'
23 import { MarkdownService } from './shared/renderer'
24 import { concat } from 'rxjs'
25 import { peertubeLocalStorage } from './shared/misc/peertube-web-storage'
29 templateUrl: './app.component.html',
30 styleUrls: [ './app.component.scss' ]
32 export class AppComponent implements OnInit, AfterViewInit {
33 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
35 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
36 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
37 @ViewChild('customModal') customModal: CustomModalComponent
40 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
42 private serverConfig: ServerConfig
45 @Inject(DOCUMENT) private document: Document,
46 @Inject(LOCALE_ID) private localeId: string,
48 private viewportScroller: ViewportScroller,
49 private router: Router,
50 private authService: AuthService,
51 private serverService: ServerService,
52 private pluginService: PluginService,
53 private instanceService: InstanceService,
54 private domSanitizer: DomSanitizer,
55 private redirectService: RedirectService,
56 private screenService: ScreenService,
57 private hotkeysService: HotkeysService,
58 private themeService: ThemeService,
59 private hooks: HooksService,
60 private location: PlatformLocation,
61 private modalService: NgbModal,
62 private markdownService: MarkdownService,
63 public menu: MenuService
67 return this.serverConfig.instance.name
71 return RedirectService.DEFAULT_ROUTE
75 document.getElementById('incompatible-browser').className += ' browser-ok'
77 this.serverConfig = this.serverService.getTmpConfig()
78 this.serverService.getConfig()
79 .subscribe(config => this.serverConfig = config)
82 this.themeService.initialize()
84 this.authService.loadClientCredentials()
86 if (this.isUserLoggedIn()) {
87 // The service will automatically redirect to the login page if the token is not valid anymore
88 this.authService.refreshUserInformation()
91 this.initRouteEvents()
94 this.injectBroadcastMessage()
98 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
100 this.openModalsIfNeeded()
102 this.document.documentElement.lang = getShortLocale(this.localeId)
106 this.pluginService.initializeCustomModal(this.customModal)
110 return this.authService.isLoggedIn()
113 hideBroadcastMessage () {
114 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
116 this.broadcastMessage = null
119 private initRouteEvents () {
120 let resetScroll = true
121 const eventsObs = this.router.events
123 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
125 scrollEvent.subscribe(e => {
127 return this.viewportScroller.scrollToPosition(e.position)
131 return this.viewportScroller.scrollToAnchor(e.anchor)
135 return this.viewportScroller.scrollToPosition([ 0, 0 ])
139 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
141 // When we add the a-state parameter, we don't want to alter the scroll
142 navigationEndEvent.pipe(pairwise())
143 .subscribe(([ e1, e2 ]) => {
147 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
148 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
150 if (previousUrl.pathname !== nextUrl.pathname) {
155 const nextSearchParams = nextUrl.searchParams
156 nextSearchParams.delete('a-state')
158 const previousSearchParams = previousUrl.searchParams
160 nextSearchParams.sort()
161 previousSearchParams.sort()
163 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
167 console.error('Cannot parse URL to check next scroll.', e)
172 navigationEndEvent.pipe(
173 map(() => window.location.pathname),
174 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
175 ).subscribe(() => this.redirectService.redirectToHomepage(true))
177 navigationEndEvent.subscribe(e => {
178 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
182 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
183 filter(() => this.screenService.isInSmallView())
184 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
187 private injectBroadcastMessage () {
189 this.serverService.getConfig().pipe(first()),
190 this.serverService.configReloaded
191 ).subscribe(async config => {
192 this.broadcastMessage = null
194 const messageConfig = config.broadcastMessage
196 if (messageConfig.enabled) {
197 // Already dismissed this message?
198 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
202 const classes: { [id in BroadcastMessageLevel]: string } = {
204 warning: 'alert-warning',
205 error: 'alert-danger'
208 this.broadcastMessage = {
209 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
210 dismissable: messageConfig.dismissable,
211 class: classes[messageConfig.level]
217 private injectJS () {
219 this.serverService.getConfig()
220 .subscribe(config => {
221 if (config.instance.customizations.javascript) {
223 // tslint:disable:no-eval
224 eval(config.instance.customizations.javascript)
226 console.error('Cannot eval custom JavaScript.', err)
232 private injectCSS () {
233 // Inject CSS if modified (admin config settings)
235 this.serverService.getConfig().pipe(first()),
236 this.serverService.configReloaded
237 ).subscribe(config => {
238 const headStyle = document.querySelector('style.custom-css-style')
239 if (headStyle) headStyle.parentNode.removeChild(headStyle)
241 // We test customCSS if the admin removed the css
242 if (this.customCSS || config.instance.customizations.css) {
243 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
244 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
249 private async loadPlugins () {
250 this.pluginService.initializePlugins()
252 this.hooks.runAction('action:application.init', 'common')
255 private async openModalsIfNeeded () {
256 this.authService.userInformationLoaded
258 map(() => this.authService.getUser()),
259 filter(user => user.role === UserRole.ADMINISTRATOR)
260 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
263 private async _openAdminModalsIfNeeded (user: User) {
264 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
266 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
268 this.instanceService.getAbout()
269 .subscribe(about => {
271 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
272 !about.instance.terms ||
273 !about.instance.administrator ||
274 !about.instance.maintenanceLifetime
276 this.instanceConfigWarningModal.show(about)
281 private initHotkeys () {
282 this.hotkeysService.add([
283 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
284 document.getElementById('search-video').focus()
286 }, undefined, this.i18n('Focus the search bar')),
288 new Hotkey('b', (event: KeyboardEvent): boolean => {
289 this.menu.toggleMenu()
291 }, undefined, this.i18n('Toggle the left menu')),
293 new Hotkey('g o', (event: KeyboardEvent): boolean => {
294 this.router.navigate([ '/videos/overview' ])
296 }, undefined, this.i18n('Go to the discover videos page')),
298 new Hotkey('g t', (event: KeyboardEvent): boolean => {
299 this.router.navigate([ '/videos/trending' ])
301 }, undefined, this.i18n('Go to the trending videos page')),
303 new Hotkey('g r', (event: KeyboardEvent): boolean => {
304 this.router.navigate([ '/videos/recently-added' ])
306 }, undefined, this.i18n('Go to the recently added videos page')),
308 new Hotkey('g l', (event: KeyboardEvent): boolean => {
309 this.router.navigate([ '/videos/local' ])
311 }, undefined, this.i18n('Go to the local videos page')),
313 new Hotkey('g u', (event: KeyboardEvent): boolean => {
314 this.router.navigate([ '/videos/upload' ])
316 }, undefined, this.i18n('Go to the videos upload page'))