-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.js
97 lines (77 loc) · 2.18 KB
/
utils.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
var request = require('request');
module.exports = {
// returns an integer in the [min, max) range
// if only min is given, the [0, min) range
random: function(min, max) {
if (max === undefined) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min));
},
// replaces {0}, {1}, ..., {n}, ... etc. in str with
// the n-th argument after str
format: function(str) {
var args = Array.prototype.slice.call(arguments, 1);
return str.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] !== 'undefined' ? args[number] : match;
});
},
// a URL shortener function, using google's goo.gl service
// see https://developers.google.com/url-shortener/v1/getting_started
shortenURL: function (url, cb) {
function retry(times) {
times--;
request.post({
url: 'https://www.googleapis.com/urlshortener/v1/url',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ longUrl: url })
}, function (err, resp, body) {
if (err) {
console.error('Couldn\'t shorten url! (' + (times || 'no') + ' more retries) Error: ' + err);
if (times) {
retry(times);
} else {
cb(err, null);
}
return;
}
if (resp.statusCode < 200 || resp.statusCode >= 300) {
console.error('Error: Google responded with a ' + resp.statusCode + ' status code. (' + (times || 'no') + ' more retries)');
if (times) {
retry(times);
} else {
cb(new Error('Failed to shorten URL: Google responded with a ' + resp.statusCode + ' status code.'), null);
}
return;
}
cb(null, JSON.parse(body).id);
});
}
retry(3);
},
// converts a positive integer in seconds to a HH:MM:SS format string
// (HH: omitted if < 1 hour; leading zero in seconds and minutes (if >= 1 h))
durationFormat: function (time) {
var s = time % 60;
time = Math.floor(time / 60);
var m = time % 60;
time = Math.floor(time / 60);
var h = time % 60;
var str = '';
if (h > 0) {
// if hours - [h]h:mm:ss
// otherwise - just [m]m:ss
str = h + ':';
if (m < 10) {
str += 0;
}
}
str += m + ':';
if (s < 10) {
str += '0';
}
str += s;
return str;
}
};