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