]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
Fix anonymous nsfw policy
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
CommitLineData
81fe3c67 1import { Component, OnInit, ViewChild, AfterViewInit, Inject, LOCALE_ID } from '@angular/core'
00b5556c 2import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
489290b8 3import { Event, GuardsCheckStart, NavigationEnd, Router, Scroll } from '@angular/router'
1a00c561 4import { AuthService, RedirectService, ServerService, ThemeService } from '@app/core'
140ea386 5import { is18nPath, getShortLocale } from '../../../shared/models/i18n'
bbe0f064 6import { ScreenService } from '@app/shared/misc/screen.service'
72c33e71 7import { filter, map, pairwise, first } from 'rxjs/operators'
489290b8 8import { Hotkey, HotkeysService } from 'angular2-hotkeys'
e33f888b 9import { I18n } from '@ngx-translate/i18n-polyfill'
140ea386 10import { PlatformLocation, ViewportScroller, DOCUMENT } from '@angular/common'
18a6f04c 11import { PluginService } from '@app/core/plugins/plugin.service'
93cae479 12import { HooksService } from '@app/core/plugins/hooks.service'
4334445d 13import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
60c2bc80 14import { POP_STATE_MODAL_DISMISS } from '@app/shared/misc/constants'
43d0ea7f
C
15import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
16import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
437e8e06 17import { CustomModalComponent } from '@app/modal/custom-modal.component'
ba430d75 18import { ServerConfig, UserRole } from '@shared/models'
43d0ea7f
C
19import { User } from '@app/shared'
20import { InstanceService } from '@app/shared/instance/instance.service'
3b20bdd6 21import { MenuService } from './core/menu/menu.service'
72c33e71
C
22import { BroadcastMessageLevel } from '@shared/models/server'
23import { MarkdownService } from './shared/renderer'
24import { concat } from 'rxjs'
25import { peertubeLocalStorage } from './shared/misc/peertube-web-storage'
e2a2d6c8 26
dc8bc31b 27@Component({
3154f382
C
28 selector: 'my-app',
29 templateUrl: './app.component.html',
30 styleUrls: [ './app.component.scss' ]
dc8bc31b 31})
437e8e06 32export class AppComponent implements OnInit, AfterViewInit {
72c33e71
C
33 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
34
2f5d2ec5
C
35 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
36 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
437e8e06 37 @ViewChild('customModal') customModal: CustomModalComponent
43d0ea7f 38
00b5556c 39 customCSS: SafeHtml
72c33e71 40 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
00b5556c 41
ba430d75
C
42 private serverConfig: ServerConfig
43
df98563e 44 constructor (
140ea386 45 @Inject(DOCUMENT) private document: Document,
81fe3c67 46 @Inject(LOCALE_ID) private localeId: string,
e33f888b 47 private i18n: I18n,
489290b8 48 private viewportScroller: ViewportScroller,
3154f382 49 private router: Router,
e2a2d6c8 50 private authService: AuthService,
00b5556c 51 private serverService: ServerService,
18a6f04c 52 private pluginService: PluginService,
43d0ea7f 53 private instanceService: InstanceService,
901637bb 54 private domSanitizer: DomSanitizer,
bbe0f064 55 private redirectService: RedirectService,
ee1fc23a 56 private screenService: ScreenService,
1a00c561 57 private hotkeysService: HotkeysService,
93cae479 58 private themeService: ThemeService,
4334445d
C
59 private hooks: HooksService,
60 private location: PlatformLocation,
3b20bdd6 61 private modalService: NgbModal,
72c33e71 62 private markdownService: MarkdownService,
3b20bdd6 63 public menu: MenuService
989e526a 64 ) { }
a99593ed 65
36f9424f 66 get instanceName () {
ba430d75 67 return this.serverConfig.instance.name
36f9424f
C
68 }
69
29f9b562
C
70 get defaultRoute () {
71 return RedirectService.DEFAULT_ROUTE
72 }
73
df98563e 74 ngOnInit () {
b3eeb529 75 document.getElementById('incompatible-browser').className += ' browser-ok'
73e09f27 76
ba430d75
C
77 this.serverConfig = this.serverService.getTmpConfig()
78 this.serverService.getConfig()
79 .subscribe(config => this.serverConfig = config)
80
a2ffd046
C
81 this.loadPlugins()
82 this.themeService.initialize()
83
d592e0a9
C
84 this.authService.loadClientCredentials()
85
d414207f 86 if (this.isUserLoggedIn()) {
e2a2d6c8 87 // The service will automatically redirect to the login page if the token is not valid anymore
bcd9f81e 88 this.authService.refreshUserInformation()
e2a2d6c8 89 }
6e07c3de 90
489290b8
C
91 this.initRouteEvents()
92 this.injectJS()
93 this.injectCSS()
72c33e71 94 this.injectBroadcastMessage()
489290b8
C
95
96 this.initHotkeys()
97
60c2bc80 98 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
43d0ea7f
C
99
100 this.openModalsIfNeeded()
81fe3c67
RK
101
102 this.document.documentElement.lang = getShortLocale(this.localeId)
489290b8
C
103 }
104
437e8e06
K
105 ngAfterViewInit () {
106 this.pluginService.initializeCustomModal(this.customModal)
107 }
108
489290b8
C
109 isUserLoggedIn () {
110 return this.authService.isLoggedIn()
111 }
112
72c33e71
C
113 hideBroadcastMessage () {
114 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
115
116 this.broadcastMessage = null
117 }
118
489290b8
C
119 private initRouteEvents () {
120 let resetScroll = true
121 const eventsObs = this.router.events
122
123 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
489290b8
C
124
125 scrollEvent.subscribe(e => {
126 if (e.position) {
127 return this.viewportScroller.scrollToPosition(e.position)
c8cf5952 128 }
00b5556c 129
489290b8
C
130 if (e.anchor) {
131 return this.viewportScroller.scrollToAnchor(e.anchor)
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
193
194 const messageConfig = config.broadcastMessage
195
196 if (messageConfig.enabled) {
197 // Already dismissed this message?
198 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
199 return
200 }
201
202 const classes: { [id in BroadcastMessageLevel]: string } = {
203 info: 'alert-info',
204 warning: 'alert-warning',
205 error: 'alert-danger'
206 }
207
208 this.broadcastMessage = {
209 message: await this.markdownService.completeMarkdownToHTML(messageConfig.message),
210 dismissable: messageConfig.dismissable,
211 class: classes[messageConfig.level]
212 }
213 }
214 })
215 }
216
489290b8 217 private injectJS () {
e032aec9 218 // Inject JS
ba430d75
C
219 this.serverService.getConfig()
220 .subscribe(config => {
e032aec9
C
221 if (config.instance.customizations.javascript) {
222 try {
223 // tslint:disable:no-eval
224 eval(config.instance.customizations.javascript)
225 } catch (err) {
226 console.error('Cannot eval custom JavaScript.', err)
227 }
228 }
229 })
489290b8 230 }
00b5556c 231
489290b8 232 private injectCSS () {
e032aec9 233 // Inject CSS if modified (admin config settings)
72c33e71
C
234 concat(
235 this.serverService.getConfig().pipe(first()),
236 this.serverService.configReloaded
237 ).subscribe(config => {
238 const headStyle = document.querySelector('style.custom-css-style')
239 if (headStyle) headStyle.parentNode.removeChild(headStyle)
240
241 // We test customCSS if the admin removed the css
242 if (this.customCSS || config.instance.customizations.css) {
243 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
244 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
245 }
246 })
489290b8 247 }
ee1fc23a 248
18a6f04c
C
249 private async loadPlugins () {
250 this.pluginService.initializePlugins()
251
c9e3eeed 252 this.hooks.runAction('action:application.init', 'common')
18a6f04c
C
253 }
254
43d0ea7f 255 private async openModalsIfNeeded () {
ba430d75 256 this.authService.userInformationLoaded
43d0ea7f 257 .pipe(
43d0ea7f
C
258 map(() => this.authService.getUser()),
259 filter(user => user.role === UserRole.ADMINISTRATOR)
ba430d75 260 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
43d0ea7f
C
261 }
262
ba430d75 263 private async _openAdminModalsIfNeeded (user: User) {
43d0ea7f
C
264 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
265
ba430d75 266 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
589d9f55
C
267
268 this.instanceService.getAbout()
269 .subscribe(about => {
270 if (
ba430d75 271 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
589d9f55
C
272 !about.instance.terms ||
273 !about.instance.administrator ||
274 !about.instance.maintenanceLifetime
275 ) {
276 this.instanceConfigWarningModal.show(about)
277 }
278 })
43d0ea7f
C
279 }
280
489290b8 281 private initHotkeys () {
ee1fc23a 282 this.hotkeysService.add([
8542dc33 283 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
ee1fc23a 284 document.getElementById('search-video').focus()
8542dc33 285 return false
e33f888b 286 }, undefined, this.i18n('Focus the search bar')),
43d0ea7f 287
8542dc33 288 new Hotkey('b', (event: KeyboardEvent): boolean => {
3b20bdd6 289 this.menu.toggleMenu()
8542dc33 290 return false
e33f888b 291 }, undefined, this.i18n('Toggle the left menu')),
43d0ea7f 292
20d21199 293 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
294 this.router.navigate([ '/videos/overview' ])
295 return false
79a89941 296 }, undefined, this.i18n('Go to the discover videos page')),
43d0ea7f 297
20d21199 298 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
299 this.router.navigate([ '/videos/trending' ])
300 return false
e33f888b 301 }, undefined, this.i18n('Go to the trending videos page')),
43d0ea7f 302
20d21199 303 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
304 this.router.navigate([ '/videos/recently-added' ])
305 return false
e33f888b 306 }, undefined, this.i18n('Go to the recently added videos page')),
43d0ea7f 307
20d21199 308 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
309 this.router.navigate([ '/videos/local' ])
310 return false
e33f888b 311 }, undefined, this.i18n('Go to the local videos page')),
43d0ea7f 312
20d21199 313 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
314 this.router.navigate([ '/videos/upload' ])
315 return false
ffb321be 316 }, undefined, this.i18n('Go to the videos upload page'))
ee1fc23a 317 ])
67167390 318 }
dc8bc31b 319}