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