]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
Fix webpack config
[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'
27bc9586 3import { DOCUMENT, getLocaleDirection, PlatformLocation, ViewportScroller } from '@angular/common'
67ed6552 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)
27bc9586 110 this.document.documentElement.dir = getLocaleDirection(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 // Plugin hooks
23bdacf8
C
194 navigationEndEvent.subscribe(e => {
195 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
196 })
197
6d0110ad 198 // Automatically hide/display the menu
489290b8
C
199 eventsObs.pipe(
200 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
1bfc7b73 201 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
245b9d27 202 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
6d0110ad
C
203
204 // Handle lazy loaded module
205 eventsObs.pipe(
206 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
207 ).subscribe(() => this.loadingBar.useRef().start())
208
209 eventsObs.pipe(
210 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
211 ).subscribe(() => this.loadingBar.useRef().complete())
489290b8
C
212 }
213
2989628b
C
214 private async injectBroadcastMessage () {
215 this.broadcastMessage = null
216 this.screenService.isBroadcastMessageDisplayed = false
72c33e71 217
2989628b 218 const messageConfig = this.serverConfig.broadcastMessage
72c33e71 219
2989628b
C
220 if (messageConfig.enabled) {
221 // Already dismissed this message?
222 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
223 return
224 }
72c33e71 225
2989628b
C
226 const classes: { [id in BroadcastMessageLevel]: string } = {
227 info: 'alert-info',
228 warning: 'alert-warning',
229 error: 'alert-danger'
230 }
7034b3c9 231
2989628b
C
232 this.broadcastMessage = {
233 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
234 dismissable: messageConfig.dismissable,
235 class: classes[messageConfig.level]
72c33e71 236 }
2989628b
C
237
238 this.screenService.isBroadcastMessageDisplayed = true
239 }
72c33e71
C
240 }
241
489290b8 242 private injectJS () {
e032aec9 243 // Inject JS
2989628b
C
244 if (this.serverConfig.instance.customizations.javascript) {
245 try {
246 // tslint:disable:no-eval
247 eval(this.serverConfig.instance.customizations.javascript)
248 } catch (err) {
249 console.error('Cannot eval custom JavaScript.', err)
250 }
251 }
489290b8 252 }
00b5556c 253
489290b8 254 private injectCSS () {
2989628b
C
255 const headStyle = document.querySelector('style.custom-css-style')
256 if (headStyle) headStyle.parentNode.removeChild(headStyle)
257
258 // We test customCSS if the admin removed the css
259 if (this.customCSS || this.serverConfig.instance.customizations.css) {
260 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
261 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
262 }
489290b8 263 }
ee1fc23a 264
43d0ea7f 265 private async openModalsIfNeeded () {
ba430d75 266 this.authService.userInformationLoaded
43d0ea7f 267 .pipe(
43d0ea7f 268 map(() => this.authService.getUser()),
2989628b
C
269 filter(user => user.role === UserRole.ADMINISTRATOR),
270 switchMap(user => {
271 return this.serverService.getConfig()
272 .pipe(map(serverConfig => ({ serverConfig, user })))
273 })
274 ).subscribe(({ serverConfig, user }) => this._openAdminModalsIfNeeded(serverConfig, user))
43d0ea7f
C
275 }
276
2989628b 277 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
43d0ea7f
C
278 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
279
2989628b 280 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
589d9f55
C
281
282 this.instanceService.getAbout()
283 .subscribe(about => {
284 if (
ba430d75 285 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
589d9f55
C
286 !about.instance.terms ||
287 !about.instance.administrator ||
288 !about.instance.maintenanceLifetime
289 ) {
290 this.instanceConfigWarningModal.show(about)
291 }
292 })
43d0ea7f
C
293 }
294
489290b8 295 private initHotkeys () {
ee1fc23a 296 this.hotkeysService.add([
8542dc33 297 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
ee1fc23a 298 document.getElementById('search-video').focus()
8542dc33 299 return false
66357162 300 }, undefined, $localize`Focus the search bar`),
43d0ea7f 301
8542dc33 302 new Hotkey('b', (event: KeyboardEvent): boolean => {
3b20bdd6 303 this.menu.toggleMenu()
8542dc33 304 return false
66357162 305 }, undefined, $localize`Toggle the left menu`),
43d0ea7f 306
20d21199 307 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
308 this.router.navigate([ '/videos/overview' ])
309 return false
66357162 310 }, undefined, $localize`Go to the discover videos page`),
43d0ea7f 311
20d21199 312 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
313 this.router.navigate([ '/videos/trending' ])
314 return false
66357162 315 }, undefined, $localize`Go to the trending videos page`),
43d0ea7f 316
20d21199 317 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
318 this.router.navigate([ '/videos/recently-added' ])
319 return false
66357162 320 }, undefined, $localize`Go to the recently added videos page`),
43d0ea7f 321
20d21199 322 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
323 this.router.navigate([ '/videos/local' ])
324 return false
66357162 325 }, undefined, $localize`Go to the local videos page`),
43d0ea7f 326
20d21199 327 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
328 this.router.navigate([ '/videos/upload' ])
329 return false
66357162 330 }, undefined, $localize`Go to the videos upload page`)
ee1fc23a 331 ])
67167390 332 }
dc8bc31b 333}