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