-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathsaveToOneNote.ts
More file actions
298 lines (253 loc) · 11.9 KB
/
saveToOneNote.ts
File metadata and controls
298 lines (253 loc) · 11.9 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
import {Constants} from "../constants";
import {PromiseUtils} from "../promiseUtils";
import {Settings} from "../settings";
import {StringUtils} from "../stringUtils";
import {UserInfo} from "../userInfo";
import {Clipper} from "../clipperUI/frontEndGlobals";
import {ClipperStorageKeys} from "../storage/clipperStorageKeys";
import * as Log from "../logging/log";
import {OneNoteApiWithLogging} from "./oneNoteApiWithLogging";
import {OneNoteApiWithRetries} from "./oneNoteApiWithRetries";
import {OneNoteSaveable} from "./oneNoteSaveable";
import * as _ from "lodash";
export interface SaveToOneNoteOptions {
page: OneNoteSaveable;
saveLocation?: string;
progressCallback?: (num: number, denom: number) => void;
}
/**
* Solely responsible for saving the user's OneNote pages
*/
export class SaveToOneNote {
private static timeBeforeFirstPatch = 1000;
private static timeBetweenPatchRequests = 7000;
private static timeBeforeFirstBatch = 1000;
private static timeBetweenBatchRequests = 7000;
private static timeBeforeFirstPost = 1000;
private static timeBetweenPostRequests = 0;
private accessToken: string;
constructor(accessToken: string) {
this.accessToken = accessToken;
}
/**
* Saves a page (and if necessary, appends PATCHES) to OneNote
*/
public save(options: SaveToOneNoteOptions): Promise<OneNoteApi.ResponsePackage<any>> {
if (options.page.getNumPages() > 1) {
return this.saveMultiplePagesSynchronously(options);
} else {
if (options.page.getNumPatches() > 0) {
return this.rejectIfNoPatchPermissions(options.saveLocation).then(() => {
return this.saveWithoutCheckingPatchPermissions(options);
});
} else {
return this.saveWithoutCheckingPatchPermissions(options);
}
}
}
private saveMultiplePagesSynchronously(options: SaveToOneNoteOptions) {
let progressCallback = options.progressCallback ? options.progressCallback : () => { };
progressCallback(0, options.page.getNumPages());
return options.page.getPage().then((page) => {
return this.getApi().createPage(page, options.saveLocation).then((responsePackage) => {
return this.synchronouslyCreateMultiplePages(options, progressCallback).then(() => {
return Promise.resolve(responsePackage);
});
});
});
}
private synchronouslyCreateMultiplePages(options: SaveToOneNoteOptions, progressCallback: (completed: number, total: number) => void = () => {}): Promise<any> {
const saveable = options.page;
const end = saveable.getNumPages();
// We start the range at 1 since we have already included the first page
return _.range(1, end).reduce((chainedPromise, i) => {
return chainedPromise = chainedPromise.then(() => {
return new Promise((resolve, reject) => {
// Parallelize the POST request intervals with the fetching of current dataUrl
let getPagePromise = this.getPageWithLogging(saveable, i);
let timeoutPromise = PromiseUtils.wait(SaveToOneNote.timeBetweenPostRequests);
Promise.all([getPagePromise, timeoutPromise]).then((values) => {
let page = values[0] as OneNoteApi.OneNotePage;
this.getApi().createPage(page, options.saveLocation).then(() => {
progressCallback(i, end);
resolve();
}).catch((error) => {
reject(error);
});
});
});
});
}, Promise.resolve());
}
private rejectIfNoPatchPermissions(saveLocation: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
Clipper.getStoredValue(ClipperStorageKeys.hasPatchPermissions, (hasPermissions) => {
// We have checked their permissions successfully in the past, or the user signed in on this device (with the latest scope)
if (hasPermissions) {
resolve();
} else {
// As of v3.2.9, we have added a new scope for MSA to allow for PATCHing, however currently-logged-in users will not have
// this scope, so this call is a workaround to check for permissions, but is very unperformant. We need to investigate a
// quicker way of doing this ... perhaps exposing an endpoint that we can use for this sole purpose.
this.getApi().getPages({ top: 1, sectionId: saveLocation }).then(() => {
Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true");
resolve();
}).catch((error) => {
reject(error);
});
}
});
});
}
private saveWithoutCheckingPatchPermissions(options: SaveToOneNoteOptions): Promise<OneNoteApi.ResponsePackage<any>> {
// options.page is a misnomer, as its the saveable, not a specific page
return options.page.getPage().then((page) => {
return this.getApi().createPage(page, options.saveLocation).then((responsePackage) => {
if (options.page.getNumPatches() > 0) {
let pageId = responsePackage.parsedResponse.id;
return this.patch(pageId, options.page).then(() => {
return Promise.resolve(responsePackage);
});
} else if (options.page.getNumBatches() > 0) {
return this.batch(options.page).then(() => {
return Promise.resolve(responsePackage);
});
} else {
return Promise.resolve(responsePackage);
}
});
});
}
private batch(saveable: OneNoteSaveable): Promise<any> {
let timeBetweenBatchRequests = SaveToOneNote.timeBeforeFirstBatch;
return _.range(saveable.getNumBatches()).reduce((chainedPromise, i) => {
return chainedPromise = chainedPromise.then(() => {
return new Promise((resolve, reject) => {
// Parallelize the BATCH request intervals with the fetching of the next set of dataUrls
let getRevisionsPromise = this.getBatchWithLogging(saveable, i);
let timeoutPromise = PromiseUtils.wait(timeBetweenBatchRequests);
Promise.all([getRevisionsPromise, timeoutPromise]).then((values) => {
let batchRequest = values[0] as OneNoteApi.BatchRequest;
this.getApi().sendBatchRequest(batchRequest).then(() => {
resolve();
}).catch((error) => {
reject(error);
});
});
});
});
}, Promise.resolve());
}
private patch(pageId: string, saveable: OneNoteSaveable): Promise<any> {
// As of 10/27/16, the page is not always ready when the 200 is returned, so we wait a bit, and then getPageContent with retries
// When the getPageContent returns a 200, we start PATCHing the page.
let timeBetweenPatchRequests = SaveToOneNote.timeBeforeFirstPatch;
return Promise.all([
_.range(saveable.getNumPatches()).reduce((chainedPromise, i) => {
return chainedPromise = chainedPromise.then(() => {
return new Promise((resolve, reject) => {
// OneNote API returns 204 on a PATCH request when it receives it, but we have no way of telling when it actually
// completes processing, so we add an artificial timeout before the next PATCH to try and ensure that they get
// processed in the order that they were sent.
// Parallelize the PATCH request intervals with the fetching of the next set of dataUrls
let getRevisionsPromise = this.getPatchWithLogging(saveable, i);
let timeoutPromise = PromiseUtils.wait(timeBetweenPatchRequests);
Promise.all([getRevisionsPromise, timeoutPromise]).then((values) => {
let revisions = values[0] as OneNoteApi.Revision[];
let thenCb = () => {
timeBetweenPatchRequests = SaveToOneNote.timeBetweenPatchRequests;
resolve();
};
let catchCb = (error: OneNoteApi.RequestError) => {
if (error.statusCode === 401) {
// The clip has taken a really long time and the user token has expired
Clipper.getExtensionCommunicator().callRemoteFunction(Constants.FunctionKeys.ensureFreshUserBeforeClip, {
callback: (updatedUser: UserInfo) => {
if (updatedUser.user.accessToken) {
// Try again with the new token
this.accessToken = updatedUser.user.accessToken;
this.updatePage(pageId, revisions, thenCb, catchCb);
} else {
reject(error);
}
}
});
} else {
reject(error);
}
};
this.updatePage(pageId, revisions, thenCb, catchCb);
});
});
});
}, this.getApi().getPageContent(pageId)) // Check if page exists with retries
]);
}
private updatePage(pageId: string, revisions: OneNoteApi.Revision[], thenCb: () => void, catchCb: (error: OneNoteApi.RequestError) => void) {
this.getApi().updatePage(pageId, revisions)
.then(thenCb)
.catch(catchCb);
}
// We try not and put logging logic in this class, but since we lazy-load images, this has to be an exception
private getPatchWithLogging(saveable: OneNoteSaveable, index: number): Promise<OneNoteApi.Revision[]> {
let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls);
return saveable.getPatch(index).then((revisions: OneNoteApi.Revision[]) => {
event.stopTimer();
let numPages = revisions.length;
event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages);
if (revisions.length > 0) {
// There's some html in the content itself, but it's negligible compared to the length of the actual dataUrls
let lengthOfDataUrls = _.sumBy(revisions, (revision) => { return revision.content.length; });
event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls);
event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages);
event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages);
}
Clipper.logger.logEvent(event);
return Promise.resolve(revisions);
});
}
private getPageWithLogging(saveable: OneNoteSaveable, index: number) {
let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls);
return saveable.getPage(index).then((page: OneNoteApi.OneNotePage) => {
event.stopTimer();
const numPages = 1;
event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages);
let lengthOfDataUrls = page.getEntireOnml().length;
event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls);
event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages);
event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages);
Clipper.logger.logEvent(event);
return Promise.resolve(page);
});
}
private getBatchWithLogging(saveable: OneNoteSaveable, index: number): Promise<OneNoteApi.BatchRequest> {
let event = new Log.Event.PromiseEvent(Log.Event.Label.ProcessPdfIntoDataUrls);
return saveable.getBatch(index).then((batchRequest: OneNoteApi.BatchRequest) => {
event.stopTimer();
let numPages = batchRequest.getNumOperations();
event.setCustomProperty(Log.PropertyName.Custom.NumPages, numPages);
if (numPages > 0) {
// There's some html in the content itself, but it's negligible compared to the length of the actual dataUrls
const batchRequestOperations = _.range(numPages).map((pageNumber) => { return batchRequest.getOperation(pageNumber); });
const lengthOfDataUrls = _.sumBy(batchRequestOperations, (op) => { return op.content.length; });
event.setCustomProperty(Log.PropertyName.Custom.ByteLength, lengthOfDataUrls);
event.setCustomProperty(Log.PropertyName.Custom.BytesPerPdfPage, lengthOfDataUrls / numPages);
event.setCustomProperty(Log.PropertyName.Custom.AverageProcessingDurationPerPage, event.getDuration() / numPages);
}
Clipper.logger.logEvent(event);
return Promise.resolve(batchRequest);
});
}
/**
* We set the correlation id each time this gets called. When using this, make sure you are not reusing
* the same object unless it's your intention to have their API calls use the same correlation id.
*/
private getApi(): OneNoteApi.IOneNoteApi {
let headers: { [key: string]: string } = {};
headers[Constants.HeaderValues.appIdKey] = Settings.getSetting("App_Id");
headers[Constants.HeaderValues.userSessionIdKey] = Clipper.getUserSessionId();
let api = new OneNoteApi.OneNoteApi(this.accessToken, undefined /* timeout */, headers);
let apiWithRetries = new OneNoteApiWithRetries(api);
return new OneNoteApiWithLogging(apiWithRetries);
}
}