]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
fix colspan for user view of reports
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
CommitLineData
67ed6552 1import { Hotkey, HotkeysService } from 'angular2-hotkeys'
fc21ef5c 2import { filter, map, pairwise, switchMap } from 'rxjs/operators'
67ed6552
C
3import { DOCUMENT, PlatformLocation, ViewportScroller } from '@angular/common'
4import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
00b5556c 5import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
6d0110ad 6import { Event, GuardsCheckStart, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, Router, Scroll } from '@angular/router'
67ed6552 7import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
93cae479 8import { HooksService } from '@app/core/plugins/hooks.service'
67ed6552 9import { PluginService } from '@app/core/plugins/plugin.service'
437e8e06 10import { CustomModalComponent } from '@app/modal/custom-modal.component'
67ed6552
C
11import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
12import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
4f926722 13import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
6d0110ad 14import { LoadingBarService } from '@ngx-loading-bar/core'
66357162 15import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
fc21ef5c 16import { getShortLocale } from '@shared/core-utils/i18n'
2989628b 17import { BroadcastMessageLevel, HTMLServerConfig, ServerConfig, UserRole } from '@shared/models'
3b20bdd6 18import { MenuService } from './core/menu/menu.service'
4504f09f 19import { POP_STATE_MODAL_DISMISS } from './helpers'
67ed6552 20import { InstanceService } from './shared/shared-instance'
e2a2d6c8 21
dc8bc31b 22@Component({
3154f382
C
23 selector: 'my-app',
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
dc8bc31b 26})
437e8e06 27export class AppComponent implements OnInit, AfterViewInit {
72c33e71
C
28 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
29
2f5d2ec5
C
30 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
31 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
437e8e06 32 @ViewChild('customModal') customModal: CustomModalComponent
43d0ea7f 33
00b5556c 34 customCSS: SafeHtml
72c33e71 35 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
00b5556c 36
2989628b 37 private serverConfig: HTMLServerConfig
ba430d75 38
df98563e 39 constructor (
140ea386 40 @Inject(DOCUMENT) private document: Document,
81fe3c67 41 @Inject(LOCALE_ID) private localeId: string,
489290b8 42 private viewportScroller: ViewportScroller,
3154f382 43 private router: Router,
e2a2d6c8 44 private authService: AuthService,
00b5556c 45 private serverService: ServerService,
18a6f04c 46 private pluginService: PluginService,
43d0ea7f 47 private instanceService: InstanceService,
901637bb 48 private domSanitizer: DomSanitizer,
bbe0f064 49 private redirectService: RedirectService,
ee1fc23a 50 private screenService: ScreenService,
1a00c561 51 private hotkeysService: HotkeysService,
93cae479 52 private themeService: ThemeService,
4334445d
C
53 private hooks: HooksService,
54 private location: PlatformLocation,
3b20bdd6 55 private modalService: NgbModal,
72c33e71 56 private markdownService: MarkdownService,
4f926722 57 private ngbConfig: NgbConfig,
6d0110ad 58 private loadingBar: LoadingBarService,
3b20bdd6 59 public menu: MenuService
4f926722
C
60 ) {
61 this.ngbConfig.animation = false
62 }
a99593ed 63
36f9424f 64 get instanceName () {
ba430d75 65 return this.serverConfig.instance.name
36f9424f
C
66 }
67
ba5d4a84 68 goToDefaultRoute () {
aea0b0e7 69 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
29f9b562
C
70 }
71
df98563e 72 ngOnInit () {
b3eeb529 73 document.getElementById('incompatible-browser').className += ' browser-ok'
73e09f27 74
2989628b 75 this.serverConfig = this.serverService.getHTMLConfig()
ba430d75 76
fc21ef5c 77 this.hooks.runAction('action:application.init', 'common')
a2ffd046
C
78 this.themeService.initialize()
79
d592e0a9
C
80 this.authService.loadClientCredentials()
81
d414207f 82 if (this.isUserLoggedIn()) {
e2a2d6c8 83 // The service will automatically redirect to the login page if the token is not valid anymore
bcd9f81e 84 this.authService.refreshUserInformation()
e2a2d6c8 85 }
6e07c3de 86
489290b8 87 this.initRouteEvents()
2989628b 88
489290b8
C
89 this.injectJS()
90 this.injectCSS()
72c33e71 91 this.injectBroadcastMessage()
489290b8 92
2989628b
C
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
489290b8
C
103 this.initHotkeys()
104
60c2bc80 105 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
43d0ea7f
C
106
107 this.openModalsIfNeeded()
81fe3c67
RK
108
109 this.document.documentElement.lang = getShortLocale(this.localeId)
489290b8
C
110 }
111
437e8e06
K
112 ngAfterViewInit () {
113 this.pluginService.initializeCustomModal(this.customModal)
114 }
115
d95bc702
C
116 getToggleTitle () {
117 if (this.menu.isDisplayed()) return $localize`Close the left menu`
118
119 return $localize`Open the left menu`
120 }
121
489290b8
C
122 isUserLoggedIn () {
123 return this.authService.isLoggedIn()
124 }
125
72c33e71
C
126 hideBroadcastMessage () {
127 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
128
129 this.broadcastMessage = null
7034b3c9 130 this.screenService.isBroadcastMessageDisplayed = false
72c33e71
C
131 }
132
489290b8
C
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))
489290b8 138
6d0110ad 139 // Handle anchors/restore position
489290b8 140 scrollEvent.subscribe(e => {
4a53fc82
K
141 // scrollToAnchor first to preserve anchor position when using history navigation
142 if (e.anchor) {
143 setTimeout(() => {
f3081d64 144 this.viewportScroller.scrollToAnchor(e.anchor)
4a53fc82
K
145 })
146
147 return
c8cf5952 148 }
00b5556c 149
4a53fc82
K
150 if (e.position) {
151 return this.viewportScroller.scrollToPosition(e.position)
489290b8
C
152 }
153
154 if (resetScroll) {
155 return this.viewportScroller.scrollToPosition([ 0, 0 ])
156 }
157 })
158
60c2bc80
C
159 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
160
489290b8
C
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
722bca90
C
167 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
168 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
489290b8
C
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
6d0110ad 192 // Plugin hooks
23bdacf8
C
193 navigationEndEvent.subscribe(e => {
194 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
195 })
196
6d0110ad 197 // Automatically hide/display the menu
489290b8
C
198 eventsObs.pipe(
199 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
1bfc7b73 200 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
245b9d27 201 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
6d0110ad
C
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())
489290b8
C
211 }
212
2989628b
C
213 private async injectBroadcastMessage () {
214 this.broadcastMessage = null
215 this.screenService.isBroadcastMessageDisplayed = false
72c33e71 216
2989628b 217 const messageConfig = this.serverConfig.broadcastMessage
72c33e71 218
2989628b
C
219 if (messageConfig.enabled) {
220 // Already dismissed this message?
221 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
222 return
223 }
72c33e71 224
2989628b
C
225 const classes: { [id in BroadcastMessageLevel]: string } = {
226 info: 'alert-info',
227 warning: 'alert-warning',
228 error: 'alert-danger'
229 }
7034b3c9 230
2989628b
C
231 this.broadcastMessage = {
232 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
233 dismissable: messageConfig.dismissable,
234 class: classes[messageConfig.level]
72c33e71 235 }
2989628b
C
236
237 this.screenService.isBroadcastMessageDisplayed = true
238 }
72c33e71
C
239 }
240
489290b8 241 private injectJS () {
e032aec9 242 // Inject JS
2989628b
C
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 }
489290b8 251 }
00b5556c 252
489290b8 253 private injectCSS () {
2989628b
C
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 }
489290b8 262 }
ee1fc23a 263
43d0ea7f 264 private async openModalsIfNeeded () {
ba430d75 265 this.authService.userInformationLoaded
43d0ea7f 266 .pipe(
43d0ea7f 267 map(() => this.authService.getUser()),
2989628b
C
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))
43d0ea7f
C
274 }
275
2989628b 276 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
43d0ea7f
C
277 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
278
2989628b 279 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
589d9f55
C
280
281 this.instanceService.getAbout()
282 .subscribe(about => {
283 if (
ba430d75 284 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
589d9f55
C
285 !about.instance.terms ||
286 !about.instance.administrator ||
287 !about.instance.maintenanceLifetime
288 ) {
289 this.instanceConfigWarningModal.show(about)
290 }
291 })
43d0ea7f
C
292 }
293
489290b8 294 private initHotkeys () {
ee1fc23a 295 this.hotkeysService.add([
8542dc33 296 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
ee1fc23a 297 document.getElementById('search-video').focus()
8542dc33 298 return false
66357162 299 }, undefined, $localize`Focus the search bar`),
43d0ea7f 300
8542dc33 301 new Hotkey('b', (event: KeyboardEvent): boolean => {
3b20bdd6 302 this.menu.toggleMenu()
8542dc33 303 return false
66357162 304 }, undefined, $localize`Toggle the left menu`),
43d0ea7f 305
20d21199 306 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
307 this.router.navigate([ '/videos/overview' ])
308 return false
66357162 309 }, undefined, $localize`Go to the discover videos page`),
43d0ea7f 310
20d21199 311 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
312 this.router.navigate([ '/videos/trending' ])
313 return false
66357162 314 }, undefined, $localize`Go to the trending videos page`),
43d0ea7f 315
20d21199 316 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
317 this.router.navigate([ '/videos/recently-added' ])
318 return false
66357162 319 }, undefined, $localize`Go to the recently added videos page`),
43d0ea7f 320
20d21199 321 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
322 this.router.navigate([ '/videos/local' ])
323 return false
66357162 324 }, undefined, $localize`Go to the local videos page`),
43d0ea7f 325
20d21199 326 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
327 this.router.navigate([ '/videos/upload' ])
328 return false
66357162 329 }, undefined, $localize`Go to the videos upload page`)
ee1fc23a 330 ])
67167390 331 }
dc8bc31b 332}