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