1 import { Component, OnInit, ViewChild, AfterViewInit } 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 { filter, map, pairwise } from 'rxjs/operators'
8 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
10 import { PlatformLocation, ViewportScroller } 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'
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
28 export class AppComponent implements OnInit, AfterViewInit {
29 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
30 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
31 @ViewChild('customModal') customModal: CustomModalComponent
35 private serverConfig: ServerConfig
39 private viewportScroller: ViewportScroller,
40 private router: Router,
41 private authService: AuthService,
42 private serverService: ServerService,
43 private pluginService: PluginService,
44 private instanceService: InstanceService,
45 private domSanitizer: DomSanitizer,
46 private redirectService: RedirectService,
47 private screenService: ScreenService,
48 private hotkeysService: HotkeysService,
49 private themeService: ThemeService,
50 private hooks: HooksService,
51 private location: PlatformLocation,
52 private modalService: NgbModal,
53 public menu: MenuService
57 return this.serverConfig.instance.name
61 return RedirectService.DEFAULT_ROUTE
65 document.getElementById('incompatible-browser').className += ' browser-ok'
67 this.serverConfig = this.serverService.getTmpConfig()
68 this.serverService.getConfig()
69 .subscribe(config => this.serverConfig = config)
72 this.themeService.initialize()
74 this.authService.loadClientCredentials()
76 if (this.isUserLoggedIn()) {
77 // The service will automatically redirect to the login page if the token is not valid anymore
78 this.authService.refreshUserInformation()
81 this.initRouteEvents()
87 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
89 this.openModalsIfNeeded()
93 this.pluginService.initializeCustomModal(this.customModal)
97 return this.authService.isLoggedIn()
100 private initRouteEvents () {
101 let resetScroll = true
102 const eventsObs = this.router.events
104 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
106 scrollEvent.subscribe(e => {
108 return this.viewportScroller.scrollToPosition(e.position)
112 return this.viewportScroller.scrollToAnchor(e.anchor)
116 return this.viewportScroller.scrollToPosition([ 0, 0 ])
120 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
122 // When we add the a-state parameter, we don't want to alter the scroll
123 navigationEndEvent.pipe(pairwise())
124 .subscribe(([ e1, e2 ]) => {
128 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
129 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
131 if (previousUrl.pathname !== nextUrl.pathname) {
136 const nextSearchParams = nextUrl.searchParams
137 nextSearchParams.delete('a-state')
139 const previousSearchParams = previousUrl.searchParams
141 nextSearchParams.sort()
142 previousSearchParams.sort()
144 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
148 console.error('Cannot parse URL to check next scroll.', e)
153 navigationEndEvent.pipe(
154 map(() => window.location.pathname),
155 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
156 ).subscribe(() => this.redirectService.redirectToHomepage(true))
158 navigationEndEvent.subscribe(e => {
159 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
163 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
164 filter(() => this.screenService.isInSmallView())
165 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
168 private injectJS () {
170 this.serverService.getConfig()
171 .subscribe(config => {
172 if (config.instance.customizations.javascript) {
174 // tslint:disable:no-eval
175 eval(config.instance.customizations.javascript)
177 console.error('Cannot eval custom JavaScript.', err)
183 private injectCSS () {
184 // Inject CSS if modified (admin config settings)
185 this.serverService.configReloaded
187 const headStyle = document.querySelector('style.custom-css-style')
188 if (headStyle) headStyle.parentNode.removeChild(headStyle)
190 // We test customCSS if the admin removed the css
191 if (this.customCSS || this.serverConfig.instance.customizations.css) {
192 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
193 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
198 private async loadPlugins () {
199 this.pluginService.initializePlugins()
201 this.hooks.runAction('action:application.init', 'common')
204 private async openModalsIfNeeded () {
205 this.authService.userInformationLoaded
207 map(() => this.authService.getUser()),
208 filter(user => user.role === UserRole.ADMINISTRATOR)
209 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
212 private async _openAdminModalsIfNeeded (user: User) {
213 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
215 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
217 this.instanceService.getAbout()
218 .subscribe(about => {
220 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
221 !about.instance.terms ||
222 !about.instance.administrator ||
223 !about.instance.maintenanceLifetime
225 this.instanceConfigWarningModal.show(about)
230 private initHotkeys () {
231 this.hotkeysService.add([
232 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
233 document.getElementById('search-video').focus()
235 }, undefined, this.i18n('Focus the search bar')),
237 new Hotkey('b', (event: KeyboardEvent): boolean => {
238 this.menu.toggleMenu()
240 }, undefined, this.i18n('Toggle the left menu')),
242 new Hotkey('g o', (event: KeyboardEvent): boolean => {
243 this.router.navigate([ '/videos/overview' ])
245 }, undefined, this.i18n('Go to the discover videos page')),
247 new Hotkey('g t', (event: KeyboardEvent): boolean => {
248 this.router.navigate([ '/videos/trending' ])
250 }, undefined, this.i18n('Go to the trending videos page')),
252 new Hotkey('g r', (event: KeyboardEvent): boolean => {
253 this.router.navigate([ '/videos/recently-added' ])
255 }, undefined, this.i18n('Go to the recently added videos page')),
257 new Hotkey('g l', (event: KeyboardEvent): boolean => {
258 this.router.navigate([ '/videos/local' ])
260 }, undefined, this.i18n('Go to the local videos page')),
262 new Hotkey('g u', (event: KeyboardEvent): boolean => {
263 this.router.navigate([ '/videos/upload' ])
265 }, undefined, this.i18n('Go to the videos upload page'))