forked from ptz0n/node-securitas-direct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
126 lines (104 loc) · 2.71 KB
/
Copy pathindex.js
File metadata and controls
126 lines (104 loc) · 2.71 KB
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
const axios = require('axios');
const { parseStringPromise } = require('xml2js');
const client = axios.create({
baseURL: 'https://mob2217.securitasdirect.es:12010/WebService/ws.do',
});
client.interceptors.response.use(async (response) => {
const data = await parseStringPromise(response.data);
if (!data.PET || data.PET.RES[0] !== 'OK') {
const error = new Error('Unknown response');
error.response = {
...response,
data,
};
error.config = response.config;
error.code = data && data.PET && data.PET.ERR && data.PET.ERR[0];
return Promise.reject(error);
}
return data.PET;
});
const sleep = (seconds) => new Promise((resolve) => {
setTimeout(resolve, seconds * 1000);
});
const buildId = (user) => {
const date = new Date().toISOString().substring(0, 19).replace(/\D/g, '');
return `AND_________________________${user}${date}`;
};
// const supportedCountries = ['es', 'fr', 'pt']
class SecuritasDirect {
constructor(username, password, country) {
this.params = {
Country: country.toUpperCase(),
ID: buildId(username),
lang: country,
pwd: password,
user: username,
};
}
login() {
return client({
method: 'POST',
params: {
...this.params,
hash: undefined,
request: 'LOGIN',
},
}).then(({ HASH }) => {
[this.params.hash] = HASH;
return this.params.hash;
});
}
logout() {
return client({
method: 'GET',
params: {
...this.params,
request: 'CLS',
numinst: '',
},
});
}
getInstallation(installation) {
return client({
method: 'POST',
params: {
...this.params,
request: 'MYINSTALLATION',
numinst: installation,
},
}).then(({ INSTALLATION }) => INSTALLATION[0]);
}
async transaction(action, installation, panel, retries = 0) {
if (retries > 10) {
return Promise.reject(new Error('Too many retries'));
}
const step = retries === 0 ? 1 : 2;
const request = {
method: 'GET',
params: {
...this.params,
callby: 'AND_61',
numinst: installation,
panel,
request: `${action}${step}`,
},
};
const response = await client(request).catch(async (error) => {
// Invalid session. Please, try again later.
if (error.code === '60022') {
request.params.hash = await this.login();
return client(request);
}
if (error.code) {
throw error;
}
return null;
});
if (response && step === 2) {
return response;
}
await sleep(1);
return this.transaction(action, installation, panel, retries + 1);
}
}
module.exports = SecuritasDirect;