forked from welovekpop/plugged
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
104 lines (88 loc) · 2.72 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
97
98
99
100
101
102
103
104
var setErrorMessage = function(statusCode, msg) {
return {
code: statusCode,
message: msg
};
};
var createIterator = function(arr) {
currentIndex = 0;
return {
next: function() {
return (currentIndex < arr.length ? {
value: arr[currentIndex++],
done: false
} : { done: true });
}
};
};
var waterfall = function(funcs, callback) {
callback = callback || function() {};
if(!Array.isArray(funcs))
throw new Error("funcs are not of type array");
else if(funcs.length <= 0)
throw new Error("array is empty!");
var iterator = createIterator(funcs);
(function _obj() {
var nxt = iterator.next();
var err = arguments[0];
var args = [];
//not so nice looking copy to keep vm optimizations
for(var i = (nxt.done ? 0 : 1), l = arguments.length; i < l; i++)
args.push(arguments[i]);
args.push(_obj);
if(!nxt.done && !err)
nxt.value.apply(nxt.value, args);
else
callback.apply(callback, (!err ? args : [err]));
})();
};
var loginClient = function(client, tries) {
tries = tries || 0;
waterfall([
client.getCSRF.bind(client),
client.setLogin.bind(client),
client._getAuthToken.bind(client)
], function _loginCredentialCheck(err) {
if(err) {
if(tries < 2 && err.code !== 401) {
client.log("an error occured while trying to log in", 0, "red");
client.log(err, 2, "red");
client.log("retrying...", 0);
loginClient(client, ++tries);
} else {
client.log("couldn't log in.", 0, "red");
client.emit(client.LOGIN_ERROR, err);
}
} else {
client._loggedIn.call(client);
}
});
};
var splitTitle = function(title) {
title = title || "";
if(typeof title === "string") {
if(title.indexOf('-') >= 0)
title = title.split('-').map(function(str) { return str.trim(); });
else if(title.indexOf(' ') >= 0)
title = title.split(' ').map(function(str) { return str.trim(); });
else
title = [title, title];
}
return title;
};
var decode = function(str) {
if(typeof str !== "string")
return str;
return str
.replace(/"/g, '\\\"')
.replace(/'/g, '\'')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
exports.setErrorMessage = setErrorMessage;
exports.createIterator = createIterator;
exports.loginClient = loginClient;
exports.splitTitle = splitTitle;
exports.waterfall = waterfall;
exports.decode = decode;