]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
WIP plugins: working hook on server side
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Component, OnInit } 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, skip } 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 { ViewportScroller } from '@angular/common'
12 import { PluginService } from '@app/core/plugins/plugin.service'
13
14 @Component({
15 selector: 'my-app',
16 templateUrl: './app.component.html',
17 styleUrls: [ './app.component.scss' ]
18 })
19 export class AppComponent implements OnInit {
20 isMenuDisplayed = true
21 isMenuChangedByUser = false
22
23 customCSS: SafeHtml
24
25 constructor (
26 private i18n: I18n,
27 private viewportScroller: ViewportScroller,
28 private router: Router,
29 private authService: AuthService,
30 private serverService: ServerService,
31 private pluginService: PluginService,
32 private domSanitizer: DomSanitizer,
33 private redirectService: RedirectService,
34 private screenService: ScreenService,
35 private hotkeysService: HotkeysService,
36 private themeService: ThemeService
37 ) { }
38
39 get serverVersion () {
40 return this.serverService.getConfig().serverVersion
41 }
42
43 get serverCommit () {
44 const commit = this.serverService.getConfig().serverCommit || ''
45 return (commit !== '') ? '...' + commit : commit
46 }
47
48 get instanceName () {
49 return this.serverService.getConfig().instance.name
50 }
51
52 get defaultRoute () {
53 return RedirectService.DEFAULT_ROUTE
54 }
55
56 ngOnInit () {
57 document.getElementById('incompatible-browser').className += ' browser-ok'
58
59 this.authService.loadClientCredentials()
60
61 if (this.isUserLoggedIn()) {
62 // The service will automatically redirect to the login page if the token is not valid anymore
63 this.authService.refreshUserInformation()
64 }
65
66 // Load custom data from server
67 this.serverService.loadConfig()
68 this.serverService.loadVideoCategories()
69 this.serverService.loadVideoLanguages()
70 this.serverService.loadVideoLicences()
71 this.serverService.loadVideoPrivacies()
72 this.serverService.loadVideoPlaylistPrivacies()
73
74 this.loadPlugins()
75
76 // Do not display menu on small screens
77 if (this.screenService.isInSmallView()) {
78 this.isMenuDisplayed = false
79 }
80
81 this.initRouteEvents()
82 this.injectJS()
83 this.injectCSS()
84
85 this.initHotkeys()
86
87 fromEvent(window, 'resize')
88 .pipe(debounceTime(200))
89 .subscribe(() => this.onResize())
90 }
91
92 isUserLoggedIn () {
93 return this.authService.isLoggedIn()
94 }
95
96 toggleMenu () {
97 this.isMenuDisplayed = !this.isMenuDisplayed
98 this.isMenuChangedByUser = true
99 }
100
101 onResize () {
102 this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
103 }
104
105 private initRouteEvents () {
106 let resetScroll = true
107 const eventsObs = this.router.events
108
109 const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
110 const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
111
112 scrollEvent.subscribe(e => {
113 if (e.position) {
114 return this.viewportScroller.scrollToPosition(e.position)
115 }
116
117 if (e.anchor) {
118 return this.viewportScroller.scrollToAnchor(e.anchor)
119 }
120
121 if (resetScroll) {
122 return this.viewportScroller.scrollToPosition([ 0, 0 ])
123 }
124 })
125
126 // When we add the a-state parameter, we don't want to alter the scroll
127 navigationEndEvent.pipe(pairwise())
128 .subscribe(([ e1, e2 ]) => {
129 try {
130 resetScroll = false
131
132 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
133 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
134
135 if (previousUrl.pathname !== nextUrl.pathname) {
136 resetScroll = true
137 return
138 }
139
140 const nextSearchParams = nextUrl.searchParams
141 nextSearchParams.delete('a-state')
142
143 const previousSearchParams = previousUrl.searchParams
144
145 nextSearchParams.sort()
146 previousSearchParams.sort()
147
148 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
149 resetScroll = true
150 }
151 } catch (e) {
152 console.error('Cannot parse URL to check next scroll.', e)
153 resetScroll = true
154 }
155 })
156
157 navigationEndEvent.pipe(
158 map(() => window.location.pathname),
159 filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
160 ).subscribe(() => this.redirectService.redirectToHomepage(true))
161
162 eventsObs.pipe(
163 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
164 filter(() => this.screenService.isInSmallView())
165 ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
166 }
167
168 private injectJS () {
169 // Inject JS
170 this.serverService.configLoaded
171 .subscribe(() => {
172 const config = this.serverService.getConfig()
173
174 if (config.instance.customizations.javascript) {
175 try {
176 // tslint:disable:no-eval
177 eval(config.instance.customizations.javascript)
178 } catch (err) {
179 console.error('Cannot eval custom JavaScript.', err)
180 }
181 }
182 })
183 }
184
185 private injectCSS () {
186 // Inject CSS if modified (admin config settings)
187 this.serverService.configLoaded
188 .pipe(skip(1)) // We only want to subscribe to reloads, because the CSS is already injected by the server
189 .subscribe(() => {
190 const headStyle = document.querySelector('style.custom-css-style')
191 if (headStyle) headStyle.parentNode.removeChild(headStyle)
192
193 const config = this.serverService.getConfig()
194
195 // We test customCSS if the admin removed the css
196 if (this.customCSS || config.instance.customizations.css) {
197 const styleTag = '<style>' + config.instance.customizations.css + '</style>'
198 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
199 }
200 })
201 }
202
203 private async loadPlugins () {
204 this.pluginService.initializePlugins()
205
206 await this.pluginService.loadPluginsByScope('common')
207
208 this.pluginService.runHook('action:application.loaded')
209 }
210
211 private initHotkeys () {
212 this.hotkeysService.add([
213 new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
214 document.getElementById('search-video').focus()
215 return false
216 }, undefined, this.i18n('Focus the search bar')),
217 new Hotkey('b', (event: KeyboardEvent): boolean => {
218 this.toggleMenu()
219 return false
220 }, undefined, this.i18n('Toggle the left menu')),
221 new Hotkey('g o', (event: KeyboardEvent): boolean => {
222 this.router.navigate([ '/videos/overview' ])
223 return false
224 }, undefined, this.i18n('Go to the videos overview page')),
225 new Hotkey('g t', (event: KeyboardEvent): boolean => {
226 this.router.navigate([ '/videos/trending' ])
227 return false
228 }, undefined, this.i18n('Go to the trending videos page')),
229 new Hotkey('g r', (event: KeyboardEvent): boolean => {
230 this.router.navigate([ '/videos/recently-added' ])
231 return false
232 }, undefined, this.i18n('Go to the recently added videos page')),
233 new Hotkey('g l', (event: KeyboardEvent): boolean => {
234 this.router.navigate([ '/videos/local' ])
235 return false
236 }, undefined, this.i18n('Go to the local videos page')),
237 new Hotkey('g u', (event: KeyboardEvent): boolean => {
238 this.router.navigate([ '/videos/upload' ])
239 return false
240 }, undefined, this.i18n('Go to the videos upload page')),
241 new Hotkey('shift+t', (event: KeyboardEvent): boolean => {
242 this.themeService.toggleDarkTheme()
243 return false
244 }, undefined, this.i18n('Toggle Dark theme'))
245 ])
246 }
247 }