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 { 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 { ServerConfig, UserRole } from '@shared/models'
18 import { User } from '@app/shared'
19 import { InstanceService } from '@app/shared/instance/instance.service'
20 import { MenuService } from './core/menu/menu.service'
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
27 export class AppComponent implements OnInit {
28 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
29 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
33 private serverConfig: ServerConfig
37 private viewportScroller: ViewportScroller,
38 private router: Router,
39 private authService: AuthService,
40 private serverService: ServerService,
41 private pluginService: PluginService,
42 private instanceService: InstanceService,
43 private domSanitizer: DomSanitizer,
44 private redirectService: RedirectService,
45 private screenService: ScreenService,
46 private hotkeysService: HotkeysService,
47 private themeService: ThemeService,
48 private hooks: HooksService,
49 private location: PlatformLocation,
50 private modalService: NgbModal,
51 public menu: MenuService
55 return this.serverConfig.instance.name
59 return RedirectService.DEFAULT_ROUTE
63 document.getElementById('incompatible-browser').className += ' browser-ok'
65 this.serverConfig = this.serverService.getTmpConfig()
66 this.serverService.getConfig()
67 .subscribe(config => this.serverConfig = config)
70 this.themeService.initialize()
72 this.authService.loadClientCredentials()
74 if (this.isUserLoggedIn()) {
75 // The service will automatically redirect to the login page if the token is not valid anymore
76 this.authService.refreshUserInformation()
79 this.initRouteEvents()
85 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
87 this.openModalsIfNeeded()
91 return this.authService.isLoggedIn()
94 private initRouteEvents () {
95 let resetScroll = true
96 const eventsObs = this.router.events
98 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
100 scrollEvent.subscribe(e => {
102 return this.viewportScroller.scrollToPosition(e.position)
106 return this.viewportScroller.scrollToAnchor(e.anchor)
110 return this.viewportScroller.scrollToPosition([ 0, 0 ])
114 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
116 // When we add the a-state parameter, we don't want to alter the scroll
117 navigationEndEvent.pipe(pairwise())
118 .subscribe(([ e1, e2 ]) => {
122 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
123 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
125 if (previousUrl.pathname !== nextUrl.pathname) {
130 const nextSearchParams = nextUrl.searchParams
131 nextSearchParams.delete('a-state')
133 const previousSearchParams = previousUrl.searchParams
135 nextSearchParams.sort()
136 previousSearchParams.sort()
138 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
142 console.error('Cannot parse URL to check next scroll.', e)
147 navigationEndEvent.pipe(
148 map(() => window.location.pathname),
149 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
150 ).subscribe(() => this.redirectService.redirectToHomepage(true))
152 navigationEndEvent.subscribe(e => {
153 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
157 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
158 filter(() => this.screenService.isInSmallView())
159 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
162 private injectJS () {
164 this.serverService.getConfig()
165 .subscribe(config => {
166 if (config.instance.customizations.javascript) {
168 // tslint:disable:no-eval
169 eval(config.instance.customizations.javascript)
171 console.error('Cannot eval custom JavaScript.', err)
177 private injectCSS () {
178 // Inject CSS if modified (admin config settings)
179 this.serverService.configReloaded
181 const headStyle = document.querySelector('style.custom-css-style')
182 if (headStyle) headStyle.parentNode.removeChild(headStyle)
184 // We test customCSS if the admin removed the css
185 if (this.customCSS || this.serverConfig.instance.customizations.css) {
186 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
187 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
192 private async loadPlugins () {
193 this.pluginService.initializePlugins()
195 this.hooks.runAction('action:application.init', 'common')
198 private async openModalsIfNeeded () {
199 this.authService.userInformationLoaded
201 map(() => this.authService.getUser()),
202 filter(user => user.role === UserRole.ADMINISTRATOR)
203 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
206 private async _openAdminModalsIfNeeded (user: User) {
207 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
209 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
211 this.instanceService.getAbout()
212 .subscribe(about => {
214 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
215 !about.instance.terms ||
216 !about.instance.administrator ||
217 !about.instance.maintenanceLifetime
219 this.instanceConfigWarningModal.show(about)
224 private initHotkeys () {
225 this.hotkeysService.add([
226 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
227 document.getElementById('search-video').focus()
229 }, undefined, this.i18n('Focus the search bar')),
231 new Hotkey('b', (event: KeyboardEvent): boolean => {
232 this.menu.toggleMenu()
234 }, undefined, this.i18n('Toggle the left menu')),
236 new Hotkey('g o', (event: KeyboardEvent): boolean => {
237 this.router.navigate([ '/videos/overview' ])
239 }, undefined, this.i18n('Go to the discover videos page')),
241 new Hotkey('g t', (event: KeyboardEvent): boolean => {
242 this.router.navigate([ '/videos/trending' ])
244 }, undefined, this.i18n('Go to the trending videos page')),
246 new Hotkey('g r', (event: KeyboardEvent): boolean => {
247 this.router.navigate([ '/videos/recently-added' ])
249 }, undefined, this.i18n('Go to the recently added videos page')),
251 new Hotkey('g l', (event: KeyboardEvent): boolean => {
252 this.router.navigate([ '/videos/local' ])
254 }, undefined, this.i18n('Go to the local videos page')),
256 new Hotkey('g u', (event: KeyboardEvent): boolean => {
257 this.router.navigate([ '/videos/upload' ])
259 }, undefined, this.i18n('Go to the videos upload page'))