1
0
Fork 0
peertube/client/src/app/app.component.ts

323 lines
11 KiB
TypeScript
Raw Normal View History

2020-06-23 12:10:17 +00:00
import { Hotkey, HotkeysService } from 'angular2-hotkeys'
import { concat } from 'rxjs'
import { filter, first, map, pairwise } from 'rxjs/operators'
import { DOCUMENT, PlatformLocation, ViewportScroller } from '@angular/common'
import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
2019-03-21 15:49:46 +00:00
import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
2020-06-23 12:10:17 +00:00
import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
2019-07-22 13:40:13 +00:00
import { HooksService } from '@app/core/plugins/hooks.service'
2020-06-23 12:10:17 +00:00
import { PluginService } from '@app/core/plugins/plugin.service'
import { CustomModalComponent } from '@app/modal/custom-modal.component'
2020-06-23 12:10:17 +00:00
import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
2020-08-06 12:58:01 +00:00
import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
import { MenuService } from './core/menu/menu.service'
2020-08-03 16:06:49 +00:00
import { POP_STATE_MODAL_DISMISS } from './helpers'
2020-06-23 12:10:17 +00:00
import { InstanceService } from './shared/shared-instance'
2016-03-14 12:50:19 +00:00
@Component({
2016-11-04 15:23:18 +00:00
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ]
2016-03-14 12:50:19 +00:00
})
export class AppComponent implements OnInit, AfterViewInit {
2020-05-28 09:15:38 +00:00
private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
2020-02-07 09:00:34 +00:00
@ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
@ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
@ViewChild('customModal') customModal: CustomModalComponent
2019-08-28 12:40:06 +00:00
customCSS: SafeHtml
2020-05-28 09:15:38 +00:00
broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
2019-12-18 14:31:54 +00:00
private serverConfig: ServerConfig
constructor (
@Inject(DOCUMENT) private document: Document,
@Inject(LOCALE_ID) private localeId: string,
2019-03-21 15:49:46 +00:00
private viewportScroller: ViewportScroller,
2016-11-04 15:23:18 +00:00
private router: Router,
private authService: AuthService,
private serverService: ServerService,
2019-07-08 13:54:08 +00:00
private pluginService: PluginService,
2019-08-28 12:40:06 +00:00
private instanceService: InstanceService,
2018-03-01 12:57:29 +00:00
private domSanitizer: DomSanitizer,
private redirectService: RedirectService,
private screenService: ScreenService,
2018-09-06 10:00:53 +00:00
private hotkeysService: HotkeysService,
2019-07-22 13:40:13 +00:00
private themeService: ThemeService,
2019-08-22 14:13:26 +00:00
private hooks: HooksService,
private location: PlatformLocation,
private modalService: NgbModal,
2020-05-28 09:15:38 +00:00
private markdownService: MarkdownService,
public menu: MenuService
2018-05-31 16:12:15 +00:00
) { }
2016-05-24 21:00:58 +00:00
2018-01-31 16:47:36 +00:00
get instanceName () {
2019-12-18 14:31:54 +00:00
return this.serverConfig.instance.name
2018-01-31 16:47:36 +00:00
}
get defaultRoute () {
return RedirectService.DEFAULT_ROUTE
}
ngOnInit () {
2018-03-08 11:04:10 +00:00
document.getElementById('incompatible-browser').className += ' browser-ok'
2019-12-18 14:31:54 +00:00
this.serverConfig = this.serverService.getTmpConfig()
this.serverService.getConfig()
.subscribe(config => this.serverConfig = config)
2019-10-25 08:57:23 +00:00
this.loadPlugins()
this.themeService.initialize()
this.authService.loadClientCredentials()
2018-03-27 14:18:25 +00:00
if (this.isUserLoggedIn()) {
// The service will automatically redirect to the login page if the token is not valid anymore
2017-10-25 15:31:11 +00:00
this.authService.refreshUserInformation()
}
2017-03-22 20:15:55 +00:00
2019-03-21 15:49:46 +00:00
this.initRouteEvents()
this.injectJS()
this.injectCSS()
2020-05-28 09:15:38 +00:00
this.injectBroadcastMessage()
2019-03-21 15:49:46 +00:00
this.initHotkeys()
this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
2019-08-28 12:40:06 +00:00
this.openModalsIfNeeded()
this.document.documentElement.lang = getShortLocale(this.localeId)
2019-03-21 15:49:46 +00:00
}
ngAfterViewInit () {
this.pluginService.initializeCustomModal(this.customModal)
}
2019-03-21 15:49:46 +00:00
isUserLoggedIn () {
return this.authService.isLoggedIn()
}
2020-05-28 09:15:38 +00:00
hideBroadcastMessage () {
peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
this.broadcastMessage = null
this.screenService.isBroadcastMessageDisplayed = false
2020-05-28 09:15:38 +00:00
}
2019-03-21 15:49:46 +00:00
private initRouteEvents () {
let resetScroll = true
const eventsObs = this.router.events
const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
scrollEvent.subscribe(e => {
// scrollToAnchor first to preserve anchor position when using history navigation
if (e.anchor) {
setTimeout(() => {
document.getElementById(e.anchor).scrollIntoView({ behavior: 'smooth', inline: 'nearest' })
})
return
}
if (e.position) {
return this.viewportScroller.scrollToPosition(e.position)
2019-03-21 15:49:46 +00:00
}
if (resetScroll) {
return this.viewportScroller.scrollToPosition([ 0, 0 ])
}
})
const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
2019-03-21 15:49:46 +00:00
// When we add the a-state parameter, we don't want to alter the scroll
navigationEndEvent.pipe(pairwise())
.subscribe(([ e1, e2 ]) => {
try {
resetScroll = false
const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
2019-03-21 15:49:46 +00:00
if (previousUrl.pathname !== nextUrl.pathname) {
resetScroll = true
return
}
const nextSearchParams = nextUrl.searchParams
nextSearchParams.delete('a-state')
const previousSearchParams = previousUrl.searchParams
nextSearchParams.sort()
previousSearchParams.sort()
if (nextSearchParams.toString() !== previousSearchParams.toString()) {
resetScroll = true
}
} catch (e) {
console.error('Cannot parse URL to check next scroll.', e)
resetScroll = true
}
})
navigationEndEvent.pipe(
map(() => window.location.pathname),
filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
).subscribe(() => this.redirectService.redirectToHomepage(true))
2019-07-25 17:02:54 +00:00
navigationEndEvent.subscribe(e => {
this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
})
2019-03-21 15:49:46 +00:00
eventsObs.pipe(
filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
filter(() => this.screenService.isInSmallView())
).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
2019-03-21 15:49:46 +00:00
}
2020-05-28 09:15:38 +00:00
private injectBroadcastMessage () {
concat(
this.serverService.getConfig().pipe(first()),
this.serverService.configReloaded
).subscribe(async config => {
this.broadcastMessage = null
this.screenService.isBroadcastMessageDisplayed = false
2020-05-28 09:15:38 +00:00
const messageConfig = config.broadcastMessage
if (messageConfig.enabled) {
// Already dismissed this message?
if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
return
}
const classes: { [id in BroadcastMessageLevel]: string } = {
info: 'alert-info',
warning: 'alert-warning',
error: 'alert-danger'
}
this.broadcastMessage = {
message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
dismissable: messageConfig.dismissable,
class: classes[messageConfig.level]
}
this.screenService.isBroadcastMessageDisplayed = true
2020-05-28 09:15:38 +00:00
}
})
}
2019-03-21 15:49:46 +00:00
private injectJS () {
// Inject JS
2019-12-18 14:31:54 +00:00
this.serverService.getConfig()
.subscribe(config => {
if (config.instance.customizations.javascript) {
try {
// tslint:disable:no-eval
eval(config.instance.customizations.javascript)
} catch (err) {
console.error('Cannot eval custom JavaScript.', err)
}
}
})
2019-03-21 15:49:46 +00:00
}
2019-03-21 15:49:46 +00:00
private injectCSS () {
// Inject CSS if modified (admin config settings)
2020-05-28 09:15:38 +00:00
concat(
this.serverService.getConfig().pipe(first()),
this.serverService.configReloaded
).subscribe(config => {
const headStyle = document.querySelector('style.custom-css-style')
if (headStyle) headStyle.parentNode.removeChild(headStyle)
// We test customCSS if the admin removed the css
if (this.customCSS || config.instance.customizations.css) {
const styleTag = '<style>' + config.instance.customizations.css + '</style>'
this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
}
})
2019-03-21 15:49:46 +00:00
}
2019-07-08 13:54:08 +00:00
private async loadPlugins () {
this.pluginService.initializePlugins()
2019-07-23 10:16:34 +00:00
this.hooks.runAction('action:application.init', 'common')
2019-07-08 13:54:08 +00:00
}
2019-08-28 12:40:06 +00:00
private async openModalsIfNeeded () {
2019-12-18 14:31:54 +00:00
this.authService.userInformationLoaded
2019-08-28 12:40:06 +00:00
.pipe(
map(() => this.authService.getUser()),
filter(user => user.role === UserRole.ADMINISTRATOR)
2019-12-18 14:31:54 +00:00
).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
2019-08-28 12:40:06 +00:00
}
2019-12-18 14:31:54 +00:00
private async _openAdminModalsIfNeeded (user: User) {
2019-08-28 12:40:06 +00:00
if (user.noWelcomeModal !== true) return this.welcomeModal.show()
2019-12-18 14:31:54 +00:00
if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
2019-08-28 13:46:56 +00:00
this.instanceService.getAbout()
.subscribe(about => {
if (
2019-12-18 14:31:54 +00:00
this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
2019-08-28 13:46:56 +00:00
!about.instance.terms ||
!about.instance.administrator ||
!about.instance.maintenanceLifetime
) {
this.instanceConfigWarningModal.show(about)
}
})
2019-08-28 12:40:06 +00:00
}
2019-03-21 15:49:46 +00:00
private initHotkeys () {
this.hotkeysService.add([
new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
document.getElementById('search-video').focus()
return false
}, undefined, $localize`Focus the search bar`),
2019-08-28 12:40:06 +00:00
new Hotkey('b', (event: KeyboardEvent): boolean => {
this.menu.toggleMenu()
return false
}, undefined, $localize`Toggle the left menu`),
2019-08-28 12:40:06 +00:00
new Hotkey('g o', (event: KeyboardEvent): boolean => {
this.router.navigate([ '/videos/overview' ])
return false
}, undefined, $localize`Go to the discover videos page`),
2019-08-28 12:40:06 +00:00
new Hotkey('g t', (event: KeyboardEvent): boolean => {
this.router.navigate([ '/videos/trending' ])
return false
}, undefined, $localize`Go to the trending videos page`),
2019-08-28 12:40:06 +00:00
new Hotkey('g r', (event: KeyboardEvent): boolean => {
this.router.navigate([ '/videos/recently-added' ])
return false
}, undefined, $localize`Go to the recently added videos page`),
2019-08-28 12:40:06 +00:00
new Hotkey('g l', (event: KeyboardEvent): boolean => {
this.router.navigate([ '/videos/local' ])
return false
}, undefined, $localize`Go to the local videos page`),
2019-08-28 12:40:06 +00:00
new Hotkey('g u', (event: KeyboardEvent): boolean => {
this.router.navigate([ '/videos/upload' ])
return false
}, undefined, $localize`Go to the videos upload page`)
])
2017-04-26 19:22:00 +00:00
}
2016-03-14 12:50:19 +00:00
}