-
Notifications
You must be signed in to change notification settings - Fork 55
/
api.js
274 lines (224 loc) · 6.99 KB
/
api.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
/**
* Helper "class" for accessing MediaWiki API and handling cookie-based session
*/
module.exports = (function() {
'use strict';
// introspect package.json to get module version
var VERSION = require('../package').version;
var
// @see https://github.com/caolan/async
async = require('async'),
// @see https://github.com/mikeal/request
request = require('request');
var api = function(options) {
this.protocol = options.protocol || 'http';
this.port = options.port || (this.protocol === 'https' ? 443 : undefined /* will default to 80 */);
this.server = options.server;
this.path = options.path;
this.proxy = options.proxy;
this.jar = request.jar(); // create new cookie jar for each instance
this.debug = options.debug;
// set up logging
var winston = require('winston');
this.logger = new (winston.Logger)();
// console logging
if (this.debug) {
this.logger.add(winston.transports.Console, {
level: 'debug'
});
}
this.logger.cli();
// file logging
var path = require('path'),
fs = require('fs'),
logDir = path.dirname(process.argv[1]) + '/log/',
logFile = logDir + path.basename(process.argv[1], '.js') + '.log';
if (fs.existsSync(logDir)) {
this.logger.add(winston.transports.File, {
colorize: true,
filename: logFile,
json: false,
level: this.debug ? 'debug' : 'info'
});
}
// requests queue
// @see https://github.com/caolan/async#queue
var concurrency = options.concurrency || 3; // how many tasks (i.e. requests) to run in parallel
this.queue = async.queue(function(task, callback) {
// process the task (and call the provided callback once it's completed)
task(callback);
}, concurrency);
// HTTP client
this.formatUrl = require('url').format;
this.userAgent = options.userAgent || ('nodemw v' + VERSION + ' (node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')');
this.version = VERSION;
// debug info
this.info(process.argv.join(' '));
this.info(this.userAgent);
this.info('Using <' + this.protocol + '://' + this.server + ':' + this.port + this.path + '/api.php> as API entry point');
this.info('----');
};
var doRequest = function(params, callback, method, done) {
var self = this,
// store requested action - will be used when parsing a response
actionName = params.action,
// "request" options
options = {
method: method || 'GET',
proxy: this.proxy || false,
jar: this.jar,
headers: {
'User-Agent': this.userAgent
}
};
// HTTP request parameters
params = params || {};
// force JSON format
params.format = 'json';
// handle uploads
if (method === 'UPLOAD') {
options.method = 'POST';
var CRLF = "\r\n",
postBody = [],
boundary = 'nodemw' + Math.random().toString().substr(2);
// encode each field
Object.keys(params).forEach(function(fieldName) {
var value = params[fieldName];
postBody.push("--" + boundary);
postBody.push(CRLF);
if (typeof value === 'string') {
// properly encode UTF8 in binary-safe POST data
postBody.push("Content-Disposition: form-data; name=\"" + fieldName + "\"");
postBody.push(CRLF);
postBody.push(CRLF);
postBody.push(new Buffer(value, 'utf8'));
}
else {
// send attachment
postBody.push("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"foo\"");
postBody.push(CRLF);
postBody.push(CRLF);
postBody.push(value);
}
postBody.push(CRLF);
});
postBody.push("--" + boundary + "--");
// encode post data
options.headers['content-type'] = 'multipart/form-data; boundary=' + boundary;
options.body = postBody;
params = {};
}
// form an URL to API
options.url = this.formatUrl({
protocol: this.protocol,
port: this.port,
hostname: this.server,
pathname: this.path + '/api.php',
query: (options.method === 'GET') ? params : {}
});
// POST all parameters (avoid "request string too long" errors)
if (method === 'POST') {
options.form = params;
}
this.logger.debug('API action: %s', actionName);
this.logger.debug('%s <%s>', options.method, options.url);
if (options.form) {
this.logger.debug('POST fields: %s', Object.keys(options.form).join(', '));
}
request(options, function(error, response, body) {
response = response || {};
if (error) {
self.logger.error('Request to API failed: %s', error);
callback(new Error('Request to API failed: ' + error));
done();
return;
}
if (response.statusCode !== 200) {
self.logger.error('Request to API failed: HTTP status code was %d for <%s>', response.statusCode || 'unknown', options.url);
self.logger.data(new Error().stack);
callback(new Error('Request to API failed: HTTP status code was ' + response.statusCode));
done();
return;
}
// parse response
var data,
info,
next;
try {
data = JSON.parse(body);
info = data && data[actionName];
next = data && data['query-continue'] && data['query-continue'][params.list];
}
catch(e) {
self.logger.error('Error parsing JSON response: %s', body);
self.logger.data(body);
callback(new Error('Error parsing JSON response'));
done();
return;
}
//if (!callback) data.error = {info: 'foo'}; // debug
if (data && !data.error && info) {
if (next) {
self.logger.debug("There's more data");
self.logger.debug(next);
}
callback(null, info, next, data);
}
else {
self.logger.error('Error returned by API: %s', data.error.info);
self.logger.data(data.error);
callback(new Error('Error returned by API: ' + data.error.info));
}
done();
});
};
// public interface
api.prototype = {
log: function() {
this.logger.log.apply(this.logger, arguments);
},
info: function() {
this.logger.info.apply(this.logger, arguments);
},
warn: function(msg, extra) {
this.logger.warn.apply(this.logger, arguments);
},
error: function(msg, extra) {
this.logger.error.apply(this.logger, arguments);
},
// adds request to the queue
call: function(params, callback, method) {
this.queue.push(function(done) {
doRequest.apply(this, [params, callback, method, done]);
}.bind(this));
},
// fetch an external resource
fetchUrl: function(url, callback, encoding) {
var self = this;
encoding = encoding || 'utf-8';
// add a request to the queue
this.queue.push(function(done) {
self.info("Fetching <%s> (as %s)...", url, encoding);
request({
url: url,
encoding: (encoding === 'binary') ? null : encoding
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
self.info('<%s>: fetched %s kB', url, (body.length/1024).toFixed(2));
callback(null, body);
}
else {
if (!error) {
error = new Error('HTTP status '+ response.statusCode);
}
self.error('Failed to fetch <' + url + '>');
self.error(error.message);
callback(error, body);
}
done();
});
});
}
};
return api;
}());