-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.js
86 lines (73 loc) · 1.88 KB
/
client.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
var et = require('elementtree')
var superagent = require('superagent')
exports.createPanClient = createPanClient
exports.PanClient = PanClient
function createPanClient(opts) {
return new PanClient(opts)
}
function PanClient(opts) {
if (! this instanceof PanClient) {
return new PanClient(opts)
}
opts = opts || {}
this.protocol = opts.protocol || 'https'
this.key = opts.key
this.api = opts.api || 'esp/restapi.esp'
this.host = opts.host
if (opts.port) {
this.url = this.protocol + '://' + this.host
+ ':' + opts.port + '/' + this.api
} else {
this.url = this.protocol + '://' + this.host + '/' + this.api
}
}
PanClient.prototype.keygen = function keygen(user, password, callback) {
var self = this
superagent
.post(this.url)
.type('form')
.send({ type : 'keygen', user : user, password : password })
.buffer(true)
.on('error', callback)
.end(done)
function done(res) {
try {
var etree = et.parse(res.text)
} catch(err) {
return callback(err, res.text, null)
}
if (ok(res, etree)) {
var key = etree.findtext('./result/key')
self.key = decodeURIComponent(key)
return callback(null, res.text, etree)
}
return callback(new Error(res.text), res.text, null)
}
}
PanClient.prototype.request = function request(params, callback) {
params.key = this.key
superagent
.post(this.url)
.type('form')
.send(params)
.buffer(true)
.on('error', callback)
.end(done)
function done(res) {
try {
var etree = et.parse(res.text)
} catch(err) {
return callback(err, res.text, null)
}
if (ok(res, etree)) {
return callback(null, res.text, etree)
}
return callback(new Error(res.text), res.text, null)
}
}
function ok(res, etree) {
if (!res.ok) return false
if (!etree) return false
if (etree.find('.').attrib.status !== 'success') return false
return true
}