1 import { Component, OnInit, ViewChild } 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 } from '../../../shared/models/i18n'
6 import { ScreenService } from '@app/shared/misc/screen.service'
7 import { debounceTime, filter, map, pairwise } from 'rxjs/operators'
8 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
10 import { fromEvent } from 'rxjs'
11 import { PlatformLocation, ViewportScroller } from '@angular/common'
12 import { PluginService } from '@app/core/plugins/plugin.service'
13 import { HooksService } from '@app/core/plugins/hooks.service'
14 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { POP_STATE_MODAL_DISMISS } from '@app/shared/misc/constants'
16 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
17 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-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'
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
28 export class AppComponent implements OnInit {
29 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
30 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
34 private serverConfig: ServerConfig
38 private viewportScroller: ViewportScroller,
39 private router: Router,
40 private authService: AuthService,
41 private serverService: ServerService,
42 private pluginService: PluginService,
43 private instanceService: InstanceService,
44 private domSanitizer: DomSanitizer,
45 private redirectService: RedirectService,
46 private screenService: ScreenService,
47 private hotkeysService: HotkeysService,
48 private themeService: ThemeService,
49 private hooks: HooksService,
50 private location: PlatformLocation,
51 private modalService: NgbModal,
52 public menu: MenuService
56 return this.serverConfig.instance.name
60 return RedirectService.DEFAULT_ROUTE
64 document.getElementById('incompatible-browser').className += ' browser-ok'
66 this.serverConfig = this.serverService.getTmpConfig()
67 this.serverService.getConfig()
68 .subscribe(config => this.serverConfig = config)
71 this.themeService.initialize()
73 this.authService.loadClientCredentials()
75 if (this.isUserLoggedIn()) {
76 // The service will automatically redirect to the login page if the token is not valid anymore
77 this.authService.refreshUserInformation()
80 this.initRouteEvents()
86 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
88 this.openModalsIfNeeded()
92 return this.authService.isLoggedIn()
95 private initRouteEvents () {
96 let resetScroll = true
97 const eventsObs = this.router.events
99 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
101 scrollEvent.subscribe(e => {
103 return this.viewportScroller.scrollToPosition(e.position)
107 return this.viewportScroller.scrollToAnchor(e.anchor)
111 return this.viewportScroller.scrollToPosition([ 0, 0 ])
115 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
117 // When we add the a-state parameter, we don't want to alter the scroll
118 navigationEndEvent.pipe(pairwise())
119 .subscribe(([ e1, e2 ]) => {
123 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
124 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
126 if (previousUrl.pathname !== nextUrl.pathname) {
131 const nextSearchParams = nextUrl.searchParams
132 nextSearchParams.delete('a-state')
134 const previousSearchParams = previousUrl.searchParams
136 nextSearchParams.sort()
137 previousSearchParams.sort()
139 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
143 console.error('Cannot parse URL to check next scroll.', e)
148 navigationEndEvent.pipe(
149 map(() => window.location.pathname),
150 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
151 ).subscribe(() => this.redirectService.redirectToHomepage(true))
153 navigationEndEvent.subscribe(e => {
154 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
158 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
159 filter(() => this.screenService.isInSmallView())
160 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
163 private injectJS () {
165 this.serverService.getConfig()
166 .subscribe(config => {
167 if (config.instance.customizations.javascript) {
169 // tslint:disable:no-eval
170 eval(config.instance.customizations.javascript)
172 console.error('Cannot eval custom JavaScript.', err)
178 private injectCSS () {
179 // Inject CSS if modified (admin config settings)
180 this.serverService.configReloaded
182 const headStyle = document.querySelector('style.custom-css-style')
183 if (headStyle) headStyle.parentNode.removeChild(headStyle)
185 // We test customCSS if the admin removed the css
186 if (this.customCSS || this.serverConfig.instance.customizations.css) {
187 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
188 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
193 private async loadPlugins () {
194 this.pluginService.initializePlugins()
196 this.hooks.runAction('action:application.init', 'common')
199 private async openModalsIfNeeded () {
200 this.authService.userInformationLoaded
202 map(() => this.authService.getUser()),
203 filter(user => user.role === UserRole.ADMINISTRATOR)
204 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
207 private async _openAdminModalsIfNeeded (user: User) {
208 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
210 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
212 this.instanceService.getAbout()
213 .subscribe(about => {
215 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
216 !about.instance.terms ||
217 !about.instance.administrator ||
218 !about.instance.maintenanceLifetime
220 this.instanceConfigWarningModal.show(about)
225 private initHotkeys () {
226 this.hotkeysService.add([
227 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
228 document.getElementById('search-video').focus()
230 }, undefined, this.i18n('Focus the search bar')),
232 new Hotkey('b', (event: KeyboardEvent): boolean => {
233 this.menu.toggleMenu()
235 }, undefined, this.i18n('Toggle the left menu')),
237 new Hotkey('g o', (event: KeyboardEvent): boolean => {
238 this.router.navigate([ '/videos/overview' ])
240 }, undefined, this.i18n('Go to the discover videos page')),
242 new Hotkey('g t', (event: KeyboardEvent): boolean => {
243 this.router.navigate([ '/videos/trending' ])
245 }, undefined, this.i18n('Go to the trending videos page')),
247 new Hotkey('g r', (event: KeyboardEvent): boolean => {
248 this.router.navigate([ '/videos/recently-added' ])
250 }, undefined, this.i18n('Go to the recently added videos page')),
252 new Hotkey('g l', (event: KeyboardEvent): boolean => {
253 this.router.navigate([ '/videos/local' ])
255 }, undefined, this.i18n('Go to the local videos page')),
257 new Hotkey('g u', (event: KeyboardEvent): boolean => {
258 this.router.navigate([ '/videos/upload' ])
260 }, undefined, this.i18n('Go to the videos upload page'))