forked from tencentyun/cos-wx-sdk-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
516 lines (464 loc) · 16.4 KB
/
util.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
'use strict';
var md5 = require('../lib/md5');
var CryptoJS = require('../lib/crypto');
var xml2json = require('../lib/xml2json');
var json2xml = require('../lib/json2xml');
var base64 = require('../lib/base64');
function camSafeUrlEncode(str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
}
//测试用的key后面可以去掉
var getAuth = function (opt) {
opt = opt || {};
var SecretId = opt.SecretId;
var SecretKey = opt.SecretKey;
var KeyTime = opt.KeyTime;
var method = (opt.method || opt.Method || 'get').toLowerCase();
var queryParams = clone(opt.Query || opt.params || {});
var headers = clone(opt.Headers || opt.headers || {});
var pathname = opt.Pathname || '/' + (opt.Key || '');
if (!SecretId) return console.error('missing param SecretId');
if (!SecretKey) return console.error('missing param SecretKey');
var getObjectKeys = function (obj) {
var list = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
list.push(key);
}
}
return list.sort(function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return a === b ? 0 : (a > b ? 1 : -1);
});
};
var obj2str = function (obj) {
var i, key, val;
var list = [];
var keyList = getObjectKeys(obj);
for (i = 0; i < keyList.length; i++) {
key = keyList[i];
val = (obj[key] === undefined || obj[key] === null) ? '' : ('' + obj[key]);
key = key.toLowerCase();
key = camSafeUrlEncode(key);
val = camSafeUrlEncode(val) || '';
list.push(key + '=' + val)
}
return list.join('&');
};
// 签名有效起止时间
var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;
var exp = now;
var Expires = opt.Expires || opt.expires;
if (Expires === undefined) {
exp += 900; // 签名过期时间为当前 + 900s
} else {
exp += (Expires * 1) || 0;
}
// 要用到的 Authorization 参数列表
var qSignAlgorithm = 'sha1';
var qAk = SecretId;
var qSignTime = KeyTime || now + ';' + exp;
var qKeyTime = KeyTime || now + ';' + exp;
var qHeaderList = getObjectKeys(headers).join(';').toLowerCase();
var qUrlParamList = getObjectKeys(queryParams).join(';').toLowerCase();
// 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
// 步骤一:计算 SignKey
var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();
// 步骤二:构成 FormatString
var formatString = [method, pathname, obj2str(queryParams), obj2str(headers), ''].join('\n');
// 步骤三:计算 StringToSign
var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\n');
// 步骤四:计算 Signature
var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();
// 步骤五:构造 Authorization
var authorization = [
'q-sign-algorithm=' + qSignAlgorithm,
'q-ak=' + qAk,
'q-sign-time=' + qSignTime,
'q-key-time=' + qKeyTime,
'q-header-list=' + qHeaderList,
'q-url-param-list=' + qUrlParamList,
'q-signature=' + qSignature
].join('&');
return authorization;
};
var noop = function () {
};
// 清除对象里值为的 undefined 或 null 的属性
var clearKey = function (obj) {
var retObj = {};
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
retObj[key] = obj[key];
}
}
return retObj;
};
var readAsBinaryString = function (blob, callback) {
var readFun;
var fr = new FileReader();
if (FileReader.prototype.readAsBinaryString) {
readFun = FileReader.prototype.readAsBinaryString;
fr.onload = function () {
callback(this.result);
};
} else if (FileReader.prototype.readAsArrayBuffer) { // 在 ie11 添加 readAsBinaryString 兼容
readFun = function (fileData) {
var binary = "";
var pt = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
callback(binary);
};
reader.readAsArrayBuffer(fileData);
};
} else {
console.error('FileReader not support readAsBinaryString');
}
readFun.call(fr, blob);
};
// 获取文件 md5 值
var getFileMd5 = function (blob, callback) {
readAsBinaryString(blob, function (content) {
var hash = md5(content, true);
callback(null, hash);
});
};
function clone(obj) {
return map(obj, function (v) {
return typeof v === 'object' ? clone(v) : v;
});
}
function extend(target, source) {
each(source, function (val, key) {
target[key] = source[key];
});
return target;
}
function isArray(arr) {
return arr instanceof Array;
}
function isInArray(arr, item) {
var flag = false;
for (var i = 0; i < arr.length; i++) {
if (item === arr[i]) {
flag = true;
break;
}
}
return flag;
}
function makeArray(arr) {
return isArray(arr) ? arr : [arr];
}
function each(obj, fn) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
fn(obj[i], i);
}
}
}
function map(obj, fn) {
var o = isArray(obj) ? [] : {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = fn(obj[i], i);
}
}
return o;
}
function filter(obj, fn) {
var iaArr = isArray(obj);
var o = iaArr ? [] : {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (fn(obj[i], i)) {
if (iaArr) {
o.push(obj[i]);
} else {
o[i] = obj[i];
}
}
}
}
return o;
}
var binaryBase64 = function (str) {
var i, len, char, res = '';
for (i = 0, len = str.length / 2; i < len; i++) {
char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
res += String.fromCharCode(char);
}
return base64.btoa(res);
};
var uuid = function () {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
var hasMissingParams = function (apiName, params) {
var Bucket = params.Bucket;
var Region = params.Region;
var Key = params.Key;
if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {
if (!Bucket) return 'Bucket';
if (!Region) return 'Region';
} else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask') {
if (!Bucket) return 'Bucket';
if (!Region) return 'Region';
if (!Key) return 'Key';
}
return false;
};
var formatParams = function (apiName, params) {
// 复制参数对象
params = extend({}, params);
// 统一处理 Headers
if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {
var Headers = params.Headers || {};
if (params && typeof params === 'object') {
(function () {
for (var key in params) {
if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {
Headers[key] = params[key];
}
}
})();
var headerMap = {
// params headers
'x-cos-mfa': 'MFA',
'Content-MD5': 'ContentMD5',
'Content-Length': 'ContentLength',
'Content-Type': 'ContentType',
'Expect': 'Expect',
'Expires': 'Expires',
'Cache-Control': 'CacheControl',
'Content-Disposition': 'ContentDisposition',
'Content-Encoding': 'ContentEncoding',
'Range': 'Range',
'If-Modified-Since': 'IfModifiedSince',
'If-Unmodified-Since': 'IfUnmodifiedSince',
'If-Match': 'IfMatch',
'If-None-Match': 'IfNoneMatch',
'x-cos-copy-source': 'CopySource',
'x-cos-copy-source-Range': 'CopySourceRange',
'x-cos-metadata-directive': 'MetadataDirective',
'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',
'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',
'x-cos-copy-source-If-Match': 'CopySourceIfMatch',
'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',
'x-cos-acl': 'ACL',
'x-cos-grant-read': 'GrantRead',
'x-cos-grant-write': 'GrantWrite',
'x-cos-grant-full-control': 'GrantFullControl',
'x-cos-grant-read-acp': 'GrantReadAcp',
'x-cos-grant-write-acp': 'GrantWriteAcp',
'x-cos-storage-class': 'StorageClass',
// SSE-C
'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',
'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',
'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',
// SSE-COS、SSE-KMS
'x-cos-server-side-encryption': 'ServerSideEncryption',
'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
'x-cos-server-side-encryption-context': 'SSEContext',
};
util.each(headerMap, function (paramKey, headerKey) {
if (params[paramKey] !== undefined) {
Headers[headerKey] = params[paramKey];
}
});
params.Headers = clearKey(Headers);
}
}
return params;
};
var apiWrapper = function (apiName, apiFn) {
return function (params, callback) {
// 处理参数
if (typeof params === 'function') {
callback = params;
params = {};
}
// 整理参数格式
params = formatParams(apiName, params);
// 代理回调函数
var formatResult = function (result) {
if (result && result.headers) {
result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);
result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);
}
return result;
};
var _callback = function (err, data) {
callback && callback(formatResult(err), formatResult(data));
};
if (apiName !== 'getService' && apiName !== 'abortUploadTask') {
// 判断参数是否完整
var missingResult;
if (missingResult = hasMissingParams(apiName, params)) {
_callback({error: 'missing param ' + missingResult});
return;
}
// 判断 region 格式
if (params.Region) {
if (params.Region.indexOf('cos.') > -1) {
_callback({error: 'param Region should not be start with "cos."'});
return;
} else if (!/^([a-z\d-]+)$/.test(params.Region)) {
_callback({error: 'Region format error.'});
return;
}
// 判断 region 格式
if (!this.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default') {
console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');
}
}
// 兼容不带 AppId 的 Bucket
if (params.Bucket) {
if (!/^([a-z\d-]+)-(\d+)$/.test(params.Bucket)) {
if (params.AppId) {
params.Bucket = params.Bucket + '-' + params.AppId;
} else if (this.options.AppId) {
params.Bucket = params.Bucket + '-' + this.options.AppId;
} else {
_callback({error: 'Bucket should format as "test-1250000000".'});
return;
}
}
if (params.AppId) {
console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).');
delete params.AppId;
}
}
}
var res = apiFn.call(this, params, _callback);
if (apiName === 'getAuth' || apiName === 'getObjectUrl') {
return res;
}
}
};
var throttleOnProgress = function (total, onProgress) {
if (!onProgress || typeof onProgress !== 'function') return noop;
var self = this;
var size0 = 0;
var size1 = 0;
var time0 = Date.now();
var time1;
var timer;
function update() {
clearTimeout(timer);
timer = 0;
time1 = Date.now();
var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100);
var percent;
if (size1 === 0 && total === 0) {
percent = 1;
} else {
percent = Math.round(size1 / total * 100) / 100 || 0;
}
time0 = time1;
size0 = size1;
try {
onProgress({loaded: size1, total: total, speed: speed, percent: percent});
} catch (e) {
}
}
return function (info, immediately) {
if (info) {
size1 = info.loaded;
total = info.total;
}
if (Date.now() - time0 > self.options.ProgressInterval || immediately) {
update();
} else {
if (timer) return;
timer = setTimeout(update, self.options.ProgressInterval);
}
};
};
var getFileSize = function (api, params, callback) {
var size;
if (typeof params.Body === 'string') {
params.Body = new Blob([params.Body], {type: 'text/plain'});
}
if ((params.Body && (params.Body instanceof Blob || params.Body.toString() === '[object File]' || params.Body.toString() === '[object Blob]'))) {
size = params.Body.size;
} else {
callback({error: 'params body format error, Only allow File|Blob|String.'});
return;
}
params.ContentLength = size;
callback(null, size);
};
var getSkewTime = function (offset) {
return Date.now() + (offset || 0);
};
var util = {
noop: noop,
formatParams: formatParams,
apiWrapper: apiWrapper,
xml2json: xml2json,
json2xml: json2xml,
md5: md5,
clearKey: clearKey,
getFileMd5: getFileMd5,
binaryBase64: binaryBase64,
extend: extend,
isArray: isArray,
isInArray: isInArray,
makeArray: makeArray,
each: each,
map: map,
filter: filter,
clone: clone,
uuid: uuid,
camSafeUrlEncode: camSafeUrlEncode,
throttleOnProgress: throttleOnProgress,
getFileSize: getFileSize,
getSkewTime: getSkewTime,
getAuth: getAuth,
isBrowser: true,
};
util.fileSlice = function (file, start, end) {
if (file.slice) {
return file.slice(start, end);
} else if (file.mozSlice) {
return file.mozSlice(start, end);
} else if (file.webkitSlice) {
return file.webkitSlice(start, end);
}
};
util.getFileUUID = function (file, ChunkSize) {
// 如果信息不完整,不获取
if (file.name && file.size && file.lastModifiedDate && ChunkSize) {
return util.md5([file.name, file.size, file.lastModifiedDate, ChunkSize].join('::'));
} else {
return null;
}
};
util.getBodyMd5 = function (UploadCheckContentMd5, Body, callback) {
callback = callback || noop;
if (UploadCheckContentMd5) {
if (typeof Body === 'string') {
callback(util.md5(Body, true));
} else {
callback();
}
} else {
callback();
}
};
module.exports = util;