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