-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbce-bos-uploader-lite.js
5596 lines (4694 loc) · 400 KB
/
bce-bos-uploader-lite.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
(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.baidubce = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file bce-bos-uploader/index.js
* @author leeight
*/
var Q = require(44);
var BosClient = require(17);
var Auth = require(15);
var Uploader = require(31);
var utils = require(32);
module.exports = {
bos: {
Uploader: Uploader
},
utils: utils,
sdk: {
Q: Q,
BosClient: BosClient,
Auth: Auth
}
};
},{"15":15,"17":17,"31":31,"32":32,"44":44}],2:[function(require,module,exports){
'use strict';
var mapAsync = require(9);
var doParallelLimit = require(3);
module.exports = doParallelLimit(mapAsync);
},{"3":3,"9":9}],3:[function(require,module,exports){
'use strict';
var eachOfLimit = require(4);
module.exports = function doParallelLimit(fn) {
return function(obj, limit, iterator, cb) {
return fn(eachOfLimit(limit), obj, iterator, cb);
};
};
},{"4":4}],4:[function(require,module,exports){
var once = require(11);
var noop = require(10);
var onlyOnce = require(12);
var keyIterator = require(7);
module.exports = function eachOfLimit(limit) {
return function(obj, iterator, cb) {
cb = once(cb || noop);
obj = obj || [];
var nextKey = keyIterator(obj);
if (limit <= 0) {
return cb(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish() {
if (done && running <= 0) {
return cb(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
cb(null);
}
return;
}
running += 1;
iterator(obj[key], key, onlyOnce(function(err) {
running -= 1;
if (err) {
cb(err);
errored = true;
} else {
replenish();
}
}));
}
})();
};
};
},{"10":10,"11":11,"12":12,"7":7}],5:[function(require,module,exports){
'use strict';
module.exports = Array.isArray || function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
},{}],6:[function(require,module,exports){
'use strict';
var isArray = require(5);
module.exports = function isArrayLike(arr) {
return isArray(arr) || (
// has a positive integer length property
typeof arr.length === 'number' &&
arr.length >= 0 &&
arr.length % 1 === 0
);
};
},{"5":5}],7:[function(require,module,exports){
'use strict';
var _keys = require(8);
var isArrayLike = require(6);
module.exports = function keyIterator(coll) {
var i = -1;
var len;
var keys;
if (isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
};
},{"6":6,"8":8}],8:[function(require,module,exports){
'use strict';
module.exports = Object.keys || function keys(obj) {
var _keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
_keys.push(k);
}
}
return _keys;
};
},{}],9:[function(require,module,exports){
'use strict';
var once = require(11);
var noop = require(10);
var isArrayLike = require(6);
module.exports = function mapAsync(eachfn, arr, iterator, cb) {
cb = once(cb || noop);
arr = arr || [];
var results = isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, cb) {
iterator(value, function (err, v) {
results[index] = v;
cb(err);
});
}, function (err) {
cb(err, results);
});
};
},{"10":10,"11":11,"6":6}],10:[function(require,module,exports){
'use strict';
module.exports = function noop () {};
},{}],11:[function(require,module,exports){
'use strict';
module.exports = function once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
};
},{}],12:[function(require,module,exports){
'use strict';
module.exports = function only_once(fn) {
return function() {
if (fn === null) throw new Error('Callback was already called.');
fn.apply(this, arguments);
fn = null;
};
};
},{}],13:[function(require,module,exports){
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
* as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && objectToString.call(value) == numberTag);
}
module.exports = isNumber;
},{}],14:[function(require,module,exports){
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],15:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file src/auth.js
* @author leeight
*/
/* eslint-env node */
/* eslint max-params:[0,10] */
var helper = require(42);
var util = require(47);
var u = require(46);
var H = require(19);
var strings = require(22);
/**
* Auth
*
* @constructor
* @param {string} ak The access key.
* @param {string} sk The security key.
*/
function Auth(ak, sk) {
this.ak = ak;
this.sk = sk;
}
/**
* Generate the signature based on http://gollum.baidu.com/AuthenticationMechanism
*
* @param {string} method The http request method, such as GET, POST, DELETE, PUT, ...
* @param {string} resource The request path.
* @param {Object=} params The query strings.
* @param {Object=} headers The http request headers.
* @param {number=} timestamp Set the current timestamp.
* @param {number=} expirationInSeconds The signature validation time.
* @param {Array.<string>=} headersToSign The request headers list which will be used to calcualate the signature.
*
* @return {string} The signature.
*/
Auth.prototype.generateAuthorization = function (method, resource, params,
headers, timestamp, expirationInSeconds, headersToSign) {
var now = timestamp ? new Date(timestamp * 1000) : new Date();
var rawSessionKey = util.format('bce-auth-v1/%s/%s/%d',
this.ak, helper.toUTCString(now), expirationInSeconds || 1800);
var sessionKey = this.hash(rawSessionKey, this.sk);
var canonicalUri = this.uriCanonicalization(resource);
var canonicalQueryString = this.queryStringCanonicalization(params || {});
var rv = this.headersCanonicalization(headers || {}, headersToSign);
var canonicalHeaders = rv[0];
var signedHeaders = rv[1];
var rawSignature = util.format('%s\n%s\n%s\n%s',
method, canonicalUri, canonicalQueryString, canonicalHeaders);
var signature = this.hash(rawSignature, sessionKey);
if (signedHeaders.length) {
return util.format('%s/%s/%s', rawSessionKey, signedHeaders.join(';'), signature);
}
return util.format('%s//%s', rawSessionKey, signature);
};
Auth.prototype.uriCanonicalization = function (uri) {
return uri;
};
/**
* Canonical the query strings.
*
* @see http://gollum.baidu.com/AuthenticationMechanism#生成CanonicalQueryString
* @param {Object} params The query strings.
* @return {string}
*/
Auth.prototype.queryStringCanonicalization = function (params) {
var canonicalQueryString = [];
u.each(u.keys(params), function (key) {
if (key.toLowerCase() === H.AUTHORIZATION.toLowerCase()) {
return;
}
var value = params[key] == null ? '' : params[key];
canonicalQueryString.push(key + '=' + strings.normalize(value));
});
canonicalQueryString.sort();
return canonicalQueryString.join('&');
};
/**
* Canonical the http request headers.
*
* @see http://gollum.baidu.com/AuthenticationMechanism#生成CanonicalHeaders
* @param {Object} headers The http request headers.
* @param {Array.<string>=} headersToSign The request headers list which will be used to calcualate the signature.
* @return {*} canonicalHeaders and signedHeaders
*/
Auth.prototype.headersCanonicalization = function (headers, headersToSign) {
if (!headersToSign || !headersToSign.length) {
headersToSign = [H.HOST, H.CONTENT_MD5, H.CONTENT_LENGTH, H.CONTENT_TYPE];
}
var headersMap = {};
u.each(headersToSign, function (item) {
headersMap[item.toLowerCase()] = true;
});
var canonicalHeaders = [];
u.each(u.keys(headers), function (key) {
var value = headers[key];
value = u.isString(value) ? strings.trim(value) : value;
if (value == null || value === '') {
return;
}
key = key.toLowerCase();
if (/^x\-bce\-/.test(key) || headersMap[key] === true) {
canonicalHeaders.push(util.format('%s:%s',
// encodeURIComponent(key), encodeURIComponent(value)));
strings.normalize(key), strings.normalize(value)));
}
});
canonicalHeaders.sort();
var signedHeaders = [];
u.each(canonicalHeaders, function (item) {
signedHeaders.push(item.split(':')[0]);
});
return [canonicalHeaders.join('\n'), signedHeaders];
};
Auth.prototype.hash = function (data, key) {
var crypto = require(40);
var sha256Hmac = crypto.createHmac('sha256', key);
sha256Hmac.update(data);
return sha256Hmac.digest('hex');
};
module.exports = Auth;
},{"19":19,"22":22,"40":40,"42":42,"46":46,"47":47}],16:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file src/bce_base_client.js
* @author leeight
*/
/* eslint-env node */
var EventEmitter = require(41).EventEmitter;
var util = require(47);
var Q = require(44);
var u = require(46);
var config = require(18);
var Auth = require(15);
/**
* BceBaseClient
*
* @constructor
* @param {Object} clientConfig The bce client configuration.
* @param {string} serviceId The service id.
* @param {boolean=} regionSupported The service supported region or not.
*/
function BceBaseClient(clientConfig, serviceId, regionSupported) {
EventEmitter.call(this);
this.config = u.extend({}, config.DEFAULT_CONFIG, clientConfig);
this.serviceId = serviceId;
this.regionSupported = !!regionSupported;
this.config.endpoint = this._computeEndpoint();
/**
* @type {HttpClient}
*/
this._httpAgent = null;
}
util.inherits(BceBaseClient, EventEmitter);
BceBaseClient.prototype._computeEndpoint = function () {
if (this.config.endpoint) {
return this.config.endpoint;
}
if (this.regionSupported) {
return util.format('%s://%s.%s.%s',
this.config.protocol,
this.serviceId,
this.config.region,
config.DEFAULT_SERVICE_DOMAIN);
}
return util.format('%s://%s.%s',
this.config.protocol,
this.serviceId,
config.DEFAULT_SERVICE_DOMAIN);
};
BceBaseClient.prototype.createSignature = function (credentials, httpMethod, path, params, headers) {
return Q.fcall(function () {
var auth = new Auth(credentials.ak, credentials.sk);
return auth.generateAuthorization(httpMethod, path, params, headers);
});
};
module.exports = BceBaseClient;
},{"15":15,"18":18,"41":41,"44":44,"46":46,"47":47}],17:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file src/bos_client.js
* @author leeight
*/
/* eslint-env node */
/* eslint max-params:[0,10] */
var path = require(43);
var util = require(47);
var u = require(46);
var Buffer = require(33);
var H = require(19);
var strings = require(22);
var HttpClient = require(20);
var BceBaseClient = require(16);
var MimeType = require(21);
var MAX_PUT_OBJECT_LENGTH = 5368709120; // 5G
var MAX_USER_METADATA_SIZE = 2048; // 2 * 1024
/**
* BOS service api
*
* @see http://gollum.baidu.com/BOS_API#BOS-API文档
*
* @constructor
* @param {Object} config The bos client configuration.
* @extends {BceBaseClient}
*/
function BosClient(config) {
BceBaseClient.call(this, config, 'bos', true);
/**
* @type {HttpClient}
*/
this._httpAgent = null;
}
util.inherits(BosClient, BceBaseClient);
// --- B E G I N ---
BosClient.prototype.deleteObject = function (bucketName, key, options) {
options = options || {};
return this.sendRequest('DELETE', {
bucketName: bucketName,
key: key,
config: options.config
});
};
BosClient.prototype.putObject = function (bucketName, key, data, options) {
if (!key) {
throw new TypeError('key should not be empty.');
}
options = this._checkOptions(options || {});
return this.sendRequest('PUT', {
bucketName: bucketName,
key: key,
body: data,
headers: options.headers,
config: options.config
});
};
BosClient.prototype.putObjectFromBlob = function (bucketName, key, blob, options) {
var headers = {};
// https://developer.mozilla.org/en-US/docs/Web/API/Blob/size
headers[H.CONTENT_LENGTH] = blob.size;
// 对于浏览器调用API的时候,默认不添加 H.CONTENT_MD5 字段,因为计算起来比较慢
// 而且根据 API 文档,这个字段不是必填的。
options = u.extend(headers, options);
return this.putObject(bucketName, key, blob, options);
};
BosClient.prototype.getObjectMetadata = function (bucketName, key, options) {
options = options || {};
return this.sendRequest('HEAD', {
bucketName: bucketName,
key: key,
config: options.config
});
};
BosClient.prototype.initiateMultipartUpload = function (bucketName, key, options) {
options = options || {};
var headers = {};
headers[H.CONTENT_TYPE] = options[H.CONTENT_TYPE] || MimeType.guess(path.extname(key));
return this.sendRequest('POST', {
bucketName: bucketName,
key: key,
params: {uploads: ''},
headers: headers,
config: options.config
});
};
BosClient.prototype.abortMultipartUpload = function (bucketName, key, uploadId, options) {
options = options || {};
return this.sendRequest('DELETE', {
bucketName: bucketName,
key: key,
params: {uploadId: uploadId},
config: options.config
});
};
BosClient.prototype.completeMultipartUpload = function (bucketName, key, uploadId, partList, options) {
var headers = {};
headers[H.CONTENT_TYPE] = 'application/json; charset=UTF-8';
options = this._checkOptions(u.extend(headers, options));
return this.sendRequest('POST', {
bucketName: bucketName,
key: key,
body: JSON.stringify({parts: partList}),
headers: options.headers,
params: {uploadId: uploadId},
config: options.config
});
};
BosClient.prototype.uploadPartFromBlob = function (bucketName, key, uploadId, partNumber,
partSize, blob, options) {
if (blob.size !== partSize) {
throw new TypeError(util.format('Invalid partSize %d and data length %d',
partSize, blob.size));
}
var headers = {};
headers[H.CONTENT_LENGTH] = partSize;
headers[H.CONTENT_TYPE] = 'application/octet-stream';
options = this._checkOptions(u.extend(headers, options));
return this.sendRequest('PUT', {
bucketName: bucketName,
key: key,
body: blob,
headers: options.headers,
params: {
partNumber: partNumber,
uploadId: uploadId
},
config: options.config
});
};
BosClient.prototype.listParts = function (bucketName, key, uploadId, options) {
/*eslint-disable*/
if (!uploadId) {
throw new TypeError('uploadId should not empty');
}
/*eslint-enable*/
var allowedParams = ['maxParts', 'partNumberMarker', 'uploadId'];
options = this._checkOptions(options || {}, allowedParams);
options.params.uploadId = uploadId;
return this.sendRequest('GET', {
bucketName: bucketName,
key: key,
params: options.params,
config: options.config
});
};
BosClient.prototype.listMultipartUploads = function (bucketName, options) {
var allowedParams = ['delimiter', 'maxUploads', 'keyMarker', 'prefix', 'uploads'];
options = this._checkOptions(options || {}, allowedParams);
options.params.uploads = '';
return this.sendRequest('GET', {
bucketName: bucketName,
params: options.params,
config: options.config
});
};
BosClient.prototype.appendObject = function (bucketName, key, data, offset, options) {
if (!key) {
throw new TypeError('key should not be empty.');
}
options = this._checkOptions(options || {});
var params = {append: ''};
if (u.isNumber(offset)) {
params.offset = offset;
}
return this.sendRequest('POST', {
bucketName: bucketName,
key: key,
body: data,
headers: options.headers,
params: params,
config: options.config
});
};
BosClient.prototype.appendObjectFromBlob = function (bucketName, key, blob, offset, options) {
var headers = {};
// https://developer.mozilla.org/en-US/docs/Web/API/Blob/size
headers[H.CONTENT_LENGTH] = blob.size;
// 对于浏览器调用API的时候,默认不添加 H.CONTENT_MD5 字段,因为计算起来比较慢
// 而且根据 API 文档,这个字段不是必填的。
options = u.extend(headers, options);
return this.appendObject(bucketName, key, blob, offset, options);
};
// --- E N D ---
BosClient.prototype.sendRequest = function (httpMethod, varArgs) {
var defaultArgs = {
bucketName: null,
key: null,
body: null,
headers: {},
params: {},
config: {},
outputStream: null
};
var args = u.extend(defaultArgs, varArgs);
var config = u.extend({}, this.config, args.config);
var resource = [
'/v1',
strings.normalize(args.bucketName || ''),
strings.normalize(args.key || '', false)
].join('/');
if (config.sessionToken) {
args.headers[H.SESSION_TOKEN] = config.sessionToken;
}
return this.sendHTTPRequest(httpMethod, resource, args, config);
};
BosClient.prototype.sendHTTPRequest = function (httpMethod, resource, args, config) {
var client = this;
var agent = this._httpAgent = new HttpClient(config);
var httpContext = {
httpMethod: httpMethod,
resource: resource,
args: args,
config: config
};
u.each(['progress', 'error', 'abort'], function (eventName) {
agent.on(eventName, function (evt) {
client.emit(eventName, evt, httpContext);
});
});
var promise = this._httpAgent.sendRequest(httpMethod, resource, args.body,
args.headers, args.params, u.bind(this.createSignature, this),
args.outputStream
);
promise.abort = function () {
if (agent._req && agent._req.xhr) {
var xhr = agent._req.xhr;
xhr.abort();
}
};
return promise;
};
BosClient.prototype._checkOptions = function (options, allowedParams) {
var rv = {};
rv.config = options.config || {};
rv.headers = this._prepareObjectHeaders(options);
rv.params = u.pick(options, allowedParams || []);
return rv;
};
BosClient.prototype._prepareObjectHeaders = function (options) {
var allowedHeaders = {};
u.each([
H.CONTENT_LENGTH,
H.CONTENT_ENCODING,
H.CONTENT_MD5,
H.X_BCE_CONTENT_SHA256,
H.CONTENT_TYPE,
H.CONTENT_DISPOSITION,
H.ETAG,
H.SESSION_TOKEN,
H.CACHE_CONTROL,
H.EXPIRES,
H.X_BCE_OBJECT_ACL,
H.X_BCE_OBJECT_GRANT_READ
], function (header) {
allowedHeaders[header] = true;
});
var metaSize = 0;
var headers = u.pick(options, function (value, key) {
if (allowedHeaders[key]) {
return true;
}
else if (/^x\-bce\-meta\-/.test(key)) {
metaSize += Buffer.byteLength(key) + Buffer.byteLength('' + value);
return true;
}
});
if (metaSize > MAX_USER_METADATA_SIZE) {
throw new TypeError('Metadata size should not be greater than ' + MAX_USER_METADATA_SIZE + '.');
}
if (headers.hasOwnProperty(H.CONTENT_LENGTH)) {
var contentLength = headers[H.CONTENT_LENGTH];
if (contentLength < 0) {
throw new TypeError('content_length should not be negative.');
}
else if (contentLength > MAX_PUT_OBJECT_LENGTH) { // 5G
throw new TypeError('Object length should be less than ' + MAX_PUT_OBJECT_LENGTH
+ '. Use multi-part upload instead.');
}
}
if (headers.hasOwnProperty('ETag')) {
var etag = headers.ETag;
if (!/^"/.test(etag)) {
headers.ETag = util.format('"%s"', etag);
}
}
if (!headers.hasOwnProperty(H.CONTENT_TYPE)) {
headers[H.CONTENT_TYPE] = 'application/octet-stream';
}
return headers;
};
module.exports = BosClient;
},{"16":16,"19":19,"20":20,"21":21,"22":22,"33":33,"43":43,"46":46,"47":47}],18:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file src/config.js
* @author leeight
*/
/* eslint-env node */
exports.DEFAULT_SERVICE_DOMAIN = 'baidubce.com';
exports.DEFAULT_CONFIG = {
protocol: 'http',
region: 'bj'
};
},{}],19:[function(require,module,exports){
/**
* Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file src/headers.js
* @author leeight
*/
/* eslint-env node */
exports.CONTENT_TYPE = 'Content-Type';
exports.CONTENT_LENGTH = 'Content-Length';
exports.CONTENT_MD5 = 'Content-MD5';
exports.CONTENT_ENCODING = 'Content-Encoding';
exports.CONTENT_DISPOSITION = 'Content-Disposition';
exports.ETAG = 'ETag';
exports.CONNECTION = 'Connection';
exports.HOST = 'Host';
exports.USER_AGENT = 'User-Agent';
exports.CACHE_CONTROL = 'Cache-Control';
exports.EXPIRES = 'Expires';