]>
Commit | Line | Data |
---|---|---|
1 | import { Hotkey, HotkeysService } from 'angular2-hotkeys' | |
2 | import { concat } from 'rxjs' | |
3 | import { filter, first, map, pairwise } from 'rxjs/operators' | |
4 | import { DOCUMENT, PlatformLocation, ViewportScroller } from '@angular/common' | |
5 | import { AfterViewInit, Component, Inject, LOCALE_ID, OnInit, ViewChild } from '@angular/core' | |
6 | import { DomSanitizer, SafeHtml } from '@angular/platform-browser' | |
7 | import { Event, GuardsCheckStart, NavigationEnd, RouteConfigLoadEnd, RouteConfigLoadStart, Router, Scroll } from '@angular/router' | |
8 | import { AuthService, MarkdownService, RedirectService, ScreenService, ServerService, ThemeService, User } from '@app/core' | |
9 | import { HooksService } from '@app/core/plugins/hooks.service' | |
10 | import { PluginService } from '@app/core/plugins/plugin.service' | |
11 | import { CustomModalComponent } from '@app/modal/custom-modal.component' | |
12 | import { InstanceConfigWarningModalComponent } from '@app/modal/instance-config-warning-modal.component' | |
13 | import { WelcomeModalComponent } from '@app/modal/welcome-modal.component' | |
14 | import { NgbConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap' | |
15 | import { LoadingBarService } from '@ngx-loading-bar/core' | |
16 | import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage' | |
17 | import { getShortLocale, is18nPath } from '@shared/core-utils/i18n' | |
18 | import { BroadcastMessageLevel, ServerConfig, UserRole } from '@shared/models' | |
19 | import { MenuService } from './core/menu/menu.service' | |
20 | import { POP_STATE_MODAL_DISMISS } from './helpers' | |
21 | import { InstanceService } from './shared/shared-instance' | |
22 | ||
23 | @Component({ | |
24 | selector: 'my-app', | |
25 | templateUrl: './app.component.html', | |
26 | styleUrls: [ './app.component.scss' ] | |
27 | }) | |
28 | export class AppComponent implements OnInit, AfterViewInit { | |
29 | private static BROADCAST_MESSAGE_KEY = 'app-broadcast-message-dismissed' | |
30 | ||
31 | @ViewChild('welcomeModal') welcomeModal: WelcomeModalComponent | |
32 | @ViewChild('instanceConfigWarningModal') instanceConfigWarningModal: InstanceConfigWarningModalComponent | |
33 | @ViewChild('customModal') customModal: CustomModalComponent | |
34 | ||
35 | customCSS: SafeHtml | |
36 | broadcastMessage: { message: string, dismissable: boolean, class: string } | null = null | |
37 | ||
38 | private serverConfig: ServerConfig | |
39 | ||
40 | constructor ( | |
41 | @Inject(DOCUMENT) private document: Document, | |
42 | @Inject(LOCALE_ID) private localeId: string, | |
43 | private viewportScroller: ViewportScroller, | |
44 | private router: Router, | |
45 | private authService: AuthService, | |
46 | private serverService: ServerService, | |
47 | private pluginService: PluginService, | |
48 | private instanceService: InstanceService, | |
49 | private domSanitizer: DomSanitizer, | |
50 | private redirectService: RedirectService, | |
51 | private screenService: ScreenService, | |
52 | private hotkeysService: HotkeysService, | |
53 | private themeService: ThemeService, | |
54 | private hooks: HooksService, | |
55 | private location: PlatformLocation, | |
56 | private modalService: NgbModal, | |
57 | private markdownService: MarkdownService, | |
58 | private ngbConfig: NgbConfig, | |
59 | private loadingBar: LoadingBarService, | |
60 | public menu: MenuService | |
61 | ) { | |
62 | this.ngbConfig.animation = false | |
63 | } | |
64 | ||
65 | get instanceName () { | |
66 | return this.serverConfig.instance.name | |
67 | } | |
68 | ||
69 | goToDefaultRoute () { | |
70 | return this.router.navigateByUrl(RedirectService.DEFAULT_ROUTE) | |
71 | } | |
72 | ||
73 | ngOnInit () { | |
74 | document.getElementById('incompatible-browser').className += ' browser-ok' | |
75 | ||
76 | this.serverConfig = this.serverService.getTmpConfig() | |
77 | this.serverService.getConfig() | |
78 | .subscribe(config => this.serverConfig = config) | |
79 | ||
80 | this.loadPlugins() | |
81 | this.themeService.initialize() | |
82 | ||
83 | this.authService.loadClientCredentials() | |
84 | ||
85 | if (this.isUserLoggedIn()) { | |
86 | // The service will automatically redirect to the login page if the token is not valid anymore | |
87 | this.authService.refreshUserInformation() | |
88 | } | |
89 | ||
90 | this.initRouteEvents() | |
91 | this.injectJS() | |
92 | this.injectCSS() | |
93 | this.injectBroadcastMessage() | |
94 | ||
95 | this.initHotkeys() | |
96 | ||
97 | this.location.onPopState(() => this.modalService.dismissAll(POP_STATE_MODAL_DISMISS)) | |
98 | ||
99 | this.openModalsIfNeeded() | |
100 | ||
101 | this.document.documentElement.lang = getShortLocale(this.localeId) | |
102 | } | |
103 | ||
104 | ngAfterViewInit () { | |
105 | this.pluginService.initializeCustomModal(this.customModal) | |
106 | } | |
107 | ||
108 | getToggleTitle () { | |
109 | if (this.menu.isDisplayed()) return $localize`Close the left menu` | |
110 | ||
111 | return $localize`Open the left menu` | |
112 | } | |
113 | ||
114 | isUserLoggedIn () { | |
115 | return this.authService.isLoggedIn() | |
116 | } | |
117 | ||
118 | hideBroadcastMessage () { | |
119 | peertubeLocalStorage.setItem(AppComponent.BROADCAST_MESSAGE_KEY, this.serverConfig.broadcastMessage.message) | |
120 | ||
121 | this.broadcastMessage = null | |
122 | this.screenService.isBroadcastMessageDisplayed = false | |
123 | } | |
124 | ||
125 | private initRouteEvents () { | |
126 | let resetScroll = true | |
127 | const eventsObs = this.router.events | |
128 | ||
129 | const scrollEvent = eventsObs.pipe(filter((e: Event): e is Scroll => e instanceof Scroll)) | |
130 | ||
131 | // Handle anchors/restore position | |
132 | scrollEvent.subscribe(e => { | |
133 | // scrollToAnchor first to preserve anchor position when using history navigation | |
134 | if (e.anchor) { | |
135 | setTimeout(() => { | |
136 | this.viewportScroller.scrollToAnchor(e.anchor) | |
137 | }) | |
138 | ||
139 | return | |
140 | } | |
141 | ||
142 | if (e.position) { | |
143 | return this.viewportScroller.scrollToPosition(e.position) | |
144 | } | |
145 | ||
146 | if (resetScroll) { | |
147 | return this.viewportScroller.scrollToPosition([ 0, 0 ]) | |
148 | } | |
149 | }) | |
150 | ||
151 | const navigationEndEvent = eventsObs.pipe(filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd)) | |
152 | ||
153 | // When we add the a-state parameter, we don't want to alter the scroll | |
154 | navigationEndEvent.pipe(pairwise()) | |
155 | .subscribe(([ e1, e2 ]) => { | |
156 | try { | |
157 | resetScroll = false | |
158 | ||
159 | const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects) | |
160 | const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects) | |
161 | ||
162 | if (previousUrl.pathname !== nextUrl.pathname) { | |
163 | resetScroll = true | |
164 | return | |
165 | } | |
166 | ||
167 | const nextSearchParams = nextUrl.searchParams | |
168 | nextSearchParams.delete('a-state') | |
169 | ||
170 | const previousSearchParams = previousUrl.searchParams | |
171 | ||
172 | nextSearchParams.sort() | |
173 | previousSearchParams.sort() | |
174 | ||
175 | if (nextSearchParams.toString() !== previousSearchParams.toString()) { | |
176 | resetScroll = true | |
177 | } | |
178 | } catch (e) { | |
179 | console.error('Cannot parse URL to check next scroll.', e) | |
180 | resetScroll = true | |
181 | } | |
182 | }) | |
183 | ||
184 | // Homepage redirection | |
185 | navigationEndEvent.pipe( | |
186 | map(() => window.location.pathname), | |
187 | filter(pathname => !pathname || pathname === '/' || is18nPath(pathname)) | |
188 | ).subscribe(() => this.redirectService.redirectToHomepage(true)) | |
189 | ||
190 | // Plugin hooks | |
191 | navigationEndEvent.subscribe(e => { | |
192 | this.hooks.runAction('action:router.navigation-end', 'common', { path: e.url }) | |
193 | }) | |
194 | ||
195 | // Automatically hide/display the menu | |
196 | eventsObs.pipe( | |
197 | filter((e: Event): e is GuardsCheckStart => e instanceof GuardsCheckStart), | |
198 | filter(() => this.screenService.isInSmallView() || this.screenService.isInTouchScreen()) | |
199 | ).subscribe(() => this.menu.setMenuDisplay(false)) // User clicked on a link in the menu, change the page | |
200 | ||
201 | // Handle lazy loaded module | |
202 | eventsObs.pipe( | |
203 | filter((e: Event): e is RouteConfigLoadStart => e instanceof RouteConfigLoadStart) | |
204 | ).subscribe(() => this.loadingBar.useRef().start()) | |
205 | ||
206 | eventsObs.pipe( | |
207 | filter((e: Event): e is RouteConfigLoadEnd => e instanceof RouteConfigLoadEnd) | |
208 | ).subscribe(() => this.loadingBar.useRef().complete()) | |
209 | } | |
210 | ||
211 | private injectBroadcastMessage () { | |
212 | concat( | |
213 | this.serverService.getConfig().pipe(first()), | |
214 | this.serverService.configReloaded | |
215 | ).subscribe(async config => { | |
216 | this.broadcastMessage = null | |
217 | this.screenService.isBroadcastMessageDisplayed = false | |
218 | ||
219 | const messageConfig = config.broadcastMessage | |
220 | ||
221 | if (messageConfig.enabled) { | |
222 | // Already dismissed this message? | |
223 | if (messageConfig.dismissable && localStorage.getItem(AppComponent.BROADCAST_MESSAGE_KEY) === messageConfig.message) { | |
224 | return | |
225 | } | |
226 | ||
227 | const classes: { [id in BroadcastMessageLevel]: string } = { | |
228 | info: 'alert-info', | |
229 | warning: 'alert-warning', | |
230 | error: 'alert-danger' | |
231 | } | |
232 | ||
233 | this.broadcastMessage = { | |
234 | message: await this.markdownService.completeMarkdownToHTML(messageConfig.message), | |
235 | dismissable: messageConfig.dismissable, | |
236 | class: classes[messageConfig.level] | |
237 | } | |
238 | ||
239 | this.screenService.isBroadcastMessageDisplayed = true | |
240 | } | |
241 | }) | |
242 | } | |
243 | ||
244 | private injectJS () { | |
245 | // Inject JS | |
246 | this.serverService.getConfig() | |
247 | .subscribe(config => { | |
248 | if (config.instance.customizations.javascript) { | |
249 | try { | |
250 | // tslint:disable:no-eval | |
251 | eval(config.instance.customizations.javascript) | |
252 | } catch (err) { | |
253 | console.error('Cannot eval custom JavaScript.', err) | |
254 | } | |
255 | } | |
256 | }) | |
257 | } | |
258 | ||
259 | private injectCSS () { | |
260 | // Inject CSS if modified (admin config settings) | |
261 | concat( | |
262 | this.serverService.getConfig().pipe(first()), | |
263 | this.serverService.configReloaded | |
264 | ).subscribe(config => { | |
265 | const headStyle = document.querySelector('style.custom-css-style') | |
266 | if (headStyle) headStyle.parentNode.removeChild(headStyle) | |
267 | ||
268 | // We test customCSS if the admin removed the css | |
269 | if (this.customCSS || config.instance.customizations.css) { | |
270 | const styleTag = '<style>' + config.instance.customizations.css + '</style>' | |
271 | this.customCSS = this.domSanitizer.bypassSecurityTrustHtml(styleTag) | |
272 | } | |
273 | }) | |
274 | } | |
275 | ||
276 | private async loadPlugins () { | |
277 | this.pluginService.initializePlugins() | |
278 | ||
279 | this.hooks.runAction('action:application.init', 'common') | |
280 | } | |
281 | ||
282 | private async openModalsIfNeeded () { | |
283 | this.authService.userInformationLoaded | |
284 | .pipe( | |
285 | map(() => this.authService.getUser()), | |
286 | filter(user => user.role === UserRole.ADMINISTRATOR) | |
287 | ).subscribe(user => setTimeout(() => this._openAdminModalsIfNeeded(user))) // setTimeout because of ngIf in template | |
288 | } | |
289 | ||
290 | private async _openAdminModalsIfNeeded (user: User) { | |
291 | if (user.noWelcomeModal !== true) return this.welcomeModal.show() | |
292 | ||
293 | if (user.noInstanceConfigWarningModal === true || !this.serverConfig.signup.allowed) return | |
294 | ||
295 | this.instanceService.getAbout() | |
296 | .subscribe(about => { | |
297 | if ( | |
298 | this.serverConfig.instance.name.toLowerCase() === 'peertube' || | |
299 | !about.instance.terms || | |
300 | !about.instance.administrator || | |
301 | !about.instance.maintenanceLifetime | |
302 | ) { | |
303 | this.instanceConfigWarningModal.show(about) | |
304 | } | |
305 | }) | |
306 | } | |
307 | ||
308 | private initHotkeys () { | |
309 | this.hotkeysService.add([ | |
310 | new Hotkey(['/', 's'], (event: KeyboardEvent): boolean => { | |
311 | document.getElementById('search-video').focus() | |
312 | return false | |
313 | }, undefined, $localize`Focus the search bar`), | |
314 | ||
315 | new Hotkey('b', (event: KeyboardEvent): boolean => { | |
316 | this.menu.toggleMenu() | |
317 | return false | |
318 | }, undefined, $localize`Toggle the left menu`), | |
319 | ||
320 | new Hotkey('g o', (event: KeyboardEvent): boolean => { | |
321 | this.router.navigate([ '/videos/overview' ]) | |
322 | return false | |
323 | }, undefined, $localize`Go to the discover videos page`), | |
324 | ||
325 | new Hotkey('g t', (event: KeyboardEvent): boolean => { | |
326 | this.router.navigate([ '/videos/trending' ]) | |
327 | return false | |
328 | }, undefined, $localize`Go to the trending videos page`), | |
329 | ||
330 | new Hotkey('g r', (event: KeyboardEvent): boolean => { | |
331 | this.router.navigate([ '/videos/recently-added' ]) | |
332 | return false | |
333 | }, undefined, $localize`Go to the recently added videos page`), | |
334 | ||
335 | new Hotkey('g l', (event: KeyboardEvent): boolean => { | |
336 | this.router.navigate([ '/videos/local' ]) | |
337 | return false | |
338 | }, undefined, $localize`Go to the local videos page`), | |
339 | ||
340 | new Hotkey('g u', (event: KeyboardEvent): boolean => { | |
341 | this.router.navigate([ '/videos/upload' ]) | |
342 | return false | |
343 | }, undefined, $localize`Go to the videos upload page`) | |
344 | ]) | |
345 | } | |
346 | } |