]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/app.component.ts
Add video filters to common video pages
[github/Chocobozzz/PeerTube.git] / client / src / app / app.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { filter, map, switchMap } from 'rxjs/operators'
3 import { DOCUMENT, getLocaleDirection, PlatformLocation } from '@angular/common'
4 import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core'
5 import { DomSanitizer, SafeHtml } from '@angular/platform-browser'
6 import { Event, GuardsCheckStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router'
7 import {
8 AuthService,
9 MarkdownService,
10 PeerTubeRouterService,
11 RedirectService,
12 ScreenService,
13 ScrollService,
14 ServerService,
15 ThemeService,
16 User
17 } from '@app/core'
18 import { HooksService } from '@app/core/plugins/hooks.service'
19 import { PluginService } from '@app/core/plugins/plugin.service'
20 import { CustomModalComponent } from '@app/modal/custom-modal.component'
21 import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component'
22 import { WelcomeModalComponent } from '@app/modal/welcome-modal.component'
23 import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'
24 import { LoadingBarService } from '@ngx-loading-bar/core'
25 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
26 import { getShortLocale } from '@shared/core-utils/i18n'
27 import { BroadcastMessageLevel, HTMLServerConfig, ServerConfig, UserRole } from '@shared/models'
28 import { MenuService } from './core/menu/menu.service'
29 import { POP_STATE_MODAL_DISMISS } from './helpers'
30 import { InstanceService } from './shared/shared-instance'
31
32 @Component({
33 selector: 'my-app',
34 templateUrl: './app.component.html',
35 styleUrls: [ './app.component.scss' ]
36 })
37 export class AppComponent implements OnInit, AfterViewInit {
38 private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed'
39
40 @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent
41 @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent
42 @ViewChild('customModal') customModal: CustomModalComponent
43
44 customCSS: SafeHtml
45 broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null
46
47 private serverConfig: HTMLServerConfig
48
49 constructor (
50 @Inject(DOCUMENT) private document: Document,
51 @Inject(LOCALE_ID) private localeId: string,
52 private router: Router,
53 private authService: AuthService,
54 private serverService: ServerService,
55 private peertubeRouter: PeerTubeRouterService,
56 private pluginService: PluginService,
57 private instanceService: InstanceService,
58 private domSanitizer: DomSanitizer,
59 private redirectService: RedirectService,
60 private screenService: ScreenService,
61 private hotkeysService: HotkeysService,
62 private themeService: ThemeService,
63 private hooks: HooksService,
64 private location: PlatformLocation,
65 private modalService: NgbModal,
66 private markdownService: MarkdownService,
67 private ngbConfig: NgbConfig,
68 private loadingBar: LoadingBarService,
69 private scrollService: ScrollService,
70 public menu: MenuService
71 ) {
72 this.ngbConfig.animation = false
73 }
74
75 get instanceName () {
76 return this.serverConfig.instance.name
77 }
78
79 goToDefaultRoute () {
80 return this.router.navigateByUrl(this.redirectService.getDefaultRoute())
81 }
82
83 ngOnInit () {
84 document.getElementById('incompatible-browser').className += ' browser-ok'
85
86 this.serverConfig = this.serverService.getHTMLConfig()
87
88 this.hooks.runAction('action:application.init', 'common')
89 this.themeService.initialize()
90
91 this.authService.loadClientCredentials()
92
93 if (this.isUserLoggedIn()) {
94 // The service will automatically redirect to the login page if the token is not valid anymore
95 this.authService.refreshUserInformation()
96 }
97
98 this.initRouteEvents()
99 this.scrollService.enableScrollRestoration()
100
101 this.injectJS()
102 this.injectCSS()
103 this.injectBroadcastMessage()
104
105 this.serverService.configReloaded
106 .subscribe(config => {
107 this.serverConfig = config
108
109 this.injectBroadcastMessage()
110 this.injectCSS()
111
112 // Don't reinject JS since it could conflict with existing one
113 })
114
115 this.initHotkeys()
116
117 this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS))
118
119 this.openModalsIfNeeded()
120
121 this.document.documentElement.lang = getShortLocale(this.localeId)
122 this.document.documentElement.dir = getLocaleDirection(this.localeId)
123 }
124
125 ngAfterViewInit () {
126 this.pluginService.initializeCustomModal(this.customModal)
127 }
128
129 getToggleTitle () {
130 if (this.menu.isDisplayed()) return $localize`Close the left menu`
131
132 return $localize`Open the left menu`
133 }
134
135 isUserLoggedIn () {
136 return this.authService.isLoggedIn()
137 }
138
139 hideBroadcastMessage () {
140 peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message)
141
142 this.broadcastMessage = null
143 this.screenService.isBroadcastMessageDisplayed = false
144 }
145
146 private initRouteEvents () {
147 const eventsObs = this.router.events
148
149 // Plugin hooks
150 this.peertubeRouter.getNavigationEndEvents().subscribe(e => {
151 this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url })
152 })
153
154 // Automatically hide/display the menu
155 eventsObs.pipe(
156 filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart),
157 filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen())
158 ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page
159
160 // Handle lazy loaded module
161 eventsObs.pipe(
162 filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart)
163 ).subscribe(() => this.loadingBar.useRef().start())
164
165 eventsObs.pipe(
166 filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd)
167 ).subscribe(() => this.loadingBar.useRef().complete())
168 }
169
170 private async injectBroadcastMessage () {
171 this.broadcastMessage = null
172 this.screenService.isBroadcastMessageDisplayed = false
173
174 const messageConfig = this.serverConfig.broadcastMessage
175
176 if (messageConfig.enabled) {
177 // Already dismissed this message?
178 if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) {
179 return
180 }
181
182 const classes: { [id in BroadcastMessageLevel]: string } = {
183 info: 'alert-info',
184 warning: 'alert-warning',
185 error: 'alert-danger'
186 }
187
188 this.broadcastMessage = {
189 message: await this.markdownService.unsafeMarkdownToHTML(messageConfig.message, true),
190 dismissable: messageConfig.dismissable,
191 class: classes[messageConfig.level]
192 }
193
194 this.screenService.isBroadcastMessageDisplayed = true
195 }
196 }
197
198 private injectJS () {
199 // Inject JS
200 if (this.serverConfig.instance.customizations.javascript) {
201 try {
202 /* eslint-disable no-eval */
203 eval(this.serverConfig.instance.customizations.javascript)
204 } catch (err) {
205 console.error('Cannot eval custom JavaScript.', err)
206 }
207 }
208 }
209
210 private injectCSS () {
211 const headStyle = document.querySelector('style.custom-css-style')
212 if (headStyle) headStyle.parentNode.removeChild(headStyle)
213
214 // We test customCSS if the admin removed the css
215 if (this.customCSS || this.serverConfig.instance.customizations.css) {
216 const styleTag = '<style>' + this.serverConfig.instance.customizations.css + '</style>'
217 this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag)
218 }
219 }
220
221 private async openModalsIfNeeded () {
222 this.authService.userInformationLoaded
223 .pipe(
224 map(() => this.authService.getUser()),
225 filter(user => user.role === UserRole.ADMINISTRATOR),
226 switchMap(user => {
227 return this.serverService.getConfig()
228 .pipe(map(serverConfig => ({ serverConfig, user })))
229 })
230 ).subscribe(({ serverConfig, user }) => this._openAdminModalsIfNeeded(serverConfig, user))
231 }
232
233 private async _openAdminModalsIfNeeded (serverConfig: ServerConfig, user: User) {
234 if (user.noWelcomeModal !== true) return this.welcomeModal.show()
235
236 if (user.noInstanceConfigWarningModal === true || !serverConfig.signup.allowed) return
237
238 this.instanceService.getAbout()
239 .subscribe(about => {
240 if (
241 this.serverConfig.instance.name.toLowerCase() === 'peertube' ||
242 !about.instance.terms ||
243 !about.instance.administrator ||
244 !about.instance.maintenanceLifetime
245 ) {
246 this.instanceConfigWarningModal.show(about)
247 }
248 })
249 }
250
251 private initHotkeys () {
252 this.hotkeysService.add([
253 new Hotkey([ '/', 's' ], (event: KeyboardEvent): boolean => {
254 document.getElementById('search-video').focus()
255 return false
256 }, undefined, $localize`Focus the search bar`),
257
258 new Hotkey('b', (event: KeyboardEvent): boolean => {
259 this.menu.toggleMenu()
260 return false
261 }, undefined, $localize`Toggle the left menu`),
262
263 new Hotkey('g o', (event: KeyboardEvent): boolean => {
264 this.router.navigate([ '/videos/overview' ])
265 return false
266 }, undefined, $localize`Go to the discover videos page`),
267
268 new Hotkey('g t', (event: KeyboardEvent): boolean => {
269 this.router.navigate([ '/videos/trending' ])
270 return false
271 }, undefined, $localize`Go to the trending videos page`),
272
273 new Hotkey('g r', (event: KeyboardEvent): boolean => {
274 this.router.navigate([ '/videos/recently-added' ])
275 return false
276 }, undefined, $localize`Go to the recently added videos page`),
277
278 new Hotkey('g l', (event: KeyboardEvent): boolean => {
279 this.router.navigate([ '/videos/local' ])
280 return false
281 }, undefined, $localize`Go to the local videos page`),
282
283 new Hotkey('g u', (event: KeyboardEvent): boolean => {
284 this.router.navigate([ '/videos/upload' ])
285 return false
286 }, undefined, $localize`Go to the videos upload page`)
287 ])
288 }
289 }