-
Notifications
You must be signed in to change notification settings - Fork 3
/
OneDrive.js
3339 lines (3137 loc) · 142 KB
/
OneDrive.js
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// https://opensource.org/licenses/MIT
var __extends = (this && this.__extends) || function (d, b) {for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];function __() { this.constructor = d; }__.prototype = b.prototype;d.prototype = new __();};
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OneDrive = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (require, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var Constants = function () {
function Constants() {
}
Constants.SDK_VERSION_NUMBER = '7.2';
Constants.SDK_VERSION = 'js-v' + Constants.SDK_VERSION_NUMBER;
Constants.TYPE_BOOLEAN = 'boolean';
Constants.TYPE_FUNCTION = 'function';
Constants.TYPE_OBJECT = 'object';
Constants.TYPE_STRING = 'string';
Constants.TYPE_NUMBER = 'number';
Constants.VROOM_URL = 'https://api.onedrive.com/v1.0/';
Constants.VROOM_ENDPOINT_HINT = 'api.onedrive.com';
Constants.GRAPH_URL = 'https://graph.microsoft.com/v1.0/';
Constants.NONCE_LENGTH = 5;
Constants.CUSTOMER_TID = '9188040d-6c67-4c5b-b112-36a304b66dad';
Constants.DEFAULT_QUERY_ITEM_PARAMETER = 'select=id';
return Constants;
}();
exports.default = Constants;
}(require, exports));
},{}],2:[function(require,module,exports){
module.exports = function (require, exports, OneDriveApp_1, Oauth_1) {
'use strict';
var OneDrive = function () {
function OneDrive() {
}
OneDrive.open = function (options) {
OneDriveApp_1.default.open(options);
};
OneDrive.save = function (options) {
OneDriveApp_1.default.save(options);
};
return OneDrive;
}();
Oauth_1.onAuth();
return OneDrive;
}(require, exports, require('./OneDriveApp'), require('./controllers/Oauth'));
},{"./OneDriveApp":3,"./controllers/Oauth":7}],3:[function(require,module,exports){
(function (require, exports, ErrorHandler_1, ErrorType_1, Logging_1, OneDriveSdkError_1, Picker_1, Saver_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var OneDriveApp = function () {
function OneDriveApp() {
}
OneDriveApp.open = function (options) {
if (!OneDriveApp.isReady()) {
return;
}
if (!options) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.unknown, 'missing picker options')).exposeToPublic();
}
Logging_1.default.logMessage('open started');
var picker = new Picker_1.default(options);
picker.launchInvoker().then(function () {
OneDriveApp.reset();
});
};
OneDriveApp.save = function (options) {
if (!OneDriveApp.isReady()) {
return;
}
if (!options) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.unknown, 'missing saver options'));
}
Logging_1.default.logMessage('save started');
var saver = new Saver_1.default(options);
saver.launchInvoker().then(function () {
OneDriveApp.reset();
});
};
OneDriveApp.reset = function () {
OneDriveApp.checked = false;
};
OneDriveApp.isReady = function () {
if (OneDriveApp.checked) {
return false;
}
OneDriveApp.checked = true;
return true;
};
OneDriveApp.checked = false;
return OneDriveApp;
}();
exports.default = OneDriveApp;
}(require, exports, require('./utilities/ErrorHandler'), require('./models/ErrorType'), require('./utilities/Logging'), require('./models/OneDriveSdkError'), require('./controllers/Picker'), require('./controllers/Saver')));
},{"./controllers/Picker":8,"./controllers/Saver":10,"./models/ErrorType":13,"./models/OneDriveSdkError":16,"./utilities/ErrorHandler":26,"./utilities/Logging":27}],4:[function(require,module,exports){
(function (require, exports, ApiEndpoint_1, ErrorType_1, Logging_1, ObjectUtilities_1, OneDriveSdkError_1, StringUtilities_1, UrlUtilities_1, XHR_1, es6_promise_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var POLLING_INTERVAL = 100;
var POLLING_COUNTER = 5;
var MAXIMUM_POLLING_INTERVAL = 30 * 60 * 1000;
var ROOT_ID = 'root';
function getItem(item, apiRequestConfig, queryParameters) {
var getRequestUrl = buildPathToItem(item, apiRequestConfig.apiEndpointUrl);
if (queryParameters) {
getRequestUrl = UrlUtilities_1.appendToPath(getRequestUrl, '?' + queryParameters);
}
var xhr = new XHR_1.default({
url: getRequestUrl,
clientId: apiRequestConfig.clientId,
method: XHR_1.default.HTTP_GET,
apiEndpoint: apiRequestConfig.apiEndpoint,
headers: { 'Authorization': 'bearer ' + apiRequestConfig.accessToken }
});
Logging_1.default.logMessage('performing GET on item with id: ' + item.id);
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode) {
var itemInDetail = JSON.parse(xhr.responseText);
resolve(itemInDetail);
}, function (xhr, statusCode, timeout) {
reject({
errorCode: ErrorType_1.default[ErrorType_1.default.webRequestFailure],
message: 'HTTP error status: ' + statusCode
});
});
});
}
exports.getItem = getItem;
function getItems(items, apiRequestConfig, queryParameters) {
var filesPromises = [];
var processedFiles = {
webUrl: null,
value: []
};
for (var _i = 0, _a = items.value; _i < _a.length; _i++) {
var item = _a[_i];
filesPromises.push(getItem(item, apiRequestConfig, queryParameters));
}
return es6_promise_1.Promise.all(filesPromises).then(function (successFiles) {
processedFiles.value = successFiles;
return processedFiles;
}, function (error) {
Logging_1.default.logError('Received ajax error.', error);
return error;
});
}
exports.getItems = getItems;
function shareItem(item, apiRequestConfig, createLinkParameters) {
var shareRequestUrl = UrlUtilities_1.appendToPath(buildPathToItem(item, apiRequestConfig.apiEndpointUrl), StringUtilities_1.format('{0}.createLink', apiRequestConfig.apiActionNamingSpace));
var xhr = new XHR_1.default({
url: shareRequestUrl,
clientId: apiRequestConfig.clientId,
method: XHR_1.default.HTTP_POST,
apiEndpoint: apiRequestConfig.apiEndpoint,
headers: { 'Authorization': 'bearer ' + apiRequestConfig.accessToken },
json: JSON.stringify(createLinkParameters)
});
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode, url) {
Logging_1.default.logMessage(StringUtilities_1.format('POST createLink succeeded via path {0}', shareRequestUrl));
item.permissions = [JSON.parse(xhr.responseText)];
resolve(item);
}, function (xhr, statusCode, timeout) {
Logging_1.default.logMessage(StringUtilities_1.format('POST createLink failed via path {0}', shareRequestUrl));
reject({
errorCode: ErrorType_1.default[ErrorType_1.default.webRequestFailure],
message: statusCode
});
});
});
}
exports.shareItem = shareItem;
function shareItems(items, apiRequestConfig, createLinkParameters) {
var sharePromises = [];
var processedFiles = {
webUrl: null,
value: []
};
for (var _i = 0, _a = items.value; _i < _a.length; _i++) {
var item = _a[_i];
sharePromises.push(shareItem(item, apiRequestConfig, createLinkParameters));
}
return es6_promise_1.Promise.all(sharePromises).then(function (successFiles) {
processedFiles.value = successFiles;
return processedFiles;
}, function (error) {
Logging_1.default.logError('Received sharing error.', error);
return error;
});
}
exports.shareItems = shareItems;
function saveItemByFormUpload(folder, itemDescription, file, apiRequestConfig, progressCallback) {
var reader = null;
return new es6_promise_1.Promise(function (resolve, reject) {
if (window['File'] && file instanceof window['File']) {
reader = new FileReader();
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.unsupportedFeature, 'FileReader is not supported in this browser'));
}
reader.onerror = function (event) {
Logging_1.default.logError('failed to read or upload the file', event);
reject(new OneDriveSdkError_1.default(ErrorType_1.default.fileReaderFailure, 'failed to read or upload the file, see console log for details'));
};
reader.onload = function (event) {
var uploadUrl = UrlUtilities_1.appendToPath(buildPathToItem(folder, apiRequestConfig.apiEndpointUrl), 'children(\'' + itemDescription.name + '\')/content');
var queryParameters = {};
queryParameters['@name.conflictBehavior'] = itemDescription['@name.conflictBehavior'];
var requestHeaders = {};
requestHeaders['Authorization'] = 'bearer ' + apiRequestConfig.accessToken;
requestHeaders['Content-Type'] = 'multipart/form-data';
var xhr = new XHR_1.default({
url: UrlUtilities_1.appendQueryStrings(uploadUrl, queryParameters),
clientId: apiRequestConfig.clientId,
headers: requestHeaders,
apiEndpoint: apiRequestConfig.apiEndpoint
});
var data = event.target.result;
xhr.upload(data, function (xhr, statusCode) {
resolve({
webUrl: null,
value: [JSON.parse(xhr.responseText)]
});
}, function (xhr, statusCode, timeout) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('file uploading failed by form uplaod with HTTP status: {0}', statusCode)));
}, function (xhr, uploadProgress) {
progressCallback(uploadProgress.progressPercentage);
});
};
reader.readAsArrayBuffer(file);
});
}
exports.saveItemByFormUpload = saveItemByFormUpload;
function saveItemByUriUpload(folder, itemDescription, sourceUri, apiRequestConfig) {
if (apiRequestConfig.apiEndpoint === ApiEndpoint_1.default.filesV2 || apiRequestConfig.apiEndpoint === ApiEndpoint_1.default.graph_odb) {
return new es6_promise_1.Promise(function (resolve, reject) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.unsupportedFeature, 'URL upload not supported for OneDrive business'));
});
}
var uploadUrl = UrlUtilities_1.appendToPath(buildPathToItem(folder, apiRequestConfig.apiEndpointUrl), 'children');
var requestHeaders = {};
requestHeaders['Prefer'] = 'respond-async';
requestHeaders['Authorization'] = 'bearer ' + apiRequestConfig.accessToken;
itemDescription[getContentSourceUrl(apiRequestConfig.apiEndpoint)] = sourceUri;
itemDescription['file'] = {};
var xhr = new XHR_1.default({
url: uploadUrl,
clientId: apiRequestConfig.clientId,
method: XHR_1.default.HTTP_POST,
headers: requestHeaders,
json: JSON.stringify(itemDescription),
apiEndpoint: apiRequestConfig.apiEndpoint
});
if (UrlUtilities_1.isPathDataUrl(sourceUri)) {
return saveItemByDateUriUpload(xhr);
} else if (UrlUtilities_1.isPathFullUrl(sourceUri)) {
return saveItemByHttpUrlUpload(xhr).then(function (location) {
return beginPolling(location).then(function (resourceId) {
var file = { id: resourceId };
return getItem(file, apiRequestConfig).then(function (file) {
var response = {
webUrl: null,
value: [file]
};
return es6_promise_1.Promise.resolve(response);
});
});
});
}
}
exports.saveItemByUriUpload = saveItemByUriUpload;
function getUserTenantUrl(apiRequestConfig) {
var queryUrl = UrlUtilities_1.appendQueryString(UrlUtilities_1.appendToPath(apiRequestConfig.apiEndpointUrl, 'me'), '$select', 'mySite');
var requestHeaders = {};
requestHeaders['Authorization'] = 'bearer ' + apiRequestConfig.accessToken;
requestHeaders['Accept'] = 'application/json';
var xhr = new XHR_1.default({
url: queryUrl,
clientId: apiRequestConfig.clientId,
method: XHR_1.default.HTTP_GET,
headers: requestHeaders,
apiEndpoint: apiRequestConfig.apiEndpoint
});
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode) {
var response = ObjectUtilities_1.deserializeJSON(xhr.responseText);
if (response.mySite) {
resolve(response.mySite);
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, StringUtilities_1.format('Cannot find the personal tenant url, response text: {0}', xhr.responseText)));
}
}, function (xhr, statusCode, timeout) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('graph/me request failed, status code: \'{0}\', response text: \'{1}\'', XHR_1.default.statusCodeToString(statusCode), xhr.responseText)));
});
});
}
exports.getUserTenantUrl = getUserTenantUrl;
function saveItemByDateUriUpload(xhr) {
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode) {
if (statusCode === 200 || statusCode === 201) {
var uploadedFile = {
webUrl: null,
value: [ObjectUtilities_1.deserializeJSON(xhr.responseText)]
};
resolve(uploadedFile);
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('file uploading failed by data uri with HTTP status: {0}', statusCode)));
}
}, function (xhr, statusCode, timeout) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('file uploading failed with HTTP status: {0}', statusCode)));
});
});
}
function saveItemByHttpUrlUpload(xhr) {
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode) {
if (statusCode === 202) {
var location_1 = xhr.getResponseHeader('Location');
if (!location_1) {
reject({
errorCode: ErrorType_1.default.badResponse,
message: 'missing \'Location\' header on response'
});
}
resolve(location_1);
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('create upload by url job failed with HTTP status: {0}', statusCode)));
}
}, function (xhr, statusCode, timeout) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('create upload by url job failed with HTTP status: {0}', statusCode)));
});
});
}
function getContentSourceUrl(apiEndpoint) {
if (apiEndpoint === ApiEndpoint_1.default.graph_odb || apiEndpoint === ApiEndpoint_1.default.graph_odc) {
return '@microsoft.graph.sourceUrl';
} else {
return '@content.sourceUrl';
}
}
function beginPolling(location) {
return new es6_promise_1.Promise(function (resolve, reject) {
(function ping(retry, pollingInterval) {
if (!retry--) {
pollingInterval *= 2;
retry = POLLING_COUNTER;
}
pollForProgress(location).then(function (monitorResponse) {
if (monitorResponse.resourceId) {
resolve(monitorResponse.resourceId);
} else if (pollingInterval <= MAXIMUM_POLLING_INTERVAL) {
setTimeout(ping(retry, pollingInterval), pollingInterval);
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, 'polling the uploading job takes too much time'));
}
});
}(POLLING_COUNTER, POLLING_INTERVAL));
});
}
function pollForProgress(location) {
var xhr = new XHR_1.default({
url: location,
method: XHR_1.default.HTTP_GET
});
return new es6_promise_1.Promise(function (resolve, reject) {
xhr.start(function (xhr, statusCode) {
switch (statusCode) {
case 202:
case 200:
var successResponse = ObjectUtilities_1.deserializeJSON(xhr.responseText);
resolve(successResponse);
break;
default:
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('polling upload job failed with HTTP status: {0}', statusCode)));
}
}, function (xhr, statusCode, timeout) {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.webRequestFailure, StringUtilities_1.format('polling upload job failed with HTTP status: {0}', statusCode)));
});
});
}
function buildPathToItem(item, apiEndpointUrl) {
var subPath;
if (item.parentReference && item.parentReference.driveId) {
subPath = UrlUtilities_1.appendToPath('drives', item.parentReference.driveId);
} else {
subPath = 'drive';
}
subPath = UrlUtilities_1.appendToPath(subPath, item.id === ROOT_ID ? 'root' : 'items/' + item.id);
return UrlUtilities_1.appendToPath(apiEndpointUrl, subPath);
}
}(require, exports, require('../models/ApiEndpoint'), require('../models/ErrorType'), require('../utilities/Logging'), require('../utilities/ObjectUtilities'), require('../models/OneDriveSdkError'), require('../utilities/StringUtilities'), require('../utilities/UrlUtilities'), require('../utilities/XHR'), require('es6-promise')));
},{"../models/ApiEndpoint":11,"../models/ErrorType":13,"../models/OneDriveSdkError":16,"../utilities/Logging":27,"../utilities/ObjectUtilities":28,"../utilities/StringUtilities":30,"../utilities/UrlUtilities":32,"../utilities/XHR":33,"es6-promise":34}],5:[function(require,module,exports){
(function (require, exports, ApiEndpoint_1, ApiRequest_1, Constants_1, DomainHint_1, ErrorHandler_1, ErrorType_1, Logging_1, LoginCache_1, Oauth_1, OneDriveSdkError_1, PickerUX_1, Popup_1, es6_promise_1, StringUtilities_1, UrlUtilities_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var Invoker = function () {
function Invoker(invokerOptions) {
this.invokerOptions = invokerOptions;
this.popup = new Popup_1.default();
}
Invoker.prototype.launchInvoker = function () {
var _this = this;
var invokerOptions = this.invokerOptions;
return this.launch().catch(function (error) {
Logging_1.default.logError('Failed due to unknown error: ', error);
invokerOptions.error(error);
}).then(function () {
_this.cleanPopupAndIFrame();
});
};
Invoker.prototype.launch = function (switchAccount) {
var _this = this;
return this.buildOauthPromise(switchAccount).then(function (oauthResponse) {
if (oauthResponse && oauthResponse.type === 'cancel') {
return oauthResponse;
} else {
return _this.buildPickerUI(oauthResponse);
}
}).then(function (response) {
var invokerOptions = _this.invokerOptions;
var type = response.type;
if (!type) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, StringUtilities_1.format('received bad response from picker UX: {0}', JSON.stringify(response)))).exposeToPublic();
}
if (response.type === 'switch') {
return _this.launch(true);
} else if (response.type === 'success') {
var items = [];
var isMicrosoftApp = false;
for (var _i = 0, _a = response.items; _i < _a.length; _i++) {
var item = _a[_i];
if (item.driveItem && !isMicrosoftApp) {
isMicrosoftApp = true;
}
items.push(item);
}
var successResponse = {
webUrl: null,
value: items
};
var successPromise = void 0;
if (!invokerOptions.needAPICall() || isMicrosoftApp && invokerOptions.accessToken.toLowerCase() === 'rps') {
if (_this.invokerOptions.forceAuthenticate) {
_this.apiRequestConfig = _this.buildApiConfig();
}
successPromise = es6_promise_1.Promise.resolve(successResponse);
} else {
_this.apiRequestConfig = _this.buildApiConfig();
successPromise = _this.makeApiRequest(successResponse);
}
return successPromise.then(function (files) {
if (_this.oauthResponse) {
files.accessToken = _this.oauthResponse.accessToken;
}
if (_this.apiRequestConfig) {
files.apiEndpoint = _this.apiRequestConfig.apiEndpointUrl;
} else if (_this.loginHint && _this.loginHint.endpointHint === DomainHint_1.default.aad) {
files.apiEndpoint = Constants_1.default.GRAPH_URL;
}
invokerOptions.success(files);
return files;
});
} else if (response.type === 'cancel') {
invokerOptions.cancel();
return es6_promise_1.Promise.resolve({
webUrl: null,
value: null
});
}
});
};
Invoker.prototype.buildOauthPromise = function (switchAccount) {
var oauthPromise;
if (switchAccount || this.invokerOptions.needOauth()) {
oauthPromise = Oauth_1.auth(Oauth_1.buildOauthConfig(this.invokerOptions, switchAccount), this.popup);
} else {
oauthPromise = es6_promise_1.Promise.resolve(null);
}
return oauthPromise;
};
Invoker.prototype.buildPickerUI = function (oauthResponse) {
var _this = this;
var loginHint;
if (oauthResponse) {
this.oauthResponse = oauthResponse;
loginHint = LoginCache_1.updateLoginHint(this.invokerOptions.clientId, this.oauthResponse.idToken, this.invokerOptions);
} else {
if (this.invokerOptions.endpointHint !== DomainHint_1.default.msa && this.invokerOptions.endpointHint !== DomainHint_1.default.tenant) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.optionsError, 'must specify the endpointHint in advanced options as \'api.onedrive.com\' for customer picker or the url for business picker/tenant')).exposeToPublic();
}
var isConsumerAccount = this.invokerOptions.endpointHint === DomainHint_1.default.msa;
loginHint = {
loginHint: null,
timeStamp: null,
apiEndpoint: isConsumerAccount ? ApiEndpoint_1.default.msa : ApiEndpoint_1.default.filesV2,
endpointHint: isConsumerAccount ? DomainHint_1.default.msa : DomainHint_1.default.tenant,
isConsumerAccount: isConsumerAccount
};
}
this.loginHint = loginHint;
var tenantPromise;
if (loginHint.apiEndpoint === ApiEndpoint_1.default.graph_odb) {
tenantPromise = ApiRequest_1.getUserTenantUrl(this.buildApiConfig());
} else {
tenantPromise = es6_promise_1.Promise.resolve(undefined);
}
return tenantPromise.then(function (tenantUrl) {
_this.pickerUX = PickerUX_1.generatePickerUX(loginHint.apiEndpoint, loginHint.endpointHint === DomainHint_1.default.tenant ? _this.invokerOptions.siteUrl : tenantUrl);
var pickerUXConfig = _this.buildPickerUXConfig(_this.invokerOptions);
if (_this.invokerOptions.navEntryLocation) {
pickerUXConfig.entryLocation = _this.invokerOptions.navEntryLocation;
}
if (_this.invokerOptions.navSourceTypes) {
pickerUXConfig.sourceTypes = _this.invokerOptions.navSourceTypes;
}
if (_this.invokerOptions.linkType) {
pickerUXConfig.linkType = _this.invokerOptions.linkType;
}
pickerUXConfig.trapFocus = _this.invokerOptions.trapFocus;
return _this.pickerUX.invokePickerUX(pickerUXConfig, _this.popup);
});
};
Invoker.prototype.getApiRequestConfig = function () {
return this.apiRequestConfig;
};
Invoker.prototype.buildApiConfig = function () {
if (!this.loginHint) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.internalError, 'missing loginHint when trying to build API request')).exposeToPublic();
}
if (!this.oauthResponse && !this.invokerOptions.accessToken) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.internalError, 'missing access token when trying to build API request')).exposeToPublic();
}
var apiEndpointUrl = null;
var apiActionNamingSpace = null;
switch (this.loginHint.apiEndpoint) {
case ApiEndpoint_1.default.graph_odb:
case ApiEndpoint_1.default.graph_odc:
apiEndpointUrl = Constants_1.default.GRAPH_URL;
apiActionNamingSpace = 'microsoft.graph';
break;
case ApiEndpoint_1.default.msa:
apiEndpointUrl = Constants_1.default.VROOM_URL;
apiActionNamingSpace = 'action';
break;
case ApiEndpoint_1.default.filesV2:
apiEndpointUrl = UrlUtilities_1.appendToPath(this.invokerOptions.siteUrl, '_api/v2.0/');
apiActionNamingSpace = 'action';
break;
default:
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.internalError, 'apiEndpoint in loginHint is not correct'));
}
var apiRequestConfig = {
accessToken: this.oauthResponse ? this.oauthResponse.accessToken : this.invokerOptions.accessToken,
apiEndpoint: this.loginHint.apiEndpoint,
apiEndpointUrl: apiEndpointUrl,
apiActionNamingSpace: apiActionNamingSpace,
clientId: this.invokerOptions.clientId
};
return apiRequestConfig;
};
Invoker.prototype.cleanPopupAndIFrame = function () {
if (this.popup) {
this.popup.close();
}
if (this.pickerUX) {
this.pickerUX.removeIFrame();
}
};
return Invoker;
}();
exports.default = Invoker;
}(require, exports, require('../models/ApiEndpoint'), require('./ApiRequest'), require('../Constants'), require('../models/DomainHint'), require('../utilities/ErrorHandler'), require('../models/ErrorType'), require('../utilities/Logging'), require('./LoginCache'), require('./Oauth'), require('../models/OneDriveSdkError'), require('./PickerUX'), require('../utilities/Popup'), require('es6-promise'), require('../utilities/StringUtilities'), require('../utilities/UrlUtilities')));
},{"../Constants":1,"../models/ApiEndpoint":11,"../models/DomainHint":12,"../models/ErrorType":13,"../models/OneDriveSdkError":16,"../utilities/ErrorHandler":26,"../utilities/Logging":27,"../utilities/Popup":29,"../utilities/StringUtilities":30,"../utilities/UrlUtilities":32,"./ApiRequest":4,"./LoginCache":6,"./Oauth":7,"./PickerUX":9,"es6-promise":34}],6:[function(require,module,exports){
(function (require, exports, ApiEndpoint_1, Cache_1, Constants_1, DomainHint_1, ErrorHandler_1, ErrorType_1, OneDriveSdkError_1, ObjectUtilities_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var ACCESS_TOKEN_LIFESPAN = 3600000;
var ID_TOKEN_TID = 'tid';
var ID_TOKEN_PREFERRED_USERNAME = 'preferred_username';
var LOGINHINT_KEY = 'odsdkLoginHint';
var LOGINHINT_ITEM_PREFIX = 'od7-';
function getLoginHint(invokerOptions) {
if (!invokerOptions) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.optionsError, 'invoker option is not defined!'));
}
var loginCache = Cache_1.getCacheItem(LOGINHINT_KEY) || {};
var loginHint = loginCache[LOGINHINT_ITEM_PREFIX + invokerOptions.clientId];
if (!loginHint) {
return null;
}
if (invokerOptions.endpointHint !== loginHint.endpointHint) {
return null;
}
if (invokerOptions.loginHint && invokerOptions.loginHint !== loginHint.loginHint) {
return null;
}
return loginHint;
}
exports.getLoginHint = getLoginHint;
function loginHintExpired() {
var loginHint = Cache_1.getCacheItem(LOGINHINT_KEY);
return new Date().getTime() - loginHint.timeStamp > ACCESS_TOKEN_LIFESPAN;
}
exports.loginHintExpired = loginHintExpired;
function updateLoginHint(clientId, idToken, invokerOptions) {
var loginHint;
var endpointHint;
var apiEndpoint;
var isConsumerAccount;
switch (invokerOptions.endpointHint) {
case DomainHint_1.default.aad:
var idTokenObj = this.parseIdToken(idToken);
loginHint = idTokenObj.preferredUserName;
if (idTokenObj.tid === Constants_1.default.CUSTOMER_TID) {
apiEndpoint = ApiEndpoint_1.default.graph_odc;
isConsumerAccount = true;
} else {
apiEndpoint = ApiEndpoint_1.default.graph_odb;
isConsumerAccount = false;
}
endpointHint = DomainHint_1.default.aad;
break;
case DomainHint_1.default.msa:
apiEndpoint = ApiEndpoint_1.default.msa;
endpointHint = DomainHint_1.default.msa;
loginHint = invokerOptions.loginHint;
isConsumerAccount = true;
break;
case DomainHint_1.default.tenant:
apiEndpoint = ApiEndpoint_1.default.filesV2;
endpointHint = DomainHint_1.default.tenant;
loginHint = invokerOptions.loginHint;
isConsumerAccount = false;
break;
}
var newLoginHint = {
apiEndpoint: apiEndpoint,
loginHint: loginHint,
endpointHint: endpointHint,
timeStamp: new Date().getTime(),
isConsumerAccount: isConsumerAccount
};
var loginCache = Cache_1.getCacheItem(LOGINHINT_KEY) || {};
loginCache[LOGINHINT_ITEM_PREFIX + clientId] = newLoginHint;
Cache_1.setCacheItem(LOGINHINT_KEY, loginCache);
return newLoginHint;
}
exports.updateLoginHint = updateLoginHint;
function parseIdToken(idToken) {
if (!idToken) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'id_token is missing in oauth response'));
}
var userInfoPart = idToken.split('.')[1];
var urlFriendlyValue = userInfoPart.replace('-', '+').replace('_', '/');
var userInfo = ObjectUtilities_1.deserializeJSON(atob(urlFriendlyValue));
if (!userInfo[ID_TOKEN_TID]) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'tid is missing in id_token response'));
}
if (!userInfo[ID_TOKEN_PREFERRED_USERNAME]) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'preferred_username is missing in id_token response'));
}
return {
tid: userInfo[ID_TOKEN_TID],
preferredUserName: userInfo[ID_TOKEN_PREFERRED_USERNAME]
};
}
exports.parseIdToken = parseIdToken;
}(require, exports, require('../models/ApiEndpoint'), require('../utilities/Cache'), require('../Constants'), require('../models/DomainHint'), require('../utilities/ErrorHandler'), require('../models/ErrorType'), require('../models/OneDriveSdkError'), require('../utilities/ObjectUtilities')));
},{"../Constants":1,"../models/ApiEndpoint":11,"../models/DomainHint":12,"../models/ErrorType":13,"../models/OneDriveSdkError":16,"../utilities/Cache":22,"../utilities/ErrorHandler":26,"../utilities/ObjectUtilities":28}],7:[function(require,module,exports){
(function (require, exports, Channel_1, DomainHint_1, DomUtilities_1, ErrorHandler_1, ErrorType_1, LoginCache_1, OauthEndpoint_1, OneDriveSdkError_1, es6_promise_1, UrlUtilities_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var PARAM_ACCESS_TOKEN = 'access_token';
var PARAM_ERROR = 'error';
var PARAM_ERROR_DESCRIPTION = 'error_description';
var PARAM_ID_TOKEN = 'id_token';
var PARAM_OAUTH_CONFIG = 'oauth';
var PARAM_STATE = 'state';
var AAD_OAUTH_ENDPOINT = 'https://login.microsoftonline.com/common/oauth2/authorize';
var AADV2_OAUTH_ENDPOINT = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
var MSA_OAUTH_ENDPONT = 'https://login.live.com/oauth20_authorize.srf';
var OAUTH_RESPONSE_HEADER = '[OneDriveSDK-OauthResponse]';
function onAuth() {
DomUtilities_1.onDocumentReady(function () {
var redirResults = UrlUtilities_1.readCurrentUrlParameters();
var isOauth = !!redirResults[PARAM_OAUTH_CONFIG] || (!!redirResults[PARAM_ERROR] || !!redirResults[PARAM_ACCESS_TOKEN]) && !!redirResults[PARAM_STATE];
if (isOauth && window.opener) {
handleOauth(redirResults, new Channel_1.default(window.opener));
}
});
}
exports.onAuth = onAuth;
function handleOauth(redirResults, channel) {
DomUtilities_1.displayOverlay();
if (redirResults[PARAM_OAUTH_CONFIG]) {
redirectToOauthPage(JSON.parse(redirResults[PARAM_OAUTH_CONFIG]));
} else if (redirResults[PARAM_ERROR]) {
sendResponseToParent(generateErrorResponse(redirResults), channel);
} else if (redirResults[PARAM_ACCESS_TOKEN]) {
sendResponseToParent(generateSuccessResponse(redirResults), channel);
}
}
exports.handleOauth = handleOauth;
function generateErrorResponse(redirResults) {
var error = new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, redirResults[PARAM_ERROR_DESCRIPTION]);
return {
type: 'error',
error: error,
state: redirResults[PARAM_STATE]
};
}
function generateSuccessResponse(redirResults) {
return {
type: 'success',
accessToken: redirResults[PARAM_ACCESS_TOKEN],
idToken: redirResults[PARAM_ID_TOKEN],
state: redirResults[PARAM_STATE]
};
}
function sendResponseToParent(response, channel) {
if (response.state) {
var responseFragment = response.state.split('_');
if (responseFragment.length !== 2) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'received bad state parameter from Oauth endpoint, state received: ' + response.state)).exposeToPublic();
}
if (channel) {
channel.send(OAUTH_RESPONSE_HEADER + JSON.stringify(response), '*');
} else {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.popupOpen, 'opener is not defined')).exposeToPublic();
}
} else {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'missing state parameter from Oauth redirect')).exposeToPublic();
}
}
function redirectToOauthPage(oauthConfig) {
var url;
switch (oauthConfig.endpoint) {
case OauthEndpoint_1.default.AAD:
url = buildAADOauthUrl(oauthConfig);
break;
case OauthEndpoint_1.default.AADv2:
url = buildAADOauthV2Url(oauthConfig);
break;
case OauthEndpoint_1.default.MSA:
url = buildMSAOauthUrl(oauthConfig);
break;
default:
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.badResponse, 'received bad oauth endpoint, endpoint value is: ' + oauthConfig.endpoint));
break;
}
if (oauthConfig.switchAccount) {
url = UrlUtilities_1.appendQueryString(url, 'prompt', 'select_account');
} else if (oauthConfig.loginHint) {
url = UrlUtilities_1.appendQueryString(url, 'login_hint', oauthConfig.loginHint);
url = UrlUtilities_1.appendQueryString(url, 'domain_hint', oauthConfig.isConsumerAccount ? 'consumers' : 'organizations');
}
UrlUtilities_1.redirect(url);
}
function buildAADOauthUrl(config) {
return UrlUtilities_1.appendQueryStrings(AAD_OAUTH_ENDPOINT, {
redirect_uri: config.redirectUri,
client_id: config.clientId,
response_type: 'token',
state: config.state,
resource: config.resource || config.origin
});
}
function buildAADOauthV2Url(config) {
var scope = 'profile openid https://graph.microsoft.com/User.Read ' + config.scopes.map(function (s) {
return 'https://graph.microsoft.com/' + s;
}).join(' ');
var url = UrlUtilities_1.appendQueryStrings(AADV2_OAUTH_ENDPOINT, {
redirect_uri: config.redirectUri,
client_id: config.clientId,
scope: scope,
response_mode: 'fragment',
state: config.state,
nonce: UrlUtilities_1.generateNonce()
});
url += '&response_type=id_token+token';
return url;
}
function buildMSAOauthUrl(config) {
var needWritePermission = false;
for (var _i = 0, _a = config.scopes; _i < _a.length; _i++) {
var scope = _a[_i];
needWritePermission = needWritePermission || scope.toLowerCase().indexOf('readwrite') > 1;
}
return UrlUtilities_1.appendQueryStrings(MSA_OAUTH_ENDPONT, {
redirect_uri: config.redirectUri,
client_id: config.clientId,
response_type: 'token',
state: config.state,
scope: 'onedrive.' + (needWritePermission ? 'readwrite' : 'readonly')
});
}
function auth(config, popupView) {
var state = document.location.origin + '_' + UrlUtilities_1.generateNonce();
config.state = state;
return new es6_promise_1.Promise(function (resolve, reject) {
var listenerId = DomUtilities_1.onMessage(function (event) {
if (event.data && event.data.indexOf(OAUTH_RESPONSE_HEADER) === 0) {
var responseData = JSON.parse(event.data.substring(OAUTH_RESPONSE_HEADER.length));
if (responseData.state === state && event.source === popupView.getPopupWindow()) {
DomUtilities_1.removeMessageListener(listenerId);
if (responseData.type === 'error' || responseData.error) {
var errorCode = ErrorType_1.default[responseData.error.errorCode];
reject(new OneDriveSdkError_1.default(errorCode, responseData.error.message));
} else {
resolve(responseData);
}
} else {
reject(new OneDriveSdkError_1.default(ErrorType_1.default.popupOpen, 'Another popup is already opened.'));
}
}
});
return popupView.openPopup(UrlUtilities_1.appendQueryString(config.redirectUri, PARAM_OAUTH_CONFIG, JSON.stringify(config))).then(function () {
resolve({
type: 'cancel',
state: state
});
});
});
}
exports.auth = auth;
function buildOauthConfig(invokerOptions, switchAccount) {
var endpoint;
switch (invokerOptions.endpointHint) {
case DomainHint_1.default.aad:
endpoint = OauthEndpoint_1.default.AADv2;
break;
case DomainHint_1.default.msa:
endpoint = OauthEndpoint_1.default.MSA;
break;
case DomainHint_1.default.tenant:
endpoint = OauthEndpoint_1.default.AAD;
break;
}
var scopes = invokerOptions.scopes.map(function (s) {
return s + (s.indexOf('Files.') > -1 && invokerOptions.needSharePointPermission ? '.All' : '');
});
var oauthConfig = {
clientId: invokerOptions.clientId,
endpoint: endpoint,
scopes: scopes,
origin: window.location.origin,
redirectUri: invokerOptions.redirectUri,
switchAccount: switchAccount,
resource: invokerOptions.resource
};
var loginHint = LoginCache_1.getLoginHint(invokerOptions);
if (invokerOptions.loginHint) {
oauthConfig.loginHint = invokerOptions.loginHint;
oauthConfig.isConsumerAccount = invokerOptions.isConsumerAccount;
} else if (loginHint) {
oauthConfig.loginHint = loginHint.loginHint;
oauthConfig.isConsumerAccount = loginHint.isConsumerAccount;
}
return oauthConfig;
}
exports.buildOauthConfig = buildOauthConfig;
}(require, exports, require('../utilities/Channel'), require('../models/DomainHint'), require('../utilities/DomUtilities'), require('../utilities/ErrorHandler'), require('../models/ErrorType'), require('./LoginCache'), require('../models/OauthEndpoint'), require('../models/OneDriveSdkError'), require('es6-promise'), require('../utilities/UrlUtilities')));
},{"../models/DomainHint":12,"../models/ErrorType":13,"../models/OauthEndpoint":15,"../models/OneDriveSdkError":16,"../utilities/Channel":24,"../utilities/DomUtilities":25,"../utilities/ErrorHandler":26,"../utilities/UrlUtilities":32,"./LoginCache":6,"es6-promise":34}],8:[function(require,module,exports){
(function (require, exports, ApiEndpoint_1, ApiRequest_1, Constants_1, Invoker_1, ObjectUtilities_1, PickerOptions_1, PickerActionType_1, StringUtilities_1, UrlUtilities_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var Picker = function (_super) {
__extends(Picker, _super);
function Picker(options) {
var _this = this;
var clonedOptions = ObjectUtilities_1.shallowClone(options);
var pickerOptions = new PickerOptions_1.default(clonedOptions);
_this = _super.call(this, pickerOptions) || this;
return _this;
}
Picker.prototype.buildPickerUXConfig = function (pickerOptions) {
var pickerUXConfig = {
applicationId: pickerOptions.clientId,
accessLevel: Picker.ACCESS_LEVEL,
filter: pickerOptions.filter,
id: UrlUtilities_1.generateNonce(),
navEnabled: pickerOptions.navEnabled,
origin: window.location.origin,
parentDiv: pickerOptions.parentDiv,
redirectUri: pickerOptions.redirectUri,
selectionMode: pickerOptions.multiSelect ? 'multiple' : 'single',
viewType: pickerOptions.viewType || 'files',
accountSwitchEnabled: pickerOptions.accountSwitchEnabled,
commandMode: pickerOptions.commandMode
};
return pickerUXConfig;
};
Picker.prototype.makeApiRequest = function (files) {
if (this.invokerOptions.action === PickerActionType_1.default.share) {
return this.shareItems(files);
} else {
var isDownload = this.invokerOptions.action === PickerActionType_1.default.download;
return this.queryItems(files, isDownload);
}
};
Picker.prototype.queryItems = function (files, isDownload) {
var itemQuery = this.invokerOptions.queryParameters || Constants_1.default.DEFAULT_QUERY_ITEM_PARAMETER;
if (isDownload) {
itemQuery = StringUtilities_1.format('{0}{1}{2}', itemQuery, itemQuery.indexOf('select') === -1 ? '&select=' : ',', 'name,size,@content.downloadUrl');
}
return ApiRequest_1.getItems(files, this.getApiRequestConfig(), itemQuery);
};
Picker.prototype.shareItems = function (files) {
var _this = this;
var pickerOptions = this.invokerOptions;
var createLinkParameters = pickerOptions.createLinkParameters || this.getDefaultSharingConfig();
return ApiRequest_1.getItems(files, this.getApiRequestConfig()).then(function (files) {
return ApiRequest_1.shareItems(files, _this.getApiRequestConfig(), createLinkParameters);
});
};
Picker.prototype.getDefaultSharingConfig = function () {
var createLinkParameters = { 'type': 'view' };
if (this.getApiRequestConfig().apiEndpoint === ApiEndpoint_1.default.graph_odc || this.getApiRequestConfig().apiEndpoint === ApiEndpoint_1.default.msa) {
return createLinkParameters;
}
createLinkParameters['scope'] = 'organization';
return createLinkParameters;
};
Picker.ACCESS_LEVEL = 'read';
return Picker;
}(Invoker_1.default);
exports.default = Picker;
}(require, exports, require('../models/ApiEndpoint'), require('./ApiRequest'), require('../Constants'), require('./Invoker'), require('../utilities/ObjectUtilities'), require('../models/PickerOptions'), require('../models/PickerActionType'), require('../utilities/StringUtilities'), require('../utilities/UrlUtilities')));
},{"../Constants":1,"../models/ApiEndpoint":11,"../models/PickerActionType":17,"../models/PickerOptions":18,"../utilities/ObjectUtilities":28,"../utilities/StringUtilities":30,"../utilities/UrlUtilities":32,"./ApiRequest":4,"./Invoker":5}],9:[function(require,module,exports){
(function (require, exports, ApiEndpoint_1, Channel_1, DomUtilities_1, ErrorHandler_1, ErrorType_1, Logging_1, OneDriveSdkError_1, UrlUtilities_1, es6_promise_1, Constants_1) {
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var CUSTOMER_PICKER_BASE_URL = 'https://onedrive.live.com/';
var RESPONSE_PREFIX = '[OneDrive-FromPicker]';
var MESSAGE_PREFIX = '[OneDrive-ToPicker]';
var INITIALIZE_RESPONSE = 'initialize';
function generatePickerUX(apiEndpoint, tenantUrl) {
return new PickerUX(apiEndpoint, tenantUrl);
}
exports.generatePickerUX = generatePickerUX;
var PickerUX = function () {
function PickerUX(apiEndpoint, tenantUrl) {
if (apiEndpoint === ApiEndpoint_1.default.graph_odc || apiEndpoint === ApiEndpoint_1.default.msa) {
this.url = UrlUtilities_1.appendQueryStrings(CUSTOMER_PICKER_BASE_URL, { 'v': '2' });
} else if (apiEndpoint === ApiEndpoint_1.default.graph_odb || apiEndpoint === ApiEndpoint_1.default.filesV2) {
if (!tenantUrl) {
ErrorHandler_1.throwError(new OneDriveSdkError_1.default(ErrorType_1.default.optionsError, 'the site url must be specified')).exposeToPublic();
}
UrlUtilities_1.validateUrlProtocol(tenantUrl, ['HTTPS']);
if (apiEndpoint === ApiEndpoint_1.default.graph_odb) {
tenantUrl = UrlUtilities_1.appendToPath(tenantUrl, '_layouts/onedrive.aspx');
}
this.url = UrlUtilities_1.appendQueryString(tenantUrl, 'p', '2');
}
}
PickerUX.prototype.invokePickerUX = function (uxConfig, popupView) {
var _this = this;
var pickerUXPromise = new es6_promise_1.Promise(function (resolve, reject) {
var channelId = DomUtilities_1.onMessage(function (event) {
var urlParts = _this.url.split('/');
var channel = new Channel_1.default(_this.iframe ? _this.iframe.contentWindow : popupView.getPopupWindow());
if (event.origin === urlParts[0] + '//' + urlParts[2]) {
var message = '' + (event.data || '');
if (message.indexOf(RESPONSE_PREFIX) === 0 && event.source === channel.getReceiver()) {
var response = JSON.parse(message.substring(RESPONSE_PREFIX.length));
var pickerId = response.pickerId, conversationId = response.conversationId, type = response.type;
if (pickerId === uxConfig.id) {
if (type === INITIALIZE_RESPONSE) {
channel.send(MESSAGE_PREFIX + JSON.stringify({
pickerId: pickerId,
conversationId: conversationId,
type: 'activate'
}), event.origin);
} else {
resolve(response);
DomUtilities_1.removeMessageListener(channelId);
}
}
}
}
});
var pickerOption = {
aid: uxConfig.applicationId,
a: uxConfig.accessLevel,
id: uxConfig.id,
l: uxConfig.linkType,
ln: uxConfig.navEnabled,
s: uxConfig.selectionMode,
f: uxConfig.filter,
v: uxConfig.viewType,
ru: uxConfig.redirectUri,
o: uxConfig.origin,
sdk: Constants_1.default.SDK_VERSION_NUMBER,
e: uxConfig.entryLocation,
st: uxConfig.sourceTypes,
sn: !uxConfig.parentDiv,
ss: uxConfig.parentDiv ? false : uxConfig.accountSwitchEnabled,
tf: uxConfig.trapFocus,
cm: uxConfig.commandMode
};
var pickerUrl = UrlUtilities_1.appendQueryString(_this.url, 'picker', JSON.stringify(pickerOption));