]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
6884068f6da8e3a1801ca7905bf44d07aac0373c
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { concat } from 'rxjs'
3 import { filter, first, map, pairwise, switchMap } from 'rxjs/operators'
4 import { DOCUMENT, PlatformLocation, ViewportScroller } 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, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, Router, Scroll } from '@angular/router'
8 import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
9 import { HooksService } from '@app/core/plugins/hooks.service'
10 import { PluginService } from '@app/core/plugins/plugin.service'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
13 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
14 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { LoadingBarService } from '@ngx-loading-bar/core'
16 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
17 import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
18 import { BroadcastMessageLevel, HTMLServerConfig, ServerConfig, UserRole } from '@shared/models'
19 import { MenuService } from './core/menu/menu.service'
20 import { POP_STATE_MODAL_DISMISS } from './helpers'
21 import { InstanceService } from './shared/shared-instance'
22
23 @Component({
24 selector: 'my-app',
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
27 })
28 export class AppComponent implements OnInit, AfterViewInit {
29 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
30
31 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
32 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
33 @ViewChild('customModal') customModal: CustomModalComponent
34
35 customCSS: SafeHtml
36 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
37
38 private serverConfig: HTMLServerConfig
39
40 constructor (
41 @Inject(DOCUMENT) private document: Document,
42 @Inject(LOCALE_ID) private localeId: string,
43 private viewportScroller: ViewportScroller,
44 private router: Router,
45 private authService: AuthService,
46 private serverService: ServerService,
47 private pluginService: PluginService,
48 private instanceService: InstanceService,
49 private domSanitizer: DomSanitizer,
50 private redirectService: RedirectService,
51 private screenService: ScreenService,
52 private hotkeysService: HotkeysService,
53 private themeService: ThemeService,
54 private hooks: HooksService,
55 private location: PlatformLocation,
56 private modalService: NgbModal,
57 private markdownService: MarkdownService,
58 private ngbConfig: NgbConfig,
59 private loadingBar: LoadingBarService,
60 public menu: MenuService
61 ) {
62 this.ngbConfig.animation = false
63 }
64
65 get instanceName () {
66 return this.serverConfig.instance.name
67 }
68
69 goToDefaultRoute () {
70 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
71 }
72
73 ngOnInit () {
74 document.getElementById('incompatible-browser').className += ' browser-ok'
75
76 this.serverConfig = this.serverService.getHTMLConfig()
77
78 this.loadPlugins()
79 this.themeService.initialize()
80
81 this.authService.loadClientCredentials()
82
83 if (this.isUserLoggedIn()) {
84 // The service will automatically redirect to the login page if the token is not valid anymore
85 this.authService.refreshUserInformation()
86 }
87
88 this.initRouteEvents()
89
90 this.injectJS()
91 this.injectCSS()
92 this.injectBroadcastMessage()
93
94 this.serverService.configReloaded
95 .subscribe(config => {
96 this.serverConfig = config
97
98 this.injectBroadcastMessage()
99 this.injectCSS()
100
101 // Don't reinject JS since it could conflict with existing one
102 })
103
104 this.initHotkeys()
105
106 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
107
108 this.openModalsIfNeeded()
109
110 this.document.documentElement.lang = getShortLocale(this.localeId)
111 }
112
113 ngAfterViewInit () {
114 this.pluginService.initializeCustomModal(this.customModal)
115 }
116
117 getToggleTitle () {
118 if (this.menu.isDisplayed()) return $localize`Close the left menu`
119
120 return $localize`Open the left menu`
121 }
122
123 isUserLoggedIn () {
124 return this.authService.isLoggedIn()
125 }
126
127 hideBroadcastMessage () {
128 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
129
130 this.broadcastMessage = null
131 this.screenService.isBroadcastMessageDisplayed = false
132 }
133
134 private initRouteEvents () {
135 let resetScroll = true
136 const eventsObs = this.router.events
137
138 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
139
140 // Handle anchors/restore position
141 scrollEvent.subscribe(e => {
142 // scrollToAnchor first to preserve anchor position when using history navigation
143 if (e.anchor) {
144 setTimeout(() => {
145 this.viewportScroller.scrollToAnchor(e.anchor)
146 })
147
148 return
149 }
150
151 if (e.position) {
152 return this.viewportScroller.scrollToPosition(e.position)
153 }
154
155 if (resetScroll) {
156 return this.viewportScroller.scrollToPosition([ 0, 0 ])
157 }
158 })
159
160 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
161
162 // When we add the a-state parameter, we don't want to alter the scroll
163 navigationEndEvent.pipe(pairwise())
164 .subscribe(([ e1, e2 ]) => {
165 try {
166 resetScroll = false
167
168 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
169 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
170
171 if (previousUrl.pathname !== nextUrl.pathname) {
172 resetScroll = true
173 return
174 }
175
176 const nextSearchParams = nextUrl.searchParams
177 nextSearchParams.delete('a-state')
178
179 const previousSearchParams = previousUrl.searchParams
180
181 nextSearchParams.sort()
182 previousSearchParams.sort()
183
184 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
185 resetScroll = true
186 }
187 } catch (e) {
188 console.error('Cannot parse URL to check next scroll.', e)
189 resetScroll = true
190 }
191 })
192
193 // Homepage redirection
194 navigationEndEvent.pipe(
195 map(() => window.location.pathname),
196 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
197 ).subscribe(() => this.redirectService.redirectToHomepage(true))
198
199 // Plugin hooks
200 navigationEndEvent.subscribe(e => {
201 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
202 })
203
204 // Automatically hide/display the menu
205 eventsObs.pipe(
206 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
207 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
208 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
209
210 // Handle lazy loaded module
211 eventsObs.pipe(
212 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
213 ).subscribe(() => this.loadingBar.useRef().start())
214
215 eventsObs.pipe(
216 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
217 ).subscribe(() => this.loadingBar.useRef().complete())
218 }
219
220 private async injectBroadcastMessage () {
221 this.broadcastMessage = null
222 this.screenService.isBroadcastMessageDisplayed = false
223
224 const messageConfig = this.serverConfig.broadcastMessage
225
226 if (messageConfig.enabled) {
227 // Already dismissed this message?
228 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
229 return
230 }
231
232 const classes: { [id in BroadcastMessageLevel]: string } = {
233 info: 'alert-info',
234 warning: 'alert-warning',
235 error: 'alert-danger'
236 }
237
238 this.broadcastMessage = {
239 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
240 dismissable: messageConfig.dismissable,
241 class: classes[messageConfig.level]
242 }
243
244 this.screenService.isBroadcastMessageDisplayed = true
245 }
246 }
247
248 private injectJS () {
249 // Inject JS
250 if (this.serverConfig.instance.customizations.javascript) {
251 try {
252 // tslint:disable:no-eval
253 eval(this.serverConfig.instance.customizations.javascript)
254 } catch (err) {
255 console.error('Cannot eval custom JavaScript.', err)
256 }
257 }
258 }
259
260 private injectCSS () {
261 const headStyle = document.querySelector('style.custom-css-style')
262 if (headStyle) headStyle.parentNode.removeChild(headStyle)
263
264 // We test customCSS if the admin removed the css
265 if (this.customCSS || this.serverConfig.instance.customizations.css) {
266 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
267 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
268 }
269 }
270
271 private async loadPlugins () {
272 this.pluginService.initializePlugins()
273
274 this.hooks.runAction('action:application.init', 'common')
275 }
276
277 private async openModalsIfNeeded () {
278 this.authService.userInformationLoaded
279 .pipe(
280 map(() => this.authService.getUser()),
281 filter(user => user.role === UserRole.ADMINISTRATOR),
282 switchMap(user => {
283 return this.serverService.getConfig()
284 .pipe(map(serverConfig => ({ serverConfig, user })))
285 })
286 ).subscribe(({ serverConfig, user }) => this._openAdminModalsIfNeeded(serverConfig, user))
287 }
288
289 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
290 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
291
292 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
293
294 this.instanceService.getAbout()
295 .subscribe(about => {
296 if (
297 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
298 !about.instance.terms ||
299 !about.instance.administrator ||
300 !about.instance.maintenanceLifetime
301 ) {
302 this.instanceConfigWarningModal.show(about)
303 }
304 })
305 }
306
307 private initHotkeys () {
308 this.hotkeysService.add([
309 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
310 document.getElementById('search-video').focus()
311 return false
312 }, undefined, $localize`Focus the search bar`),
313
314 new Hotkey('b', (event: KeyboardEvent): boolean => {
315 this.menu.toggleMenu()
316 return false
317 }, undefined, $localize`Toggle the left menu`),
318
319 new Hotkey('g o', (event: KeyboardEvent): boolean => {
320 this.router.navigate([ '/videos/overview' ])
321 return false
322 }, undefined, $localize`Go to the discover videos page`),
323
324 new Hotkey('g t', (event: KeyboardEvent): boolean => {
325 this.router.navigate([ '/videos/trending' ])
326 return false
327 }, undefined, $localize`Go to the trending videos page`),
328
329 new Hotkey('g r', (event: KeyboardEvent): boolean => {
330 this.router.navigate([ '/videos/recently-added' ])
331 return false
332 }, undefined, $localize`Go to the recently added videos page`),
333
334 new Hotkey('g l', (event: KeyboardEvent): boolean => {
335 this.router.navigate([ '/videos/local' ])
336 return false
337 }, undefined, $localize`Go to the local videos page`),
338
339 new Hotkey('g u', (event: KeyboardEvent): boolean => {
340 this.router.navigate([ '/videos/upload' ])
341 return false
342 }, undefined, $localize`Go to the videos upload page`)
343 ])
344 }
345 }