-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbots.service.js
221 lines (200 loc) · 6.3 KB
/
bots.service.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
const fs = require('fs');
const request = require('superagent');
const crypto = require('crypto');
const Promise = require('bluebird');
const {
CSML_CLIENT_API_KEY,
CSML_CLIENT_API_SECRET,
CSML_CLIENT_URL = 'https://clients.csml.dev/v1',
DEBUG,
} = process.env;
class BotsService {
/**
* Get airules of a bot
*
* @async
* @returns array
*/
static async getRepoAirules() {
try {
console.log('Getting airules.json...')
let airules = (fs.existsSync('airules.json'))
? JSON.parse(fs.readFileSync('airules.json'))
: [];
if (DEBUG) console.log({ airules });
console.log(`Got ${airules.length} airules.`)
return airules;
}
catch (err) {
console.warn("Invalid airules.json file.")
return []
}
}
/**
* Get flows of a bot
* @async
* @returns array
*/
static async getRepoFlows() {
console.log('Getting repository flows...')
const flows = [];
if (fs.existsSync('flows')) {
fs.readdirSync('flows')
.forEach((fileName) => {
if (fileName.endsWith('.csml')) {
flows.push(fs.readFileSync(`flows/${fileName}`).toString());
}
});
}
if (DEBUG) console.log(flows);
console.log(`Got ${flows.length} repository flows.`)
return flows;
}
/**
* Create the signature to authentify call towards csml client's api
*
* @returns array
*/
static setAuthenticationHeader() {
const UNIX_TIMESTAMP = Math.floor(Date.now() / 1000);
const XApiKey = `${CSML_CLIENT_API_KEY}|${UNIX_TIMESTAMP}`;
const signature = crypto.createHmac('sha256', CSML_CLIENT_API_SECRET)
.update(XApiKey, 'utf-8')
.digest('hex');
const XApiSignature = `sha256=${signature}`;
return [XApiKey, XApiSignature];
}
/**
* Build the bot via the studio client API
*/
static async buildBot() {
const [XApiKey, XApiSignature] = BotsService.setAuthenticationHeader();
await request.post(`${CSML_CLIENT_URL}/api/bot/build`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send()
.catch(err => {
if (DEBUG) console.error(err);
throw err;
});
console.log('Successfully built bot');
}
/**
* Sync the flows and airule from the repository to the csml studio.
*/
static async updateBot() {
const [XApiKey, XApiSignature] = BotsService.setAuthenticationHeader();
const localFlows = await BotsService.getRepoFlows();
const airules = await BotsService.getRepoAirules();
console.log('Getting CSML Studio flows...')
const studioFlows = await request.get(`${CSML_CLIENT_URL}/api/bot/flows`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.then(res => res.body);
console.log(`Got ${studioFlows.length} CSML Studio flows.`)
const deleteFlows = [];
const updateFlows = [];
const createFlows = [];
studioFlows.forEach(studioFlow => {
const found = localFlows.find(f => f.name.toLowerCase() === studioFlow.name.toLowerCase());
if (found) updateFlows.push({ ...studioFlow, ...found });
else deleteFlows.push(studioFlow);
});
localFlows.forEach(f => {
const found = studioFlows.find(sf => sf.name.toLowerCase() === f.name.toLowerCase());
if (!found) createFlows.push(f);
})
console.log(`Deleting ${deleteFlows.length} removed flows...`)
if (deleteFlows.length) {
await Promise.each(deleteFlows, async df => {
await request.del(`${CSML_CLIENT_URL}/api/bot/flows/${df.id}`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send(df)
.catch(err => {
if (DEBUG) console.error(df, err);
throw err;
});
});
console.log('Deleted flows.');
}
console.log(`Updating ${updateFlows.length} flows...`)
if (updateFlows.length) {
await Promise.each(updateFlows, async uf => {
await request.put(`${CSML_CLIENT_URL}/api/bot/flows/${uf.id}`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send(uf)
.catch(err => {
if (DEBUG) console.error(uf, err);
throw err;
});
});
console.log('Updated flows.');
}
console.log(`Creating ${createFlows.length} new flows...`)
if (createFlows.length) {
await Promise.each(createFlows, async cf => {
await request.post(`${CSML_CLIENT_URL}/api/bot/flows`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send(cf)
.catch(err => {
if (DEBUG) console.error(cf, err);
throw err;
});
});
console.log('Created flows.');
}
if (airules) {
console.log('Updating airules...')
await request.put(`${CSML_CLIENT_URL}/api/bot`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send({ airules })
.catch(err => {
if (DEBUG) console.error({ airules }, err);
throw err;
});
console.log('Updated airules.')
}
}
/**
* Create a new snapshot
*
* @param {string} snapshotName
*/
static async createSnapshot(snapshotName) {
const [XApiKey, XApiSignature] = BotsService.setAuthenticationHeader();
console.log(`Creating snapshot ${snapshotName}...`);
await request.post(`${CSML_CLIENT_URL}/api/bot/label`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.send({ label: snapshotName })
.then(res => res.body)
.catch(err => {
if (DEBUG) console.error(err);
throw err;
});
console.log(`Successfully created bot snapshot ${snapshotName}.`);
}
/**
* Delete an existing snapshot
*
* @param {string} snapshotName
*/
static async deleteSnapshot(snapshotName) {
const [XApiKey, XApiSignature] = BotsService.setAuthenticationHeader();
console.log(`Deleting snapshot ${snapshotName}...`);
await request.del(`${CSML_CLIENT_URL}/api/bot/label/${snapshotName}`)
.set('X-Api-Key', XApiKey)
.set('X-Api-Signature', XApiSignature)
.then(res => res.body)
.catch(err => {
if (DEBUG) console.error(err);
throw err;
});
console.log(`Successfully deleted bot snapshot ${snapshotName}.`);
}
}
module.exports = { BotsService };