]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Migrate to $localize
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { concat } from 'rxjs'
3 import { filter, first, map, pairwise } from 'rxjs/operators'
4 import { DOCUMENT, PlatformLocation, ViewportScroller } from '@angular/common'
5 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
6 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
7 import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
8 import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
9 import { HooksService } from '@app/core/plugins/hooks.service'
10 import { PluginService } from '@app/core/plugins/plugin.service'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
13 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
14 import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
15 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
16 import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
17 import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
18 import { MenuService } from './core/menu/menu.service'
19 import { POP_STATE_MODAL_DISMISS } from './helpers'
20 import { InstanceService } from './shared/shared-instance'
21
22 @Component({
23 selector: 'my-app',
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
26 })
27 export class AppComponent implements OnInit, AfterViewInit {
28 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
29
30 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
31 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
32 @ViewChild('customModal') customModal: CustomModalComponent
33
34 customCSS: SafeHtml
35 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
36
37 private serverConfig: ServerConfig
38
39 constructor (
40 @Inject(DOCUMENT) private document: Document,
41 @Inject(LOCALE_ID) private localeId: string,
42 private viewportScroller: ViewportScroller,
43 private router: Router,
44 private authService: AuthService,
45 private serverService: ServerService,
46 private pluginService: PluginService,
47 private instanceService: InstanceService,
48 private domSanitizer: DomSanitizer,
49 private redirectService: RedirectService,
50 private screenService: ScreenService,
51 private hotkeysService: HotkeysService,
52 private themeService: ThemeService,
53 private hooks: HooksService,
54 private location: PlatformLocation,
55 private modalService: NgbModal,
56 private markdownService: MarkdownService,
57 public menu: MenuService
58 ) { }
59
60 get instanceName () {
61 return this.serverConfig.instance.name
62 }
63
64 get defaultRoute () {
65 return RedirectService.DEFAULT_ROUTE
66 }
67
68 ngOnInit () {
69 document.getElementById('incompatible-browser').className += ' browser-ok'
70
71 this.serverConfig = this.serverService.getTmpConfig()
72 this.serverService.getConfig()
73 .subscribe(config => this.serverConfig = config)
74
75 this.loadPlugins()
76 this.themeService.initialize()
77
78 this.authService.loadClientCredentials()
79
80 if (this.isUserLoggedIn()) {
81 // The service will automatically redirect to the login page if the token is not valid anymore
82 this.authService.refreshUserInformation()
83 }
84
85 this.initRouteEvents()
86 this.injectJS()
87 this.injectCSS()
88 this.injectBroadcastMessage()
89
90 this.initHotkeys()
91
92 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
93
94 this.openModalsIfNeeded()
95
96 this.document.documentElement.lang = getShortLocale(this.localeId)
97 }
98
99 ngAfterViewInit () {
100 this.pluginService.initializeCustomModal(this.customModal)
101 }
102
103 isUserLoggedIn () {
104 return this.authService.isLoggedIn()
105 }
106
107 hideBroadcastMessage () {
108 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
109
110 this.broadcastMessage = null
111 this.screenService.isBroadcastMessageDisplayed = false
112 }
113
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))
119
120 scrollEvent.subscribe(e => {
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
128 }
129
130 if (e.position) {
131 return this.viewportScroller.scrollToPosition(e.position)
132 }
133
134 if (resetScroll) {
135 return this.viewportScroller.scrollToPosition([ 0, 0 ])
136 }
137 })
138
139 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
140
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
147 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
148 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
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
177 navigationEndEvent.subscribe(e => {
178 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
179 })
180
181 eventsObs.pipe(
182 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
183 filter(() => this.screenService.isInSmallView())
184 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
185 }
186
187 private injectBroadcastMessage () {
188 concat(
189 this.serverService.getConfig().pipe(first()),
190 this.serverService.configReloaded
191 ).subscribe(async config => {
192 this.broadcastMessage = null
193 this.screenService.isBroadcastMessageDisplayed = false
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 }
214
215 this.screenService.isBroadcastMessageDisplayed = true
216 }
217 })
218 }
219
220 private injectJS () {
221 // Inject JS
222 this.serverService.getConfig()
223 .subscribe(config => {
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 })
233 }
234
235 private injectCSS () {
236 // Inject CSS if modified (admin config settings)
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 })
250 }
251
252 private async loadPlugins () {
253 this.pluginService.initializePlugins()
254
255 this.hooks.runAction('action:application.init', 'common')
256 }
257
258 private async openModalsIfNeeded () {
259 this.authService.userInformationLoaded
260 .pipe(
261 map(() => this.authService.getUser()),
262 filter(user => user.role === UserRole.ADMINISTRATOR)
263 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
264 }
265
266 private async _openAdminModalsIfNeeded (user: User) {
267 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
268
269 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
270
271 this.instanceService.getAbout()
272 .subscribe(about => {
273 if (
274 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
275 !about.instance.terms ||
276 !about.instance.administrator ||
277 !about.instance.maintenanceLifetime
278 ) {
279 this.instanceConfigWarningModal.show(about)
280 }
281 })
282 }
283
284 private initHotkeys () {
285 this.hotkeysService.add([
286 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
287 document.getElementById('search-video').focus()
288 return false
289 }, undefined, $localize`Focus the search bar`),
290
291 new Hotkey('b', (event: KeyboardEvent): boolean => {
292 this.menu.toggleMenu()
293 return false
294 }, undefined, $localize`Toggle the left menu`),
295
296 new Hotkey('g o', (event: KeyboardEvent): boolean => {
297 this.router.navigate([ '/videos/overview' ])
298 return false
299 }, undefined, $localize`Go to the discover videos page`),
300
301 new Hotkey('g t', (event: KeyboardEvent): boolean => {
302 this.router.navigate([ '/videos/trending' ])
303 return false
304 }, undefined, $localize`Go to the trending videos page`),
305
306 new Hotkey('g r', (event: KeyboardEvent): boolean => {
307 this.router.navigate([ '/videos/recently-added' ])
308 return false
309 }, undefined, $localize`Go to the recently added videos page`),
310
311 new Hotkey('g l', (event: KeyboardEvent): boolean => {
312 this.router.navigate([ '/videos/local' ])
313 return false
314 }, undefined, $localize`Go to the local videos page`),
315
316 new Hotkey('g u', (event: KeyboardEvent): boolean => {
317 this.router.navigate([ '/videos/upload' ])
318 return false
319 }, undefined, $localize`Go to the videos upload page`)
320 ])
321 }
322 }