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

332 lines
11 KiB
TypeScript
Raw Normal View History

2020-06-23 12:10:17 +00:00
import { Hotkey, HotkeysService } from 'angular2-hotkeys'
import { delay, forkJoin } from 'rxjs'
import { filter, first, map } from 'rxjs/operators'
import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
2020-06-23 12:10:17 +00:00
import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
import {
AuthService,
MarkdownService,
PeerTubeRouterService,
RedirectService,
ScreenService,
ScrollService,
ServerService,
ThemeService,
User,
UserLocalStorageService
} 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 { AccountSetupWarningModalComponent } from '@app/modal/account-setup-warning-modal.component'
import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
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 { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
2021-01-13 10:29:55 +00:00
import { LoadingBarService } from '@ngx-loading-bar/core'
import { logger } from '@root-helpers/logger'
import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
2021-06-04 12:39:47 +00:00
import { getShortLocale } from '@shared/core-utils/i18n'
import { BroadcastMessageLevel, HTMLServerConfig, 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'
import { GlobalIconName } from './shared/shared-icons'
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'
@ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
@ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
2020-02-07 09:00:34 +00:00
@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
2021-06-04 11:31:41 +00:00
private serverConfig: HTMLServerConfig
2019-12-18 14:31:54 +00:00
constructor (
@Inject(DOCUMENT) private document: Document,
@Inject(LOCALE_ID) private localeId: string,
2016-11-04 15:23:18 +00:00
private router: Router,
private authService: AuthService,
private serverService: ServerService,
private peertubeRouter: PeerTubeRouterService,
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,
private ngbConfig: NgbConfig,
2021-01-13 10:29:55 +00:00
private loadingBar: LoadingBarService,
private scrollService: ScrollService,
private userLocalStorage: UserLocalStorageService,
public menu: MenuService
) {
this.ngbConfig.animation = false
}
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
}
ngOnInit () {
2018-03-08 11:04:10 +00:00
document.getElementById('incompatible-browser').className += ' browser-ok'
this.loadUser()
2021-06-04 11:31:41 +00:00
this.serverConfig = this.serverService.getHTMLConfig()
2019-12-18 14:31:54 +00:00
2021-06-04 12:39:47 +00:00
this.hooks.runAction('action:application.init', 'common')
2019-10-25 08:57:23 +00:00
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.scrollService.enableScrollRestoration()
2021-06-04 11:31:41 +00:00
2019-03-21 15:49:46 +00:00
this.injectJS()
this.injectCSS()
2020-05-28 09:15:38 +00:00
this.injectBroadcastMessage()
2019-03-21 15:49:46 +00:00
2021-06-04 11:31:41 +00:00
this.serverService.configReloaded
.subscribe(config => {
this.serverConfig = config
this.injectBroadcastMessage()
this.injectCSS()
// Don't reinject JS since it could conflict with existing one
})
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)
2021-06-07 15:38:31 +00:00
this.document.documentElement.dir = getLocaleDirection(this.localeId)
2019-03-21 15:49:46 +00:00
}
ngAfterViewInit () {
this.pluginService.initializeCustomModal(this.customModal)
}
2023-03-15 13:20:26 +00:00
getDefaultRoute () {
return this.redirectService.getDefaultRoute()
}
2021-01-13 09:44:34 +00:00
getToggleTitle () {
if (this.menu.isDisplayed()) return $localize`Close the left menu`
return $localize`Open the left menu`
}
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
}
getNotificationIcon (message: { severity: 'success' | 'error' | 'info' }): GlobalIconName {
switch (message.severity) {
case 'error':
return 'cross'
case 'success':
return 'tick'
case 'info':
return 'help'
}
}
2019-03-21 15:49:46 +00:00
private initRouteEvents () {
const eventsObs = this.router.events
2021-01-13 10:29:55 +00:00
// Plugin hooks
this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
2019-07-25 17:02:54 +00:00
this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
})
2021-01-13 10:29:55 +00:00
// Automatically hide/display the menu
2019-03-21 15:49:46 +00:00
eventsObs.pipe(
filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
2020-08-17 08:19:45 +00: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 10:29:55 +00: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 15:49:46 +00:00
}
2021-06-04 11:31:41 +00:00
private async injectBroadcastMessage () {
this.broadcastMessage = null
this.screenService.isBroadcastMessageDisplayed = false
2020-05-28 09:15:38 +00:00
2021-06-04 11:31:41 +00:00
const messageConfig = this.serverConfig.broadcastMessage
2020-05-28 09:15:38 +00:00
2021-06-04 11:31:41 +00:00
if (messageConfig.enabled) {
// Already dismissed this message?
if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
return
}
2020-05-28 09:15:38 +00:00
2021-06-04 11:31:41 +00:00
const classes: { [id in BroadcastMessageLevel]: string } = {
info: 'alert-info',
warning: 'alert-warning',
error: 'alert-danger'
}
2021-06-04 11:31:41 +00:00
this.broadcastMessage = {
message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
2021-06-04 11:31:41 +00:00
dismissable: messageConfig.dismissable,
class: classes[messageConfig.level]
2020-05-28 09:15:38 +00:00
}
2021-06-04 11:31:41 +00:00
this.screenService.isBroadcastMessageDisplayed = true
}
2020-05-28 09:15:38 +00:00
}
2019-03-21 15:49:46 +00:00
private injectJS () {
// Inject JS
2021-06-04 11:31:41 +00:00
if (this.serverConfig.instance.customizations.javascript) {
try {
2021-08-17 12:42:53 +00:00
/* eslint-disable no-eval */
2021-06-04 11:31:41 +00:00
eval(this.serverConfig.instance.customizations.javascript)
} catch (err) {
logger.error('Cannot eval custom JavaScript.', err)
2021-06-04 11:31:41 +00:00
}
}
2019-03-21 15:49:46 +00:00
}
2019-03-21 15:49:46 +00:00
private injectCSS () {
2021-06-04 11:31:41 +00:00
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 || this.serverConfig.instance.customizations.css) {
const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
}
2019-03-21 15:49:46 +00:00
}
2021-08-25 14:14:11 +00:00
private openModalsIfNeeded () {
const userSub = this.authService.userInformationLoaded
2021-08-30 15:13:16 +00:00
.pipe(
delay(0), // Wait for modals creations
map(() => this.authService.getUser())
)
// Admin modal
userSub.pipe(
filter(user => user.role.id === UserRole.ADMINISTRATOR)
).subscribe(user => this.openAdminModalsIfNeeded(user))
// Account modal
userSub.pipe(
filter(user => user.role.id !== UserRole.ADMINISTRATOR)
).subscribe(user => this.openAccountModalsIfNeeded(user))
2019-08-28 12:40:06 +00:00
}
private openAdminModalsIfNeeded (user: User) {
if (this.adminWelcomeModal.shouldOpen(user)) {
return this.adminWelcomeModal.show()
}
if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
forkJoin([
this.serverService.getConfig().pipe(first()),
this.instanceService.getAbout().pipe(first())
]).subscribe(([ config, about ]) => {
if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
this.instanceConfigWarningModal.show(about)
}
})
}
private openAccountModalsIfNeeded (user: User) {
if (this.accountSetupWarningModal.shouldOpen(user)) {
this.accountSetupWarningModal.show(user)
}
2019-08-28 12:40:06 +00:00
}
2019-03-21 15:49:46 +00:00
private initHotkeys () {
this.hotkeysService.add([
2021-08-17 12:42:53 +00:00
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
}
private loadUser () {
const tokens = this.userLocalStorage.getTokens()
if (!tokens) return
const user = this.userLocalStorage.getLoggedInUser()
if (!user) return
// Initialize user
this.authService.buildAuthUser(user, tokens)
}
2016-03-14 12:50:19 +00:00
}