-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.component.ts
304 lines (266 loc) · 11.3 KB
/
app.component.ts
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
import {Component, Inject} from "@angular/core";
import {AuthService} from "./auth/auth.service";
import {Hub, Logger} from "@aws-amplify/core";
import {ActivatedRoute, Router} from "@angular/router";
import {environment} from "../environments/environment";
import {PreferenceService} from "./pref/preference.service";
import {NotificationService} from "./services/notification.service";
import {SessionService} from "./auth/session.service";
import * as Rollbar from "rollbar";
import {RollbarService} from "./error";
import {DataStore} from "@aws-amplify/datastore";
import Auth from "@aws-amplify/auth";
import {AnnotationService} from "./pref/annotation.service";
import {UIExecutionService} from "./services/uiexecution.service";
import {LoadingProgressService} from "./services/loading-progress.service";
import {NgForageCache} from "ngforage";
import {DateAdapter} from "@angular/material/core";
import {MapSelectionService} from "./map-selection.service";
const log = new Logger("app");
function getLang() {
if (navigator.languages !== undefined) {
return navigator.languages[0];
} else {
return navigator.language;
}
}
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent {
title = "SocialSensing.com";
public isDev: boolean = !environment.production;
user: any;
isAuthenticated: boolean;
public isSignup: boolean = !environment.production;
private dataStoreListener: any;
private initiateLogout: boolean;
private dataStoreSynced: boolean;
public ready = false;
constructor(public auth: AuthService,
public pref: PreferenceService,
private _router: Router,
public route: ActivatedRoute,
private _notify: NotificationService,
private _session: SessionService,
private _annotation: AnnotationService,
private _cache: NgForageCache,
public map: MapSelectionService,
private _adapter: DateAdapter<any>,
@Inject(RollbarService) private _rollbar: Rollbar, private _exec: UIExecutionService,
public loading: LoadingProgressService) {
loading.progress("Starting Application", 1);
Auth.currentAuthenticatedUser({bypassCache: true})
.then(user => this.isAuthenticated = (user != null))
.then(user => this.auth.loggedIn = (user != null))
.then(() => this.checkSession())
.catch(err => log.debug(err));
auth.state.subscribe(async (event: string) => {
if (event === AuthService.SIGN_IN) {
this.isAuthenticated = true;
this.isSignup = false;
await this.checkSession();
}
if (event === AuthService.SIGN_OUT) {
this.user = undefined;
this.isAuthenticated = false;
this.isSignup = !environment.production;
this.pref.clear();
}
});
Hub.listen('app.logout', async (data) => {
const {payload} = data;
await this.logout();
});
this._router.events.subscribe((val) => log.verbose("Router Event: ", val));
}
async checkSession() {
if (this.route.snapshot.queryParamMap.has("__clear_cache__")) {
try {
await this.hardLogout();
} finally {
log.info("Logged out, redirecting.");
window.location.href = "/";
}
}
log.debug("checkSession()");
if (!this.isAuthenticated) {
log.debug("Not authenticated");
return;
}
log.debug("Authenticated");
this.dataStoreListener = Hub.listen("datastore", async (capsule) => {
const {
payload: {event, data},
} = capsule;
log.debug("DataStore event", event, data);
if (event === "outboxStatus") {
this.dataStoreSynced = data.isEmpty;
if (data.isEmpty && this.initiateLogout) {
this.loading.progress("Synced", 2);
setTimeout(() => this.doLogout(), 500);
}
}
if (event === "ready" && !this.initiateLogout) {
this.loading.progress("Synced data with the server ...", 2);
const user = await Auth.currentAuthenticatedUser();
const userInfo = await Auth.currentUserInfo();
if (userInfo) {
try {
await this.pref.init(userInfo);
this.ready = true;
} catch (e) {
this._rollbar.error(e);
log.error(e);
this._notify.show(
// tslint:disable-next-line:max-line-length
"There was a problem with your application preferences, please ask an administrator to fix this. The application may not work correctly until you do.",
"I Will",
30);
return;
}
this._adapter.setLocale(this.pref.combined.locale);
try {
await this._session.open(userInfo);
} catch (e) {
log.error(
"There was a problem with creating your session, please ask an administrator to look into this.",
e);
log.error(user);
this._rollbar.error(
"There was a problem with creating your session, please ask an administrator to look into this.", e);
}
try {
await this._annotation.init(userInfo);
} catch (e) {
log.error(
"There was a problem with the annotation service, please ask an administrator to look into this.",
e);
log.error(user);
this._rollbar.error(
"There was a problem with creating the annotation service, " +
"please ask an administrator to look into this.",
e);
}
await this._exec.start();
log.info("Locale detected: " + getLang());
log.info("Locale in use: " + this.pref.combined.locale);
log.info("Timezone detected: " + Intl.DateTimeFormat().resolvedOptions().timeZone);
log.info("Timezone in use: " + this.pref.combined.timezone);
// Start the DataStore, this kicks-off the sync process.
this._rollbar.configure(
{
enabled: environment.rollbar,
// environment: environment.name,
captureIp: "anonymize",
code_version: environment.version,
payload: {
person: {
id: userInfo.username,
username: userInfo.username,
groups: this.pref.groups
},
// environment: environment.name,
environment_info: environment,
prefs: {
group: this.pref.combined
}
}
}
);
if (userInfo && userInfo.attributes.profile) {
this.user = userInfo;
this.isAuthenticated = true;
this.isSignup = false;
}
}
}
});
try {
if (environment.showLoadingMessages) {
this.loading.progress("Syncing data with the server ...", 3);
}
let datastoreStarted = false;
setTimeout(async () => {
if (!datastoreStarted) {
try {
await DataStore.stop()
await DataStore.clear();
await DataStore.start();
} catch (e) {
log.error(e);
} finally {
setTimeout(async () => {
window.location.reload();
}, 2000);
}
}
}, 5000);
await DataStore.start();
datastoreStarted = true;
if (environment.showLoadingMessages) {
this.loading.progress("Data synced with the server ...", 4);
}
} catch (e) {
log.error(e);
await DataStore.clear();
await DataStore.start();
this._notify.show("Failed to sync data with the server. Please refresh the page.", "OK", 300000);
}
}
public async logout() {
log.info("LOGOUT: Logout triggered by user.");
await this._session.close();
this._notify.show("Clearing application data");
if (!this.dataStoreSynced) {
this.initiateLogout = true;
// failsafe
setTimeout(() => this.doLogout(), 5000);
this.loading.progress("Syncing data before logout.", 1);
} else {
await this.doLogout();
}
}
private async hardLogout(): Promise<void> {
// log.info("Clearing ngForage cache");
// await this._cache.clear();
await Auth.signOut();
log.info("Clearing DataStore cache");
await DataStore.stop();
// await DataStore.clear();
log.info("Clearing IndexDB");
["amplify-datastore", "ngForage"].forEach(item => {
window.indexedDB.deleteDatabase(item).onsuccess = async ev => {
log.info("Clearing session storage");
sessionStorage.clear();
log.info("Clearing local storage");
localStorage.clear();
log.info("Clearing cookies");
document.cookie.split(";").forEach(c => {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
log.info("ALL caches cleared, logging out.");
};
});
}
private async doLogout() {
if (!this.initiateLogout) {
return;
}
this.isAuthenticated = false;
log.info("LOGOUT: Performing sign out.");
this.loading.progress("Signing out...", 1);
this._exec.stop();
try {
await this.hardLogout();
this.loading.progress("Signed out...", 4);
} catch (e) {
this._notify.error(e);
}
this.initiateLogout = false;
window.location.reload();
log.info("LOGOUT: Performed sign out.");
}
}