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, skip, switchMap } 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 { 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', { static: false }) welcomeModal: WelcomeModalComponent
29 @ViewChild('instanceConfigWarningModal', { static: false }) instanceConfigWarningModal: InstanceConfigWarningModalComponent
31 isMenuDisplayed = true
32 isMenuChangedByUser = false
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
54 get serverVersion () {
55 return this.serverService.getConfig().serverVersion
59 const commit = this.serverService.getConfig().serverCommit || ''
60 return (commit !== '') ? '...' + commit : commit
64 return this.serverService.getConfig().instance.name
68 return RedirectService.DEFAULT_ROUTE
72 document.getElementById('incompatible-browser').className += ' browser-ok'
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 // Load custom data from server
82 this.serverService.loadConfig()
83 this.serverService.loadVideoCategories()
84 this.serverService.loadVideoLanguages()
85 this.serverService.loadVideoLicences()
86 this.serverService.loadVideoPrivacies()
87 this.serverService.loadVideoPlaylistPrivacies()
90 this.themeService.initialize()
92 // Do not display menu on small screens
93 if (this.screenService.isInSmallView()) {
94 this.isMenuDisplayed = false
97 this.initRouteEvents()
103 fromEvent(window, 'resize')
104 .pipe(debounceTime(200))
105 .subscribe(() => this.onResize())
107 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
109 this.openModalsIfNeeded()
113 return this.authService.isLoggedIn()
117 this.isMenuDisplayed = !this.isMenuDisplayed
118 this.isMenuChangedByUser = true
122 this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
125 private initRouteEvents () {
126 let resetScroll = true
127 const eventsObs = this.router.events
129 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
131 scrollEvent.subscribe(e => {
133 return this.viewportScroller.scrollToPosition(e.position)
137 return this.viewportScroller.scrollToAnchor(e.anchor)
141 return this.viewportScroller.scrollToPosition([ 0, 0 ])
145 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
147 // When we add the a-state parameter, we don't want to alter the scroll
148 navigationEndEvent.pipe(pairwise())
149 .subscribe(([ e1, e2 ]) => {
153 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
154 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
156 if (previousUrl.pathname !== nextUrl.pathname) {
161 const nextSearchParams = nextUrl.searchParams
162 nextSearchParams.delete('a-state')
164 const previousSearchParams = previousUrl.searchParams
166 nextSearchParams.sort()
167 previousSearchParams.sort()
169 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
173 console.error('Cannot parse URL to check next scroll.', e)
178 navigationEndEvent.pipe(
179 map(() => window.location.pathname),
180 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
181 ).subscribe(() => this.redirectService.redirectToHomepage(true))
183 navigationEndEvent.subscribe(e => {
184 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
188 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
189 filter(() => this.screenService.isInSmallView())
190 ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
193 private injectJS () {
195 this.serverService.configLoaded
197 const config = this.serverService.getConfig()
199 if (config.instance.customizations.javascript) {
201 // tslint:disable:no-eval
202 eval(config.instance.customizations.javascript)
204 console.error('Cannot eval custom JavaScript.', err)
210 private injectCSS () {
211 // Inject CSS if modified (admin config settings)
212 this.serverService.configLoaded
213 .pipe(skip(1)) // We only want to subscribe to reloads, because the CSS is already injected by the server
215 const headStyle = document.querySelector('style.custom-css-style')
216 if (headStyle) headStyle.parentNode.removeChild(headStyle)
218 const config = this.serverService.getConfig()
220 // We test customCSS if the admin removed the css
221 if (this.customCSS || config.instance.customizations.css) {
222 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
223 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
228 private async loadPlugins () {
229 this.pluginService.initializePlugins()
231 this.hooks.runAction('action:application.init', 'common')
234 private async openModalsIfNeeded () {
235 this.serverService.configLoaded
237 switchMap(() => this.authService.userInformationLoaded),
238 map(() => this.authService.getUser()),
239 filter(user => user.role === UserRole.ADMINISTRATOR)
240 ).subscribe(user => setTimeout(() => this.openAdminModals(user))) // setTimeout because of ngIf in template
243 private async openAdminModals (user: User) {
244 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
246 const config = this.serverService.getConfig()
247 if (user.noInstanceConfigWarningModal === true || !config.signup.allowed) return
249 this.instanceService.getAbout()
250 .subscribe(about => {
252 config.instance.name.toLowerCase() === 'peertube' ||
253 !about.instance.terms ||
254 !about.instance.administrator ||
255 !about.instance.maintenanceLifetime
257 this.instanceConfigWarningModal.show(about)
262 private initHotkeys () {
263 this.hotkeysService.add([
264 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
265 document.getElementById('search-video').focus()
267 }, undefined, this.i18n('Focus the search bar')),
269 new Hotkey('b', (event: KeyboardEvent): boolean => {
272 }, undefined, this.i18n('Toggle the left menu')),
274 new Hotkey('g o', (event: KeyboardEvent): boolean => {
275 this.router.navigate([ '/videos/overview' ])
277 }, undefined, this.i18n('Go to the discover videos page')),
279 new Hotkey('g t', (event: KeyboardEvent): boolean => {
280 this.router.navigate([ '/videos/trending' ])
282 }, undefined, this.i18n('Go to the trending videos page')),
284 new Hotkey('g r', (event: KeyboardEvent): boolean => {
285 this.router.navigate([ '/videos/recently-added' ])
287 }, undefined, this.i18n('Go to the recently added videos page')),
289 new Hotkey('g l', (event: KeyboardEvent): boolean => {
290 this.router.navigate([ '/videos/local' ])
292 }, undefined, this.i18n('Go to the local videos page')),
294 new Hotkey('g u', (event: KeyboardEvent): boolean => {
295 this.router.navigate([ '/videos/upload' ])
297 }, undefined, this.i18n('Go to the videos upload page'))