]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/app/app.component.ts
Update ffmpeg min version
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
... / ...
CommitLineData
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'
6import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
7import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
8import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core'
9import { HooksService } from '@app/core/plugins/hooks.service'
10import { PluginService } from '@app/core/plugins/plugin.service'
11import { CustomModalComponent } from '@app/modal/custom-modal.component'
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'
15import { I18n } from '@ngx-translate/i18n-polyfill'
16import { getShortLocale, is18nPath } from '@shared/core-utils/i18n'
17import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models'
18import { MenuService } from './core/menu/menu.service'
19import { POP_STATE_MODAL_DISMISS } from './helpers'
20import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
21import { InstanceService } from './shared/shared-instance'
22
23@Component({
24 selector: 'my-app',
25 templateUrl: './app.component.html',
26 styleUrls: [ './app.component.scss' ]
27})
28export class AppComponent implements OnInit, AfterViewInit {
29 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
30
31 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
32 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
33 @ViewChild('customModal') customModal: CustomModalComponent
34
35 customCSS: SafeHtml
36 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
37
38 private serverConfig: ServerConfig
39
40 constructor (
41 @Inject(DOCUMENT) private document: Document,
42 @Inject(LOCALE_ID) private localeId: string,
43 private i18n: I18n,
44 private viewportScroller: ViewportScroller,
45 private router: Router,
46 private authService: AuthService,
47 private serverService: ServerService,
48 private pluginService: PluginService,
49 private instanceService: InstanceService,
50 private domSanitizer: DomSanitizer,
51 private redirectService: RedirectService,
52 private screenService: ScreenService,
53 private hotkeysService: HotkeysService,
54 private themeService: ThemeService,
55 private hooks: HooksService,
56 private location: PlatformLocation,
57 private modalService: NgbModal,
58 private markdownService: MarkdownService,
59 public menu: MenuService
60 ) { }
61
62 get instanceName () {
63 return this.serverConfig.instance.name
64 }
65
66 get defaultRoute () {
67 return RedirectService.DEFAULT_ROUTE
68 }
69
70 ngOnInit () {
71 document.getElementById('incompatible-browser').className += ' browser-ok'
72
73 this.serverConfig = this.serverService.getTmpConfig()
74 this.serverService.getConfig()
75 .subscribe(config => this.serverConfig = config)
76
77 this.loadPlugins()
78 this.themeService.initialize()
79
80 this.authService.loadClientCredentials()
81
82 if (this.isUserLoggedIn()) {
83 // The service will automatically redirect to the login page if the token is not valid anymore
84 this.authService.refreshUserInformation()
85 }
86
87 this.initRouteEvents()
88 this.injectJS()
89 this.injectCSS()
90 this.injectBroadcastMessage()
91
92 this.initHotkeys()
93
94 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
95
96 this.openModalsIfNeeded()
97
98 this.document.documentElement.lang = getShortLocale(this.localeId)
99 }
100
101 ngAfterViewInit () {
102 this.pluginService.initializeCustomModal(this.customModal)
103 }
104
105 isUserLoggedIn () {
106 return this.authService.isLoggedIn()
107 }
108
109 hideBroadcastMessage () {
110 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
111
112 this.broadcastMessage = null
113 this.screenService.isBroadcastMessageDisplayed = false
114 }
115
116 private initRouteEvents () {
117 let resetScroll = true
118 const eventsObs = this.router.events
119
120 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
121
122 scrollEvent.subscribe(e => {
123 // scrollToAnchor first to preserve anchor position when using history navigation
124 if (e.anchor) {
125 setTimeout(() => {
126 this.viewportScroller.scrollToAnchor(e.anchor)
127 })
128
129 return
130 }
131
132 if (e.position) {
133 return this.viewportScroller.scrollToPosition(e.position)
134 }
135
136 if (resetScroll) {
137 return this.viewportScroller.scrollToPosition([ 0, 0 ])
138 }
139 })
140
141 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
142
143 // When we add the a-state parameter, we don't want to alter the scroll
144 navigationEndEvent.pipe(pairwise())
145 .subscribe(([ e1, e2 ]) => {
146 try {
147 resetScroll = false
148
149 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
150 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
151
152 if (previousUrl.pathname !== nextUrl.pathname) {
153 resetScroll = true
154 return
155 }
156
157 const nextSearchParams = nextUrl.searchParams
158 nextSearchParams.delete('a-state')
159
160 const previousSearchParams = previousUrl.searchParams
161
162 nextSearchParams.sort()
163 previousSearchParams.sort()
164
165 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
166 resetScroll = true
167 }
168 } catch (e) {
169 console.error('Cannot parse URL to check next scroll.', e)
170 resetScroll = true
171 }
172 })
173
174 navigationEndEvent.pipe(
175 map(() => window.location.pathname),
176 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
177 ).subscribe(() => this.redirectService.redirectToHomepage(true))
178
179 navigationEndEvent.subscribe(e => {
180 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
181 })
182
183 eventsObs.pipe(
184 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
185 filter(() => this.screenService.isInSmallView())
186 ).subscribe(() => this.menu.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
187 }
188
189 private injectBroadcastMessage () {
190 concat(
191 this.serverService.getConfig().pipe(first()),
192 this.serverService.configReloaded
193 ).subscribe(async config => {
194 this.broadcastMessage = null
195 this.screenService.isBroadcastMessageDisplayed = false
196
197 const messageConfig = config.broadcastMessage
198
199 if (messageConfig.enabled) {
200 // Already dismissed this message?
201 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
202 return
203 }
204
205 const classes: { [id in BroadcastMessageLevel]: string } = {
206 info: 'alert-info',
207 warning: 'alert-warning',
208 error: 'alert-danger'
209 }
210
211 this.broadcastMessage = {
212 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
213 dismissable: messageConfig.dismissable,
214 class: classes[messageConfig.level]
215 }
216
217 this.screenService.isBroadcastMessageDisplayed = true
218 }
219 })
220 }
221
222 private injectJS () {
223 // Inject JS
224 this.serverService.getConfig()
225 .subscribe(config => {
226 if (config.instance.customizations.javascript) {
227 try {
228 // tslint:disable:no-eval
229 eval(config.instance.customizations.javascript)
230 } catch (err) {
231 console.error('Cannot eval custom JavaScript.', err)
232 }
233 }
234 })
235 }
236
237 private injectCSS () {
238 // Inject CSS if modified (admin config settings)
239 concat(
240 this.serverService.getConfig().pipe(first()),
241 this.serverService.configReloaded
242 ).subscribe(config => {
243 const headStyle = document.querySelector('style.custom-css-style')
244 if (headStyle) headStyle.parentNode.removeChild(headStyle)
245
246 // We test customCSS if the admin removed the css
247 if (this.customCSS || config.instance.customizations.css) {
248 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
249 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
250 }
251 })
252 }
253
254 private async loadPlugins () {
255 this.pluginService.initializePlugins()
256
257 this.hooks.runAction('action:application.init', 'common')
258 }
259
260 private async openModalsIfNeeded () {
261 this.authService.userInformationLoaded
262 .pipe(
263 map(() => this.authService.getUser()),
264 filter(user => user.role === UserRole.ADMINISTRATOR)
265 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
266 }
267
268 private async _openAdminModalsIfNeeded (user: User) {
269 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
270
271 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
272
273 this.instanceService.getAbout()
274 .subscribe(about => {
275 if (
276 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
277 !about.instance.terms ||
278 !about.instance.administrator ||
279 !about.instance.maintenanceLifetime
280 ) {
281 this.instanceConfigWarningModal.show(about)
282 }
283 })
284 }
285
286 private initHotkeys () {
287 this.hotkeysService.add([
288 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
289 document.getElementById('search-video').focus()
290 return false
291 }, undefined, this.i18n('Focus the search bar')),
292
293 new Hotkey('b', (event: KeyboardEvent): boolean => {
294 this.menu.toggleMenu()
295 return false
296 }, undefined, this.i18n('Toggle the left menu')),
297
298 new Hotkey('g o', (event: KeyboardEvent): boolean => {
299 this.router.navigate([ '/videos/overview' ])
300 return false
301 }, undefined, this.i18n('Go to the discover videos page')),
302
303 new Hotkey('g t', (event: KeyboardEvent): boolean => {
304 this.router.navigate([ '/videos/trending' ])
305 return false
306 }, undefined, this.i18n('Go to the trending videos page')),
307
308 new Hotkey('g r', (event: KeyboardEvent): boolean => {
309 this.router.navigate([ '/videos/recently-added' ])
310 return false
311 }, undefined, this.i18n('Go to the recently added videos page')),
312
313 new Hotkey('g l', (event: KeyboardEvent): boolean => {
314 this.router.navigate([ '/videos/local' ])
315 return false
316 }, undefined, this.i18n('Go to the local videos page')),
317
318 new Hotkey('g u', (event: KeyboardEvent): boolean => {
319 this.router.navigate([ '/videos/upload' ])
320 return false
321 }, undefined, this.i18n('Go to the videos upload page'))
322 ])
323 }
324}