-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathextensionBase.ts
414 lines (354 loc) · 14.6 KB
/
extensionBase.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import {ClientInfo} from "../clientInfo";
import {ClientType} from "../clientType";
import {Constants} from "../constants";
import {StringUtils} from "../stringUtils";
import {UrlUtils} from "../urlUtils";
import {TooltipType} from "../clipperUI/tooltipType";
import {SmartValue} from "../communicator/smartValue";
import {HttpWithRetries} from "../http/httpWithRetries";
import {Localization} from "../localization/localization";
import {LocalizationHelper} from "../localization/localizationHelper";
import * as Log from "../logging/log";
import {Logger} from "../logging/logger";
import {ClipperData} from "../storage/clipperData";
import {ClipperStorageKeys} from "../storage/clipperStorageKeys";
import {ChangeLog} from "../versioning/changeLog";
import {ChangeLogHelper} from "../versioning/changelogHelper";
import {Version} from "../versioning/version";
import {AuthenticationHelper} from "./authenticationHelper";
import {ExtensionWorkerBase} from "./extensionWorkerBase";
import {TooltipHelper} from "./tooltipHelper";
import {WorkerPassthroughLogger} from "./workerPassthroughLogger";
/**
* The abstract base class for all of the extensions
*/
export abstract class ExtensionBase<TWorker extends ExtensionWorkerBase<TTab, TTabIdentifier>, TTab, TTabIdentifier> {
private workers: TWorker[];
private logger: Logger;
private static extensionId: string;
protected clipperIdProcessed: Promise<void>;
protected clipperData: ClipperData;
protected auth: AuthenticationHelper;
protected tooltip: TooltipHelper;
protected clientInfo: SmartValue<ClientInfo>;
protected static version = "3.10.10";
constructor(clipperType: ClientType, clipperData: ClipperData) {
this.setUnhandledExceptionLogging();
this.workers = [];
this.logger = new WorkerPassthroughLogger(this.workers);
ExtensionBase.extensionId = StringUtils.generateGuid();
this.clipperData = clipperData;
this.clipperData.setLogger(this.logger);
this.auth = new AuthenticationHelper(this.clipperData, this.logger);
this.tooltip = new TooltipHelper(this.clipperData);
let clipperFirstRun = false;
this.clipperIdProcessed = this.clipperData.getValue(ClipperStorageKeys.clipperId).then((clipperId) => {
if (!clipperId) {
// New install
clipperFirstRun = true;
clipperId = ExtensionBase.generateClipperId();
this.clipperData.setValue(ClipperStorageKeys.clipperId, clipperId);
// Ensure fresh installs don't trigger thats What's New experience
this.updateLastSeenVersionInStorageToCurrent();
}
this.clientInfo = new SmartValue<ClientInfo>({
clipperType: clipperType,
clipperVersion: ExtensionBase.getExtensionVersion(),
clipperId: clipperId
});
if (clipperFirstRun) {
this.onFirstRun();
}
this.initializeUserFlighting();
this.listenForOpportunityToShowPageNavTooltip();
});
}
protected abstract addPageNavListener(callback: (tab: TTab) => void);
protected abstract checkIfTabIsOnWhitelistedUrl(tab: TTab): boolean;
protected abstract getIdFromTab(tab: TTab): TTabIdentifier;
protected abstract createWorker(tab: TTab): TWorker;
protected abstract onFirstRun();
public static getExtensionId(): string {
return ExtensionBase.extensionId;
}
public static getExtensionVersion(): string {
return ExtensionBase.version;
}
public static shouldCheckForMajorUpdates(lastSeenVersion: Version, currentVersion: Version) {
return !!currentVersion && (!lastSeenVersion || lastSeenVersion.isLesserThan(currentVersion));
};
public addWorker(worker: TWorker) {
worker.setOnUnloading(() => {
worker.destroy();
this.removeWorker(worker);
});
this.workers.push(worker);
}
public getWorkers(): TWorker[] {
return this.workers;
}
public removeWorker(worker: TWorker) {
let index = this.workers.indexOf(worker);
if (index > -1) {
this.workers.splice(index, 1);
}
}
/**
* Determines if the url is on our domain or not
*/
protected static isOnOneNoteDomain(url: string): boolean {
return url.indexOf("onenote.com") >= 0 || url.indexOf("onenote-int.com") >= 0;
}
protected fetchAndStoreLocStrings(): Promise<{}> {
// navigator.userLanguage is only available in IE, and Typescript will not recognize this property
let locale = navigator.language || (<any>navigator).userLanguage;
return LocalizationHelper.makeLocStringsFetchRequest(locale).then((responsePackage) => {
try {
let locStringsDict = JSON.parse(responsePackage.parsedResponse);
if (locStringsDict) {
this.clipperData.setValue(ClipperStorageKeys.locale, locale);
this.clipperData.setValue(ClipperStorageKeys.locStrings, responsePackage.parsedResponse);
Localization.setLocalizedStrings(locStringsDict);
}
return Promise.resolve(locStringsDict);
} catch (e) {
return Promise.reject(undefined);
}
});
}
/**
* Returns the URL for more information about the Clipper
*/
protected getClipperInstalledPageUrl(clipperId: string, clipperType: ClientType, isInlineInstall: boolean): string {
let installUrl: string = Constants.Urls.clipperInstallPageUrl;
this.logger.logTrace(Log.Trace.Label.RequestForClipperInstalledPageUrl, Log.Trace.Level.Information, installUrl);
return installUrl;
}
protected getExistingWorkerForTab(tabUniqueId: TTabIdentifier): TWorker {
let workers = this.getWorkers();
for (let worker of workers) {
if (worker.getUniqueId() === tabUniqueId) {
return worker;
}
}
return undefined;
}
/**
* Gets the last seen version from storage, and returns undefined if there is none in storage
*/
protected async getLastSeenVersion(): Promise<Version> {
let lastSeenVersionStr = await this.clipperData.getValue(ClipperStorageKeys.lastSeenVersion);
return lastSeenVersionStr ? new Version(lastSeenVersionStr) : undefined;
}
protected getNewUpdates(lastSeenVersion: Version, currentVersion: Version): Promise<ChangeLog.Update[]> {
return new Promise<ChangeLog.Update[]>(async(resolve, reject) => {
let localeOverride = await this.clipperData.getValue(ClipperStorageKeys.displayLanguageOverride);
let localeToGet = localeOverride || navigator.language || (<any>navigator).userLanguage;
let changelogUrl = UrlUtils.addUrlQueryValue(Constants.Urls.changelogUrl, Constants.Urls.QueryParams.changelogLocale, localeToGet);
HttpWithRetries.get(changelogUrl).then((response: Response) => {
response.text().then((responseText: string) => {
try {
let schemas: ChangeLog.Schema[] = JSON.parse(responseText);
let allUpdates: ChangeLog.Update[];
for (let i = 0; i < schemas.length; i++) {
if (schemas[i].schemaVersion === ChangeLog.schemaVersionSupported) {
allUpdates = schemas[i].updates;
break;
}
}
if (allUpdates) {
let updatesSinceLastVersion = ChangeLogHelper.getUpdatesBetweenVersions(allUpdates, lastSeenVersion, currentVersion);
resolve(updatesSinceLastVersion);
} else {
throw new Error("No matching schemas were found.");
}
} catch (error) {
reject(error);
}
});
}, (error) => {
reject(error);
});
});
}
protected getOrCreateWorkerForTab(tab: TTab, tabToIdMapping: (tab: TTab) => TTabIdentifier): TWorker {
let tabId = tabToIdMapping(tab);
let worker = this.getExistingWorkerForTab(tabId);
if (!worker) {
worker = this.createWorker(tab);
this.addWorker(worker);
}
return worker;
}
/**
* Generates a new clipperId, should only be called on first run
*/
private static generateClipperId(): string {
let clipperPrefix = "ON";
return clipperPrefix + "-" + StringUtils.generateGuid();
}
/**
* Initializes the flighting info for the user.
*/
private initializeUserFlighting() {
// We don't have any flights
this.updateClientInfoWithFlightInformation([]);
}
private async shouldShowTooltip(tab: TTab, tooltipTypes: TooltipType[]): Promise<TooltipType> {
let type = this.checkIfTabMatchesATooltipType(tab, tooltipTypes);
if (!type) {
return Promise.reject(undefined);
}
if (!await this.tooltip.tooltipDelayIsOver(type, Date.now())) {
return Promise.reject(undefined);
}
return type;
}
private async shouldShowVideoTooltip(tab: TTab): Promise<boolean> {
const isTabAVideoDomain = await this.checkIfTabIsAVideoDomain(tab);
if (isTabAVideoDomain && await this.tooltip.tooltipDelayIsOver(TooltipType.Video, Date.now())) {
return true;
}
return false;
}
private showTooltip(tab: TTab, tooltipType: TooltipType): void {
let worker = this.getOrCreateWorkerForTab(tab, this.getIdFromTab);
let tooltipImpressionEvent = new Log.Event.BaseEvent(Log.Event.Label.TooltipImpression);
tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.TooltipType, TooltipType[tooltipType]);
let lastSeenTooltipTimeBase = this.tooltip.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType);
let numTimesTooltipHasBeenSeenBase = this.tooltip.getTooltipInformation(ClipperStorageKeys.numTimesTooltipHasBeenSeenBase, tooltipType);
worker.invokeTooltip(tooltipType).then((wasInvoked) => {
if (wasInvoked) {
this.tooltip.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType, Date.now().toString());
let numSeenStorageKey = ClipperStorageKeys.numTimesTooltipHasBeenSeenBase;
this.tooltip.getTooltipInformation(numSeenStorageKey, tooltipType).then((value) => {
let numTimesSeen = value + 1;
this.tooltip.setTooltipInformation(ClipperStorageKeys.numTimesTooltipHasBeenSeenBase, tooltipType, numTimesSeen.toString());
});
}
tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.FeatureEnabled, wasInvoked);
Promise.all([lastSeenTooltipTimeBase, numTimesTooltipHasBeenSeenBase]).then((values) => {
tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.LastSeenTooltipTime, values[0]);
tooltipImpressionEvent.setCustomProperty(Log.PropertyName.Custom.NumTimesTooltipHasBeenSeen, values[1]);
worker.getLogger().logEvent(tooltipImpressionEvent);
});
});
}
private shouldShowWhatsNewTooltip(_tab: TTab, _lastSeenVersion: Version, _extensionVersion: Version): boolean {
// Disable the "What's New" tooltip for OneNote Web Clipper for now
return false;
}
private showWhatsNewTooltip(tab: TTab, lastSeenVersion: Version, extensionVersion: Version): void {
this.getNewUpdates(lastSeenVersion, extensionVersion).then((newUpdates) => {
let filteredUpdates = ChangeLogHelper.filterUpdatesThatDontApplyToBrowser(newUpdates, ClientType[this.clientInfo.get().clipperType]);
if (!!filteredUpdates && filteredUpdates.length > 0) {
let worker: TWorker = this.getOrCreateWorkerForTab(tab, this.getIdFromTab);
worker.invokeWhatsNewTooltip(filteredUpdates).then((wasInvoked) => {
if (wasInvoked) {
let whatsNewImpressionEvent = new Log.Event.BaseEvent(Log.Event.Label.WhatsNewImpression);
whatsNewImpressionEvent.setCustomProperty(Log.PropertyName.Custom.FeatureEnabled, wasInvoked);
worker.getLogger().logEvent(whatsNewImpressionEvent);
// We don't want to do this if the tooltip was not invoked (e.g., on about:blank) so we can show it at the next opportunity
this.updateLastSeenVersionInStorageToCurrent();
}
});
} else {
this.updateLastSeenVersionInStorageToCurrent();
}
}, (error) => {
Log.ErrorUtils.sendFailureLogRequest({
label: Log.Failure.Label.GetChangeLog,
properties: {
failureType: Log.Failure.Type.Unexpected,
failureInfo: { error: error },
failureId: "GetChangeLog",
stackTrace: error
},
clientInfo: this.clientInfo
});
});
}
/**
* Skeleton method that sets a listener that listens for the opportunity to show a tooltip,
* then invokes it when appropriate.
*/
private listenForOpportunityToShowPageNavTooltip() {
this.addPageNavListener((tab: TTab) => {
if (this.clientInfo.get().clipperType !== ClientType.FirefoxExtension) {
let tooltips = [TooltipType.Pdf, TooltipType.Product, TooltipType.Recipe];
// Returns the Type of tooltip to show IF the delay is over and the tab has the correct content type
this.shouldShowTooltip(tab, tooltips).then((typeToShow) => {
if (typeToShow) {
this.showTooltip(tab, typeToShow);
return;
}
})
.catch(() => {
// No specific actions to be taken if shouldShowTooltip returns a failed promise
});
this.shouldShowVideoTooltip(tab).then((shouldShow) => {
if (shouldShow) {
this.showTooltip(tab, TooltipType.Video);
return;
}
let extensionVersion = new Version(ExtensionBase.getExtensionVersion());
// Fallback behavior for if the last seen version in storage is somehow in a corrupted format
try {
this.getLastSeenVersion().then((lastSeenVersion) => {
// We don't show updates more recent than the local version for now, as it is easy
// for a changelog to be released before a version is actually out
if (this.shouldShowWhatsNewTooltip(tab, lastSeenVersion, extensionVersion)) {
this.showWhatsNewTooltip(tab, lastSeenVersion, extensionVersion);
return;
}
});
} catch (e) {
this.updateLastSeenVersionInStorageToCurrent();
return;
}
});
}
});
}
private setUnhandledExceptionLogging() {
let oldOnError = self.onerror;
self.onerror = (message: string, filename?: string, lineno?: number, colno?: number, error?: Error) => {
let callStack = error ? Log.Failure.getStackTrace(error) : "[unknown stacktrace]";
Log.ErrorUtils.sendFailureLogRequest({
label: Log.Failure.Label.UnhandledExceptionThrown,
properties: {
failureType: Log.Failure.Type.Unexpected,
failureInfo: { error: JSON.stringify({ error: error.toString(), message: message, lineno: lineno, colno: colno }) },
failureId: "ExtensionBase",
stackTrace: callStack
},
clientInfo: this.clientInfo
});
if (oldOnError) {
oldOnError(message, filename, lineno, colno, error);
}
};
}
/**
* Returns True if the Extension determines the tab is a Product, Recipe, or PDF. False otherwise
*/
protected abstract checkIfTabMatchesATooltipType(tab: TTab, tooltipTypes: TooltipType[]): TooltipType;
/**
* Returns True if the Extension determines the tab is a Video, false otherwise
*/
protected abstract checkIfTabIsAVideoDomain(tab: TTab): Promise<boolean>;
/**
* Updates the ClientInfo with the given flighting info.
*/
private updateClientInfoWithFlightInformation(flightingInfo: string[]) {
this.clientInfo.set({
clipperType: this.clientInfo.get().clipperType,
clipperVersion: this.clientInfo.get().clipperVersion,
clipperId: this.clientInfo.get().clipperId,
flightingInfo: flightingInfo
});
}
private updateLastSeenVersionInStorageToCurrent() {
this.clipperData.setValue(ClipperStorageKeys.lastSeenVersion, ExtensionBase.getExtensionVersion());
}
}