-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
457 lines (373 loc) · 12.7 KB
/
index.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
var _ = require('lodash'),
querystring = require('querystring'),
crypto = require('crypto'),
request = require('request');
/*
How to use:
1. Go to http://api.ucoz.net/ru/join.
2. Get the following keys:
Consumer key
Consumer secret
OAuth token
OAuth token secret
4. Make sure the checkbox "Enable uAPI module" in the module settings (in the Control Panel of the site).
3. Use:
var UAPI = require('ucoz-uapi');
var uAPI = new UAPI({
consumerKey : 'dfg98dfg8df8g9d98gd98g8dfg',
consumerSecret : '.dA7xzR7fDlOrltTc7tZHVI95oMsEa',
oauthToken : 'BRKkNkf3ZbijzdRC6F9bPhCeYVW7FTtqNRbwsDbq',
oauthTokenSecret : 'qSSUWTG7FbryN3ZXpSf0fbZeEVdDkLXYrX2jGrsl',
url : 'yousiteurl'
});
uAPI.filesDirectory().get(
function(err, data) {
console.log(err, data);
}
)
*/
function urlencode(str) {
// discuss at: http://phpjs.org/functions/urlencode/
// original by: Philip Peterson
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Lars Fischer
// input by: AJ
// input by: travc
// input by: Brett Zamir (http://brett-zamir.me)
// input by: Ratheous
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Joris
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// note: This reflects PHP 5.3/6.0+ behavior
// note: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
// note: pages served as UTF-8
// example 1: urlencode('Kevin van Zonneveld!');
// returns 1: 'Kevin+van+Zonneveld%21'
// example 2: urlencode('http://kevin.vanzonneveld.net/');
// returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
// example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
// returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
str = (str + '')
.toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.
replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/%20/g, '+');
}
function md5(str) {
return crypto.createHash('md5').update(str).digest("hex");
}
function getSha1(str, key) {
return crypto['createHmac']('sha1', key).update(str).digest("binary");
}
function base64_encode(data) {
// discuss at: http://phpjs.org/functions/base64_encode/
// original by: Tyler Akins (http://rumkin.com)
// improved by: Bayron Guevara
// improved by: Thunder.m
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Rafał Kukawski (http://kukawski.pl)
// bugfixed by: Pellentesque Malesuada
// example 1: base64_encode('Kevin van Zonneveld');
// returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// example 2: base64_encode('a');
// returns 2: 'YQ=='
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
function mt_rand(min, max) {
// discuss at: http://phpjs.org/functions/mt_rand/
// original by: Onno Marsman
// improved by: Brett Zamir (http://brett-zamir.me)
// input by: Kongo
// example 1: mt_rand(1, 1);
// returns 1: 1
var argc = arguments.length;
if (argc === 0) {
min = 0;
max = 2147483647;
} else if (argc === 1) {
throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
} else {
min = parseInt(min, 10);
max = parseInt(max, 10);
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function time() {
return Math.floor(new Date().getTime() / 1000);
}
function http_build_query(formdata, numeric_prefix, arg_separator) {
// discuss at: http://phpjs.org/functions/http_build_query/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Legaev Andrey
// improved by: Michael White (http://getsprink.com)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Brett Zamir (http://brett-zamir.me)
// revised by: stag019
// input by: Dreamer
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
// note: If the value is null, key and value are skipped in the http_build_query of PHP while in phpjs they are not.
// depends on: urlencode
// example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&');
// returns 1: 'foo=bar&php=hypertext+processor&baz=boom&cow=milk'
// example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_');
// returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'
var value, key, tmp = [],
that = this;
var _http_build_query_helper = function(key, val, arg_separator) {
var k, tmp = [];
if (val === true) {
val = '1';
} else if (val === false) {
val = '0';
}
if (val != null) {
if (typeof val === 'object') {
for (k in val) {
if (val[k] != null) {
tmp.push(_http_build_query_helper(key + '[' + k + ']', val[k], arg_separator));
}
}
return tmp.join(arg_separator);
} else if (typeof val !== 'function') {
return urlencode(key) + '=' + urlencode(val);
} else {
throw new Error('There was an error processing for http_build_query().');
}
} else {
return '';
}
};
if (!arg_separator) {
arg_separator = '&';
}
for (key in formdata) {
value = formdata[key];
if (numeric_prefix && !isNaN(key)) {
key = String(numeric_prefix) + key;
}
var query = _http_build_query_helper(key, value, arg_separator);
if (query !== '') {
tmp.push(query);
}
}
return tmp.join(arg_separator);
}
function prepareResponce(err, body, cb) {
if (err) return cb(err);
var json = null;
try {
json = JSON.parse(body);
} catch(e) {
return cb(e);
}
if (json.error) {
return cb(json.error);
}
cb(null, json)
};
var moduleNameMap = {
};
var sigMethod = 'HMAC-SHA1';
var oauthVersion = '1.0';
function Query(context, moduleName) {
var me = this;
if ( ! context) {
throw new Error('Query: "context" not defined');
}
if ( ! moduleName) {
throw new Error('Query: "moduleName" not defined');
}
me.context = context;
me.moduleName = moduleName;
}
Query.prototype.get = function(cb) {
this.exec(this.moduleName, 'get', null, cb);
};
Query.prototype.post = function(params, cb) {
this.exec(this.moduleName, 'post', params, cb);
};
Query.prototype.put = function(params, cb) {
this.exec(this.moduleName, 'put', params, cb);
};
Query.prototype.delete = function(params, cb) {
this.exec(this.moduleName + '/posts', 'delete', params, cb);
};
Query.prototype.exec = function(moduleName, method, addParams, cb) {
var me = this,
mt_rand_val = mt_rand();
oauth_nonce = md5(new Date().getTime() + '' + mt_rand_val),
timestamp = time(),
parametrs = _.extend(
{
'oauth_consumer_key' : me.context.consumerKey,
'oauth_nonce' : oauth_nonce,
'oauth_signature_method' : sigMethod,
'oauth_timestamp' : '' + timestamp,
'oauth_token' : me.context.oauthToken,
'oauth_version' : oauthVersion
}
);
try {
if ( ! moduleName) {
throw new Error('exec: moduleName not defined');
return ;
}
if ( ! method ) {
throw new Error('exec: method not defined');
return ;
}
if ( ! cb ) {
throw new Error('exec: cb not defined');
return ;
}
if (addParams) {
Object.keys(addParams).forEach(function(key) {
parametrs[key] = addParams[key];
});
}
parametrs = Object.keys(parametrs)
.sort(function(a, b) {
return a.localeCompare(b);
})
.reduce(function(obj, key) {
obj[key] = parametrs[key];
return obj;
}, {});
if (moduleNameMap[moduleName]) {
moduleName = moduleNameMap[moduleName];
}
//начинается формирование подписи для правильного запроса
var request_url = 'http://' + me.context.url + '/uapi' + moduleName.trim().toLowerCase();
method = method.toUpperCase();
var parametrs2 = parametrs;
parametrs = Object.keys(parametrs).reduce(function (obj, key) {
// Это не я придумал, так написано в оригиальном модуле
obj[key] = parametrs[key].replace('@', '');
return obj;
}, {});
var basestring = http_build_query(parametrs).replace(/\+/g, '%20');
basestring = method + '&' + urlencode(request_url) + '&' + urlencode(basestring);
var hash_key = me.context.consumerSecret + '&' + me.context.oauthTokenSecret;
var oauth_signature = urlencode(
base64_encode(
getSha1(
basestring,
hash_key
)
).trim()
);
var parametrs_forurl = http_build_query(parametrs);
var url = request_url + '?oauth_signature=' + oauth_signature;
var url_for = request_url + '?' + parametrs_forurl + '&oauth_signature=' + oauth_signature;
} catch(e) {
console.log('e', e.stack);
}
if (method == 'GET') {
request(url_for, function(err, result, body) {
prepareResponce(err, body, cb);
});
} else if (method == 'POST') {
request.post(url_for, {form: parametrs2}, function(err, result, body) {
prepareResponce(err, body, cb);
});
} else if (method == 'PUT') {
request({ url: url_for, method: 'PUT', form: parametrs2}, function(err, result, body) {
prepareResponce(err, body, cb);
});
} else if (method == 'DELETE') {
request({ url: url, method: 'DELETE', form: parametrs2}, function(err, result, body) {
prepareResponce(err, body, cb);
});
} else {
return cb(new Error('method "' + method + '" not implemented'));
}
return me;
};
function UCozUAPI(params) {
var me = this;
// Обработка параметров
if ( ! params) throw new Error('first param is empty');
['consumerKey', 'consumerSecret', 'oauthToken', 'oauthTokenSecret', 'url'].forEach(function(key) {
if ( ! params[key]) throw new Error('"' + key + '" is not defined');
me[key] = params[key];
});
me.url = me.url
.replace('http:\/\/', '')
.replace(/\/$/, '');
// Список методов, возвращающий объект запроса к определенному модулю.
// У каждого модуля набор методов свой, если в API сервиса его нет, вернет ошибку вида
// {msg: 'Not supported method', code: 'NOT_SUPPORTED_METHOD'}
// Записал такой копипастой, чтобы было видно, какие модули есть и что внутри вообще творится.
me.blog = function() {
return new Query(me, '/blog');
};
me.search = function() {
return new Query(me, '/search');
};
me.guestBook = function() {
return new Query(me, '/gb');
};
me.board = function() {
return new Query(me, '/board');
};
me.sitesDirectory = function() {
return new Query(me, '/dir');
};
me.articlesDirectory = function() {
return new Query(me, '/publ');
};
me.filesDirectory = function() {
return new Query(me, '/load');
};
me.miniChat = function() {
return new Query(me, '/mchat');
};
me.news = function() {
return new Query(me, '/news');
};
me.onlineGames = function() {
return new Query(me, '/stuff');
};
me.polls = function() {
return new Query(me, '/polls');
};
me.users = function() {
return new Query(me, '/users');
};
}
module.exports = UCozUAPI;