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