1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | import { GraphClientError } from "../GraphClientError";
|
13 | import { GraphResponseHandler } from "../GraphResponseHandler";
|
14 | import { Client } from "../index";
|
15 | import { ResponseType } from "../ResponseType";
|
16 | import { UploadEventHandlers } from "./FileUploadTask/Interfaces/IUploadEventHandlers";
|
17 | import { Range } from "./FileUploadTask/Range";
|
18 | import { UploadResult } from "./FileUploadTask/UploadResult";
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | interface KeyValuePairObjectStringNumber {
|
26 | [key: string]: string | number;
|
27 | }
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | interface UploadStatusResponse {
|
36 | expirationDateTime: string;
|
37 | nextExpectedRanges: string[];
|
38 | }
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | export interface LargeFileUploadTaskOptions {
|
47 | rangeSize?: number;
|
48 | uploadEventHandlers?: UploadEventHandlers;
|
49 | }
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | export interface LargeFileUploadSession {
|
58 | url: string;
|
59 | expiry: Date;
|
60 | isCancelled?: boolean;
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | export type SliceType = ArrayBuffer | Blob | Uint8Array;
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | export interface FileObject<T> {
|
77 | content: T;
|
78 | name: string;
|
79 | size: number;
|
80 | sliceFile(range: Range): SliceType | Promise<SliceType>;
|
81 | }
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | export class LargeFileUploadTask<T> {
|
88 | |
89 |
|
90 |
|
91 |
|
92 | private DEFAULT_FILE_SIZE: number = 5 * 1024 * 1024;
|
93 |
|
94 | |
95 |
|
96 |
|
97 |
|
98 | protected client: Client;
|
99 |
|
100 | |
101 |
|
102 |
|
103 |
|
104 | protected file: FileObject<T>;
|
105 |
|
106 | |
107 |
|
108 |
|
109 |
|
110 | protected options: LargeFileUploadTaskOptions;
|
111 |
|
112 | |
113 |
|
114 |
|
115 |
|
116 | protected uploadSession: LargeFileUploadSession;
|
117 |
|
118 | |
119 |
|
120 |
|
121 |
|
122 | protected nextRange: Range;
|
123 |
|
124 | |
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 |
|
134 |
|
135 | public static async createUploadSession(client: Client, requestUrl: string, payload: any, headers: KeyValuePairObjectStringNumber = {}): Promise<LargeFileUploadSession> {
|
136 | const session = await client
|
137 | .api(requestUrl)
|
138 | .headers(headers)
|
139 | .post(payload);
|
140 | const largeFileUploadSession: LargeFileUploadSession = {
|
141 | url: session.uploadUrl,
|
142 | expiry: new Date(session.expirationDateTime),
|
143 | isCancelled: false,
|
144 | };
|
145 | return largeFileUploadSession;
|
146 | }
|
147 |
|
148 | |
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 | public constructor(client: Client, file: FileObject<T>, uploadSession: LargeFileUploadSession, options: LargeFileUploadTaskOptions = {}) {
|
159 | this.client = client;
|
160 |
|
161 | if (!file.sliceFile) {
|
162 | throw new GraphClientError("Please pass the FileUpload object, StreamUpload object or any custom implementation of the FileObject interface");
|
163 | } else {
|
164 | this.file = file;
|
165 | }
|
166 | this.file = file;
|
167 | if (!options.rangeSize) {
|
168 | options.rangeSize = this.DEFAULT_FILE_SIZE;
|
169 | }
|
170 |
|
171 | this.options = options;
|
172 | this.uploadSession = uploadSession;
|
173 | this.nextRange = new Range(0, this.options.rangeSize - 1);
|
174 | }
|
175 |
|
176 | |
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 | private parseRange(ranges: string[]): Range {
|
183 | const rangeStr = ranges[0];
|
184 | if (typeof rangeStr === "undefined" || rangeStr === "") {
|
185 | return new Range();
|
186 | }
|
187 | const firstRange = rangeStr.split("-");
|
188 | const minVal = parseInt(firstRange[0], 10);
|
189 | let maxVal = parseInt(firstRange[1], 10);
|
190 | if (Number.isNaN(maxVal)) {
|
191 | maxVal = this.file.size - 1;
|
192 | }
|
193 | return new Range(minVal, maxVal);
|
194 | }
|
195 |
|
196 | |
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 | private updateTaskStatus(response: UploadStatusResponse): void {
|
203 | this.uploadSession.expiry = new Date(response.expirationDateTime);
|
204 | this.nextRange = this.parseRange(response.nextExpectedRanges);
|
205 | }
|
206 |
|
207 | |
208 |
|
209 |
|
210 |
|
211 |
|
212 | public getNextRange(): Range {
|
213 | if (this.nextRange.minValue === -1) {
|
214 | return this.nextRange;
|
215 | }
|
216 | const minVal = this.nextRange.minValue;
|
217 | let maxValue = minVal + this.options.rangeSize - 1;
|
218 | if (maxValue >= this.file.size) {
|
219 | maxValue = this.file.size - 1;
|
220 | }
|
221 | return new Range(minVal, maxValue);
|
222 | }
|
223 |
|
224 | |
225 |
|
226 |
|
227 |
|
228 |
|
229 |
|
230 |
|
231 | public sliceFile(range: Range): ArrayBuffer | Blob {
|
232 | console.warn("The LargeFileUploadTask.sliceFile() function has been deprecated and moved into the FileObject interface.");
|
233 | if (this.file.content instanceof ArrayBuffer || this.file.content instanceof Blob || this.file.content instanceof Uint8Array) {
|
234 | return this.file.content.slice(range.minValue, range.maxValue + 1);
|
235 | }
|
236 | throw new GraphClientError("The LargeFileUploadTask.sliceFile() function expects only Blob, ArrayBuffer or Uint8Array file content. Please note that the sliceFile() function is deprecated.");
|
237 | }
|
238 |
|
239 | |
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 | public async upload(): Promise<UploadResult> {
|
246 | const uploadEventHandlers = this.options && this.options.uploadEventHandlers;
|
247 | while (!this.uploadSession.isCancelled) {
|
248 | const nextRange = this.getNextRange();
|
249 | if (nextRange.maxValue === -1) {
|
250 | const err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file");
|
251 | err.name = "Invalid Session";
|
252 | throw err;
|
253 | }
|
254 | const fileSlice = await this.file.sliceFile(nextRange);
|
255 | const rawResponse = await this.uploadSliceGetRawResponse(fileSlice, nextRange, this.file.size);
|
256 | if (!rawResponse) {
|
257 | throw new GraphClientError("Something went wrong! Large file upload slice response is null.");
|
258 | }
|
259 |
|
260 | const responseBody = await GraphResponseHandler.getResponse(rawResponse);
|
261 | |
262 |
|
263 |
|
264 |
|
265 | if (rawResponse.status === 201 || (rawResponse.status === 200 && responseBody.id)) {
|
266 | this.reportProgress(uploadEventHandlers, nextRange);
|
267 | return UploadResult.CreateUploadResult(responseBody, rawResponse.headers);
|
268 | }
|
269 |
|
270 | |
271 |
|
272 |
|
273 | const res: UploadStatusResponse = {
|
274 | expirationDateTime: responseBody.expirationDateTime || responseBody.ExpirationDateTime,
|
275 | nextExpectedRanges: responseBody.NextExpectedRanges || responseBody.nextExpectedRanges,
|
276 | };
|
277 | this.updateTaskStatus(res);
|
278 | this.reportProgress(uploadEventHandlers, nextRange);
|
279 | }
|
280 | }
|
281 |
|
282 | private reportProgress(uploadEventHandlers: UploadEventHandlers, nextRange: Range) {
|
283 | if (uploadEventHandlers && uploadEventHandlers.progress) {
|
284 | uploadEventHandlers.progress(nextRange, uploadEventHandlers.extraCallbackParam);
|
285 | }
|
286 | }
|
287 |
|
288 | |
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 | public async uploadSlice(fileSlice: ArrayBuffer | Blob | File, range: Range, totalSize: number): Promise<unknown> {
|
298 | return await this.client
|
299 | .api(this.uploadSession.url)
|
300 | .headers({
|
301 | "Content-Length": `${range.maxValue - range.minValue + 1}`,
|
302 | "Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`,
|
303 | "Content-Type": "application/octet-stream",
|
304 | })
|
305 | .put(fileSlice);
|
306 | }
|
307 |
|
308 | |
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 | public async uploadSliceGetRawResponse(fileSlice: unknown, range: Range, totalSize: number): Promise<Response> {
|
318 | return await this.client
|
319 | .api(this.uploadSession.url)
|
320 | .headers({
|
321 | "Content-Length": `${range.maxValue - range.minValue + 1}`,
|
322 | "Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`,
|
323 | "Content-Type": "application/octet-stream",
|
324 | })
|
325 | .responseType(ResponseType.RAW)
|
326 | .put(fileSlice);
|
327 | }
|
328 |
|
329 | |
330 |
|
331 |
|
332 |
|
333 |
|
334 |
|
335 | public async cancel(): Promise<unknown> {
|
336 | const cancelResponse = await this.client
|
337 | .api(this.uploadSession.url)
|
338 | .responseType(ResponseType.RAW)
|
339 | .delete();
|
340 | if (cancelResponse.status === 204) {
|
341 | this.uploadSession.isCancelled = true;
|
342 | }
|
343 | return cancelResponse;
|
344 | }
|
345 |
|
346 | |
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 | public async getStatus(): Promise<unknown> {
|
353 | const response = await this.client.api(this.uploadSession.url).get();
|
354 | this.updateTaskStatus(response);
|
355 | return response;
|
356 | }
|
357 |
|
358 | |
359 |
|
360 |
|
361 |
|
362 |
|
363 |
|
364 | public async resume(): Promise<unknown> {
|
365 | await this.getStatus();
|
366 | return await this.upload();
|
367 | }
|
368 |
|
369 | |
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 | public getUploadSession(): LargeFileUploadSession {
|
376 | return this.uploadSession;
|
377 | }
|
378 | }
|