/
FavoritePropertiesStorage.ts
390 lines (349 loc) · 16.3 KB
/
FavoritePropertiesStorage.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Core
*/
import { AccessToken, compareStrings, Dictionary, Guid, IDisposable, isIDisposable, OrderedComparator } from "@itwin/core-bentley";
import { InternetConnectivityStatus } from "@itwin/core-common";
import { IModelApp } from "@itwin/core-frontend";
import { PresentationError, PresentationStatus } from "@itwin/presentation-common";
import { ConnectivityInformationProvider, IConnectivityInformationProvider } from "../ConnectivityInformationProvider";
import { FavoritePropertiesOrderInfo, PropertyFullName } from "./FavoritePropertiesManager";
/** @internal */
export const IMODELJS_PRESENTATION_SETTING_NAMESPACE = "imodeljs.presentation";
/** @internal */
export const DEPRECATED_PROPERTIES_SETTING_NAMESPACE = "Properties";
/** @internal */
export const FAVORITE_PROPERTIES_SETTING_NAME = "FavoriteProperties";
/** @internal */
export const FAVORITE_PROPERTIES_ORDER_INFO_SETTING_NAME = "FavoritePropertiesOrderInfo";
/**
* Stores user preferences for favorite properties.
* @public
*/
export interface IFavoritePropertiesStorage {
/** Load Favorite properties from user-specific settings.
* @param iTwinId ITwin Id, if the settings is specific to a iTwin, otherwise undefined.
* @param imodelId iModel Id, if the setting is specific to an iModel, otherwise undefined. The iTwinId must be specified if iModelId is specified.
*/
loadProperties(iTwinId?: string, imodelId?: string): Promise<Set<PropertyFullName> | undefined>;
/** Saves Favorite properties to user-specific settings.
* @param properties Favorite properties to save.
* @param iTwinId iTwin Id, if the settings is specific to a iTwin, otherwise undefined.
* @param iModelId iModel Id, if the setting is specific to an iModel, otherwise undefined. The iTwinId must be specified if iModelId is specified.
*/
saveProperties(properties: Set<PropertyFullName>, iTwinId?: string, imodelId?: string): Promise<void>;
/** Load array of FavoritePropertiesOrderInfo from user-specific settings.
* Setting is specific to an iModel.
* @param iTwinId iTwin Id.
* @param imodelId iModel Id.
*/
loadPropertiesOrder(iTwinId: string | undefined, imodelId: string): Promise<FavoritePropertiesOrderInfo[] | undefined>;
/** Saves FavoritePropertiesOrderInfo array to user-specific settings.
* Setting is specific to an iModel.
* @param orderInfo Array of FavoritePropertiesOrderInfo to save.
* @param iTwinId iTwin Id.
* @param imodelId iModel Id.
*/
savePropertiesOrder(orderInfos: FavoritePropertiesOrderInfo[], iTwinId: string | undefined, imodelId: string): Promise<void>;
}
/**
* Available implementations of [[IFavoritePropertiesStorage]].
* @public
*/
export enum DefaultFavoritePropertiesStorageTypes {
/** A no-op storage that doesn't store or return anything. Used for cases when favorite properties aren't used by the application. */
Noop,
/** A storage that stores favorite properties information in a browser local storage. */
BrowserLocalStorage,
/** A storage that stores favorite properties in a user preferences storage (see [[IModelApp.userPreferences]]). */
UserPreferencesStorage,
}
/**
* A factory method to create one of the available [[IFavoritePropertiesStorage]] implementations.
* @public
*/
export function createFavoritePropertiesStorage(type: DefaultFavoritePropertiesStorageTypes): IFavoritePropertiesStorage {
switch (type) {
case DefaultFavoritePropertiesStorageTypes.Noop:
return new NoopFavoritePropertiesStorage();
case DefaultFavoritePropertiesStorageTypes.BrowserLocalStorage:
return new BrowserLocalFavoritePropertiesStorage();
case DefaultFavoritePropertiesStorageTypes.UserPreferencesStorage:
return new OfflineCachingFavoritePropertiesStorage({ impl: new IModelAppFavoritePropertiesStorage() });
}
}
/**
* @internal
*/
export class IModelAppFavoritePropertiesStorage implements IFavoritePropertiesStorage {
private async ensureIsSignedIn(): Promise<{ accessToken: AccessToken }> {
const accessToken = IModelApp.authorizationClient ? await IModelApp.authorizationClient.getAccessToken() : "";
if (accessToken) {
return { accessToken };
}
throw new PresentationError(PresentationStatus.Error, "Current user is not authorized to use the settings service");
}
public async loadProperties(iTwinId?: string, imodelId?: string): Promise<Set<PropertyFullName> | undefined> {
if (!IModelApp.userPreferences) {
throw new PresentationError(PresentationStatus.Error, "User preferences service is not set up");
}
const { accessToken } = await this.ensureIsSignedIn();
let setting = await IModelApp.userPreferences.get({
accessToken,
iTwinId,
iModelId: imodelId,
namespace: IMODELJS_PRESENTATION_SETTING_NAMESPACE,
key: FAVORITE_PROPERTIES_SETTING_NAME,
});
if (setting !== undefined) {
return new Set<PropertyFullName>(setting);
}
// try to check the old namespace
setting = await IModelApp.userPreferences.get({
accessToken,
iTwinId,
iModelId: imodelId,
namespace: DEPRECATED_PROPERTIES_SETTING_NAMESPACE,
key: FAVORITE_PROPERTIES_SETTING_NAME,
});
if (
setting !== undefined &&
setting.hasOwnProperty("nestedContentInfos") &&
setting.hasOwnProperty("propertyInfos") &&
setting.hasOwnProperty("baseFieldInfos")
) {
return new Set<PropertyFullName>([...setting.nestedContentInfos, ...setting.propertyInfos, ...setting.baseFieldInfos]);
}
return undefined;
}
public async saveProperties(properties: Set<PropertyFullName>, iTwinId?: string, imodelId?: string): Promise<void> {
if (!IModelApp.userPreferences) {
throw new PresentationError(PresentationStatus.Error, "User preferences service is not set up");
}
const { accessToken } = await this.ensureIsSignedIn();
await IModelApp.userPreferences.save({
accessToken,
iTwinId,
iModelId: imodelId,
namespace: IMODELJS_PRESENTATION_SETTING_NAMESPACE,
key: FAVORITE_PROPERTIES_SETTING_NAME,
content: Array.from(properties),
});
}
public async loadPropertiesOrder(iTwinId: string | undefined, imodelId: string): Promise<FavoritePropertiesOrderInfo[] | undefined> {
if (!IModelApp.userPreferences) {
throw new PresentationError(PresentationStatus.Error, "User preferences service is not set up");
}
const { accessToken } = await this.ensureIsSignedIn();
const setting = await IModelApp.userPreferences.get({
accessToken,
iTwinId,
iModelId: imodelId,
namespace: IMODELJS_PRESENTATION_SETTING_NAMESPACE,
key: FAVORITE_PROPERTIES_ORDER_INFO_SETTING_NAME,
});
return setting as FavoritePropertiesOrderInfo[];
}
public async savePropertiesOrder(orderInfos: FavoritePropertiesOrderInfo[], iTwinId: string | undefined, imodelId: string) {
if (!IModelApp.userPreferences) {
throw new PresentationError(PresentationStatus.Error, "User preferences service is not set up");
}
const { accessToken } = await this.ensureIsSignedIn();
await IModelApp.userPreferences.save({
accessToken,
iTwinId,
iModelId: imodelId,
namespace: IMODELJS_PRESENTATION_SETTING_NAMESPACE,
key: FAVORITE_PROPERTIES_ORDER_INFO_SETTING_NAME,
content: orderInfos,
});
}
}
/** @internal */
export interface OfflineCachingFavoritePropertiesStorageProps {
impl: IFavoritePropertiesStorage;
connectivityInfo?: IConnectivityInformationProvider;
}
/** @internal */
export class OfflineCachingFavoritePropertiesStorage implements IFavoritePropertiesStorage, IDisposable {
private _connectivityInfo: IConnectivityInformationProvider;
private _impl: IFavoritePropertiesStorage;
private _propertiesOfflineCache = new DictionaryWithReservations<ITwinAndIModelIdsKey, Set<PropertyFullName>>(iTwinAndIModelIdsKeyComparer);
private _propertiesOrderOfflineCache = new DictionaryWithReservations<ITwinAndIModelIdsKey, FavoritePropertiesOrderInfo[]>(iTwinAndIModelIdsKeyComparer);
public constructor(props: OfflineCachingFavoritePropertiesStorageProps) {
this._impl = props.impl;
// istanbul ignore next
this._connectivityInfo = props.connectivityInfo ?? new ConnectivityInformationProvider();
this._connectivityInfo.onInternetConnectivityChanged.addListener(this.onConnectivityStatusChanged);
}
public dispose() {
if (isIDisposable(this._connectivityInfo)) {
this._connectivityInfo.dispose();
}
}
public get impl() {
return this._impl;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
private onConnectivityStatusChanged = (args: { status: InternetConnectivityStatus }) => {
// istanbul ignore else
if (args.status === InternetConnectivityStatus.Online) {
// note: we're copying the cached values to temp arrays because `saveProperties` and `savePropertiesOrder` both
// attempt to modify cache dictionaries
const propertiesCache = new Array<{ properties: Set<PropertyFullName>; iTwinId?: string; imodelId?: string }>();
this._propertiesOfflineCache.forEach((key, value) => propertiesCache.push({ properties: value, iTwinId: key[0], imodelId: key[1] }));
propertiesCache.forEach(async (cached) => this.saveProperties(cached.properties, cached.iTwinId, cached.imodelId));
const ordersCache = new Array<{ order: FavoritePropertiesOrderInfo[]; iTwinId?: string; imodelId: string }>();
this._propertiesOrderOfflineCache.forEach((key, value) => ordersCache.push({ order: value, iTwinId: key[0], imodelId: key[1]! }));
ordersCache.forEach(async (cached) => this.savePropertiesOrder(cached.order, cached.iTwinId, cached.imodelId));
}
};
public async loadProperties(iTwinId?: string, imodelId?: string) {
if (this._connectivityInfo.status === InternetConnectivityStatus.Online) {
try {
return await this._impl.loadProperties(iTwinId, imodelId);
} catch {
// return from offline cache if the above fails
}
}
return this._propertiesOfflineCache.get([iTwinId, imodelId]);
}
public async saveProperties(properties: Set<PropertyFullName>, iTwinId?: string, imodelId?: string) {
const key: ITwinAndIModelIdsKey = [iTwinId, imodelId];
if (this._connectivityInfo.status === InternetConnectivityStatus.Offline) {
this._propertiesOfflineCache.set(key, properties);
return;
}
const reservationId = this._propertiesOfflineCache.reserve(key);
try {
await this._impl.saveProperties(properties, iTwinId, imodelId);
this._propertiesOfflineCache.reservedDelete(key, reservationId);
} catch {
this._propertiesOfflineCache.reservedSet(key, properties, reservationId);
}
}
public async loadPropertiesOrder(iTwinId: string | undefined, imodelId: string) {
if (this._connectivityInfo.status === InternetConnectivityStatus.Online) {
try {
return await this._impl.loadPropertiesOrder(iTwinId, imodelId);
} catch {
// return from offline cache if the above fails
}
}
return this._propertiesOrderOfflineCache.get([iTwinId, imodelId]);
}
public async savePropertiesOrder(orderInfos: FavoritePropertiesOrderInfo[], iTwinId: string | undefined, imodelId: string) {
const key: ITwinAndIModelIdsKey = [iTwinId, imodelId];
if (this._connectivityInfo.status === InternetConnectivityStatus.Offline) {
this._propertiesOrderOfflineCache.set(key, orderInfos);
return;
}
const reservationId = this._propertiesOrderOfflineCache.reserve(key);
try {
await this._impl.savePropertiesOrder(orderInfos, iTwinId, imodelId);
this._propertiesOrderOfflineCache.reservedDelete(key, reservationId);
} catch {
this._propertiesOrderOfflineCache.reservedSet(key, orderInfos, reservationId);
}
}
}
class DictionaryWithReservations<TKey, TValue> {
private _impl: Dictionary<TKey, { value?: TValue; lastReservationId?: string }>;
public constructor(compareKeys: OrderedComparator<TKey>) {
this._impl = new Dictionary(compareKeys);
}
public get(key: TKey) {
return this._impl.get(key)?.value;
}
public forEach(func: (key: TKey, value: TValue) => void): void {
this._impl.forEach((key, entry) => {
// istanbul ignore else
if (entry.value) {
func(key, entry.value);
}
});
}
public reserve(key: TKey) {
const reservationId = Guid.createValue();
this._impl.set(key, { lastReservationId: reservationId });
return reservationId;
}
public set(key: TKey, value: TValue) {
return this._impl.set(key, { value });
}
public reservedSet(key: TKey, value: TValue, reservationId: string) {
const entry = this._impl.get(key);
if (entry && entry.lastReservationId === reservationId) {
this._impl.set(key, { value });
}
}
public reservedDelete(key: TKey, reservationId: string) {
const entry = this._impl.get(key);
if (entry && entry.lastReservationId === reservationId) {
this._impl.delete(key);
}
}
}
type ITwinAndIModelIdsKey = [string | undefined, string | undefined];
// istanbul ignore next
function iTwinAndIModelIdsKeyComparer(lhs: ITwinAndIModelIdsKey, rhs: ITwinAndIModelIdsKey) {
const iTwinIdCompare = compareStrings(lhs[0] ?? "", rhs[0] ?? "");
return iTwinIdCompare !== 0 ? iTwinIdCompare : compareStrings(lhs[1] ?? "", rhs[1] ?? "");
}
/** @internal */
export class NoopFavoritePropertiesStorage implements IFavoritePropertiesStorage {
// istanbul ignore next
public async loadProperties(_iTwinId?: string, _imodelId?: string): Promise<Set<PropertyFullName> | undefined> {
return undefined;
}
// istanbul ignore next
public async saveProperties(_properties: Set<PropertyFullName>, _iTwinId?: string, _imodelId?: string) {}
// istanbul ignore next
public async loadPropertiesOrder(_iTwinId: string | undefined, _imodelId: string): Promise<FavoritePropertiesOrderInfo[] | undefined> {
return undefined;
}
// istanbul ignore next
public async savePropertiesOrder(_orderInfos: FavoritePropertiesOrderInfo[], _iTwinId: string | undefined, _imodelId: string): Promise<void> {}
}
/** @internal */
export class BrowserLocalFavoritePropertiesStorage implements IFavoritePropertiesStorage {
private _localStorage: Storage;
public constructor(props?: { localStorage?: Storage }) {
// istanbul ignore next
this._localStorage = props?.localStorage ?? window.localStorage;
}
public createFavoritesSettingItemKey(iTwinId?: string, imodelId?: string): string {
return `${IMODELJS_PRESENTATION_SETTING_NAMESPACE}${FAVORITE_PROPERTIES_SETTING_NAME}?iTwinId=${iTwinId}&imodelId=${imodelId}`;
}
public createOrderSettingItemKey(iTwinId?: string, imodelId?: string): string {
return `${IMODELJS_PRESENTATION_SETTING_NAMESPACE}${FAVORITE_PROPERTIES_ORDER_INFO_SETTING_NAME}?iTwinId=${iTwinId}&imodelId=${imodelId}`;
}
public async loadProperties(iTwinId?: string, imodelId?: string): Promise<Set<PropertyFullName> | undefined> {
const value = this._localStorage.getItem(this.createFavoritesSettingItemKey(iTwinId, imodelId));
if (!value) {
return undefined;
}
const properties: PropertyFullName[] = JSON.parse(value);
return new Set(properties);
}
public async saveProperties(properties: Set<PropertyFullName>, iTwinId?: string, imodelId?: string) {
this._localStorage.setItem(this.createFavoritesSettingItemKey(iTwinId, imodelId), JSON.stringify([...properties]));
}
public async loadPropertiesOrder(iTwinId: string | undefined, imodelId: string): Promise<FavoritePropertiesOrderInfo[] | undefined> {
const value = this._localStorage.getItem(this.createOrderSettingItemKey(iTwinId, imodelId));
if (!value) {
return undefined;
}
const orderInfos: FavoritePropertiesOrderInfo[] = JSON.parse(value).map((json: any) => ({
...json,
orderedTimestamp: new Date(json.orderedTimestamp),
}));
return orderInfos;
}
public async savePropertiesOrder(orderInfos: FavoritePropertiesOrderInfo[], iTwinId: string | undefined, imodelId: string): Promise<void> {
this._localStorage.setItem(this.createOrderSettingItemKey(iTwinId, imodelId), JSON.stringify(orderInfos));
}
}