]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Fix custom default route link
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { delay, forkJoin } from 'rxjs'
3 import { filter, first, map } from 'rxjs/operators'
4 import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
5 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
6 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
7 import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
8 import {
9 AuthService,
10 MarkdownService,
11 PeerTubeRouterService,
12 RedirectService,
13 ScreenService,
14 ScrollService,
15 ServerService,
16 ThemeService,
17 User,
18 UserLocalStorageService
19 } from '@app/core'
20 import { HooksService } from '@app/core/plugins/hooks.service'
21 import { PluginService } from '@app/core/plugins/plugin.service'
22 import { AccountSetupWarningModalComponent } from '@app/modal/account-setup-warning-modal.component'
23 import { AdminWelcomeModalComponent } from '@app/modal/admin-welcome-modal.component'
24 import { CustomModalComponent } from '@app/modal/custom-modal.component'
25 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
26 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
27 import { LoadingBarService } from '@ngx-loading-bar/core'
28 import { logger } from '@root-helpers/logger'
29 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
30 import { getShortLocale } from '@shared/core-utils/i18n'
31 import { BroadcastMessageLevel, HTMLServerConfig, UserRole } from '@shared/models'
32 import { MenuService } from './core/menu/menu.service'
33 import { POP_STATE_MODAL_DISMISS } from './helpers'
34 import { GlobalIconName } from './shared/shared-icons'
35 import { InstanceService } from './shared/shared-instance'
36
37 @Component({
38 selector: 'my-app',
39 templateUrl: './app.component.html',
40 styleUrls: [ './app.component.scss' ]
41 })
42 export class AppComponent implements OnInit, AfterViewInit {
43 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
44
45 @ViewChild('accountSetupWarningModal') accountSetupWarningModal: AccountSetupWarningModalComponent
46 @ViewChild('adminWelcomeModal') adminWelcomeModal: AdminWelcomeModalComponent
47 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
48 @ViewChild('customModal') customModal: CustomModalComponent
49
50 customCSS: SafeHtml
51 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
52
53 private serverConfig: HTMLServerConfig
54
55 constructor (
56 @Inject(DOCUMENT) private document: Document,
57 @Inject(LOCALE_ID) private localeId: string,
58 private router: Router,
59 private authService: AuthService,
60 private serverService: ServerService,
61 private peertubeRouter: PeerTubeRouterService,
62 private pluginService: PluginService,
63 private instanceService: InstanceService,
64 private domSanitizer: DomSanitizer,
65 private redirectService: RedirectService,
66 private screenService: ScreenService,
67 private hotkeysService: HotkeysService,
68 private themeService: ThemeService,
69 private hooks: HooksService,
70 private location: PlatformLocation,
71 private modalService: NgbModal,
72 private markdownService: MarkdownService,
73 private ngbConfig: NgbConfig,
74 private loadingBar: LoadingBarService,
75 private scrollService: ScrollService,
76 private userLocalStorage: UserLocalStorageService,
77 public menu: MenuService
78 ) {
79 this.ngbConfig.animation = false
80 }
81
82 get instanceName () {
83 return this.serverConfig.instance.name
84 }
85
86 ngOnInit () {
87 document.getElementById('incompatible-browser').className += ' browser-ok'
88
89 this.loadUser()
90
91 this.serverConfig = this.serverService.getHTMLConfig()
92
93 this.hooks.runAction('action:application.init', 'common')
94 this.themeService.initialize()
95
96 this.authService.loadClientCredentials()
97
98 if (this.isUserLoggedIn()) {
99 // The service will automatically redirect to the login page if the token is not valid anymore
100 this.authService.refreshUserInformation()
101 }
102
103 this.initRouteEvents()
104 this.scrollService.enableScrollRestoration()
105
106 this.injectJS()
107 this.injectCSS()
108 this.injectBroadcastMessage()
109
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
120 this.initHotkeys()
121
122 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
123
124 this.openModalsIfNeeded()
125
126 this.document.documentElement.lang = getShortLocale(this.localeId)
127 this.document.documentElement.dir = getLocaleDirection(this.localeId)
128 }
129
130 ngAfterViewInit () {
131 this.pluginService.initializeCustomModal(this.customModal)
132 }
133
134 // ---------------------------------------------------------------------------
135
136 getDefaultRoute () {
137 return this.redirectService.getDefaultRoute().split('?')[0]
138 }
139
140 getDefaultRouteQuery () {
141 return this.router.parseUrl(this.redirectService.getDefaultRoute()).queryParams
142 }
143
144 // ---------------------------------------------------------------------------
145
146 getToggleTitle () {
147 if (this.menu.isDisplayed()) return $localize`Close the left menu`
148
149 return $localize`Open the left menu`
150 }
151
152 isUserLoggedIn () {
153 return this.authService.isLoggedIn()
154 }
155
156 hideBroadcastMessage () {
157 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
158
159 this.broadcastMessage = null
160 this.screenService.isBroadcastMessageDisplayed = false
161 }
162
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
174 private initRouteEvents () {
175 const eventsObs = this.router.events
176
177 // Plugin hooks
178 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
179 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
180 })
181
182 // Automatically hide/display the menu
183 eventsObs.pipe(
184 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
185 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
186 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
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())
196 }
197
198 private async injectBroadcastMessage () {
199 this.broadcastMessage = null
200 this.screenService.isBroadcastMessageDisplayed = false
201
202 const messageConfig = this.serverConfig.broadcastMessage
203
204 if (messageConfig.enabled) {
205 // Already dismissed this message?
206 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
207 return
208 }
209
210 const classes: { [id in BroadcastMessageLevel]: string } = {
211 info: 'alert-info',
212 warning: 'alert-warning',
213 error: 'alert-danger'
214 }
215
216 this.broadcastMessage = {
217 message: await this.markdownService.markdownToUnsafeHTML({ markdown: messageConfig.message }),
218 dismissable: messageConfig.dismissable,
219 class: classes[messageConfig.level]
220 }
221
222 this.screenService.isBroadcastMessageDisplayed = true
223 }
224 }
225
226 private injectJS () {
227 // Inject JS
228 if (this.serverConfig.instance.customizations.javascript) {
229 try {
230 /* eslint-disable no-eval */
231 eval(this.serverConfig.instance.customizations.javascript)
232 } catch (err) {
233 logger.error('Cannot eval custom JavaScript.', err)
234 }
235 }
236 }
237
238 private injectCSS () {
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 }
247 }
248
249 private openModalsIfNeeded () {
250 const userSub = this.authService.userInformationLoaded
251 .pipe(
252 delay(0), // Wait for modals creations
253 map(() => this.authService.getUser())
254 )
255
256 // Admin modal
257 userSub.pipe(
258 filter(user => user.role.id === UserRole.ADMINISTRATOR)
259 ).subscribe(user => this.openAdminModalsIfNeeded(user))
260
261 // Account modal
262 userSub.pipe(
263 filter(user => user.role.id !== UserRole.ADMINISTRATOR)
264 ).subscribe(user => this.openAccountModalsIfNeeded(user))
265 }
266
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 }
288 }
289
290 private initHotkeys () {
291 this.hotkeysService.add([
292 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
293 document.getElementById('search-video').focus()
294 return false
295 }, undefined, $localize`Focus the search bar`),
296
297 new Hotkey('b', (event: KeyboardEvent): boolean => {
298 this.menu.toggleMenu()
299 return false
300 }, undefined, $localize`Toggle the left menu`),
301
302 new Hotkey('g o', (event: KeyboardEvent): boolean => {
303 this.router.navigate([ '/videos/overview' ])
304 return false
305 }, undefined, $localize`Go to the discover videos page`),
306
307 new Hotkey('g t', (event: KeyboardEvent): boolean => {
308 this.router.navigate([ '/videos/trending' ])
309 return false
310 }, undefined, $localize`Go to the trending videos page`),
311
312 new Hotkey('g r', (event: KeyboardEvent): boolean => {
313 this.router.navigate([ '/videos/recently-added' ])
314 return false
315 }, undefined, $localize`Go to the recently added videos page`),
316
317 new Hotkey('g l', (event: KeyboardEvent): boolean => {
318 this.router.navigate([ '/videos/local' ])
319 return false
320 }, undefined, $localize`Go to the local videos page`),
321
322 new Hotkey('g u', (event: KeyboardEvent): boolean => {
323 this.router.navigate([ '/videos/upload' ])
324 return false
325 }, undefined, $localize`Go to the videos upload page`)
326 ])
327 }
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 }
339 }