]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/app.component.ts
Lazy load static objects
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
CommitLineData
43d0ea7f 1import { Component, OnInit, ViewChild } 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'
989e526a 5import { is18nPath } from '../../../shared/models/i18n'
bbe0f064 6import { ScreenService } from '@app/shared/misc/screen.service'
41413133 7import { debounceTime, filter, first, map, pairwise, skip, switchMap } from 'rxjs/operators'
489290b8 8import { Hotkey, HotkeysService } from 'angular2-hotkeys'
e33f888b 9import { I18n } from '@ngx-translate/i18n-polyfill'
a5858241 10import { fromEvent } from 'rxjs'
4334445d 11import { PlatformLocation, ViewportScroller } from '@angular/common'
18a6f04c 12import { PluginService } from '@app/core/plugins/plugin.service'
93cae479 13import { HooksService } from '@app/core/plugins/hooks.service'
4334445d 14import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
60c2bc80 15import { POP_STATE_MODAL_DISMISS } from '@app/shared/misc/constants'
43d0ea7f
C
16import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
17import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
ba430d75 18import { ServerConfig, UserRole } from '@shared/models'
43d0ea7f
C
19import { User } from '@app/shared'
20import { InstanceService } from '@app/shared/instance/instance.service'
e2a2d6c8 21
dc8bc31b 22@Component({
3154f382
C
23 selector: 'my-app',
24 templateUrl: './app.component.html',
25 styleUrls: [ './app.component.scss' ]
dc8bc31b 26})
e2a2d6c8 27export class AppComponent implements OnInit {
43d0ea7f
C
28 @ViewChild('welcomeModal', { static: false }) welcomeModal: WelcomeModalComponent
29 @ViewChild('instanceConfigWarningModal', { static: false }) instanceConfigWarningModal: InstanceConfigWarningModalComponent
30
df98563e 31 isMenuDisplayed = true
a5858241 32 isMenuChangedByUser = false
67167390 33
00b5556c
C
34 customCSS: SafeHtml
35
ba430d75
C
36 private serverConfig: ServerConfig
37
df98563e 38 constructor (
e33f888b 39 private i18n: I18n,
489290b8 40 private viewportScroller: ViewportScroller,
3154f382 41 private router: Router,
e2a2d6c8 42 private authService: AuthService,
00b5556c 43 private serverService: ServerService,
18a6f04c 44 private pluginService: PluginService,
43d0ea7f 45 private instanceService: InstanceService,
901637bb 46 private domSanitizer: DomSanitizer,
bbe0f064 47 private redirectService: RedirectService,
ee1fc23a 48 private screenService: ScreenService,
1a00c561 49 private hotkeysService: HotkeysService,
93cae479 50 private themeService: ThemeService,
4334445d
C
51 private hooks: HooksService,
52 private location: PlatformLocation,
53 private modalService: NgbModal
989e526a 54 ) { }
a99593ed 55
36f9424f 56 get instanceName () {
ba430d75 57 return this.serverConfig.instance.name
36f9424f
C
58 }
59
29f9b562
C
60 get defaultRoute () {
61 return RedirectService.DEFAULT_ROUTE
62 }
63
df98563e 64 ngOnInit () {
b3eeb529 65 document.getElementById('incompatible-browser').className += ' browser-ok'
73e09f27 66
ba430d75
C
67 this.serverConfig = this.serverService.getTmpConfig()
68 this.serverService.getConfig()
69 .subscribe(config => this.serverConfig = config)
70
a2ffd046
C
71 this.loadPlugins()
72 this.themeService.initialize()
73
d592e0a9
C
74 this.authService.loadClientCredentials()
75
d414207f 76 if (this.isUserLoggedIn()) {
e2a2d6c8 77 // The service will automatically redirect to the login page if the token is not valid anymore
bcd9f81e 78 this.authService.refreshUserInformation()
e2a2d6c8 79 }
6e07c3de 80
3eeeb87f 81 // Do not display menu on small screens
bbe0f064 82 if (this.screenService.isInSmallView()) {
df98563e 83 this.isMenuDisplayed = false
3eeeb87f 84 }
c8cf5952 85
489290b8
C
86 this.initRouteEvents()
87 this.injectJS()
88 this.injectCSS()
89
90 this.initHotkeys()
91
92 fromEvent(window, 'resize')
93 .pipe(debounceTime(200))
94 .subscribe(() => this.onResize())
4334445d 95
60c2bc80 96 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
43d0ea7f
C
97
98 this.openModalsIfNeeded()
489290b8
C
99 }
100
101 isUserLoggedIn () {
102 return this.authService.isLoggedIn()
103 }
104
105 toggleMenu () {
106 this.isMenuDisplayed = !this.isMenuDisplayed
107 this.isMenuChangedByUser = true
108 }
109
110 onResize () {
111 this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
112 }
113
dbdf2d51
C
114 getServerVersionAndCommit () {
115 return this.serverService.getServerVersionAndCommit()
116 }
117
489290b8
C
118 private initRouteEvents () {
119 let resetScroll = true
120 const eventsObs = this.router.events
121
122 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
489290b8
C
123
124 scrollEvent.subscribe(e => {
125 if (e.position) {
126 return this.viewportScroller.scrollToPosition(e.position)
c8cf5952 127 }
00b5556c 128
489290b8
C
129 if (e.anchor) {
130 return this.viewportScroller.scrollToAnchor(e.anchor)
131 }
132
133 if (resetScroll) {
134 return this.viewportScroller.scrollToPosition([ 0, 0 ])
135 }
136 })
137
60c2bc80
C
138 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
139
489290b8
C
140 // When we add the a-state parameter, we don't want to alter the scroll
141 navigationEndEvent.pipe(pairwise())
142 .subscribe(([ e1, e2 ]) => {
143 try {
144 resetScroll = false
145
722bca90
C
146 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
147 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
489290b8
C
148
149 if (previousUrl.pathname !== nextUrl.pathname) {
150 resetScroll = true
151 return
152 }
153
154 const nextSearchParams = nextUrl.searchParams
155 nextSearchParams.delete('a-state')
156
157 const previousSearchParams = previousUrl.searchParams
158
159 nextSearchParams.sort()
160 previousSearchParams.sort()
161
162 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
163 resetScroll = true
164 }
165 } catch (e) {
166 console.error('Cannot parse URL to check next scroll.', e)
167 resetScroll = true
168 }
169 })
170
171 navigationEndEvent.pipe(
172 map(() => window.location.pathname),
173 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
174 ).subscribe(() => this.redirectService.redirectToHomepage(true))
175
23bdacf8
C
176 navigationEndEvent.subscribe(e => {
177 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
178 })
179
489290b8
C
180 eventsObs.pipe(
181 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
182 filter(() => this.screenService.isInSmallView())
183 ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
184 }
185
186 private injectJS () {
e032aec9 187 // Inject JS
ba430d75
C
188 this.serverService.getConfig()
189 .subscribe(config => {
e032aec9
C
190 if (config.instance.customizations.javascript) {
191 try {
192 // tslint:disable:no-eval
193 eval(config.instance.customizations.javascript)
194 } catch (err) {
195 console.error('Cannot eval custom JavaScript.', err)
196 }
197 }
198 })
489290b8 199 }
00b5556c 200
489290b8 201 private injectCSS () {
e032aec9 202 // Inject CSS if modified (admin config settings)
ba430d75 203 this.serverService.configReloaded
e032aec9
C
204 .subscribe(() => {
205 const headStyle = document.querySelector('style.custom-css-style')
206 if (headStyle) headStyle.parentNode.removeChild(headStyle)
00b5556c 207
e032aec9 208 // We test customCSS if the admin removed the css
ba430d75
C
209 if (this.customCSS || this.serverConfig.instance.customizations.css) {
210 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
e032aec9 211 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
00b5556c 212 }
e032aec9 213 })
489290b8 214 }
ee1fc23a 215
18a6f04c
C
216 private async loadPlugins () {
217 this.pluginService.initializePlugins()
218
c9e3eeed 219 this.hooks.runAction('action:application.init', 'common')
18a6f04c
C
220 }
221
43d0ea7f 222 private async openModalsIfNeeded () {
ba430d75 223 this.authService.userInformationLoaded
43d0ea7f 224 .pipe(
43d0ea7f
C
225 map(() => this.authService.getUser()),
226 filter(user => user.role === UserRole.ADMINISTRATOR)
ba430d75 227 ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template
43d0ea7f
C
228 }
229
ba430d75 230 private async _openAdminModalsIfNeeded (user: User) {
43d0ea7f
C
231 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
232
ba430d75 233 if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return
589d9f55
C
234
235 this.instanceService.getAbout()
236 .subscribe(about => {
237 if (
ba430d75 238 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
589d9f55
C
239 !about.instance.terms ||
240 !about.instance.administrator ||
241 !about.instance.maintenanceLifetime
242 ) {
243 this.instanceConfigWarningModal.show(about)
244 }
245 })
43d0ea7f
C
246 }
247
489290b8 248 private initHotkeys () {
ee1fc23a 249 this.hotkeysService.add([
8542dc33 250 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
ee1fc23a 251 document.getElementById('search-video').focus()
8542dc33 252 return false
e33f888b 253 }, undefined, this.i18n('Focus the search bar')),
43d0ea7f 254
8542dc33
RK
255 new Hotkey('b', (event: KeyboardEvent): boolean => {
256 this.toggleMenu()
257 return false
e33f888b 258 }, undefined, this.i18n('Toggle the left menu')),
43d0ea7f 259
20d21199 260 new Hotkey('g o', (event: KeyboardEvent): boolean => {
a54991da
RK
261 this.router.navigate([ '/videos/overview' ])
262 return false
79a89941 263 }, undefined, this.i18n('Go to the discover videos page')),
43d0ea7f 264
20d21199 265 new Hotkey('g t', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
266 this.router.navigate([ '/videos/trending' ])
267 return false
e33f888b 268 }, undefined, this.i18n('Go to the trending videos page')),
43d0ea7f 269
20d21199 270 new Hotkey('g r', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
271 this.router.navigate([ '/videos/recently-added' ])
272 return false
e33f888b 273 }, undefined, this.i18n('Go to the recently added videos page')),
43d0ea7f 274
20d21199 275 new Hotkey('g l', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
276 this.router.navigate([ '/videos/local' ])
277 return false
e33f888b 278 }, undefined, this.i18n('Go to the local videos page')),
43d0ea7f 279
20d21199 280 new Hotkey('g u', (event: KeyboardEvent): boolean => {
ee1fc23a
RK
281 this.router.navigate([ '/videos/upload' ])
282 return false
ffb321be 283 }, undefined, this.i18n('Go to the videos upload page'))
ee1fc23a 284 ])
67167390 285 }
dc8bc31b 286}