]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
Fix custom default route link
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
CommitLineData
67ed6552 1import { Hotkey, HotkeysService } from 'angular2-hotkeys'
42b40636 2import { delay, forkJoin } from 'rxjs'
8f581725 3import { filter, first, map } from 'rxjs/operators'
dd24f1bb 4import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
67ed6552 5import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
00b5556c 6import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
dd24f1bb
C
7import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
8import {
9 AuthService,
10 MarkdownService,
11 PeerTubeRouterService,
12 RedirectService,
13 ScreenService,
14 ScrollService,
15 ServerService,
16 ThemeService,
a9bfa85d
C
17 User,
18 UserLocalStorageService
dd24f1bb 19} from '@app/core'
93cae479 20import { HooksService } from '@app/core/plugins/hooks.service'
67ed6552 21import { PluginService } from '@app/core/plugins/plugin.service'
8f581725 22import { AccountSetupWarningModalComponent } from '@app/modal/account-setup-warning-modal.component'
42b40636 23import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
437e8e06 24import { CustomModalComponent } from '@app/modal/custom-modal.component'
67ed6552 25import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
4f926722 26import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
6d0110ad 27import { LoadingBarService } from '@ngx-loading-bar/core'
42b40636 28import { logger } from '@root-helpers/logger'
66357162 29import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
fc21ef5c 30import { getShortLocale } from '@shared/core-utils/i18n'
8f581725 31import { BroadcastMessageLevel, HTMLServerConfig, UserRole } from '@shared/models'
3b20bdd6 32import { MenuService } from './core/menu/menu.service'
4504f09f 33import { POP_STATE_MODAL_DISMISS } from './helpers'
073367bb 34import { GlobalIconName } from './shared/shared-icons'
42b40636 35import { InstanceService } from './shared/shared-instance'
e2a2d6c8 36
dc8bc31b 37@Component({
3154f382
C
38 selector: 'my-app',
39 templateUrl: './app.component.html',
40 styleUrls: [ './app.component.scss' ]
dc8bc31b 41})
437e8e06 42export class AppComponent implements OnInit, AfterViewInit {
72c33e71
C
43 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
44
8f581725
C
45 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
46 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
2f5d2ec5 47 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
437e8e06 48 @ViewChild('customModal') customModal: CustomModalComponent
43d0ea7f 49
00b5556c 50 customCSS: SafeHtml
72c33e71 51 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
00b5556c 52
2989628b 53 private serverConfig: HTMLServerConfig
ba430d75 54
df98563e 55 constructor (
140ea386 56 @Inject(DOCUMENT) private document: Document,
81fe3c67 57 @Inject(LOCALE_ID) private localeId: string,
3154f382 58 private router: Router,
e2a2d6c8 59 private authService: AuthService,
00b5556c 60 private serverService: ServerService,
dd24f1bb 61 private peertubeRouter: PeerTubeRouterService,
18a6f04c 62 private pluginService: PluginService,
43d0ea7f 63 private instanceService: InstanceService,
901637bb 64 private domSanitizer: DomSanitizer,
bbe0f064 65 private redirectService: RedirectService,
ee1fc23a 66 private screenService: ScreenService,
1a00c561 67 private hotkeysService: HotkeysService,
93cae479 68 private themeService: ThemeService,
4334445d
C
69 private hooks: HooksService,
70 private location: PlatformLocation,
3b20bdd6 71 private modalService: NgbModal,
72c33e71 72 private markdownService: MarkdownService,
4f926722 73 private ngbConfig: NgbConfig,
6d0110ad 74 private loadingBar: LoadingBarService,
dd24f1bb 75 private scrollService: ScrollService,
a9bfa85d 76 private userLocalStorage: UserLocalStorageService,
3b20bdd6 77 public menu: MenuService
4f926722
C
78 ) {
79 this.ngbConfig.animation = false
80 }
a99593ed 81
36f9424f 82 get instanceName () {
ba430d75 83 return this.serverConfig.instance.name
36f9424f
C
84 }
85
df98563e 86 ngOnInit () {
b3eeb529 87 document.getElementById('incompatible-browser').className += ' browser-ok'
73e09f27 88
a9bfa85d
C
89 this.loadUser()
90
2989628b 91 this.serverConfig = this.serverService.getHTMLConfig()
ba430d75 92
fc21ef5c 93 this.hooks.runAction('action:application.init', 'common')
a2ffd046
C
94 this.themeService.initialize()
95
d592e0a9
C
96 this.authService.loadClientCredentials()
97
d414207f 98 if (this.isUserLoggedIn()) {
e2a2d6c8 99 // The service will automatically redirect to the login page if the token is not valid anymore
bcd9f81e 100 this.authService.refreshUserInformation()
e2a2d6c8 101 }
6e07c3de 102
489290b8 103 this.initRouteEvents()
dd24f1bb 104 this.scrollService.enableScrollRestoration()
2989628b 105
489290b8
C
106 this.injectJS()
107 this.injectCSS()
72c33e71 108 this.injectBroadcastMessage()
489290b8 109
2989628b
C
110 this.serverService.configReloaded
111 .subscribe(config => {
112 this.serverConfig = config
113
114 this.injectBroadcastMessage()
115 this.injectCSS()
116
117 // Don't reinject JS since it could conflict with existing one
118 })
119
489290b8
C
120 this.initHotkeys()
121
60c2bc80 122 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
43d0ea7f
C
123
124 this.openModalsIfNeeded()
81fe3c67
RK
125
126 this.document.documentElement.lang = getShortLocale(this.localeId)
27bc9586 127 this.document.documentElement.dir = getLocaleDirection(this.localeId)
489290b8
C
128 }
129
437e8e06
K
130 ngAfterViewInit () {
131 this.pluginService.initializeCustomModal(this.customModal)
132 }
133
25d7cc3c
C
134 // ---------------------------------------------------------------------------
135
dc9c9500 136 getDefaultRoute () {
25d7cc3c
C
137 return this.redirectService.getDefaultRoute().split('?')[0]
138 }
139
140 getDefaultRouteQuery () {
141 return this.router.parseUrl(this.redirectService.getDefaultRoute()).queryParams
dc9c9500
C
142 }
143
25d7cc3c
C
144 // ---------------------------------------------------------------------------
145
d95bc702
C
146 getToggleTitle () {
147 if (this.menu.isDisplayed()) return $localize`Close the left menu`
148
149 return $localize`Open the left menu`
150 }
151
489290b8
C
152 isUserLoggedIn () {
153 return this.authService.isLoggedIn()
154 }
155
72c33e71
C
156 hideBroadcastMessage () {
157 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
158
159 this.broadcastMessage = null
7034b3c9 160 this.screenService.isBroadcastMessageDisplayed = false
72c33e71
C
161 }
162
073367bb
C
163 getNotificationIcon (message: { severity: 'success' | 'error' | 'info' }): GlobalIconName {
164 switch (message.severity) {
165 case 'error':
166 return 'cross'
167 case 'success':
168 return 'tick'
169 case 'info':
170 return 'help'
171 }
172 }
173
489290b8 174 private initRouteEvents () {
489290b8
C
175 const eventsObs = this.router.events
176
6d0110ad 177 // Plugin hooks
dd24f1bb 178 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
23bdacf8
C
179 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
180 })
181
6d0110ad 182 // Automatically hide/display the menu
489290b8
C
183 eventsObs.pipe(
184 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
1bfc7b73 185 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
245b9d27 186 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
6d0110ad
C
187
188 // Handle lazy loaded module
189 eventsObs.pipe(
190 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
191 ).subscribe(() => this.loadingBar.useRef().start())
192
193 eventsObs.pipe(
194 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
195 ).subscribe(() => this.loadingBar.useRef().complete())
489290b8
C
196 }
197
2989628b
C
198 private async injectBroadcastMessage () {
199 this.broadcastMessage = null
200 this.screenService.isBroadcastMessageDisplayed = false
72c33e71 201
2989628b 202 const messageConfig = this.serverConfig.broadcastMessage
72c33e71 203
2989628b
C
204 if (messageConfig.enabled) {
205 // Already dismissed this message?
206 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
207 return
208 }
72c33e71 209
2989628b
C
210 const classes: { [id in BroadcastMessageLevel]: string } = {
211 info: 'alert-info',
212 warning: 'alert-warning',
213 error: 'alert-danger'
214 }
7034b3c9 215
2989628b 216 this.broadcastMessage = {
0e45e336 217 message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
2989628b
C
218 dismissable: messageConfig.dismissable,
219 class: classes[messageConfig.level]
72c33e71 220 }
2989628b
C
221
222 this.screenService.isBroadcastMessageDisplayed = true
223 }
72c33e71
C
224 }
225
489290b8 226 private injectJS () {
e032aec9 227 // Inject JS
2989628b
C
228 if (this.serverConfig.instance.customizations.javascript) {
229 try {
9df52d66 230 /* eslint-disable no-eval */
2989628b
C
231 eval(this.serverConfig.instance.customizations.javascript)
232 } catch (err) {
42b40636 233 logger.error('Cannot eval custom JavaScript.', err)
2989628b
C
234 }
235 }
489290b8 236 }
00b5556c 237
489290b8 238 private injectCSS () {
2989628b
C
239 const headStyle = document.querySelector('style.custom-css-style')
240 if (headStyle) headStyle.parentNode.removeChild(headStyle)
241
242 // We test customCSS if the admin removed the css
243 if (this.customCSS || this.serverConfig.instance.customizations.css) {
244 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
245 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
246 }
489290b8 247 }
ee1fc23a 248
98ab5dc8 249 private openModalsIfNeeded () {
8f581725 250 const userSub = this.authService.userInformationLoaded
af6766e3
C
251 .pipe(
252 delay(0), // Wait for modals creations
253 map(() => this.authService.getUser())
254 )
8f581725
C
255
256 // Admin modal
257 userSub.pipe(
9e5cf66b 258 filter(user => user.role.id === UserRole.ADMINISTRATOR)
8f581725
C
259 ).subscribe(user => this.openAdminModalsIfNeeded(user))
260
261 // Account modal
262 userSub.pipe(
9e5cf66b 263 filter(user => user.role.id !== UserRole.ADMINISTRATOR)
8f581725 264 ).subscribe(user => this.openAccountModalsIfNeeded(user))
43d0ea7f
C
265 }
266
8f581725
C
267 private openAdminModalsIfNeeded (user: User) {
268 if (this.adminWelcomeModal.shouldOpen(user)) {
269 return this.adminWelcomeModal.show()
270 }
271
272 if (!this.instanceConfigWarningModal.shouldOpenByUser(user)) return
273
274 forkJoin([
275 this.serverService.getConfig().pipe(first()),
276 this.instanceService.getAbout().pipe(first())
277 ]).subscribe(([ config, about ]) => {
278 if (this.instanceConfigWarningModal.shouldOpen(config, about)) {
279 this.instanceConfigWarningModal.show(about)
280 }
281 })
282 }
283
284 private openAccountModalsIfNeeded (user: User) {
285 if (this.accountSetupWarningModal.shouldOpen(user)) {
286 this.accountSetupWarningModal.show(user)
287 }
43d0ea7f
C
288 }
289
489290b8 290 private initHotkeys () {
ee1fc23a 291 this.hotkeysService.add([
9df52d66 292 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
ee1fc23a 293 document.getElementById('search-video').focus()
8542dc33 294 return false
66357162 295 }, undefined, $localize`Focus the search bar`),
43d0ea7f 296
8542dc33 297 new Hotkey('b', (event: KeyboardEvent): boolean => {
3b20bdd6 298 this.menu.toggleMenu()
8542dc33 299 return false
66357162 300 }, undefined, $localize`Toggle the left menu`),
43d0ea7f 301
20d21199 302 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
303 this.router.navigate([ '/videos/overview' ])
304 return false
66357162 305 }, undefined, $localize`Go to the discover videos page`),
43d0ea7f 306
20d21199 307 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
308 this.router.navigate([ '/videos/trending' ])
309 return false
66357162 310 }, undefined, $localize`Go to the trending videos page`),
43d0ea7f 311
20d21199 312 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
313 this.router.navigate([ '/videos/recently-added' ])
314 return false
66357162 315 }, undefined, $localize`Go to the recently added videos page`),
43d0ea7f 316
20d21199 317 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
318 this.router.navigate([ '/videos/local' ])
319 return false
66357162 320 }, undefined, $localize`Go to the local videos page`),
43d0ea7f 321
20d21199 322 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
323 this.router.navigate([ '/videos/upload' ])
324 return false
66357162 325 }, undefined, $localize`Go to the videos upload page`)
ee1fc23a 326 ])
67167390 327 }
a9bfa85d
C
328
329 private loadUser () {
330 const tokens = this.userLocalStorage.getTokens()
331 if (!tokens) return
332
333 const user = this.userLocalStorage.getLoggedInUser()
334 if (!user) return
335
336 // Initialize user
337 this.authService.buildAuthUser(user, tokens)
338 }
dc8bc31b 339}