-
Notifications
You must be signed in to change notification settings - Fork 1
/
callws.js
323 lines (246 loc) · 8.52 KB
/
callws.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
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
var express = require('express')
var cheerio = require('cheerio');
var querystring = require('querystring');
var app = express()
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
const pug = require('pug');
var quip = require('./quip.js');
var jsforce = require('jsforce');
var qclient = new quip.Client({accessToken: process.env.QUIP_TOKEN});
var store = new MongoDBStore(
{
uri: process.env.MONGODB_URI,
collection: 'QuipBotSessions'
});
// Catch errors
store.on('error', function(error) {
//assert.ifError(error);
//assert.ok(false);
console.log(error);
});
app.set('views', './views');
app.set('view engine', 'pug');
//no idea if this is right, seems to work.
app.use('/favicon.ico', express.static(__dirname + '/favicon.ico'));
app.use('/assets', express.static(__dirname + '/node_modules/@salesforce-ux/design-system/assets'));
app.use(require('express-session')({
secret: 'This is a secret',
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
},
store: store,
// Boilerplate options, see:
// * https://www.npmjs.com/package/express-session#resave
// * https://www.npmjs.com/package/express-session#saveuninitialized
resave: true,
saveUninitialized: true
}));
app.get('/', function (req, res) {
res.render('home', { title: 'Hey', message: 'Hello there!' })
// res.send('Hello World! ' + JSON.stringify(req.session))
})
//use heroku port, otherwise 3000
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Quipbot listening on port ' + port)
})
var sfcon;
//
// OAuth2 client information can be shared with multiple connections.
//
var oauth2 = new jsforce.OAuth2({
// you can change loginUrl to connect to sandbox or prerelease env.
// loginUrl : 'https://test.salesforce.com',
clientId : process.env.SFDC_CONSUMER,
clientSecret : process.env.SFDC_SECRET,
redirectUri : process.env.WHERE + '/oauth2/callback'
});
//
// Get authz url and redirect to it.
//
app.get('/oauth2/auth', function(req, res) {
res.redirect(oauth2.getAuthorizationUrl({ scope : 'full refresh_token offline_access' }));
});
app.get('/oauth2/callback', function(req, res) {
var conn = new jsforce.Connection({ oauth2 : oauth2 });
var code = req.param('code');
conn.authorize(code, function(err, userInfo) {
if (err) { res.send('Error Authenticating, you didnt try org62 did you?'); return console.error(err); }
// Now you can get the access token, refresh token, and instance URL information.
// Save them to establish connection next time.
//req.session.sfdcconn = conn;
req.session.userinfo = userInfo;
req.session.sfdc_accessToken = conn.accessToken;
req.session.sfdc_refreshToken = conn.refreshToken;
req.session.sfdc_instanceUrl = conn.instanceUrl;
sfcon = conn;
res.send('connected to ' + conn.instanceUrl);
// ...
});
});
var Client = require('node-rest-client').Client;
var rclient = new Client();
var WebSocketClient = require('websocket').client;
var client = new WebSocketClient();
var args = {
headers: { "Authorization": "Bearer " + process.env.QUIP_TOKEN } // request headers
};
var url;
// direct way
rclient.get("https://platform.quip.com/1/websockets/new", args, function (data, response) {
// parsed response body as js object
console.log(data);
url = data;
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
//hope this is part of the Acceptable usage policy?
console.log('echo-protocol Connection Closed');
setTimeout(startnew, 5000);
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
var mess = JSON.parse(message.utf8Data);
if(mess.type == 'message'){
if(mess.message.text.startsWith("#")){
console.log('bot');
var thread = mess.thread.id;
var annotation = '';
if(mess.message.annotation){
annotation = mess.message.annotation.id;
}
var records = [];
// qclient.getThread(thread, function(err, threads){
//console.log(err);
//console.log(threads);
//});
if(mess.message.text.startsWith('#upload')){
uploadtable(thread, annotation, mess.message.text);
} else {
queryrespond(thread, annotation, mess.message.text);
}
}
// console.log(mess.message.text);
}
}
});
});
//quip expects origin to be set.
client.connect(url.url, null, 'https://quip.com' , null , null);
});
const compiledFunction = pug.compileFile('./views/index.pug');
function uploadtable(thread, annotation, message){
var uploadfields = [];
var uploadData;
//sobject name is in second argument
var sobject = message.split(' ')[1];
var $;
//get the latest thread from quip
qclient.getThread(thread, function(err, threads){
$ = cheerio.load(threads.html);
//first find the header in the table with sobject name
$('table[title=' + sobject + ']').find('thead span').each(function(i, elem) {
uploadfields.push($(this).text());
//console.log($(this).text());
});;
//create array to store all records in
var uploadtable = [];
//loop trough all table rows
$('table[title=' + sobject + ']').find('tr').each(function(i, elem) {
//dont care about the header
if(i == 0){return;}
//new datarow
var datarow = {};
$(this).find('span').each(function(t, elem) {
var rowfield = {};
//add fields to datarow
datarow[uploadfields[t]] = $(this).text();
//datarow.push(rowfield);
//console.log(i + ' ' + $(this).text());
})
uploadtable.push(datarow);
});;
//do a bulkupdate, otherwise api gets killed
sfcon.sobject(sobject).bulkload('update', uploadtable,
function(err, rets) {
if (err) { return console.error(err); }
for (var i=0; i < rets.length; i++) {
if (rets[i].success) {
console.log("Updated Successfully : " + rets[i].id);
} else {
console.log(rets);
}
}
});
// console.log(uploadtable);
})
}
function queryrespond(thread, annotation, message){
var sobject = message.split(' ', 1)[0].substring(1);
var limit = message.split(' ', 2)[1] || 10;
var fields = message.split(' ', 3)[2] || null;
if(fields == null){
//myArray = myString.split(',');
switch (sobject) {
case 'case':
fields ='Id, Subject, description, Status';
break;
case 'workorder':
fields ='id, Subject, Status';
break;
case 'contact':
fields ='id, lastname, firstname';
break;
default:
fields ='Id, Name';
}
}
//yeah a where clause would be cool
sfcon.sobject(sobject)
.find({}, fields )
.limit(limit)
.execute(function(err, result){
// sfcon.query("SELECT " + fields + " FROM " + sobject + " LIMIT " + limit, function(err, result) {
if (err) {
respond(thread, 'error', annotation, null);
return console.error(err); }
console.log(result);
//get rid of the attributes
for (var i = 0, len = result.length; i < len; i++) {
delete result[i].attributes;
}
//call addsection to add to spreadsheet
addsection(thread, compiledFunction({ records: result, rtype: sobject}));
}
)}
function addsection(thread, message){
var newsection = {
threadId : thread,
content : message
}
console.log(newsection);
qclient.editDocument(newsection, sentedit);
}
function sentedit(error, message){
console.log('edit sent ' + error);
console.log(message);
}
function respond(thread, message, responseto, parts){
//parts need very specific generation, too much effort so took it out
var newmessages = { threadId : thread , content : message, annotation_id : responseto};
qclient.newMessage(newmessages, sentmessage);
}
function sentmessage(error, message){
// console.log('message sent ' + error + message);
}
function startnew(){
client.connect(url.url, null, 'https://quip.com' , null , null);
}