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