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