This repository was archived by the owner on May 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
456 lines (416 loc) · 10.1 KB
/
index.js
File metadata and controls
456 lines (416 loc) · 10.1 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
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
const Https = require('./https')
/**
* Politely tell someone they didn't define an arg
* @param {string} name
*/
function required(name) {
throw new Error(
`You are missing some params! Make sure you set ${name} properly (maybe .env) 🤷🏼`
)
}
class Sprucebot {
constructor({
apiKey = required('apiKey'),
id = required('id'),
host = required('host'),
name = required('name'),
description = required('description'),
interfaceUrl = required('interfaceUrl'),
serverUrl = required('serverUrl'),
svgIcon = required('svgIcon'),
allowSelfSignedCerts = false,
dbEnabled = false
}) {
const hostMatches = host.match(/^(https?\:\/\/|)([^\/:?#]+)(?:[\/:?#]|$)/i)
const cleanedHost =
hostMatches && hostMatches[2] ? hostMatches[2] : required('host')
this.name = name || required('name')
this.description = description || required('description')
this.icon = svgIcon || required('svgIcon')
this.webhookUrl = (serverUrl || required('serverUrl')) + '/hook.json'
this.iframeUrl = interfaceUrl || required('interfaceUrl')
this.marketingUrl =
(interfaceUrl || required('interfaceUrl')) + '/marketing'
this.dbEnabled = dbEnabled
this._mutexes = {}
this.version = '1.0' // maybe pull from package.json?
// Setup http(s) class with everything it needs to talk to api
this.https = new Https({
host: cleanedHost,
apiKey,
id,
version: this.version,
allowSelfSignedCerts
})
console.log(
`🌲 Sprucebot🌲 Skills Kit API ${this
.version}\n\nhost : ${cleanedHost} \nid : ${id} \napiKey : ${apiKey.replace(
/./g,
'*'
)} \nname : ${name}\n---------------------------------`
)
}
/**
* Sync the settings saved here with specified host (including name,)
*/
async sync() {
const data = {
name: this.name,
description: this.description,
icon: this.icon,
webhookUrl: this.webhookUrl,
iframeUrl: this.iframeUrl,
marketingUrl: this.marketingUrl
}
const results = await this.https.patch('/', data)
let database = null
if (this.dbEnabled) {
database = await this.provisionDatabase()
}
return { ...results, database }
}
async provisionDatabase() {
return this.https.get('/database/provision')
}
/**
* Fetch a user based on their id and location
*
* @param {String} userId
* @param {String} locationId
* @param {Object} query Optional query string to be added onto request
* @returns {Promise}
*/
async user(locationId, userId, query) {
return this.https.get(`/locations/${locationId}/users/${userId}`, query)
}
/**
* Get a user without a location. GLOBAL SKILLS ONLY
*
* @param {String} userId
* @param {Object} Optional query string to be added to the request
*/
async globalUser(userId, query) {
return this.https.get(`/users/${userId}`, query)
}
/**
* Get all locations. GLOBAL SKILLS ONLY
*
* @param {Object} Optional query string to be added to the request
*/
async globalLocations(query) {
return this.https.get(`/ge/locations`, query)
}
/**
* Create a user
*
* @param {Object} values
* @returns {Promise}
*/
async createUser(values) {
return this.https.post('/ge/users', values)
}
/**
* Update a users role
*
* @param {String} locationId
* @param {String} userId
* @param {String} role
* @returns {Promise}
*/
async updateRole(locationId, userId, role) {
return this.https.patch(
`/ge/locations/${locationId}/users/${userId}/${role}`
)
}
/**
* Search for users who have been to this location
*
* @param {String} locationId
* @param {Object} query
* @returns {Promise}
*/
async users(locationId, { role, status, page, limit } = {}) {
return this.https.get(
`/locations/${locationId}/users/`,
Array.from(arguments)[1]
)
}
/**
* Update for user who have been to this location
*
* @param {String} id
* @param {Object} values
* @returns {Promise}
*/
async updateUser(id, values) {
return this.https.patch('/users/' + id, values)
}
/**
* Get a location by id
*
* @param {String} locationId
* @param {Object} query
* @returns {Promise}
*/
async location(locationId, query) {
return this.https.get(`/locations/${locationId}`, query)
}
/**
* Fetch all locations where this skill is installed
*
* @param {Object} query
* @returns {Promise}
*/
async locations({ page, limit } = {}) {
return this.https.get('/locations', Array.from(arguments)[0])
}
/**
* Send a message to a user.
*
* @param {String} locationId
* @param {String} userId
* @param {String} message
* @param {Object} data Additional data sent when POST'ing message
*/
async message(
locationId,
userId,
message,
{ linksToWebView, webViewQueryData, payload } = {},
query = {}
) {
const data = Array.from(arguments)[3] || {}
data.userId = userId
data.message = message
if (data.webViewQueryData) {
data.webViewQueryData = JSON.stringify(data.webViewQueryData)
}
return this.https.post(`/locations/${locationId}/messages`, data, query)
}
/**
* ONLY APPLIES TO SKILLS THAT ARE GLOBAL (are not attached to a location).
* This allows Sprucebot to communicate to business owners without them
* actually needing any skills enabled. Core usage only.
*
* @param {String} userId
* @param {String} message
*/
async globalMessage(userId, message) {
return this.https.post('/messages', { userId, message })
}
/**
* Get a bunch of meta data at once
*
* @param {Object} query
* @param {Boolean} suppressErrors
*/
async metas(
{
key,
locationId,
userId,
createdAt,
updatedAt,
sortBy,
order,
limit,
value
} = {},
suppressParseErrors = true
) {
const query = { ...(Array.from(arguments)[0] || {}) }
if (query.value) {
query.value = JSON.stringify(query.value)
}
if (query.userId) {
query.userId = JSON.stringify(query.userId)
}
if (query.locationId) {
query.locationId = JSON.stringify(query.locationId)
}
if (query.createdAt) {
query.createdAt = JSON.stringify(query.createdAt)
}
if (query.updatedAt) {
query.updatedAt = JSON.stringify(query.updatedAt)
}
return this.https.get('/data', query)
}
/**
* Get one meta object back.
*
* @param {String} key
* @param {Object} query
* @param {Boolean} suppressParseErrors
*/
async meta(
key,
{ locationId, userId, value, sortBy, order } = {},
suppressParseErrors = true
) {
const args = Array.from(arguments)
const query = { ...(args[1] || {}) }
query.key = key
query.limit = 1
const metas = await this.metas(query)
return metas[0]
}
/**
* Get skill meta data by id
*
* @param {String} id
*/
async metaById(id, { locationId, userId } = {}) {
return this.https.get(`/data/${id}`, Array.from(arguments)[1])
}
/**
* Create a meta data record.
*
* @param {String} key
* @param {*} value
* @param {Object} data
*/
async createMeta(key, value, { locationId, userId } = {}) {
const data = {
...(Array.from(arguments)[2] || {}),
key,
value
}
const meta = await this.https.post('/data', data)
return meta
}
/**
* Update some meta data by id
*
* @param {String} id
* @param {Object} data
*/
async updateMeta(id, { key, value, locationId, userId }) {
const data = {
...(Array.from(arguments)[1] || {})
}
const meta = await this.https.patch(`/data/${id}`, data)
return meta
}
/**
* Fetch some meta. Create it if it does not exist
*
* @param {String} key
* @param {*} value
* @param {Object} query
* @param {Boolean} suppressParseErrors
*/
async metaOrCreate(
key,
value,
{ locationId, userId } = {},
suppressParseErrors = true
) {
let meta = await this.meta(
key,
Array.from(arguments)[2],
suppressParseErrors
)
// not found, create it
if (!meta) {
meta = await this.createMeta(key, value, Array.from(arguments)[2])
}
return meta
}
/**
* Creates a meta if it does not exist, updates it if it does
* @param {String} key
* @param {*} value
* @param {Object} query
* @param {Boolean} suppressParseErrors
*/
async upsertMeta(
key,
value,
{ locationId, userId } = {},
suppressParseErrors = true
) {
let meta = await this.meta(
key,
Array.from(arguments)[2],
suppressParseErrors
)
// not found, create it
if (!meta) {
meta = await this.createMeta(key, value, Array.from(arguments)[2])
} else if (JSON.stringify(meta.value) !== JSON.stringify(value)) {
//found, but value has changed
meta = await this.updateMeta(meta.id, { value: value })
}
return meta
}
/**
* Delete meta data by id
*
* @param {String} id
*/
async deleteMeta(id) {
return this.https.delete(`/data/${id}`)
}
/**
* Emit a custom event. The response is the response from all skills
*
* @param {String} name
* @param {Object} payload
*/
async emit(locationId, eventName, payload = {}) {
return this.https.post(`locations/${locationId}/emit`, {
eventName,
payload
})
}
/**
* To stop race conditions, you can have requests wait before starting the next.
*
* @param {String} key
*/
async wait(key) {
if (!this._mutexes[key]) {
this._mutexes[key] = {
promises: [],
resolvers: [],
count: 0
}
}
//track which we are on
this._mutexes[key].count++
//first is always auto resolved
if (this._mutexes[key].count === 1) {
this._mutexes[key].promises.push(new Promise(resolve => resolve()))
this._mutexes[key].resolvers.push(() => {})
} else {
let resolver = resolve => {
this._mutexes[key].resolvers.push(resolve)
}
let promise = new Promise(resolver)
this._mutexes[key].promises.push(promise)
}
return this._mutexes[key].promises[this._mutexes[key].count - 1]
}
/**
* Long operation is complete, start up again.
*
* @param {String} key
*/
async go(key) {
if (this._mutexes[key]) {
//remove this promise
this._mutexes[key].promises.shift()
this._mutexes[key].resolvers.shift()
this._mutexes[key].count--
//if we are done, clear
if (this._mutexes[key].count === 0) {
delete this._mutexes[key]
} else {
//otherwise resolve the next promise
this._mutexes[key].resolvers[0]()
}
}
}
}
module.exports = Sprucebot