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