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'
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
31 isMenuDisplayed = true
32 isMenuChangedByUser = false
36 private serverConfig: ServerConfig
40 private viewportScroller: ViewportScroller,
41 private router: Router,
42 private authService: AuthService,
43 private serverService: ServerService,
44 private pluginService: PluginService,
45 private instanceService: InstanceService,
46 private domSanitizer: DomSanitizer,
47 private redirectService: RedirectService,
48 private screenService: ScreenService,
49 private hotkeysService: HotkeysService,
50 private themeService: ThemeService,
51 private hooks: HooksService,
52 private location: PlatformLocation,
53 private modalService: NgbModal
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 // Do not display menu on small screens
82 if (this.screenService.isInSmallView()) {
83 this.isMenuDisplayed = false
86 this.initRouteEvents()
92 fromEvent(window, 'resize')
93 .pipe(debounceTime(200))
94 .subscribe(() => this.onResize())
96 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
98 this.openModalsIfNeeded()
102 return this.authService.isLoggedIn()
106 this.isMenuDisplayed = !this.isMenuDisplayed
107 this.isMenuChangedByUser = true
111 this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
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.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
182 private injectJS () {
184 this.serverService.getConfig()
185 .subscribe(config => {
186 if (config.instance.customizations.javascript) {
188 // tslint:disable:no-eval
189 eval(config.instance.customizations.javascript)
191 console.error('Cannot eval custom JavaScript.', err)
197 private injectCSS () {
198 // Inject CSS if modified (admin config settings)
199 this.serverService.configReloaded
201 const headStyle = document.querySelector('style.custom-css-style')
202 if (headStyle) headStyle.parentNode.removeChild(headStyle)
204 // We test customCSS if the admin removed the css
205 if (this.customCSS || this.serverConfig.instance.customizations.css) {
206 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
207 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
212 private async loadPlugins () {
213 this.pluginService.initializePlugins()
215 this.hooks.runAction('action:application.init', 'common')
218 private async openModalsIfNeeded () {
219 this.authService.userInformationLoaded
221 map(() => this.authService.getUser()),
222 filter(user => user.role === UserRole.ADMINISTRATOR)
223 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
226 private async _openAdminModalsIfNeeded (user: User) {
227 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
229 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
231 this.instanceService.getAbout()
232 .subscribe(about => {
234 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
235 !about.instance.terms ||
236 !about.instance.administrator ||
237 !about.instance.maintenanceLifetime
239 this.instanceConfigWarningModal.show(about)
244 private initHotkeys () {
245 this.hotkeysService.add([
246 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
247 document.getElementById('search-video').focus()
249 }, undefined, this.i18n('Focus the search bar')),
251 new Hotkey('b', (event: KeyboardEvent): boolean => {
254 }, undefined, this.i18n('Toggle the left menu')),
256 new Hotkey('g o', (event: KeyboardEvent): boolean => {
257 this.router.navigate([ '/videos/overview' ])
259 }, undefined, this.i18n('Go to the discover videos page')),
261 new Hotkey('g t', (event: KeyboardEvent): boolean => {
262 this.router.navigate([ '/videos/trending' ])
264 }, undefined, this.i18n('Go to the trending videos page')),
266 new Hotkey('g r', (event: KeyboardEvent): boolean => {
267 this.router.navigate([ '/videos/recently-added' ])
269 }, undefined, this.i18n('Go to the recently added videos page')),
271 new Hotkey('g l', (event: KeyboardEvent): boolean => {
272 this.router.navigate([ '/videos/local' ])
274 }, undefined, this.i18n('Go to the local videos page')),
276 new Hotkey('g u', (event: KeyboardEvent): boolean => {
277 this.router.navigate([ '/videos/upload' ])
279 }, undefined, this.i18n('Go to the videos upload page'))