PeerTube/client/src/app/app.component.ts

347 lines
12 KiB
TypeScript
Raw Normal View History

2020-06-23 07:10:17 -05:00
import { Hotkey, HotkeysService } from 'angular2-hotkeys'
import { concat } from 'rxjs'
2020-11-30 02:11:12 -06:00
import { filter, first, map, pairwise } from 'rxjs/operators'
2020-06-23 07:10:17 -05:00
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'
2021-01-13 04:29:55 -06:00
import { Event, GuardsCheckStart, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, Router, Scroll } from '@angular/router'
2020-06-23 07:10:17 -05:00
import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
2019-07-22 08:40:13 -05:00
import { HooksService } from '@app/core/plugins/hooks.service'
2020-06-23 07:10:17 -05:00
import { PluginService } from '@app/core/plugins/plugin.service'
import { CustomModalComponent } from '@app/modal/custom-modal.component'
2020-06-23 07:10:17 -05:00
import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
2021-01-13 04:29:55 -06:00
import { LoadingBarService } from '@ngx-loading-bar/core'
import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
2020-08-06 07:58:01 -05: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 11:06:49 -05:00
import { POP_STATE_MODAL_DISMISS } from './helpers'
2020-06-23 07:10:17 -05:00
import { InstanceService } from './shared/shared-instance'
2016-03-14 07:50:19 -05:00
@Component({
2016-11-04 10:23:18 -05:00
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ]
2016-03-14 07:50:19 -05:00
})
export class AppComponent implements OnInit, AfterViewInit {
2020-05-28 04:15:38 -05:00
private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
2020-02-07 03:00:34 -06:00
@ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
@ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
@ViewChild('customModal') customModal: CustomModalComponent
2019-08-28 07:40:06 -05:00
customCSS: SafeHtml
2020-05-28 04:15:38 -05:00
broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
2019-12-18 08:31:54 -06:00
private serverConfig: ServerConfig
constructor (
@Inject(DOCUMENT) private document: Document,
@Inject(LOCALE_ID) private localeId: string,
2019-03-21 10:49:46 -05:00
private viewportScroller: ViewportScroller,
2016-11-04 10:23:18 -05:00
private router: Router,
private authService: AuthService,
private serverService: ServerService,
2019-07-08 08:54:08 -05:00
private pluginService: PluginService,
2019-08-28 07:40:06 -05:00
private instanceService: InstanceService,
2018-03-01 06:57:29 -06:00
private domSanitizer: DomSanitizer,
private redirectService: RedirectService,
private screenService: ScreenService,
2018-09-06 05:00:53 -05:00
private hotkeysService: HotkeysService,
2019-07-22 08:40:13 -05:00
private themeService: ThemeService,
2019-08-22 09:13:26 -05:00
private hooks: HooksService,
private location: PlatformLocation,
private modalService: NgbModal,
2020-05-28 04:15:38 -05:00
private markdownService: MarkdownService,
private ngbConfig: NgbConfig,
2021-01-13 04:29:55 -06:00
private loadingBar: LoadingBarService,
public menu: MenuService
) {
this.ngbConfig.animation = false
}
2016-05-24 16:00:58 -05:00
2018-01-31 10:47:36 -06:00
get instanceName () {
2019-12-18 08:31:54 -06:00
return this.serverConfig.instance.name
2018-01-31 10:47:36 -06:00
}
2021-01-27 10:15:21 -06:00
goToDefaultRoute () {
2021-05-14 05:04:44 -05:00
return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
}
ngOnInit () {
2018-03-08 05:04:10 -06:00
document.getElementById('incompatible-browser').className += ' browser-ok'
2019-12-18 08:31:54 -06:00
this.serverConfig = this.serverService.getTmpConfig()
this.serverService.getConfig()
.subscribe(config => this.serverConfig = config)
2019-10-25 03:57:23 -05:00
this.loadPlugins()
this.themeService.initialize()
this.authService.loadClientCredentials()
2018-03-27 09:18:25 -05:00
if (this.isUserLoggedIn()) {
// The service will automatically redirect to the login page if the token is not valid anymore
2017-10-25 10:31:11 -05:00
this.authService.refreshUserInformation()
}
2017-03-22 15:15:55 -05:00
2019-03-21 10:49:46 -05:00
this.initRouteEvents()
this.injectJS()
this.injectCSS()
2020-05-28 04:15:38 -05:00
this.injectBroadcastMessage()
2019-03-21 10:49:46 -05:00
this.initHotkeys()
this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
2019-08-28 07:40:06 -05:00
this.openModalsIfNeeded()
this.document.documentElement.lang = getShortLocale(this.localeId)
2019-03-21 10:49:46 -05:00
}
ngAfterViewInit () {
this.pluginService.initializeCustomModal(this.customModal)
}
2021-01-13 03:44:34 -06:00
getToggleTitle () {
if (this.menu.isDisplayed()) return $localize`Close the left menu`
return $localize`Open the left menu`
}
2019-03-21 10:49:46 -05:00
isUserLoggedIn () {
return this.authService.isLoggedIn()
}
2020-05-28 04:15:38 -05:00
hideBroadcastMessage () {
peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
this.broadcastMessage = null
this.screenService.isBroadcastMessageDisplayed = false
2020-05-28 04:15:38 -05:00
}
2019-03-21 10:49:46 -05:00
private initRouteEvents () {
let resetScroll = true
const eventsObs = this.router.events
const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
2021-01-13 04:29:55 -06:00
// Handle anchors/restore position
2019-03-21 10:49:46 -05:00
scrollEvent.subscribe(e => {
// scrollToAnchor first to preserve anchor position when using history navigation
if (e.anchor) {
setTimeout(() => {
this.viewportScroller.scrollToAnchor(e.anchor)
})
return
}
if (e.position) {
return this.viewportScroller.scrollToPosition(e.position)
2019-03-21 10:49:46 -05: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 10:49:46 -05: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 10:49:46 -05: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
}
})
2021-01-13 04:29:55 -06:00
// Homepage redirection
2019-03-21 10:49:46 -05:00
navigationEndEvent.pipe(
map(() => window.location.pathname),
filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
).subscribe(() => this.redirectService.redirectToHomepage(true))
2021-01-13 04:29:55 -06:00
// Plugin hooks
2019-07-25 12:02:54 -05:00
navigationEndEvent.subscribe(e => {
this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
})
2021-01-13 04:29:55 -06:00
// Automatically hide/display the menu
2019-03-21 10:49:46 -05:00
eventsObs.pipe(
filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
2020-08-17 03:19:45 -05:00
filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
2021-01-13 04:29:55 -06:00
// Handle lazy loaded module
eventsObs.pipe(
filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
).subscribe(() => this.loadingBar.useRef().start())
eventsObs.pipe(
filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
).subscribe(() => this.loadingBar.useRef().complete())
2019-03-21 10:49:46 -05:00
}
2020-05-28 04:15:38 -05: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 04:15:38 -05: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.unsafeMarkdownToHTML(messageConfig.message, true),
2020-05-28 04:15:38 -05:00
dismissable: messageConfig.dismissable,
class: classes[messageConfig.level]
}
this.screenService.isBroadcastMessageDisplayed = true
2020-05-28 04:15:38 -05:00
}
})
}
2019-03-21 10:49:46 -05:00
private injectJS () {
// Inject JS
2019-12-18 08:31:54 -06: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 10:49:46 -05:00
}
2019-03-21 10:49:46 -05:00
private injectCSS () {
// Inject CSS if modified (admin config settings)
2020-05-28 04:15:38 -05: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 10:49:46 -05:00
}
2019-07-08 08:54:08 -05:00
private async loadPlugins () {
this.pluginService.initializePlugins()
2019-07-23 05:16:34 -05:00
this.hooks.runAction('action:application.init', 'common')
2019-07-08 08:54:08 -05:00
}
2019-08-28 07:40:06 -05:00
private async openModalsIfNeeded () {
2019-12-18 08:31:54 -06:00
this.authService.userInformationLoaded
2019-08-28 07:40:06 -05:00
.pipe(
map(() => this.authService.getUser()),
filter(user => user.role === UserRole.ADMINISTRATOR)
2019-12-18 08:31:54 -06:00
).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
2019-08-28 07:40:06 -05:00
}
2019-12-18 08:31:54 -06:00
private async _openAdminModalsIfNeeded (user: User) {
2019-08-28 07:40:06 -05:00
if (user.noWelcomeModal !== true) return this.welcomeModal.show()
2019-12-18 08:31:54 -06:00
if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
2019-08-28 08:46:56 -05:00
this.instanceService.getAbout()
.subscribe(about => {
if (
2019-12-18 08:31:54 -06:00
this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
2019-08-28 08:46:56 -05:00
!about.instance.terms ||
!about.instance.administrator ||
!about.instance.maintenanceLifetime
) {
this.instanceConfigWarningModal.show(about)
}
})
2019-08-28 07:40:06 -05:00
}
2019-03-21 10:49:46 -05: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 07:40:06 -05:00
new Hotkey('b', (event: KeyboardEvent): boolean => {
this.menu.toggleMenu()
return false
}, undefined, $localize`Toggle the left menu`),
2019-08-28 07:40:06 -05: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 07:40:06 -05: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 07:40:06 -05: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 07:40:06 -05: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 07:40:06 -05: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 14:22:00 -05:00
}
2016-03-14 07:50:19 -05:00
}