-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircuit.js
103 lines (91 loc) · 2.51 KB
/
circuit.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
/* jslint node: true */
'use strict';
const Circuit = require('circuit-sdk');
const config = require('./config.json');
let client;
let emitter;
let appUserId;
//Circuit.setLogger(console);
//Circuit.logger.setLevel(Circuit.Enums.LogLevel.Debug);
function init (events) {
emitter = events;
client = new Circuit.Client(config.bot);
return client.logon()
.then(user => appUserId = user.userId)
.then(setupListeners);
}
function createConversation(userIds, name) {
return client.createGroupConversation(userIds, `Cust: ${name}`);
}
function getUsersByEmail(emails) {
return client.getUsersByEmail(emails)
}
function sendMessage(convId, obj) {
return client.addTextItem(convId, obj)
}
function getMessages(convId, threadId) {
// getItemsByThread does not include the parent, so get it first
// or does it???
return new Promise((resolve, reject) => {
let res = [];
client.getItemById(threadId)
// .then(item => res.push(item))
.then(() => client.getItemsByThread(convId, threadId, { number: -1 }))
.then(resp => res.push(...resp.items))
.then(() => {
res = res.map(m => {
return {
content: m.text.content,
fromCustomer: m.creatorId === appUserId,
timestamp: m.creationTime
}
});
resolve(res);
})
.catch(reject);
});
}
/**
* Setup the listeners
*/
function setupListeners() {
client.addEventListener('itemAdded', evt => {
// Raise text messages for further processing
console.log(evt);
if (!evt.item.text) {
// not a text message
return;
}
emitter.emit('message-received', {
convId: evt.item.convId,
thread: evt.item.parentItemId || evt.item.itemId,
message: evt.item.text.content,
fromCustomer: evt.item.creatorId === appUserId
});
});
client.addEventListener('itemUpdated', evt => {
// Raise text messages for further processing
console.log(evt);
if (!evt.item.text) {
// not a text message
return;
}
emitter.emit('thread-updated', {
convId: evt.item.convId,
thread: evt.item.parentItemId || evt.item.itemId
});
});
}
Circuit.Injectors.itemInjector = function (item) {
if (item.type === 'TEXT') {
// Replacing br and hr tags with a space
item.text.content = item.text.content.replace(/<(\/li|hr[\/]?)>/gi, '<br>');
}
};
module.exports = {
init,
createConversation,
sendMessage,
getMessages,
getUsersByEmail
}