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