-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.component.ts
More file actions
494 lines (436 loc) · 18.2 KB
/
app.component.ts
File metadata and controls
494 lines (436 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import { BidiModule } from '@angular/cdk/bidi';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout';
import { CdkScrollable } from '@angular/cdk/scrolling';
import { AsyncPipe, DOCUMENT } from '@angular/common';
import { Component, DestroyRef, Inject, OnDestroy, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButton, MatIconAnchor, MatIconButton } from '@angular/material/button';
import { MatDivider } from '@angular/material/divider';
import { MatIcon } from '@angular/material/icon';
import { MatMenu, MatMenuItem, MatMenuTrigger } from '@angular/material/menu';
import { MatProgressBar } from '@angular/material/progress-bar';
import { MatDrawer, MatDrawerContainer } from '@angular/material/sidenav';
import { MatToolbar, MatToolbarRow } from '@angular/material/toolbar';
import { MatTooltip } from '@angular/material/tooltip';
import { NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import Bugsnag from '@bugsnag/js';
import { TranslocoModule } from '@ngneat/transloco';
import { cloneDeep } from 'lodash-es';
import { CookieService } from 'ngx-cookie-service';
import { SystemRole } from 'realtime-server/lib/esm/common/models/system-role';
import { AuthType, getAuthType, User } from 'realtime-server/lib/esm/common/models/user';
import { SFProjectRole } from 'realtime-server/lib/esm/scriptureforge/models/sf-project-role';
import { Observable, Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ActivatedProjectService } from 'xforge-common/activated-project.service';
import { AuthService } from 'xforge-common/auth.service';
import { AvatarComponent } from 'xforge-common/avatar/avatar.component';
import { DataLoadingComponent } from 'xforge-common/data-loading-component';
import { DiagnosticOverlayService } from 'xforge-common/diagnostic-overlay.service';
import { DialogService } from 'xforge-common/dialog.service';
import { ErrorReportingService } from 'xforge-common/error-reporting.service';
import { ExternalUrlService } from 'xforge-common/external-url.service';
import { FeatureFlagService } from 'xforge-common/feature-flags/feature-flag.service';
import { FeatureFlagsDialogComponent } from 'xforge-common/feature-flags/feature-flags-dialog.component';
import { FileService } from 'xforge-common/file.service';
import { I18nService } from 'xforge-common/i18n.service';
import { LocationService } from 'xforge-common/location.service';
import { Breakpoint, MediaBreakpointService } from 'xforge-common/media-breakpoints/media-breakpoint.service';
import { UserDoc } from 'xforge-common/models/user-doc';
import { NoticeService } from 'xforge-common/notice.service';
import { OnlineStatusService } from 'xforge-common/online-status.service';
import { PWA_BEFORE_PROMPT_CAN_BE_SHOWN_AGAIN, PwaService } from 'xforge-common/pwa.service';
import { RouterLinkDirective } from 'xforge-common/router-link.directive';
import {
BrowserIssue,
SupportedBrowsersDialogComponent
} from 'xforge-common/supported-browsers-dialog/supported-browsers-dialog.component';
import { ThemeService } from 'xforge-common/theme.service';
import { UserService } from 'xforge-common/user.service';
import { quietTakeUntilDestroyed } from 'xforge-common/util/rxjs-util';
import { issuesEmailTemplate, supportedBrowser } from 'xforge-common/utils';
import versionData from '../../../version.json';
import { environment } from '../environments/environment';
import { SFProjectProfileDoc } from './core/models/sf-project-profile-doc';
import { roleCanAccessTranslate } from './core/models/sf-project-role-info';
import { SFProjectUserConfigDoc } from './core/models/sf-project-user-config-doc';
import { SFProjectService } from './core/sf-project.service';
import { NavigationComponent } from './navigation/navigation.component';
import { GlobalNoticesComponent } from './shared/global-notices/global-notices.component';
import { checkAppAccess } from './shared/utils';
declare function gtag(...args: any): void;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
imports: [
AsyncPipe,
TranslocoModule,
RouterLink,
AvatarComponent,
RouterLinkDirective,
NavigationComponent,
GlobalNoticesComponent,
RouterOutlet,
MatIcon,
MatDrawerContainer,
MatButton,
MatIconAnchor,
MatIconButton,
MatMenu,
MatMenuItem,
MatMenuTrigger,
MatTooltip,
MatToolbar,
MatToolbarRow,
MatProgressBar,
MatDivider,
MatDrawer,
MatDrawerContainer,
CdkScrollable,
BidiModule
]
})
export class AppComponent extends DataLoadingComponent implements OnInit, OnDestroy {
version: string = versionData.version;
issueEmail: string = environment.issueEmail;
versionNumberClickCount = 0;
hasUpdate: boolean = false;
protected isAppOnline: boolean = false;
protected isExpanded: boolean = false;
protected isScreenTiny = false;
private currentUserDoc?: UserDoc;
private projectUserConfigDoc?: SFProjectUserConfigDoc;
private isLoggedInUserAnonymous: boolean = false;
private _selectedProjectDoc?: SFProjectProfileDoc;
private selectedProjectDeleteSub?: Subscription;
private permissionsChangedSub?: Subscription;
private _isDrawerPermanent: boolean = true;
constructor(
private readonly router: Router,
private readonly authService: AuthService,
@Inject(DOCUMENT) private readonly document: Document,
private readonly userService: UserService,
private readonly projectService: SFProjectService,
private readonly dialogService: DialogService,
private readonly diagnosticOverlayService: DiagnosticOverlayService,
private readonly fileService: FileService,
private readonly reportingService: ErrorReportingService,
private readonly activatedProjectService: ActivatedProjectService,
private readonly locationService: LocationService,
private readonly breakpointObserver: BreakpointObserver,
private readonly breakpointService: MediaBreakpointService,
private readonly cookieService: CookieService,
readonly noticeService: NoticeService,
readonly i18n: I18nService,
readonly urls: ExternalUrlService,
readonly featureFlags: FeatureFlagService,
private readonly pwaService: PwaService,
private readonly themeService: ThemeService,
onlineStatusService: OnlineStatusService,
private destroyRef: DestroyRef
) {
super(noticeService);
this.breakpointObserver
.observe(this.breakpointService.width('>', Breakpoint.LG))
.pipe(quietTakeUntilDestroyed(this.destroyRef))
.subscribe((value: BreakpointState) => (this.isDrawerPermanent = value.matches));
this.breakpointObserver
.observe(this.breakpointService.width('<', Breakpoint.SM))
.pipe(quietTakeUntilDestroyed(this.destroyRef))
.subscribe((state: BreakpointState) => (this.isScreenTiny = state.matches));
// Check full online status changes
this.isAppOnline = onlineStatusService.isOnline;
onlineStatusService.onlineStatus$.pipe(quietTakeUntilDestroyed(this.destroyRef)).subscribe(status => {
if (status !== this.isAppOnline) {
this.isAppOnline = status;
this.checkDeviceStorage();
}
});
// Check browser online status to allow checks with Auth0
onlineStatusService.onlineBrowserStatus$.pipe(quietTakeUntilDestroyed(this.destroyRef)).subscribe(status => {
// Check authentication when coming back online
// This is also run on first load when the websocket connects for the first time
if (status && !this.isAppLoading) {
void this.authService.checkOnlineAuth();
}
});
pwaService.hasUpdate$.pipe(quietTakeUntilDestroyed(this.destroyRef)).subscribe(() => (this.hasUpdate = true));
// Google Analytics - send data at end of navigation so we get data inside the SPA client-side routing
if (environment.releaseStage === 'live') {
const navEndEvent$ = router.events.pipe(
filter(e => e instanceof NavigationEnd),
map(e => e as NavigationEnd)
);
navEndEvent$.pipe(quietTakeUntilDestroyed(this.destroyRef)).subscribe(e => {
if (this.isAppOnline) {
gtag('config', 'UA-22170471-15', { page_path: e.urlAfterRedirects });
}
});
}
}
get canInstallOnDevice$(): Observable<boolean> {
return this.pwaService.canInstall$;
}
get showInstallIconOnAvatar$(): Observable<boolean> {
return this.canInstallOnDevice$.pipe(
filter(() => this.pwaService.installPromptLastShownTime + PWA_BEFORE_PROMPT_CAN_BE_SHOWN_AGAIN < Date.now())
);
}
get showCheckingDisabled(): boolean {
return (
this._selectedProjectDoc != null &&
this._selectedProjectDoc.data != null &&
!this._selectedProjectDoc.data.checkingConfig.checkingEnabled &&
!roleCanAccessTranslate(this.selectedProjectRole)
);
}
get issueMailTo(): string {
return issuesEmailTemplate();
}
/** If is production server. */
get isLive(): boolean {
return environment.releaseStage === 'live';
}
get isDrawerPermanent(): boolean {
return this._isDrawerPermanent;
}
set isDrawerPermanent(value: boolean) {
if (this._isDrawerPermanent !== value) {
this._isDrawerPermanent = value;
if (!this._isDrawerPermanent) {
this.collapseDrawer();
}
}
}
get lastSelectedProjectId(): string | undefined {
return this.currentUser?.sites[environment.siteId].currentProjectId;
}
get appIconLink(): string[] {
return this.router.url === '/projects' && this.lastSelectedProjectId != null
? ['/projects', this.lastSelectedProjectId]
: ['/projects'];
}
get isLoggedIn(): Observable<boolean> {
return this.authService.loggedInState$.pipe(map(state => state.loggedIn));
}
get isAppLoading(): boolean {
return this.noticeService.isAppLoading;
}
get isServalAdmin(): boolean {
return this.authService.currentUserRoles.includes(SystemRole.ServalAdmin);
}
get isSystemAdmin(): boolean {
return this.authService.currentUserRoles.includes(SystemRole.SystemAdmin);
}
get currentUser(): User | undefined {
return this.currentUserDoc == null ? undefined : this.currentUserDoc.data;
}
get canChangePassword(): boolean {
if (this.currentUser == null || this.isLoggedInUserAnonymous) {
return false;
}
return getAuthType(this.currentUser.authId) === AuthType.Account;
}
get selectedProjectDoc(): SFProjectProfileDoc | undefined {
return this.activatedProjectService.projectDoc;
}
get selectedProjectId(): string | undefined {
return this._selectedProjectDoc == null ? undefined : this._selectedProjectDoc.id;
}
get isProjectSelected(): boolean {
return this.activatedProjectService.projectId != null;
}
get selectedProjectRole(): SFProjectRole | undefined {
return this.currentUserDoc == null
? undefined
: (this._selectedProjectDoc?.data?.userRoles[this.currentUserDoc.id] as SFProjectRole);
}
async ngOnInit(): Promise<void> {
await this.authService.loggedIn;
this.document.title = environment.siteName;
this.featureFlags.darkMode.enabled$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(enabled => {
this.themeService.setDarkMode(enabled);
});
this.loadingStarted();
this.currentUserDoc = await this.userService.getCurrentUser();
const userData: User | undefined = cloneDeep(this.currentUserDoc.data);
if (userData != null) {
const userDataWithId = { ...userData, id: this.currentUserDoc.id };
this.reportingService.addMeta(userDataWithId, 'user');
if (Bugsnag.isStarted()) Bugsnag.setUser(this.currentUserDoc.id);
}
const isNewlyLoggedIn = await this.authService.isNewlyLoggedIn;
this.isLoggedInUserAnonymous = await this.authService.isLoggedInUserAnonymous;
const isBrowserSupported = supportedBrowser();
this.reportingService.addMeta({ isBrowserSupported });
if (isNewlyLoggedIn && !isBrowserSupported) {
this.dialogService.openMatDialog(SupportedBrowsersDialogComponent, {
data: BrowserIssue.Upgrade
});
}
// Set the locale to the Auth0 user profile on first login
const languageTag: string | undefined = this.currentUserDoc.data!.interfaceLanguage;
if (
isNewlyLoggedIn &&
languageTag != null &&
I18nService.getLocale(languageTag)?.canonicalTag !== this.i18n.localeCode
) {
this.i18n.setLocale(languageTag);
}
// Monitor current project
this.activatedProjectService.projectDoc$
.pipe(quietTakeUntilDestroyed(this.destroyRef))
.subscribe(async (selectedProjectDoc?: SFProjectProfileDoc) => {
this._selectedProjectDoc = selectedProjectDoc;
if (this._selectedProjectDoc == null || !this._selectedProjectDoc.isLoaded) {
return;
}
void this.userService.setCurrentProjectId(this.currentUserDoc!, this._selectedProjectDoc.id);
this.projectUserConfigDoc = await this.projectService.getUserConfig(
this._selectedProjectDoc.id,
this.currentUserDoc!.id
);
if (this.selectedProjectDeleteSub != null) {
this.selectedProjectDeleteSub.unsubscribe();
}
this.selectedProjectDeleteSub = this._selectedProjectDoc?.delete$.subscribe(() => {
// handle remotely deleted project
const userDoc = this.currentUserDoc;
if (userDoc != null && this.userService.currentProjectId(userDoc) != null) {
void this.showProjectDeletedDialog();
}
});
this.permissionsChangedSub?.unsubscribe();
this.permissionsChangedSub = this._selectedProjectDoc?.remoteChanges$.subscribe(() => {
if (this._selectedProjectDoc?.data != null && this.currentUserDoc != null) {
// If the user is in the Serval administration area, do not check access, as they will be modifying the
// project's properties. We suppress this in the event log, as if a sync occurs while a serval admin is
// viewing it, it will result in the project deleted dialog erroneously being shown.
const servalAdminAreaRegex = /serval-administration|event-log/;
if (
servalAdminAreaRegex.test(this.locationService.pathname) &&
this.currentUser?.roles.includes(SystemRole.ServalAdmin)
) {
return;
}
// See if the user was removed from the project
if (!(this.currentUserDoc.id in this._selectedProjectDoc.data.userRoles)) {
// The user has been removed from the project
void this.showProjectDeletedDialog();
void this.projectService.localDelete(this._selectedProjectDoc.id);
}
if (this.projectUserConfigDoc != null) {
checkAppAccess(
this._selectedProjectDoc,
this.currentUserDoc.id,
this.projectUserConfigDoc,
this.locationService.pathname,
this.router
);
}
}
});
this.checkDeviceStorage();
});
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
// Any time we navigate somewhere, the drawer shouldn't still be expanded (which will only be noticeable on
// smaller screens where the drawer is not permanent).
this.isExpanded = false;
}
});
this.loadingFinished();
}
ngOnDestroy(): void {
this.selectedProjectDeleteSub?.unsubscribe();
this.permissionsChangedSub?.unsubscribe();
}
setLocale(locale: string): void {
this.i18n.setLocale(locale);
void this.authService.updateInterfaceLanguage(locale);
}
changePassword(): void {
if (this.currentUser == null) {
return;
} else if (!this.isAppOnline) {
this.noticeService.show(this.i18n.translateStatic('app.action_not_available_offline'));
} else {
void this.authService
.changePassword(this.currentUser.email)
.then(() => {
this.noticeService.show(this.i18n.translateStatic('app.password_reset_email_sent'));
})
.catch(() => {
void this.dialogService.message('app.cannot_change_password');
});
}
}
editName(): void {
if (this.isAppOnline) {
void this.userService.editDisplayName(false);
} else {
this.noticeService.show(this.i18n.translateStatic('app.action_not_available_offline'));
}
}
dismissInstallIcon(): void {
this.pwaService.setInstallPromptLastShownTime();
}
async hangfireDashboard(): Promise<void> {
// The access token will be undefined if offline
const accessToken: string | undefined = await this.authService.getAccessToken();
if (accessToken != null) {
// Grant 30 minutes access to the dashboard
const expires = new Date();
expires.setMinutes(expires.getMinutes() + 30);
this.cookieService.set('Hangfire', accessToken, expires, '/hangfire');
this.locationService.openInNewTab('/hangfire');
}
}
installOnDevice(): void {
void this.pwaService.install();
}
logOut(): void {
void this.authService.logOut();
}
collapseDrawer(): void {
this.isExpanded = false;
}
openDrawer(): void {
this.isExpanded = true;
}
toggleDrawer(): void {
this.isExpanded = !this.isExpanded;
}
drawerCollapsed(): void {
this.isExpanded = false;
}
reloadWithUpdates(): void {
this.pwaService.activateUpdates();
}
openFeatureFlagDialog(): void {
this.dialogService.openMatDialog(FeatureFlagsDialogComponent);
}
openDiagnosticOverlay(): void {
this.diagnosticOverlayService.open();
}
versionNumberClicked(): void {
this.versionNumberClickCount++;
if (this.versionNumberClickCount >= 7) {
this.featureFlags.showDeveloperTools.enabled = true;
}
}
private async showProjectDeletedDialog(): Promise<void> {
await this.userService.setCurrentProjectId(this.currentUserDoc!, undefined);
await this.dialogService.message('app.project_has_been_deleted');
this.navigateToStart();
}
private navigateToStart(): void {
setTimeout(() => this.router.navigateByUrl('/projects', { replaceUrl: true }));
}
private checkDeviceStorage(): void {
// Allow 5 seconds for the app to process any caching in progress
const SPACE_IN_MB = 20;
setTimeout(() => this.fileService.notifyUserIfStorageQuotaBelow(SPACE_IN_MB), 5000);
}
}