| 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 |
1
1
1
1
1
1
1
1
1
1
1
43
43
26
43
1
1
77
1
76
1
77029
1
4
1
237
1
372
1
814
1
27
27
27
1
2467
1
28000
1319
26681
8
26673
1
1
3495
1
3494
1
3370
1
3369
1
323
166
323
1
1
1883
1
546
546
1576
242
304
1
32
5
27
27
19
8
1
10
10
1
2630
2630
1467
1163
1085
2630
1
2
2
1
1
14
14
14
14
14
14
14
14
14
14
14
1
22
22
22
1
1
256
256
256
256
256
255
1
1
255
1
1
256
256
256
256
256
256
256
256
1
68
68
68
68
1
2188
2176
6
6
1
122
118
4
4
1
20
20
1
| //
// Copyright (c) Microsoft and contributors. 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.
//
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var _ = require('underscore');
var util = require('util');
var url = require('url');
var stream = require('stream');
var Constants = require('./constants');
var StorageUtilities = require('./storageutilities');
var SR = require('./sr');
/**
* Trim the default port in the url.
*
* @param {string} uri The URI to be encoded.
* @return {string} The URI without defualt port.
*/
exports.trimPortFromUri = function (uri) {
var uri = url.parse(uri);
if ((uri.protocol === Constants.HTTPS && uri.port == Constants.DEFAULT_HTTPS_PORT) || (uri.protocol === Constants.HTTP && uri.port == Constants.DEFAULT_HTTP_PORT)) {
uri.host = uri.hostname;
}
return url.format(uri);
};
/**
* Encodes an URI.
*
* @param {string} uri The URI to be encoded.
* @return {string} The encoded URI.
*/
exports.encodeUri = function (uri) {
return encodeURIComponent(uri)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
};
/**
* Returns the number of keys (properties) in an object.
*
* @param {object} value The object which keys are to be counted.
* @return {number} The number of keys in the object.
*/
exports.objectKeysLength = function (value) {
if (!value) {
return 0;
}
return _.keys(value).length;
};
/**
* Checks if a value is null or undefined.
*
* @param {object} value The value to check for null or undefined.
* @return {bool} True if the value is null or undefined, false otherwise.
*/
exports.objectIsNull = function (value) {
return _.isNull(value) || _.isUndefined(value);
};
/**
* Checks if an object is empty.
*
* @param {object} object The object to check if it is null.
* @return {bool} True if the object is empty, false otherwise.
*/
exports.objectIsEmpty = function (object) {
return _.isEmpty(object);
};
/**
* Determines if an object contains an integer number.
*
* @param {object} value The object to assert.
* @return {bool} True if the object contains an integer number; false otherwise.
*/
exports.objectIsInt = function (value) {
return typeof value === 'number' && parseFloat(value) == parseInt(value, 10) && !isNaN(value);
};
/**
* Checks if an object is a string.
*
* @param {object} object The object to check if it is a string.
* @return {bool} True if the object is a strign, false otherwise.
*/
exports.objectIsString = function (object) {
return _.isString(object);
};
/**
* Check if an object is a function
* @param {object} object The object to check whether it is function
* @return {bool} True if the specified object is function, otherwise false
*/
exports.objectIsFunction = function (object) {
return _.isFunction(object);
};
/**
* Front zero padding of string to sepcified length
*/
exports.zeroPaddingString = function(str, len) {
var paddingStr = '0000000000' + str;
Iif(paddingStr.length < len) {
return exports.zeroPaddingString(paddingStr, len);
} else {
return paddingStr.substr(-1 * len);
}
};
/**
* Checks if a value is an empty string, null or undefined.
*
* @param {object} value The value to check for an empty string, null or undefined.
* @return {bool} True if the value is an empty string, null or undefined, false otherwise.
*/
exports.stringIsEmpty = function (value) {
return _.isNull(value) || _.isUndefined(value) || value === '';
};
/**
* Checks if a value is null, empty, undefined or consists only of white-space characters.
*
* @param {object} value The value to check for null, empty, undefined and white-space only characters.
* @return {bool} True if the value is an empty string, null, undefined, or consists only of white-space characters, false otherwise.
*/
exports.IsNullOrEmptyOrUndefinedOrWhiteSpace = function (value) {
if(_.isNull(value) || _.isUndefined(value) || value === '') {
return true;
}
if(_.isString(value) && value.trim().length === 0) {
return true;
}
return false;
};
/**
* Formats a text replacing '?' by the arguments.
*
* @param {string} text The string where the ? should be replaced.
* @param {array} arguments Value(s) to insert in question mark (?) parameters.
* @return {string}
*/
exports.stringFormat = function (text) {
if (arguments.length > 1) {
for (var i = 1; text.indexOf('?') !== -1; i++) {
text = text.replace('?', arguments[i]);
}
}
return text;
};
/**
* Determines if a string starts with another.
*
* @param {string} text The string to assert.
* @param {string} prefix The string prefix.
* @return {Bool} True if the string starts with the prefix; false otherwise.
*/
exports.stringStartsWith = function (text, prefix) {
if (_.isNull(prefix)) {
return true;
}
return text.substr(0, prefix.length) === prefix;
};
/**
* Determines if a string ends with another.
*
* @param {string} text The string to assert.
* @param {string} suffix The string suffix.
* @return {Bool} True if the string ends with the suffix; false otherwise.
*/
exports.stringEndsWith = function (text, suffix) {
if (_.isNull(suffix)) {
return true;
}
return text.substr(text.length - suffix.length) === suffix;
};
/**
* Removes the BOM from a string.
*
* @param {string} str The string from where the BOM is to be removed
* @return {string} The string without the BOM.
*/
exports.removeBOM = function (str) {
if (str.charCodeAt(0) === 0xfeff || str.charCodeAt(0) === 0xffef) {
str = str.substring(1);
}
return str;
};
/**
* Merges multiple objects.
*
* @param {object} object The objects to be merged
* @return {object} The merged object.
*/
exports.merge = function () {
return _.extend.apply(this, arguments);
};
/**
* Checks if a value exists in an array. The comparison is done in a case
* insensitive manner.
*
* @param {string} needle The searched value.
* @param {array} haystack The array.
*
* @static
*
* @return {boolean}
*/
exports.inArrayInsensitive = function (needle, haystack) {
return _.contains(_.map(haystack, function (h) { return h.toLowerCase(); }), needle.toLowerCase());
};
/**
* Returns the specified value of the key passed from object and in case that
* this key doesn't exist, the default value is returned. The key matching is
* done in a case insensitive manner.
*
* @param {string} key The array key.
* @param {object} haystack The object to be used.
* @param {mix} default The value to return if $key is not found in $array.
*
* @static
*
* @return mix
*/
exports.tryGetValueInsensitive = function (key, haystack, defaultValue) {
Eif (haystack) {
for (var i in haystack) {
if (haystack.hasOwnProperty(i) && i.toString().toLowerCase() === key.toString().toLowerCase()) {
return haystack[i];
}
}
}
return defaultValue;
};
/**
* Returns the value in a chained object.
*
* @param {object} object The object with the values.
* @param {array} keys The keys.
* @param {mix} default The value to return if $key is not found in $array.
*
* @static
*
* @return mix
*/
exports.tryGetValueChain = function (object, keys, defaultValue) {
if (keys.length === 0) {
return object;
}
var currentKey = keys.shift();
if (object && object[currentKey]) {
return exports.tryGetValueChain(object[currentKey], keys, defaultValue);
}
return defaultValue;
};
/**
* Rounds a date off to seconds.
*
* @param {Date} a date
* @return {string} the date in ISO8061 format, with no milliseconds component
*/
exports.truncatedISO8061Date = function (date) {
var dateString = date.toISOString();
return dateString.substring(0, dateString.length - 5) + 'Z';
};
exports.normalizeArgs = function (optionsOrCallback, callback, result) {
var options = {};
if(_.isFunction(optionsOrCallback) && !callback) {
callback = optionsOrCallback;
} else if (optionsOrCallback) {
options = optionsOrCallback;
}
result(options, callback);
};
exports.getNodeVersion = function () {
var parsedVersion = process.version.split('.');
return {
major: parseInt(parsedVersion[0].substr(1), 10),
minor: parseInt(parsedVersion[1], 10),
patch: parseInt(parsedVersion[2], 10)
};
};
exports.analyzeStream = function (stream, calculateMD5, callback) {
var digest = null;
var length = 0;
if (calculateMD5) {
digest = crypto.createHash('md5');
}
stream.on('data', function (chunk) {
if (calculateMD5) {
digest.update(chunk);
}
length += chunk.length;
});
stream.on('end', function () {
var md5 = null;
if (calculateMD5) {
md5 = digest.digest('base64');
}
callback(length, md5);
});
};
/**
* Calculate md5sum for the stream
* @ignore
*/
exports.calculateMD5 = function(readStream, bufferLength, options, callback) {
var internalBuff = new Buffer(bufferLength);
var index = 0;
var internalHash = crypto.createHash('md5');
readStream.on('data', function(data) {
Iif (index + data.length > bufferLength) {
throw new Error(SR.INVALID_STREAM_LENGTH);
}
else {
data.copy(internalBuff, index);
internalHash.update(data);
index += data.length;
}
}).on('end', function() {
internalBuff = internalBuff.slice(0, index);
options.contentMD5 = internalHash.digest('base64');
callback(internalBuff);
});
};
/**
* Whether the content of buffer is all zero
*/
exports.isBufferAllZero = function (buffer) {
for(var i = 0, len = buffer.length; i < len; i++) {
Eif (buffer[i] !== 0) {
return false;
}
}
return true;
};
/**
* Write zero to stream
*/
var zeroBuffer = null;
exports.writeZerosToStream = function (stream, length, md5Hash, progressCallback, callback) {
var defaultBufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
var bufferSize = Math.min(defaultBufferSize, length);
var remaining = length - bufferSize;
var buffer = null;
if (bufferSize == defaultBufferSize) {
if (!zeroBuffer) {
zeroBuffer = new Buffer(defaultBufferSize);
zeroBuffer.fill(0);
}
buffer = zeroBuffer;
} else {
buffer = new Buffer(bufferSize);
buffer.fill(0);
}
Eif (md5Hash) {
md5Hash.update(buffer);
}
//We can only write the entire buffer to stream instead of part of buffer.
return stream.write(buffer, function () {
Eif (exports.objectIsFunction(progressCallback)) {
progressCallback(null, buffer.length);
}
buffer = null;
Iif (remaining > 0) {
exports.writeZerosToStream(stream, remaining, md5Hash, progressCallback, callback);
} else Iif (exports.objectIsFunction(callback)) {
callback(null, null);
}
});
};
/**
* Calculate md5sum for the content
*/
exports.getContentMd5 = function (content, encoding) {
Eif (!encoding) encoding = 'base64';
var internalHash = crypto.createHash('md5');
internalHash.update(content, 'utf8');
return internalHash.digest(encoding);
};
exports.getNextLocation = function(lastLocation, locationMode) {
switch(locationMode) {
case StorageUtilities.LocationMode.PRIMARY_ONLY:
return Constants.StorageLocation.PRIMARY;
case StorageUtilities.LocationMode.SECONDARY_ONLY:
return Constants.StorageLocation.SECONDARY;
case StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY:
case StorageUtilities.LocationMode.SECONDARY_THEN_PRIMARY:
return (lastLocation === Constants.StorageLocation.PRIMARY) ? Constants.StorageLocation.SECONDARY : Constants.StorageLocation.PRIMARY;
default:
throw new Error(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'locationMode', locationMode));
}
};
exports.getNextListingLocationMode = function (token) {
if(_.isNull(token) || _.isUndefined(token)) {
return Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
}
else {
switch (token.targetLocation) {
case Constants.StorageLocation.PRIMARY:
return Constants.RequestLocationMode.PRIMARY_ONLY;
case Constants.StorageLocation.SECONDARY:
return Constants.RequestLocationMode.SECONDARY_ONLY;
default:
throw new Error(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'targetLocation', token.targetLocation));
}
}
};
exports.isStreamPaused = function (object) {
Eif (object instanceof stream) {
return object._paused === true || (object._readableState && object._readableState.flowing === false);
}
return false;
};
exports.pathExistsSync = fs.existsSync ? fs.existsSync : path.existsSync;
|