Add peertube version in features table
[oweals/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, first, map, pairwise, skip, switchMap } 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 { UserRole } from '@shared/models'
19 import { User } from '@app/shared'
20 import { InstanceService } from '@app/shared/instance/instance.service'
21
22 @Component({
23   selector: 'my-app',
24   templateUrl: './app.component.html',
25   styleUrls: [ './app.component.scss' ]
26 })
27 export class AppComponent implements OnInit {
28   @ViewChild('welcomeModal', { static: false }) welcomeModal: WelcomeModalComponent
29   @ViewChild('instanceConfigWarningModal', { static: false }) instanceConfigWarningModal: InstanceConfigWarningModalComponent
30
31   isMenuDisplayed = true
32   isMenuChangedByUser = false
33
34   customCSS: SafeHtml
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   ) { }
53
54   get instanceName () {
55     return this.serverService.getConfig().instance.name
56   }
57
58   get defaultRoute () {
59     return RedirectService.DEFAULT_ROUTE
60   }
61
62   ngOnInit () {
63     document.getElementById('incompatible-browser').className += ' browser-ok'
64
65     this.loadPlugins()
66     this.themeService.initialize()
67
68     this.authService.loadClientCredentials()
69
70     if (this.isUserLoggedIn()) {
71       // The service will automatically redirect to the login page if the token is not valid anymore
72       this.authService.refreshUserInformation()
73     }
74
75     // Load custom data from server
76     this.serverService.loadConfig()
77     this.serverService.loadVideoCategories()
78     this.serverService.loadVideoLanguages()
79     this.serverService.loadVideoLicences()
80     this.serverService.loadVideoPrivacies()
81     this.serverService.loadVideoPlaylistPrivacies()
82
83     // Do not display menu on small screens
84     if (this.screenService.isInSmallView()) {
85       this.isMenuDisplayed = false
86     }
87
88     this.initRouteEvents()
89     this.injectJS()
90     this.injectCSS()
91
92     this.initHotkeys()
93
94     fromEvent(window, 'resize')
95       .pipe(debounceTime(200))
96       .subscribe(() => this.onResize())
97
98     this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
99
100     this.openModalsIfNeeded()
101   }
102
103   isUserLoggedIn () {
104     return this.authService.isLoggedIn()
105   }
106
107   toggleMenu () {
108     this.isMenuDisplayed = !this.isMenuDisplayed
109     this.isMenuChangedByUser = true
110   }
111
112   onResize () {
113     this.isMenuDisplayed = window.innerWidth >= 800 && !this.isMenuChangedByUser
114   }
115
116   getServerVersionAndCommit () {
117     return this.serverService.getServerVersionAndCommit()
118   }
119
120   private initRouteEvents () {
121     let resetScroll = true
122     const eventsObs = this.router.events
123
124     const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
125
126     scrollEvent.subscribe(e => {
127       if (e.position) {
128         return this.viewportScroller.scrollToPosition(e.position)
129       }
130
131       if (e.anchor) {
132         return this.viewportScroller.scrollToAnchor(e.anchor)
133       }
134
135       if (resetScroll) {
136         return this.viewportScroller.scrollToPosition([ 0, 0 ])
137       }
138     })
139
140     const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd))
141
142     // When we add the a-state parameter, we don't want to alter the scroll
143     navigationEndEvent.pipe(pairwise())
144                       .subscribe(([ e1, e2 ]) => {
145                         try {
146                           resetScroll = false
147
148                           const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
149                           const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
150
151                           if (previousUrl.pathname !== nextUrl.pathname) {
152                             resetScroll = true
153                             return
154                           }
155
156                           const nextSearchParams = nextUrl.searchParams
157                           nextSearchParams.delete('a-state')
158
159                           const previousSearchParams = previousUrl.searchParams
160
161                           nextSearchParams.sort()
162                           previousSearchParams.sort()
163
164                           if (nextSearchParams.toString() !== previousSearchParams.toString()) {
165                             resetScroll = true
166                           }
167                         } catch (e) {
168                           console.error('Cannot parse URL to check next scroll.', e)
169                           resetScroll = true
170                         }
171                       })
172
173     navigationEndEvent.pipe(
174       map(() => window.location.pathname),
175       filter(pathname => !pathname || pathname === '/' || is18nPath(pathname))
176     ).subscribe(() => this.redirectService.redirectToHomepage(true))
177
178     navigationEndEvent.subscribe(e => {
179       this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
180     })
181
182     eventsObs.pipe(
183       filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
184       filter(() => this.screenService.isInSmallView())
185     ).subscribe(() => this.isMenuDisplayed = false) // User clicked on a link in the menu, change the page
186   }
187
188   private injectJS () {
189     // Inject JS
190     this.serverService.configLoaded
191         .subscribe(() => {
192           const config = this.serverService.getConfig()
193
194           if (config.instance.customizations.javascript) {
195             try {
196               // tslint:disable:no-eval
197               eval(config.instance.customizations.javascript)
198             } catch (err) {
199               console.error('Cannot eval custom JavaScript.', err)
200             }
201           }
202         })
203   }
204
205   private injectCSS () {
206     // Inject CSS if modified (admin config settings)
207     this.serverService.configLoaded
208         .pipe(skip(1)) // We only want to subscribe to reloads, because the CSS is already injected by the server
209         .subscribe(() => {
210           const headStyle = document.querySelector('style.custom-css-style')
211           if (headStyle) headStyle.parentNode.removeChild(headStyle)
212
213           const config = this.serverService.getConfig()
214
215           // We test customCSS if the admin removed the css
216           if (this.customCSS || config.instance.customizations.css) {
217             const styleTag = '<style>' + config.instance.customizations.css + '</style>'
218             this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
219           }
220         })
221   }
222
223   private async loadPlugins () {
224     this.pluginService.initializePlugins()
225
226     this.hooks.runAction('action:application.init', 'common')
227   }
228
229   private async openModalsIfNeeded () {
230     this.serverService.configLoaded
231         .pipe(
232           first(),
233           switchMap(() => this.authService.userInformationLoaded),
234           map(() => this.authService.getUser()),
235           filter(user => user.role === UserRole.ADMINISTRATOR)
236         ).subscribe(user => setTimeout(() => this.openAdminModals(user))) // setTimeout because of ngIf in template
237   }
238
239   private async openAdminModals (user: User) {
240     if (user.noWelcomeModal !== true) return this.welcomeModal.show()
241
242     const config = this.serverService.getConfig()
243     if (user.noInstanceConfigWarningModal === true || !config.signup.allowed) return
244
245     this.instanceService.getAbout()
246       .subscribe(about => {
247         if (
248           config.instance.name.toLowerCase() === 'peertube' ||
249           !about.instance.terms ||
250           !about.instance.administrator ||
251           !about.instance.maintenanceLifetime
252         ) {
253           this.instanceConfigWarningModal.show(about)
254         }
255       })
256   }
257
258   private initHotkeys () {
259     this.hotkeysService.add([
260       new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => {
261         document.getElementById('search-video').focus()
262         return false
263       }, undefined, this.i18n('Focus the search bar')),
264
265       new Hotkey('b', (event: KeyboardEvent): boolean => {
266         this.toggleMenu()
267         return false
268       }, undefined, this.i18n('Toggle the left menu')),
269
270       new Hotkey('g o', (event: KeyboardEvent): boolean => {
271         this.router.navigate([ '/videos/overview' ])
272         return false
273       }, undefined, this.i18n('Go to the discover videos page')),
274
275       new Hotkey('g t', (event: KeyboardEvent): boolean => {
276         this.router.navigate([ '/videos/trending' ])
277         return false
278       }, undefined, this.i18n('Go to the trending videos page')),
279
280       new Hotkey('g r', (event: KeyboardEvent): boolean => {
281         this.router.navigate([ '/videos/recently-added' ])
282         return false
283       }, undefined, this.i18n('Go to the recently added videos page')),
284
285       new Hotkey('g l', (event: KeyboardEvent): boolean => {
286         this.router.navigate([ '/videos/local' ])
287         return false
288       }, undefined, this.i18n('Go to the local videos page')),
289
290       new Hotkey('g u', (event: KeyboardEvent): boolean => {
291         this.router.navigate([ '/videos/upload' ])
292         return false
293       }, undefined, this.i18n('Go to the videos upload page'))
294     ])
295   }
296 }