]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
Use HTML config when possible
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
CommitLineData
67ed6552
C
1import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2import { concat } from 'rxjs'
2989628b 3import { filter, first, map, pairwise, switchMap } 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'
6d0110ad 7import { Event, GuardsCheckStart, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, 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'
6d0110ad 15import { LoadingBarService } from '@ngx-loading-bar/core'
66357162 16import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
bd45d503 17import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
2989628b 18import { BroadcastMessageLevel, HTMLServerConfig, ServerConfig, UserRole } from '@shared/models'
3b20bdd6 19import { MenuService } from './core/menu/menu.service'
4504f09f 20import { POP_STATE_MODAL_DISMISS } from './helpers'
67ed6552 21import { InstanceService } from './shared/shared-instance'
e2a2d6c8 22
dc8bc31b 23@Component({
3154f382
C
24 selector: 'my-app',
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
dc8bc31b 27})
437e8e06 28export class AppComponent implements OnInit, AfterViewInit {
72c33e71
C
29 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
30
2f5d2ec5
C
31 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
32 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
437e8e06 33 @ViewChild('customModal') customModal: CustomModalComponent
43d0ea7f 34
00b5556c 35 customCSS: SafeHtml
72c33e71 36 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
00b5556c 37
2989628b 38 private serverConfig: HTMLServerConfig
ba430d75 39
df98563e 40 constructor (
140ea386 41 @Inject(DOCUMENT) private document: Document,
81fe3c67 42 @Inject(LOCALE_ID) private localeId: string,
489290b8 43 private viewportScroller: ViewportScroller,
3154f382 44 private router: Router,
e2a2d6c8 45 private authService: AuthService,
00b5556c 46 private serverService: ServerService,
18a6f04c 47 private pluginService: PluginService,
43d0ea7f 48 private instanceService: InstanceService,
901637bb 49 private domSanitizer: DomSanitizer,
bbe0f064 50 private redirectService: RedirectService,
ee1fc23a 51 private screenService: ScreenService,
1a00c561 52 private hotkeysService: HotkeysService,
93cae479 53 private themeService: ThemeService,
4334445d
C
54 private hooks: HooksService,
55 private location: PlatformLocation,
3b20bdd6 56 private modalService: NgbModal,
72c33e71 57 private markdownService: MarkdownService,
4f926722 58 private ngbConfig: NgbConfig,
6d0110ad 59 private loadingBar: LoadingBarService,
3b20bdd6 60 public menu: MenuService
4f926722
C
61 ) {
62 this.ngbConfig.animation = false
63 }
a99593ed 64
36f9424f 65 get instanceName () {
ba430d75 66 return this.serverConfig.instance.name
36f9424f
C
67 }
68
ba5d4a84 69 goToDefaultRoute () {
aea0b0e7 70 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
29f9b562
C
71 }
72
df98563e 73 ngOnInit () {
b3eeb529 74 document.getElementById('incompatible-browser').className += ' browser-ok'
73e09f27 75
2989628b 76 this.serverConfig = this.serverService.getHTMLConfig()
ba430d75 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 88 this.initRouteEvents()
2989628b 89
489290b8
C
90 this.injectJS()
91 this.injectCSS()
72c33e71 92 this.injectBroadcastMessage()
489290b8 93
2989628b
C
94 this.serverService.configReloaded
95 .subscribe(config => {
96 this.serverConfig = config
97
98 this.injectBroadcastMessage()
99 this.injectCSS()
100
101 // Don't reinject JS since it could conflict with existing one
102 })
103
489290b8
C
104 this.initHotkeys()
105
60c2bc80 106 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
43d0ea7f
C
107
108 this.openModalsIfNeeded()
81fe3c67
RK
109
110 this.document.documentElement.lang = getShortLocale(this.localeId)
489290b8
C
111 }
112
437e8e06
K
113 ngAfterViewInit () {
114 this.pluginService.initializeCustomModal(this.customModal)
115 }
116
d95bc702
C
117 getToggleTitle () {
118 if (this.menu.isDisplayed()) return $localize`Close the left menu`
119
120 return $localize`Open the left menu`
121 }
122
489290b8
C
123 isUserLoggedIn () {
124 return this.authService.isLoggedIn()
125 }
126
72c33e71
C
127 hideBroadcastMessage () {
128 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
129
130 this.broadcastMessage = null
7034b3c9 131 this.screenService.isBroadcastMessageDisplayed = false
72c33e71
C
132 }
133
489290b8
C
134 private initRouteEvents () {
135 let resetScroll = true
136 const eventsObs = this.router.events
137
138 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
489290b8 139
6d0110ad 140 // Handle anchors/restore position
489290b8 141 scrollEvent.subscribe(e => {
4a53fc82
K
142 // scrollToAnchor first to preserve anchor position when using history navigation
143 if (e.anchor) {
144 setTimeout(() => {
f3081d64 145 this.viewportScroller.scrollToAnchor(e.anchor)
4a53fc82
K
146 })
147
148 return
c8cf5952 149 }
00b5556c 150
4a53fc82
K
151 if (e.position) {
152 return this.viewportScroller.scrollToPosition(e.position)
489290b8
C
153 }
154
155 if (resetScroll) {
156 return this.viewportScroller.scrollToPosition([ 0, 0 ])
157 }
158 })
159
60c2bc80
C
160 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
161
489290b8
C
162 // When we add the a-state parameter, we don't want to alter the scroll
163 navigationEndEvent.pipe(pairwise())
164 .subscribe(([ e1, e2 ]) => {
165 try {
166 resetScroll = false
167
722bca90
C
168 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
169 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
489290b8
C
170
171 if (previousUrl.pathname !== nextUrl.pathname) {
172 resetScroll = true
173 return
174 }
175
176 const nextSearchParams = nextUrl.searchParams
177 nextSearchParams.delete('a-state')
178
179 const previousSearchParams = previousUrl.searchParams
180
181 nextSearchParams.sort()
182 previousSearchParams.sort()
183
184 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
185 resetScroll = true
186 }
187 } catch (e) {
188 console.error('Cannot parse URL to check next scroll.', e)
189 resetScroll = true
190 }
191 })
192
6d0110ad 193 // Homepage redirection
489290b8
C
194 navigationEndEvent.pipe(
195 map(() => window.location.pathname),
196 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
197 ).subscribe(() => this.redirectService.redirectToHomepage(true))
198
6d0110ad 199 // Plugin hooks
23bdacf8
C
200 navigationEndEvent.subscribe(e => {
201 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
202 })
203
6d0110ad 204 // Automatically hide/display the menu
489290b8
C
205 eventsObs.pipe(
206 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
1bfc7b73 207 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
245b9d27 208 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
6d0110ad
C
209
210 // Handle lazy loaded module
211 eventsObs.pipe(
212 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
213 ).subscribe(() => this.loadingBar.useRef().start())
214
215 eventsObs.pipe(
216 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
217 ).subscribe(() => this.loadingBar.useRef().complete())
489290b8
C
218 }
219
2989628b
C
220 private async injectBroadcastMessage () {
221 this.broadcastMessage = null
222 this.screenService.isBroadcastMessageDisplayed = false
72c33e71 223
2989628b 224 const messageConfig = this.serverConfig.broadcastMessage
72c33e71 225
2989628b
C
226 if (messageConfig.enabled) {
227 // Already dismissed this message?
228 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
229 return
230 }
72c33e71 231
2989628b
C
232 const classes: { [id in BroadcastMessageLevel]: string } = {
233 info: 'alert-info',
234 warning: 'alert-warning',
235 error: 'alert-danger'
236 }
7034b3c9 237
2989628b
C
238 this.broadcastMessage = {
239 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
240 dismissable: messageConfig.dismissable,
241 class: classes[messageConfig.level]
72c33e71 242 }
2989628b
C
243
244 this.screenService.isBroadcastMessageDisplayed = true
245 }
72c33e71
C
246 }
247
489290b8 248 private injectJS () {
e032aec9 249 // Inject JS
2989628b
C
250 if (this.serverConfig.instance.customizations.javascript) {
251 try {
252 // tslint:disable:no-eval
253 eval(this.serverConfig.instance.customizations.javascript)
254 } catch (err) {
255 console.error('Cannot eval custom JavaScript.', err)
256 }
257 }
489290b8 258 }
00b5556c 259
489290b8 260 private injectCSS () {
2989628b
C
261 const headStyle = document.querySelector('style.custom-css-style')
262 if (headStyle) headStyle.parentNode.removeChild(headStyle)
263
264 // We test customCSS if the admin removed the css
265 if (this.customCSS || this.serverConfig.instance.customizations.css) {
266 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
267 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
268 }
489290b8 269 }
ee1fc23a 270
18a6f04c
C
271 private async loadPlugins () {
272 this.pluginService.initializePlugins()
273
c9e3eeed 274 this.hooks.runAction('action:application.init', 'common')
18a6f04c
C
275 }
276
43d0ea7f 277 private async openModalsIfNeeded () {
ba430d75 278 this.authService.userInformationLoaded
43d0ea7f 279 .pipe(
43d0ea7f 280 map(() => this.authService.getUser()),
2989628b
C
281 filter(user => user.role === UserRole.ADMINISTRATOR),
282 switchMap(user => {
283 return this.serverService.getConfig()
284 .pipe(map(serverConfig => ({ serverConfig, user })))
285 })
286 ).subscribe(({ serverConfig, user }) => this._openAdminModalsIfNeeded(serverConfig, user))
43d0ea7f
C
287 }
288
2989628b 289 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
43d0ea7f
C
290 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
291
2989628b 292 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
589d9f55
C
293
294 this.instanceService.getAbout()
295 .subscribe(about => {
296 if (
ba430d75 297 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
589d9f55
C
298 !about.instance.terms ||
299 !about.instance.administrator ||
300 !about.instance.maintenanceLifetime
301 ) {
302 this.instanceConfigWarningModal.show(about)
303 }
304 })
43d0ea7f
C
305 }
306
489290b8 307 private initHotkeys () {
ee1fc23a 308 this.hotkeysService.add([
8542dc33 309 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
ee1fc23a 310 document.getElementById('search-video').focus()
8542dc33 311 return false
66357162 312 }, undefined, $localize`Focus the search bar`),
43d0ea7f 313
8542dc33 314 new Hotkey('b', (event: KeyboardEvent): boolean => {
3b20bdd6 315 this.menu.toggleMenu()
8542dc33 316 return false
66357162 317 }, undefined, $localize`Toggle the left menu`),
43d0ea7f 318
20d21199 319 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
320 this.router.navigate([ '/videos/overview' ])
321 return false
66357162 322 }, undefined, $localize`Go to the discover videos page`),
43d0ea7f 323
20d21199 324 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
325 this.router.navigate([ '/videos/trending' ])
326 return false
66357162 327 }, undefined, $localize`Go to the trending videos page`),
43d0ea7f 328
20d21199 329 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
330 this.router.navigate([ '/videos/recently-added' ])
331 return false
66357162 332 }, undefined, $localize`Go to the recently added videos page`),
43d0ea7f 333
20d21199 334 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
335 this.router.navigate([ '/videos/local' ])
336 return false
66357162 337 }, undefined, $localize`Go to the local videos page`),
43d0ea7f 338
20d21199 339 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
340 this.router.navigate([ '/videos/upload' ])
341 return false
66357162 342 }, undefined, $localize`Go to the videos upload page`)
ee1fc23a 343 ])
67167390 344 }
dc8bc31b 345}