@tiledesk/tiledesk-server 2.9.5 → 2.9.7

Sign up to get free protection for your applications and to get access to all the features.
@@ -25,7 +25,7 @@ var mongoose = require('mongoose');
25
25
  const requestConstants = require("../models/requestConstants");
26
26
  var RoleConstants = require('../models/roleConstants');
27
27
 
28
- let configSecretOrPubicKay = process.env.GLOBAL_SECRET || config.secret;
28
+ let configSecretOrPubicKay = process.env.GLOBAL_SECRET || config.secret;
29
29
 
30
30
  var pKey = process.env.GLOBAL_SECRET_OR_PUB_KEY;
31
31
  // console.log("pKey",pKey);
@@ -38,16 +38,16 @@ var cacheEnabler = require("../services/cacheEnabler");
38
38
 
39
39
 
40
40
  var lastRequestsLimit = process.env.WS_HISTORY_REQUESTS_LIMIT || 100;
41
- winston.debug('lastRequestsLimit:'+ lastRequestsLimit);
41
+ winston.debug('lastRequestsLimit:' + lastRequestsLimit);
42
42
 
43
43
  var messagesLimit = process.env.WS_HISTORY_MESSAGES_LIMIT || 300;
44
- winston.debug('messagesLimit:'+ messagesLimit);
44
+ winston.debug('messagesLimit:' + messagesLimit);
45
45
 
46
46
  var lastEventsLimit = process.env.WS_HISTORY_EVENTS_LIMIT || 20;
47
- winston.debug('lastEventsLimit:'+ lastEventsLimit);
47
+ winston.debug('lastEventsLimit:' + lastEventsLimit);
48
48
 
49
49
  var websocketServerPath = process.env.WS_SERVER_PATH || '/';
50
- winston.debug('websocketServerPath:'+ websocketServerPath);
50
+ winston.debug('websocketServerPath:' + websocketServerPath);
51
51
 
52
52
 
53
53
 
@@ -56,117 +56,117 @@ class WebSocketServer {
56
56
  constructor() {
57
57
  this.clientsSubscriptions = {};
58
58
  }
59
-
59
+
60
60
 
61
61
  // https://hackernoon.com/nodejs-web-socket-example-tutorial-send-message-connect-express-set-up-easy-step-30347a2c5535
62
62
  // https://medium.com/@martin.sikora/node-js-websocket-simple-chat-tutorial-2def3a841b61
63
63
  init(server) {
64
-
65
- winston.info('Starting websocket on path: '+ websocketServerPath);
64
+
65
+ winston.info('Starting websocket on path: ' + websocketServerPath);
66
66
 
67
67
  //var wss = new WebSocket.Server({ port: 40510 });
68
68
  //var wss = new WebSocket.Server({ port: 40510 , path: "/messages" });
69
69
  //var wss = new WebSocket.Server({ port: 80 ,path: "/messages" });
70
70
  // var wss = new WebSocket.Server({ server: server,path: "/messages" });
71
71
 
72
- var wss = new WebSocket.Server({
73
- server: server,
74
- path: websocketServerPath,
75
- verifyClient: function (info, cb) {
76
- //console.log('info.req', info.req);
77
- // var token = info.req.headers.Authorization
78
- let urlParsed = url.parse(info.req.url, true);
79
- // console.log('urlParsed', urlParsed);
80
- var queryParameter = urlParsed.query;
81
- winston.debug('queryParameter', queryParameter);
82
-
83
- var token = queryParameter.token;
84
- winston.debug('token:'+ token);
85
- winston.debug('configSecretOrPubicKay:'+ configSecretOrPubicKay);
86
-
87
-
88
- if (!token)
89
- cb(false, 401, 'Unauthorized');
90
- else {
91
- token = token.replace('JWT ', '');
92
- jwt.verify(token, configSecretOrPubicKay, function (err, decoded) { //pub_jwt pp_jwt
93
- if (err) {
94
- winston.error('WebSocket error verifing websocket jwt token ', err);
95
- return cb(false, 401, 'Unauthorized');
96
- } else {
97
- // uncomment it
98
- const identifier = decoded._id || decoded._doc._id;
99
-
100
-
101
- winston.debug('valid token:'+identifier);
102
- // roleChecker.hasRoleAsPromise().then(function(project_user) {
103
- // winston.debug('hasRoleAsPromise project_user',project_user);
104
- // winston.debug('ok websocket');
105
-
106
- User.findOne({_id: identifier, status: 100}, 'email firstname lastname emailverified id') //TODO user_cache_here ma attento select.. ATTENTO SERVER SELECT??
107
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, "users:id:"+identifier) //user_cache
108
- .exec(function (err, user) {
109
-
110
-
111
- if (err) {
112
- // console.log("BasicStrategy err.stop");
113
- return winston.error('error verifing websocket jwt token. User find error ', err);
114
- }
115
- if (!user) {
116
- winston.verbose('websocket user not found with id : '+identifier);
117
- return cb(false, 401, 'Unauthorized');
118
- }
119
-
120
- // info.req.user = decoded;
121
- info.req.user = user;
122
- winston.debug('info.req.user',info.req.user.toObject());
123
- return cb(true);
72
+ var wss = new WebSocket.Server({
73
+ server: server,
74
+ path: websocketServerPath,
75
+ verifyClient: function (info, cb) {
76
+ //console.log('info.req', info.req);
77
+ // var token = info.req.headers.Authorization
78
+ let urlParsed = url.parse(info.req.url, true);
79
+ // console.log('urlParsed', urlParsed);
80
+ var queryParameter = urlParsed.query;
81
+ winston.debug('queryParameter', queryParameter);
82
+
83
+ var token = queryParameter.token;
84
+ winston.debug('token:' + token);
85
+ winston.debug('configSecretOrPubicKay:' + configSecretOrPubicKay);
86
+
87
+
88
+ if (!token)
89
+ cb(false, 401, 'Unauthorized');
90
+ else {
91
+ token = token.replace('JWT ', '');
92
+ jwt.verify(token, configSecretOrPubicKay, function (err, decoded) { //pub_jwt pp_jwt
93
+ if (err) {
94
+ winston.error('WebSocket error verifing websocket jwt token ', err);
95
+ return cb(false, 401, 'Unauthorized');
96
+ } else {
97
+ // uncomment it
98
+ const identifier = decoded._id || decoded._doc._id;
99
+
100
+
101
+ winston.debug('valid token:' + identifier);
102
+ // roleChecker.hasRoleAsPromise().then(function(project_user) {
103
+ // winston.debug('hasRoleAsPromise project_user',project_user);
104
+ // winston.debug('ok websocket');
105
+
106
+ User.findOne({ _id: identifier, status: 100 }, 'email firstname lastname emailverified id') //TODO user_cache_here ma attento select.. ATTENTO SERVER SELECT??
107
+ //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, "users:id:"+identifier) //user_cache
108
+ .exec(function (err, user) {
124
109
 
125
- });
126
110
 
127
-
128
- // }).catch(function(err){
129
- // winston.error('hasRoleAsPromise err',err);
130
- // cb(false, 401, err.msg);
131
- // });
132
-
111
+ if (err) {
112
+ // console.log("BasicStrategy err.stop");
113
+ return winston.error('error verifing websocket jwt token. User find error ', err);
114
+ }
115
+ if (!user) {
116
+ winston.verbose('websocket user not found with id : ' + identifier);
117
+ return cb(false, 401, 'Unauthorized');
133
118
  }
134
- })
135
119
 
136
- }
120
+ // info.req.user = decoded;
121
+ info.req.user = user;
122
+ winston.debug('info.req.user', info.req.user.toObject());
123
+ return cb(true);
124
+
125
+ });
126
+
127
+
128
+ // }).catch(function(err){
129
+ // winston.error('hasRoleAsPromise err',err);
130
+ // cb(false, 401, err.msg);
131
+ // });
132
+
133
+ }
134
+ })
135
+
137
136
  }
137
+ }
138
138
  });
139
139
 
140
140
 
141
- var onConnectCallback = async function(client, req) {
141
+ var onConnectCallback = async function (client, req) {
142
142
  winston.debug('onConnectCallback ');
143
- return new Promise(function(resolve, reject) {
143
+ return new Promise(function (resolve, reject) {
144
144
  return resolve("ok");
145
145
  });
146
146
  // check here if you can subscript o publish message
147
147
  }
148
148
 
149
- var onDisconnectCallback = async function(subscript, id) {
150
- winston.debug('onDisconnectCallback: '+subscript +":"+ id);
151
- return new Promise(function(resolve, reject) {
149
+ var onDisconnectCallback = async function (subscript, id) {
150
+ winston.debug('onDisconnectCallback: ' + subscript + ":" + id);
151
+ return new Promise(function (resolve, reject) {
152
152
  return resolve("ok");
153
153
  });
154
154
  // check here if you can subscript o publish message
155
155
  }
156
156
 
157
157
 
158
- //tilebaseMess.send('{ "action": "publish", "payload": { "topic": "/apps/123/requests/sendid/conversations/RFN", "message":{"sender_id":"sendid","sender_fullname":"SFN", "recipient_id":"RFN", "recipient_fullname":"RFN","text":"hi","app_id":"123"}}}');
159
- var onPublishCallback = async function(publishTopic, publishMessage, from) {
160
- winston.debug("onPublish topic: "+publishTopic +" from: "+from, publishMessage);
161
- return new Promise(function(resolve, reject) {
158
+ //tilebaseMess.send('{ "action": "publish", "payload": { "topic": "/apps/123/requests/sendid/conversations/RFN", "message":{"sender_id":"sendid","sender_fullname":"SFN", "recipient_id":"RFN", "recipient_fullname":"RFN","text":"hi","app_id":"123"}}}');
159
+ var onPublishCallback = async function (publishTopic, publishMessage, from) {
160
+ winston.debug("onPublish topic: " + publishTopic + " from: " + from, publishMessage);
161
+ return new Promise(function (resolve, reject) {
162
162
  return resolve("ok");
163
163
  });
164
-
164
+
165
165
  }
166
166
 
167
- var onMessageCallback = async function(id, message) {
168
- winston.debug('onMessageCallback ',id, message);
169
- return new Promise(function(resolve, reject) {
167
+ var onMessageCallback = async function (id, message) {
168
+ winston.debug('onMessageCallback ', id, message);
169
+ return new Promise(function (resolve, reject) {
170
170
  return resolve("ok");
171
171
  });
172
172
  // check here if you can subscript o publish message
@@ -174,467 +174,483 @@ class WebSocketServer {
174
174
 
175
175
  // tilebase.send('{ "action": "subscribe", "payload": { "topic": "/app1/requests"}}');
176
176
 
177
- var onSubscribeCallback = async function(topic, clientId, req) {
178
- return new Promise(function(resolve, reject) {
179
- winston.debug('onSubscribeCallback :'+topic+ " "+ clientId);
180
-
181
- winston.debug(' req.user._id: '+ req.user);
177
+ var onSubscribeCallback = async function (topic, clientId, req) {
178
+ return new Promise(function (resolve, reject) {
179
+ winston.debug('onSubscribeCallback :' + topic + " " + clientId);
182
180
 
183
- if (!topic) {
184
- winston.error('WebSocket - Error getting topic. Topic can t be null');
185
- return reject('WebSocket - Error getting topic. Topic can t be null');
186
- }
187
- var urlSub = topic.split('/');
188
- winston.debug('urlSub: '+urlSub);
181
+ winston.debug(' req.user._id: ' + req.user);
182
+
183
+ if (!topic) {
184
+ winston.error('WebSocket - Error getting topic. Topic can t be null');
185
+ return reject('WebSocket - Error getting topic. Topic can t be null');
186
+ }
187
+ var urlSub = topic.split('/');
188
+ winston.debug('urlSub: ' + urlSub);
189
+
190
+ if (!urlSub || (urlSub && urlSub.length == 0)) {
191
+ winston.error('WebSocket - Error getting topic. Topic is not properly configured');
192
+ return reject('WebSocket - Error getting topic. Topic is not properly configured');
193
+ }
194
+ // Error getting Project Cast to ObjectId failed for value "N7VJlLZ1" (type string) at path "_id" for model "project" {"kind":"ObjectId","path":"_id","reason":{},"stack":"CastError: Cast to ObjectId failed for value \"N7VJlLZ1\" (type string) at path \"_id\" for model \"project\"\n at model.Query.exec (/usr/src/app/node_modules/mongoose/lib/query.js:4498:21)\n at /usr/src/app/websocket/webSocketServer.js:180:14\n at new Promise (<anonymous>)\n at Object.onSubscribeCallback [as onSubscribe] (/usr/src/app/websocket/webSocketServer.js:167:14)\n at PubSub.handleReceivedClientMessage (/usr/src/app/websocket/pubsub.js:358:57)\n at runMicrotasks (<anonymous>)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)","stringValue":"\"N7VJlLZ1\"","value":"N7VJlLZ1","valueType":"string"}
195
+
196
+ var projectId = urlSub[1];
197
+ winston.debug('projectId: ' + projectId);
198
+
199
+
200
+ let q = Project.findOne({ _id: projectId, status: 100 })
201
+
202
+ if (cacheEnabler.project) {
203
+ q.cache(cacheUtil.defaultTTL, "projects:id:" + projectId) //project_cache
204
+ winston.debug('project cache enabled for websocket');
205
+ }
189
206
 
190
- if (!urlSub || (urlSub && urlSub.length==0)) {
191
- winston.error('WebSocket - Error getting topic. Topic is not properly configured');
192
- return reject('WebSocket - Error getting topic. Topic is not properly configured');
207
+ return q.exec(function (err, project) {
208
+ if (err) {
209
+ winston.error('WebSocket - Error getting Project', err);
210
+ return reject(err);
193
211
  }
194
- // Error getting Project Cast to ObjectId failed for value "N7VJlLZ1" (type string) at path "_id" for model "project" {"kind":"ObjectId","path":"_id","reason":{},"stack":"CastError: Cast to ObjectId failed for value \"N7VJlLZ1\" (type string) at path \"_id\" for model \"project\"\n at model.Query.exec (/usr/src/app/node_modules/mongoose/lib/query.js:4498:21)\n at /usr/src/app/websocket/webSocketServer.js:180:14\n at new Promise (<anonymous>)\n at Object.onSubscribeCallback [as onSubscribe] (/usr/src/app/websocket/webSocketServer.js:167:14)\n at PubSub.handleReceivedClientMessage (/usr/src/app/websocket/pubsub.js:358:57)\n at runMicrotasks (<anonymous>)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)","stringValue":"\"N7VJlLZ1\"","value":"N7VJlLZ1","valueType":"string"}
195
212
 
196
- var projectId = urlSub[1];
197
- winston.debug('projectId: '+projectId);
213
+ if (!project) {
214
+ winston.warn('WebSocket project not found for projectid ' + projectId);
215
+ return reject({ err: 'project not found for projectid ' + projectId });
216
+ }
198
217
 
218
+ if (topic.endsWith('/messages')) {
219
+ winston.debug(' messages: ');
199
220
 
200
- let q = Project.findOne({ _id: projectId, status: 100})
221
+ var recipientId = urlSub[3];
222
+ winston.debug('recipientId: ' + recipientId);
223
+ // winston.debug(' req.: ',req);
224
+
225
+
226
+ Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
227
+ //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
228
+ .exec(function (err, projectuser) {
229
+ if (err) {
230
+ winston.error('WebSocket error getting Project_user', err);
231
+ return reject(err);
232
+ }
233
+ if (!projectuser) {
234
+ winston.verbose('WebSocket project_user not found for user id ' + req.user._id + ' and projectid ' + projectId);
235
+ return reject({ err: 'Project_user not found for user id ' + req.user._id + ' and projectid ' + projectId });
236
+ }
237
+
238
+ var queryRequest = { id_project: projectId, request_id: recipientId };
239
+
240
+ if (projectuser.role == "owner" || projectuser.role == "admin") {
241
+ winston.debug('queryRequest admin: ' + JSON.stringify(queryRequest));
242
+ } else {
243
+ queryRequest["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
244
+ winston.debug('queryRequest agent: ' + JSON.stringify(queryRequest));
245
+ }
201
246
 
202
- if (cacheEnabler.project) {
203
- q.cache(cacheUtil.defaultTTL, "projects:id:"+projectId) //project_cache
204
- winston.debug('project cache enabled for websocket');
205
- }
206
-
207
- return q.exec(function(err, project) {
208
- if (err) {
209
- winston.error('WebSocket - Error getting Project', err);
210
- return reject(err);
211
- }
212
-
213
- if (!project) {
214
- winston.warn('WebSocket project not found for projectid ' + projectId);
215
- return reject({err:'project not found for projectid ' + projectId});
216
- }
217
-
218
- if (topic.endsWith('/messages')) {
219
- winston.debug(' messages: ');
220
-
221
- var recipientId = urlSub[3];
222
- winston.debug('recipientId: '+recipientId);
223
- // winston.debug(' req.: ',req);
224
-
225
-
226
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or:[ {"role": "agent"}, {"role": "admin"}, {"role": "owner"}], status: "active" })
227
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
228
- .exec(function (err, projectuser) {
229
- if (err) {
230
- winston.error('WebSocket error getting Project_user', err);
231
- return reject(err);
232
- }
233
- if (!projectuser) {
234
- winston.verbose('WebSocket project_user not found for user id '+ req.user._id + ' and projectid ' + projectId);
235
- return reject({err:'Project_user not found for user id '+ req.user._id + ' and projectid ' + projectId});
236
- }
237
-
238
- var queryRequest = {id_project:projectId, request_id: recipientId };
239
-
240
- if (projectuser.role == "owner" || projectuser.role == "admin") {
241
- winston.debug('queryRequest admin: '+ JSON.stringify(queryRequest));
242
- }else {
243
- queryRequest["$or"] = [ { "snapshot.agents.id_user": req.user.id}, {"participants": req.user.id}]
244
- winston.debug('queryRequest agent: '+ JSON.stringify(queryRequest));
245
- }
246
-
247
247
  // requestcachefarequi nocachepopulatereqired
248
- Request.findOne(queryRequest)
249
- .exec(function(err, request) {
250
-
251
- if (err) {
252
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
253
- return reject(err);
254
- }
255
- if (!request) {
256
- winston.verbose('WebSocket Request query not found for user id '+ req.user._id + ' and projectid ' + projectId);
257
- return reject({err:'Request query not found for user id '+ req.user._id + ' and projectid ' + projectId});
258
- }
259
-
260
- winston.debug('found request for onSubscribeCallback', request);
261
-
262
-
263
-
264
- var query = {id_project:projectId, recipient: recipientId };
265
- winston.debug('query : '+ JSON.stringify(query));
266
-
267
- Message.find(query).sort({createdAt: 'asc'})
268
- .limit(messagesLimit).exec(function(err, messages) {
269
-
270
- if (err) {
271
- winston.error('WebSocket Error finding message for onSubscribeCallback', err);
272
- return reject(err);
273
- }
274
- winston.debug('onSubscribeCallback find', messages);
275
-
276
-
277
- return resolve({publishFunction:function() {
278
- // handlePublishMessageToClientId (topic, message, clientId, method) {
279
- pubSubServer.handlePublishMessageToClientId (topic, messages, clientId, "CREATE");
280
- }});
281
-
248
+ Request.findOne(queryRequest)
249
+ .exec(function (err, request) {
250
+
251
+ if (err) {
252
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
253
+ return reject(err);
254
+ }
255
+ if (!request) {
256
+ winston.verbose('WebSocket Request query not found for user id ' + req.user._id + ' and projectid ' + projectId);
257
+ return reject({ err: 'Request query not found for user id ' + req.user._id + ' and projectid ' + projectId });
258
+ }
259
+
260
+ winston.debug('found request for onSubscribeCallback', request);
261
+
262
+
263
+
264
+ var query = { id_project: projectId, recipient: recipientId };
265
+ winston.debug('query : ' + JSON.stringify(query));
266
+
267
+ Message.find(query).sort({ createdAt: 'asc' })
268
+ .limit(messagesLimit).exec(function (err, messages) {
269
+
270
+ if (err) {
271
+ winston.error('WebSocket Error finding message for onSubscribeCallback', err);
272
+ return reject(err);
273
+ }
274
+ winston.debug('onSubscribeCallback find', messages);
275
+
276
+
277
+ return resolve({
278
+ publishFunction: function () {
279
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
280
+ pubSubServer.handlePublishMessageToClientId(topic, messages, clientId, "CREATE");
281
+ }
282
282
  });
283
- });
284
-
285
- });
286
-
287
- } else if (topic.endsWith('/requests')) {
288
-
289
- winston.debug('req.user._id: '+req.user._id);
290
- // winston.debug(' req.: ',req);
291
-
292
- winston.debug('find project_user');
293
-
294
-
295
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or:[ {"role": "agent"}, {"role": "admin"}, {"role": "owner"}], status: "active"})
296
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
297
- .exec(function (err, projectuser) {
298
- if (err) {
299
- winston.error('WebSocket error getting Project_user', err);
300
- return reject(err);
301
- }
302
- if (!projectuser) {
303
- winston.verbose('WebSocket Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId);
304
- return reject({err:'Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId});
305
- }
306
- winston.debug('projectuser', projectuser.toObject());
307
-
308
- // db.getCollection('requests').find({"id_project":"5e15bef09877c800176d217f","status":{"$lt":1000},"$or":[{"agents":{"id_user":"5ddd30bff0195f0017f72c6d"}},{"participants":"5ddd30bff0195f0017f72c6d"}]})
309
- // pubblica dopo toni
310
- var query = {"id_project":projectId, "status": { $lt: 1000, $gt: 50 }, preflight:false};
311
- // add hasBot:false
312
-
313
- // var query = {"id_project":projectId, "status": { $lt: 1000, $gt: 50 }, $or:[ {preflight:false}, { preflight : { $exists: false } } ] };
314
-
315
- // qui1000
316
- // var query = { id_project: projectId, statusObj: {closed:false, preflight:false} };
317
-
318
- var cacheUserId;
319
- if (projectuser.role == "owner" || projectuser.role == "admin") {
320
- winston.debug('query admin: '+ JSON.stringify(query));
321
- cacheUserId = "/admin-owner";
322
- }else {
323
- query["$or"] = [ { "snapshot.agents.id_user": req.user.id}, {"participants": req.user.id}]
324
- winston.debug('query agent: '+ JSON.stringify(query));
325
- cacheUserId = "/agent/"+req.user.id;
326
- }
327
283
 
328
- //cacheimportantehere
329
- // requestcachefarequi populaterequired
284
+ });
285
+ });
286
+
287
+ });
288
+
289
+ } else if (topic.endsWith('/requests')) {
290
+
291
+ winston.debug('req.user._id: ' + req.user._id);
292
+ // winston.debug(' req.: ',req);
293
+
294
+ winston.debug('find project_user');
295
+
296
+
297
+ Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
298
+ //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
299
+ .exec(function (err, projectuser) {
300
+ if (err) {
301
+ winston.error('WebSocket error getting Project_user', err);
302
+ return reject(err);
303
+ }
304
+ if (!projectuser) {
305
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
306
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
307
+ }
308
+ winston.debug('projectuser', projectuser.toObject());
309
+
310
+ // db.getCollection('requests').find({"id_project":"5e15bef09877c800176d217f","status":{"$lt":1000},"$or":[{"agents":{"id_user":"5ddd30bff0195f0017f72c6d"}},{"participants":"5ddd30bff0195f0017f72c6d"}]})
311
+ // pubblica dopo toni
312
+ var query = { "id_project": projectId, "status": { $lt: 1000, $gt: 50 }, preflight: false, "draft": { $in: [false, null] } };
313
+ // add hasBot:false
314
+
315
+ // var query = {"id_project":projectId, "status": { $lt: 1000, $gt: 50 }, $or:[ {preflight:false}, { preflight : { $exists: false } } ] };
316
+
317
+ // qui1000
318
+ // var query = { id_project: projectId, statusObj: {closed:false, preflight:false} };
319
+
320
+ var cacheUserId;
321
+ if (projectuser.role == "owner" || projectuser.role == "admin") {
322
+ winston.debug('query admin: ' + JSON.stringify(query));
323
+ cacheUserId = "/admin-owner";
324
+ } else {
325
+ query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
326
+ winston.debug('query agent: ' + JSON.stringify(query));
327
+ cacheUserId = "/agent/" + req.user.id;
328
+ }
329
+
330
+ //cacheimportantehere
331
+ // requestcachefarequi populaterequired
330
332
 
331
333
  // TODO proviamo a fare esempio con 100 agenti tutti
332
- // elimina capo availableAgents (chiedi a Nico se gli usa altrimenti metti a select false)
333
- var startDate = new Date();
334
- Request.find(query)
334
+ // elimina capo availableAgents (chiedi a Nico se gli usa altrimenti metti a select false)
335
+ var startDate = new Date();
336
+ Request.find(query)
335
337
  .select("+snapshot.agents")
336
338
  // .populate('lead') //??
337
339
  // .populate('department')
338
340
  // .populate('participatingBots')
339
341
  // .populate('participatingAgents')
340
342
  // .populate({path:'requester',populate:{path:'id_user'}})
341
- .sort({updatedAt: 'desc'})
342
- .limit(lastRequestsLimit)
343
+ .sort({ updatedAt: 'desc' })
344
+ .limit(lastRequestsLimit)
343
345
  // DISABLED 23Marzo2021 per problema request.snapshot.requester.isAuthenticated = undefined
344
346
  .lean() //https://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/ https://stackoverflow.com/questions/33104136/mongodb-mongoose-slow-query-when-fetching-10k-documents
345
347
  //@DISABLED_CACHE .cache(cacheUtil.queryTTL, projectId+":requests:query:status-50-1000:preflight-false:select_snapshot_agents:"+cacheUserId)
346
- .exec(function(err, requests) {
347
-
348
- if (err) {
349
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
350
- return reject(err);
351
- }
352
- winston.debug('found requests for onSubscribeCallback', requests);
353
-
354
- if (requests && requests.length>0) {
355
- requests.forEach(request => {
348
+ .exec(function (err, requests) {
349
+
350
+ if (err) {
351
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
352
+ return reject(err);
353
+ }
354
+ winston.debug('found requests for onSubscribeCallback', requests);
356
355
 
357
- request.id = request._id; //importante
356
+ if (requests && requests.length > 0) {
357
+ requests.forEach(request => {
358
358
 
359
+ request.id = request._id; //importante
359
360
 
360
- if (request.lead) {
361
- // request.requester_id = request.lead._id; //parla con NICO di questo
362
- request.requester_id = request.lead;
363
- }else {
364
- request.requester_id = null;
365
- }
366
361
 
367
- if (request.snapshot.requester) {
368
- if (request.snapshot.requester.role === RoleConstants.GUEST ) {
369
- request.snapshot.requester.isAuthenticated = false;
370
- }else {
371
- request.snapshot.requester.isAuthenticated = true;
372
- }
373
-
374
- }
362
+ if (request.lead) {
363
+ // request.requester_id = request.lead._id; //parla con NICO di questo
364
+ request.requester_id = request.lead;
365
+ } else {
366
+ request.requester_id = null;
367
+ }
375
368
 
376
- // attento qui
377
- if (request.snapshot.agents && request.snapshot.agents.length>0) {
378
- var agentsnew = [];
379
- request.snapshot.agents.forEach(a => {
380
- agentsnew.push({id_user: a.id_user}) //remove unnecessary request.agents[].project_user fields. keep only id_user
381
- });
382
- request.snapshot.agents = agentsnew;
369
+ if (request.snapshot.requester) {
370
+ if (request.snapshot.requester.role === RoleConstants.GUEST) {
371
+ request.snapshot.requester.isAuthenticated = false;
372
+ } else {
373
+ request.snapshot.requester.isAuthenticated = true;
383
374
  }
384
-
385
375
 
386
-
376
+ }
377
+
378
+ // attento qui
379
+ if (request.snapshot.agents && request.snapshot.agents.length > 0) {
380
+ var agentsnew = [];
381
+ request.snapshot.agents.forEach(a => {
382
+ agentsnew.push({ id_user: a.id_user }) //remove unnecessary request.agents[].project_user fields. keep only id_user
383
+ });
384
+ request.snapshot.agents = agentsnew;
385
+ }
386
+
387
+
387
388
 
388
- });
389
- }
390
389
 
391
- var endDate = new Date();
392
- winston.debug('ws count: ' + query +' '+ requests.length +' '+ startDate +' '+endDate +' '+ endDate - startDate )
393
- return resolve({publishFunction:function() {
390
+ });
391
+ }
392
+
393
+ var endDate = new Date();
394
+ winston.debug('ws count: ' + query + ' ' + requests.length + ' ' + startDate + ' ' + endDate + ' ' + endDate - startDate)
395
+ return resolve({
396
+ publishFunction: function () {
394
397
  // handlePublishMessageToClientId (topic, message, clientId, method) {
395
- pubSubServer.handlePublishMessageToClientId (topic, requests, clientId, "CREATE");
396
- }});
397
-
398
-
398
+ pubSubServer.handlePublishMessageToClientId(topic, requests, clientId, "CREATE");
399
+ }
400
+ });
401
+
402
+
399
403
  });
400
-
401
- });
402
-
403
-
404
- } else if (topic.indexOf('/project_users/users/') > -1) {
405
-
406
- var userId = urlSub[4];
407
- winston.debug('userId: '+userId);
408
-
409
- //check if current user can see the data
410
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or:[ {"role": "agent"}, {"role": "admin"}, {"role": "owner"}], status: "active"})
411
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
412
- .exec(function (err, currentProjectuser) {
413
- if (err) {
414
- winston.error('WebSocket error getting Project_user', err);
415
- return reject(err);
416
- }
417
- if (!currentProjectuser) {
418
- winston.verbose('WebSocket Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId);
419
- return reject({err:'Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId});
420
- }
421
- winston.debug('currentProjectuser', currentProjectuser.toObject());
422
-
423
-
424
- var isObjectId = mongoose.Types.ObjectId.isValid(userId);
425
- winston.debug("isObjectId:"+ isObjectId);
426
-
427
- var query = { id_project: projectId, status: "active"};
428
- winston.debug(' query: ',query);
429
-
430
- if (isObjectId) {
431
- query.id_user = userId;
432
- }else {
433
- query.uuid_user = userId;
404
+
405
+ });
406
+
407
+
408
+ } else if (topic.indexOf('/project_users/users/') > -1) {
409
+
410
+ var userId = urlSub[4];
411
+ winston.debug('userId: ' + userId);
412
+
413
+ //check if current user can see the data
414
+ Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
415
+ //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
416
+ .exec(function (err, currentProjectuser) {
417
+ if (err) {
418
+ winston.error('WebSocket error getting Project_user', err);
419
+ return reject(err);
420
+ }
421
+ if (!currentProjectuser) {
422
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
423
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
424
+ }
425
+ winston.debug('currentProjectuser', currentProjectuser.toObject());
426
+
427
+
428
+ var isObjectId = mongoose.Types.ObjectId.isValid(userId);
429
+ winston.debug("isObjectId:" + isObjectId);
430
+
431
+ var query = { id_project: projectId, status: "active" };
432
+ winston.debug(' query: ', query);
433
+
434
+ if (isObjectId) {
435
+ query.id_user = userId;
436
+ } else {
437
+ query.uuid_user = userId;
438
+ }
439
+
440
+ Project_user.findOne(query)
441
+ // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:users:"+userId)
442
+ .exec(function (err, projectuser) {
443
+ if (err) {
444
+ winston.error('WebSocket error getting Project_user', err);
445
+ return reject(err);
446
+ }
447
+ if (!projectuser) {
448
+ winston.verbose('WebSocket Project_user not found with user id ' + userId + ' and projectid ' + projectId);
449
+ return reject({ err: 'Project_user not found with user id ' + userId + ' and projectid ' + projectId });
434
450
  }
435
451
 
436
- Project_user.findOne(query)
437
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:users:"+userId)
438
- .exec(function (err, projectuser) {
439
- if (err) {
440
- winston.error('WebSocket error getting Project_user', err);
441
- return reject(err);
442
- }
443
- if (!projectuser) {
444
- winston.verbose('WebSocket Project_user not found with user id '+ userId + ' and projectid ' + projectId);
445
- return reject({err:'Project_user not found with user id '+ userId + ' and projectid ' + projectId});
452
+
453
+ var pu = projectuser.toJSON();
454
+ pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
455
+
456
+
457
+ return resolve({
458
+ publishFunction: function () {
459
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
460
+ pubSubServer.handlePublishMessageToClientId(topic, pu, clientId, "CREATE");
446
461
  }
447
-
448
-
449
- var pu = projectuser.toJSON();
450
- pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
451
-
452
-
453
- return resolve({publishFunction:function() {
454
- // handlePublishMessageToClientId (topic, message, clientId, method) {
455
- pubSubServer.handlePublishMessageToClientId (topic, pu, clientId, "CREATE");
456
- }});
457
-
458
462
  });
459
-
460
463
 
464
+ });
461
465
 
462
466
 
463
- });
464
-
465
467
 
466
- // tilebase.send('{ "action": "subscribe", "payload": { "topic": "/5e71139f61dd040bc9594cee/project_users/5e71139f61dd040bc9594cef"}}')
467
- //curl -v -X PUT -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"user_available":false}' http://localhost:3000/5e71139f61dd040bc9594cee/project_users/
468
- } else if (topic.indexOf('/project_users/') > -1) {
469
-
468
+
469
+ });
470
+
471
+
472
+ // tilebase.send('{ "action": "subscribe", "payload": { "topic": "/5e71139f61dd040bc9594cee/project_users/5e71139f61dd040bc9594cef"}}')
473
+ //curl -v -X PUT -H 'Content-Type:application/json' -u andrea.leo@f21.it:123456 -d '{"user_available":false}' http://localhost:3000/5e71139f61dd040bc9594cee/project_users/
474
+ } else if (topic.indexOf('/project_users/') > -1) {
475
+
470
476
 
471
477
  // TODO aggiungere tutti i prject users
472
478
 
473
479
  var puId = urlSub[3];
474
- winston.debug('puId: '+puId);
475
-
480
+ winston.debug('puId: ' + puId);
481
+
476
482
  //var query = { _id: puId, id_project: projectId};
477
- var query = { _id: puId, id_project: projectId, id_user: req.user._id, $or:[ {"role": "agent"}, {"role": "admin"}, {"role": "owner"}], status: "active" };
478
- winston.debug(' query: ',query);
479
-
483
+ var query = { _id: puId, id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" };
484
+ winston.debug(' query: ', query);
485
+
480
486
  Project_user.findOne(query)
481
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:"+puId)
482
- .exec(function (err, projectuser) {
483
- if (err) {
484
- winston.error('WebSocket error getting Project_user', err);
485
- return reject(err);
486
- }
487
- if (!projectuser) {
488
- winston.verbose('WebSocket Project_user not found with project_user id '+ puId + ' and projectid ' + projectId);
489
- return reject({err:'Project_user not found with project_user id '+ puId + ' and projectid ' + projectId});
490
- }
491
-
492
-
493
- var pu = projectuser.toJSON();
494
- pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
495
-
496
-
497
- return resolve({publishFunction:function() {
498
- // handlePublishMessageToClientId (topic, message, clientId, method) {
499
- pubSubServer.handlePublishMessageToClientId (topic, pu, clientId, "CREATE");
500
- }});
501
-
502
- });
503
- }
504
-
505
- else if (topic.indexOf('/events/') > -1) {
506
-
487
+ // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:"+puId)
488
+ .exec(function (err, projectuser) {
489
+ if (err) {
490
+ winston.error('WebSocket error getting Project_user', err);
491
+ return reject(err);
492
+ }
493
+ if (!projectuser) {
494
+ winston.verbose('WebSocket Project_user not found with project_user id ' + puId + ' and projectid ' + projectId);
495
+ return reject({ err: 'Project_user not found with project_user id ' + puId + ' and projectid ' + projectId });
496
+ }
497
+
498
+
499
+ var pu = projectuser.toJSON();
500
+ pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
501
+
502
+
503
+ return resolve({
504
+ publishFunction: function () {
505
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
506
+ pubSubServer.handlePublishMessageToClientId(topic, pu, clientId, "CREATE");
507
+ }
508
+ });
509
+
510
+ });
511
+ }
512
+
513
+ else if (topic.indexOf('/events/') > -1) {
514
+
507
515
  var puId = urlSub[3];
508
- winston.debug('puId: '+puId);
509
-
516
+ winston.debug('puId: ' + puId);
517
+
510
518
  var eventName = urlSub[4];
511
- winston.debug('eventName: '+eventName);
512
-
519
+ winston.debug('eventName: ' + eventName);
520
+
513
521
  var query = { project_user: puId, id_project: projectId };
514
522
  if (eventName) {
515
523
  query.name = eventName;
516
524
  }
517
525
  //TODO esclude status volatile events
518
- winston.debug(' query: ',query);
519
-
526
+ winston.debug(' query: ', query);
527
+
520
528
  EventModel.find(query)
521
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":events:"+puId)
522
- .sort({createdAt: 'desc'})
523
- .limit(lastEventsLimit)
524
- .exec(function(err, events) {
525
- if (err) {
526
- winston.error('WebSocket error getting events', err);
527
- return reject(err);
528
- }
529
-
530
-
531
- return resolve({publishFunction:function() {
532
- // handlePublishMessageToClientId (topic, message, clientId, method) {
533
- pubSubServer.handlePublishMessageToClientId (topic, events, clientId, "CREATE");
534
- }});
535
-
536
- })
537
-
538
- } else if (topic.indexOf('/bots/') > -1) {
539
-
540
- // var puId = urlSub[3];
541
- // winston.info('puId: '+puId);
542
-
543
- winston.debug('urlSub: '+urlSub);
544
-
545
- var botId = urlSub[3];
546
- winston.debug('botId: '+botId);
547
-
548
- var query = { _id: botId, id_project: projectId };
549
-
550
- winston.debug(' query: ',query);
551
-
552
- Faq_kb.findOne(query)
553
- .exec(function(err, bot) {
529
+ // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":events:"+puId)
530
+ .sort({ createdAt: 'desc' })
531
+ .limit(lastEventsLimit)
532
+ .exec(function (err, events) {
533
+ if (err) {
534
+ winston.error('WebSocket error getting events', err);
535
+ return reject(err);
536
+ }
537
+
538
+
539
+ return resolve({
540
+ publishFunction: function () {
541
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
542
+ pubSubServer.handlePublishMessageToClientId(topic, events, clientId, "CREATE");
543
+ }
544
+ });
545
+
546
+ })
547
+
548
+ } else if (topic.indexOf('/bots/') > -1) {
549
+
550
+ // var puId = urlSub[3];
551
+ // winston.info('puId: '+puId);
552
+
553
+ winston.debug('urlSub: ' + urlSub);
554
+
555
+ var botId = urlSub[3];
556
+ winston.debug('botId: ' + botId);
557
+
558
+ var query = { _id: botId, id_project: projectId };
559
+
560
+ winston.debug(' query: ', query);
561
+
562
+ Faq_kb.findOne(query)
563
+ .exec(function (err, bot) {
554
564
  if (err) {
555
- winston.error('WebSocket error getting bots', err);
556
- return reject(err);
557
- }
558
-
559
-
560
- return resolve({publishFunction:function() {
561
- // handlePublishMessageToClientId (topic, message, clientId, method) {
562
- pubSubServer.handlePublishMessageToClientId (topic, bot, clientId, "CREATE");
563
- }});
564
-
565
+ winston.error('WebSocket error getting bots', err);
566
+ return reject(err);
567
+ }
568
+
569
+
570
+ return resolve({
571
+ publishFunction: function () {
572
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
573
+ pubSubServer.handlePublishMessageToClientId(topic, bot, clientId, "CREATE");
574
+ }
575
+ });
576
+
565
577
  });
566
-
567
- } else {
568
-
569
- //request/id
570
-
571
- // winston.debug(' req.: ',req);
572
-
573
- var recipientId = urlSub[3];
574
- winston.debug('recipientId: '+recipientId);
575
-
576
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or:[ {"role": "agent"}, {"role": "admin"}, {"role": "owner"}], status: "active" })
577
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
578
- .exec(function (err, projectuser) {
578
+
579
+ } else {
580
+
581
+ //request/id
582
+
583
+ // winston.debug(' req.: ',req);
584
+
585
+ var recipientId = urlSub[3];
586
+ winston.debug('recipientId: ' + recipientId);
587
+
588
+ Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
589
+ // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
590
+ .exec(function (err, projectuser) {
591
+ if (err) {
592
+ winston.error('WebSocket error getting Project_user', err);
593
+ return reject(err);
594
+ }
595
+ if (!projectuser) {
596
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
597
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
598
+ }
599
+
600
+ var query = { id_project: projectId, request_id: recipientId };
601
+ winston.debug('query: ' + JSON.stringify(query));
602
+
603
+ if (projectuser.role == "owner" || projectuser.role == "admin") {
604
+ winston.debug('query admin: ' + JSON.stringify(query));
605
+ } else {
606
+ query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
607
+ winston.debug('query agent: ' + JSON.stringify(query));
608
+ }
609
+
610
+ // requestcachefarequi populaterequired
611
+
612
+ Request.findOne(query)
613
+ .populate('lead')
614
+ .populate('department')
615
+ .populate('participatingBots')
616
+ .populate('participatingAgents')
617
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
618
+ .sort({ updatedAt: 'asc' }).exec(function (err, request) {
619
+
579
620
  if (err) {
580
- winston.error('WebSocket error getting Project_user', err);
581
- return reject(err);
582
- }
583
- if (!projectuser) {
584
- winston.verbose('WebSocket Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId);
585
- return reject({err:'Project_user not found with user id '+ req.user._id + ' and projectid ' + projectId});
621
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
622
+ return reject(err);
586
623
  }
587
-
588
- var query = {id_project:projectId, request_id: recipientId};
589
- winston.debug('query: '+ JSON.stringify(query));
590
-
591
- if (projectuser.role == "owner" || projectuser.role == "admin") {
592
- winston.debug('query admin: '+ JSON.stringify(query));
593
- }else {
594
- query["$or"] = [ { "snapshot.agents.id_user": req.user.id}, {"participants": req.user.id}]
595
- winston.debug('query agent: '+ JSON.stringify(query));
596
- }
597
-
598
- // requestcachefarequi populaterequired
599
-
600
- Request.findOne(query)
601
- .populate('lead')
602
- .populate('department')
603
- .populate('participatingBots')
604
- .populate('participatingAgents')
605
- .populate({path:'requester',populate:{path:'id_user'}})
606
- .sort({updatedAt: 'asc'}).exec(function(err, request) {
607
-
608
- if (err) {
609
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
610
- return reject(err);
611
- }
612
- winston.debug('onSubscribeCallback find', request);
613
-
614
- return resolve({publishFunction:function() {
615
- // handlePublishMessageToClientId (topic, message, clientId, method) {
616
- pubSubServer.handlePublishMessageToClientId (topic, request, clientId, "CREATE");
617
- }});
618
-
624
+ winston.debug('onSubscribeCallback find', request);
625
+
626
+ return resolve({
627
+ publishFunction: function () {
628
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
629
+ pubSubServer.handlePublishMessageToClientId(topic, request, clientId, "CREATE");
630
+ }
619
631
  });
620
-
632
+
621
633
  });
622
-
623
- }
624
634
 
625
-
635
+ });
636
+
637
+ }
626
638
 
627
639
 
628
- });
629
640
 
630
- });
641
+
642
+ });
643
+
644
+ });
631
645
  }
632
646
 
633
647
 
634
648
 
635
649
 
636
- const pubSubServer = new PubSub(wss, {onConnect: onConnectCallback, onDisconnect: onDisconnectCallback,
637
- onMessage: onMessageCallback, onSubscribe: onSubscribeCallback, onPublish:onPublishCallback});
650
+ const pubSubServer = new PubSub(wss, {
651
+ onConnect: onConnectCallback, onDisconnect: onDisconnectCallback,
652
+ onMessage: onMessageCallback, onSubscribe: onSubscribeCallback, onPublish: onPublishCallback
653
+ });
638
654
 
639
655
  var that = this;
640
656
 
@@ -647,9 +663,9 @@ class WebSocketServer {
647
663
 
648
664
  messageEvent.on(messageCreateKey, function (message) {
649
665
  setImmediate(async () => {
650
- winston.debug('messageEvent websocket server: '+messageCreateKey, message);
666
+ winston.debug('messageEvent websocket server: ' + messageCreateKey, message);
651
667
  if (message.request) {
652
- pubSubServer.handlePublishMessage ('/'+message.id_project+'/requests/'+message.request.request_id+'/messages', message, undefined, true, "CREATE");
668
+ pubSubServer.handlePublishMessage('/' + message.id_project + '/requests/' + message.request.request_id + '/messages', message, undefined, true, "CREATE");
653
669
  }
654
670
  });
655
671
  });
@@ -660,75 +676,75 @@ class WebSocketServer {
660
676
  requestCreateKey = 'request.create.queue.pubsub';
661
677
  }
662
678
  winston.debug('requestCreateKey: ' + requestCreateKey);
663
- requestEvent.on(requestCreateKey, async function (request) {
664
- setImmediate(async () => {
679
+ requestEvent.on(requestCreateKey, async function (request) {
680
+ setImmediate(async () => {
665
681
 
666
- winston.debug('requestEvent websocket server: '+requestCreateKey, request);
682
+ winston.debug('requestEvent websocket server: ' + requestCreateKey, request);
667
683
  // TODO scarta riquesta se agente (req.user._id) non sta ne in participants ne in agents
668
684
 
669
- if (request.preflight===false) {
685
+ if (request.preflight === false) {
670
686
 
671
687
  //TODO ATTENTION change value by reference requestJSON.snapshot
672
688
  let requestJSON = Object.assign({}, request);
673
689
  // var requestJSON = request;
674
690
 
675
691
  if (request.toObject) {
676
- requestJSON = request.toObject();
692
+ requestJSON = request.toObject();
677
693
  }
678
-
694
+
679
695
  //deleted snapshot department lead, etc..
680
696
  delete requestJSON.snapshot;
681
697
  requestJSON.snapshot = {};
682
698
 
683
699
 
684
700
 
685
-
686
- // ATTENTO https://stackoverflow.com/questions/64059795/mongodb-get-error-message-mongoerror-path-collision-at-activity
701
+
702
+ // ATTENTO https://stackoverflow.com/questions/64059795/mongodb-get-error-message-mongoerror-path-collision-at-activity
687
703
  try {
688
- var snapshotAgents = await Request.findById(request.id).select({"snapshot":1}).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
689
- winston.debug('snapshotAgents',snapshotAgents);
704
+ var snapshotAgents = await Request.findById(request.id).select({ "snapshot": 1 }).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
705
+ winston.debug('snapshotAgents', snapshotAgents);
690
706
  // requestJSON.snapshot.agents = snapshotAgents;
691
707
 
692
- if (snapshotAgents.snapshot.agents && snapshotAgents.snapshot.agents.length>0) {
708
+ if (snapshotAgents.snapshot.agents && snapshotAgents.snapshot.agents.length > 0) {
693
709
  var agentsnew = [];
694
710
  snapshotAgents.snapshot.agents.forEach(a => {
695
- agentsnew.push({id_user: a.id_user})
711
+ agentsnew.push({ id_user: a.id_user })
696
712
  });
697
713
  //TODO ATTENTION change value by reference requestJSON.snapshot.agents. but it's fixed with line 640
698
714
  requestJSON.snapshot.agents = agentsnew;
699
715
  }
700
- winston.debug('requestJSON',requestJSON);
716
+ winston.debug('requestJSON', requestJSON);
701
717
  } catch (e) {
702
- winston.error('Error getting snapshotAgents in ws. This is a mongo issue',e);
718
+ winston.error('Error getting snapshotAgents in ws. This is a mongo issue', e);
703
719
  }
704
720
 
705
- pubSubServer.handlePublishMessage ('/'+request.id_project+'/requests', request, undefined, true, "CREATE");
706
- pubSubServer.handlePublishMessage ('/'+request.id_project+'/requests/'+request.request_id, request, undefined, true, "CREATE");
721
+ pubSubServer.handlePublishMessage('/' + request.id_project + '/requests', request, undefined, true, "CREATE");
722
+ pubSubServer.handlePublishMessage('/' + request.id_project + '/requests/' + request.request_id, request, undefined, true, "CREATE");
707
723
  }
708
724
  });
709
- });
725
+ });
710
726
 
711
- var requestUpdateKey = 'request.update';
712
- if (requestEvent.queueEnabled) {
713
- requestUpdateKey = 'request.update.queue.pubsub';
714
- }
727
+ var requestUpdateKey = 'request.update';
728
+ if (requestEvent.queueEnabled) {
729
+ requestUpdateKey = 'request.update.queue.pubsub';
730
+ }
715
731
 
716
- winston.debug('requestUpdateKey: ' + requestUpdateKey);
717
- requestEvent.on(requestUpdateKey, async function(request) {
718
- setImmediate(async () => {
732
+ winston.debug('requestUpdateKey: ' + requestUpdateKey);
733
+ requestEvent.on(requestUpdateKey, async function (request) {
734
+ setImmediate(async () => {
719
735
 
720
736
  // TODO setImmediate(() => {
721
- winston.debug('requestEvent websocket server: '+requestUpdateKey, request);
722
- if (request.preflight===false && request.status > requestConstants.TEMP) {
737
+ winston.debug('requestEvent websocket server: ' + requestUpdateKey, request);
738
+ if (request.preflight === false && request.status > requestConstants.TEMP) {
723
739
 
724
740
  //TODO ATTENTION change value by reference requestJSON.snapshot
725
741
  let requestJSON = Object.assign({}, request);
726
742
  // var requestJSON = request;
727
743
 
728
744
  if (request.toObject) {
729
- requestJSON = request.toObject();
745
+ requestJSON = request.toObject();
730
746
  }
731
-
747
+
732
748
  //deleted snapshot department lead, etc..
733
749
  delete requestJSON.snapshot;
734
750
  requestJSON.snapshot = {};
@@ -736,85 +752,83 @@ class WebSocketServer {
736
752
  // ATTENTO https://stackoverflow.com/questions/64059795/mongodb-get-error-message-mongoerror-path-collision-at-activity
737
753
 
738
754
  try {
739
- var snapshotAgents = await Request.findById(request.id).select({"snapshot":1}).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
740
- winston.debug('snapshotAgents',snapshotAgents);
755
+ var snapshotAgents = await Request.findById(request.id).select({ "snapshot": 1 }).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
756
+ winston.debug('snapshotAgents', snapshotAgents);
741
757
  // requestJSON.snapshot.agents = snapshotAgents;
742
758
 
743
- if (snapshotAgents.snapshot.agents && snapshotAgents.snapshot.agents.length>0) {
759
+ if (snapshotAgents.snapshot.agents && snapshotAgents.snapshot.agents.length > 0) {
744
760
  var agentsnew = [];
745
761
  snapshotAgents.snapshot.agents.forEach(a => {
746
- agentsnew.push({id_user: a.id_user})
762
+ agentsnew.push({ id_user: a.id_user })
747
763
  });
748
- //TODO ATTENTION change value by reference requestJSON.snapshot.agents . fixed with line 693
764
+ //TODO ATTENTION change value by reference requestJSON.snapshot.agents . fixed with line 693
749
765
  requestJSON.snapshot.agents = agentsnew;
750
766
  }
751
- winston.debug('requestJSON',requestJSON);
767
+ winston.debug('requestJSON', requestJSON);
752
768
 
753
- }catch (e) {
754
- winston.error('Error getting snapshotAgents in ws. This is a mongo issue',e);
769
+ } catch (e) {
770
+ winston.error('Error getting snapshotAgents in ws. This is a mongo issue', e);
755
771
  }
756
-
757
-
758
-
759
-
760
772
 
773
+ if (requestJSON.draft !== true) {
774
+ pubSubServer.handlePublishMessage('/' + request.id_project + '/requests', requestJSON, undefined, true, "UPDATE");
775
+ }
776
+ pubSubServer.handlePublishMessage('/' + request.id_project + '/requests/' + request.request_id, requestJSON, undefined, true, "UPDATE");
761
777
 
762
- pubSubServer.handlePublishMessage ('/'+request.id_project+'/requests', requestJSON, undefined, true, "UPDATE");
763
- pubSubServer.handlePublishMessage ('/'+request.id_project+'/requests/'+request.request_id, requestJSON, undefined, true, "UPDATE");
764
778
  }
765
779
  });
766
- });
780
+ });
767
781
 
768
782
 
769
783
 
770
784
 
771
- // TODO request.close is missing?
785
+ // TODO request.close is missing?
772
786
 
773
787
 
774
- var projectuserUpdateKey = 'project_user.update';
775
- if (authEvent.queueEnabled) {
776
- projectuserUpdateKey = 'project_user.update.queue.pubsub';
777
- }
778
- winston.debug('projectuserUpdateKey: ' + projectuserUpdateKey);
779
- authEvent.on(projectuserUpdateKey,function(data) {
780
- setImmediate(async () => {
788
+ var projectuserUpdateKey = 'project_user.update';
789
+ if (authEvent.queueEnabled) {
790
+ projectuserUpdateKey = 'project_user.update.queue.pubsub';
791
+ }
792
+ winston.debug('projectuserUpdateKey: ' + projectuserUpdateKey);
793
+ authEvent.on(projectuserUpdateKey, function (data) {
794
+ setImmediate(async () => {
781
795
 
782
796
  var pu = data.updatedProject_userPopulated;
783
797
  winston.debug('ws pu', pu);
784
-
798
+
785
799
  //TODO pubSubServer.handlePublishMessage ('/'+pu.id_project+'/project_users/', pu, undefined, true, "UPDATE");
786
800
 
787
- pubSubServer.handlePublishMessage ('/'+pu.id_project+'/project_users/'+pu.id, pu, undefined, true, "UPDATE");
801
+ pubSubServer.handlePublishMessage('/' + pu.id_project + '/project_users/' + pu.id, pu, undefined, true, "UPDATE");
788
802
 
789
803
  var userId;
790
804
  if (pu.uuid_user) {
791
805
  userId = pu.uuid_user;
792
- }else {
806
+ } else {
793
807
  userId = pu.id_user._id;
794
808
  }
795
- winston.debug('userId:'+ userId);
796
- pubSubServer.handlePublishMessage ('/'+pu.id_project+'/project_users/users/'+userId, pu, undefined, true, "UPDATE");
809
+ winston.debug('userId:' + userId);
810
+ pubSubServer.handlePublishMessage('/' + pu.id_project + '/project_users/users/' + userId, pu, undefined, true, "UPDATE");
797
811
  });
798
- });
799
-
812
+ });
800
813
 
801
814
 
802
- var eventEmitKey = 'event.emit';
803
- if (eventEvent.queueEnabled) {
804
- eventEmitKey = 'event.emit.queue.pubsub';
805
- }
806
- winston.debug('eventEmitKey: ' + eventEmitKey);
807
- eventEvent.on(eventEmitKey,function(event) {
808
- setImmediate(async () => {
815
+
816
+ var eventEmitKey = 'event.emit';
817
+ if (eventEvent.queueEnabled) {
818
+ eventEmitKey = 'event.emit.queue.pubsub';
819
+ }
820
+ winston.debug('eventEmitKey: ' + eventEmitKey);
821
+ eventEvent.on(eventEmitKey, function (event) {
822
+ setImmediate(async () => {
809
823
  winston.debug('event', event);
810
824
  if (event.project_user === undefined) {
811
825
  //with "faqbot.answer_not_found" project_user is undefined but it's ok
812
826
  winston.debug('not sending with ws event with project_user undefined', event);
813
- return ;
827
+ return;
814
828
  }
815
- pubSubServer.handlePublishMessage ('/'+event.id_project+'/events/'+event.project_user._id, event, undefined, true, "CREATE");
816
- });
829
+ pubSubServer.handlePublishMessage('/' + event.id_project + '/events/' + event.project_user._id, event, undefined, true, "CREATE");
817
830
  });
831
+ });
818
832
 
819
833
 
820
834
 
@@ -823,31 +837,31 @@ class WebSocketServer {
823
837
 
824
838
 
825
839
 
826
- var botUpdateKey = 'faqbot.update';
827
- if (botEvent.queueEnabled) {
828
- botUpdateKey = 'faqbot.update.queue.pubsub';
829
- }
830
-
831
- winston.debug('botUpdateKey: ' + botUpdateKey);
832
- botEvent.on(botUpdateKey, async function(bot) {
833
- setImmediate(async () => {
840
+ var botUpdateKey = 'faqbot.update';
841
+ if (botEvent.queueEnabled) {
842
+ botUpdateKey = 'faqbot.update.queue.pubsub';
843
+ }
844
+
845
+ winston.debug('botUpdateKey: ' + botUpdateKey);
846
+ botEvent.on(botUpdateKey, async function (bot) {
847
+ setImmediate(async () => {
834
848
 
835
849
  // TODO setImmediate(() => {
836
850
 
837
- let botJSON = Object.assign({}, bot);
851
+ let botJSON = Object.assign({}, bot);
852
+
853
+ if (bot.toObject) {
854
+ botJSON = bot.toObject();
855
+ }
838
856
 
839
- if (bot.toObject) {
840
- botJSON = bot.toObject();
841
- }
857
+ let topic = '/' + bot.id_project + '/bots/' + bot._id;
858
+ winston.debug('botEvent websocket server: ' + botUpdateKey + " on topic " + topic, botJSON);
842
859
 
843
- let topic = '/'+bot.id_project+'/bots/'+bot._id;
844
- winston.debug('botEvent websocket server: '+botUpdateKey + " on topic " + topic , botJSON);
845
860
 
846
-
847
- pubSubServer.handlePublishMessage (topic, botJSON, undefined, true, "UPDATE");
848
- });
861
+ pubSubServer.handlePublishMessage(topic, botJSON, undefined, true, "UPDATE");
849
862
  });
850
-
863
+ });
864
+
851
865
 
852
866
 
853
867
 
@@ -858,106 +872,106 @@ class WebSocketServer {
858
872
  // IMPORTANTE https://blog.usejournal.com/using-mongodb-as-realtime-db-with-nodejs-c6f52c266750
859
873
 
860
874
  // start mongo with: mongod --port 27017 --replSet rs0
861
- // wss.on('connection', function connection(ws, req) {
875
+ // wss.on('connection', function connection(ws, req) {
876
+
877
+ // winston.debug('ws connection. req.url)', req.url);
878
+ // //console.log('ws connection. req', req);
879
+
880
+ // let urlParsed = url.parse(req.url, true);
881
+ // winston.debug('urlParsed', urlParsed);
882
+
883
+ // var queryParameter = urlParsed.query;
884
+ // winston.debug('queryParameter', queryParameter);
885
+
886
+ // var id_project = queryParameter.id_project;
887
+ // winston.debug('id_project=', id_project);
888
+
889
+ // if (!id_project) {
890
+ // winston.error('id_project not specified');
891
+ // return 0;
892
+ // }
862
893
 
863
- // winston.debug('ws connection. req.url)', req.url);
864
- // //console.log('ws connection. req', req);
894
+ // winston.debug('queryParameter.events'+ queryParameter.events);
895
+ // var events = JSON.parse(queryParameter.events);
896
+ // winston.debug('events', events);
865
897
 
866
- // let urlParsed = url.parse(req.url, true);
867
- // winston.debug('urlParsed', urlParsed);
868
-
869
- // var queryParameter = urlParsed.query;
870
- // winston.debug('queryParameter', queryParameter);
871
-
872
- // var id_project = queryParameter.id_project;
873
- // winston.debug('id_project=', id_project);
898
+ // if (!events) {
899
+ // winston.error('events not specified');
900
+ // return 0;
901
+ // }
874
902
 
875
- // if (!id_project) {
876
- // winston.error('id_project not specified');
877
- // return 0;
878
- // }
903
+ // that.subscribeClient(id_project, events, ws);
879
904
 
880
- // winston.debug('queryParameter.events'+ queryParameter.events);
881
- // var events = JSON.parse(queryParameter.events);
882
- // winston.debug('events', events);
883
-
884
- // if (!events) {
885
- // winston.error('events not specified');
886
- // return 0;
887
- // }
888
905
 
889
- // that.subscribeClient(id_project, events, ws);
890
-
891
906
 
907
+ // winston.debug('queryParameter.q', queryParameter.q);
892
908
 
893
- // winston.debug('queryParameter.q', queryParameter.q);
894
-
895
- // var query = JSON.parse(queryParameter.q);
896
- // query['id_project'] = id_project;
897
- // winston.debug('query=', query);
909
+ // var query = JSON.parse(queryParameter.q);
910
+ // query['id_project'] = id_project;
911
+ // winston.debug('query=', query);
898
912
 
899
- // that.sendInitialData(events,query,ws);
900
-
901
- // // https://www.sitepoint.com/build-node-js-powered-chatroom-web-app-node-mongodb-socket/
902
- // // usa stream come qui
913
+ // that.sendInitialData(events,query,ws);
903
914
 
904
-
915
+ // // https://www.sitepoint.com/build-node-js-powered-chatroom-web-app-node-mongodb-socket/
916
+ // // usa stream come qui
905
917
 
906
918
 
907
919
 
908
920
 
909
921
 
910
922
 
911
- // // message2Event.on(id_project+'.message.create', function (message) {
912
- // // console.log('message2Event=', message);
913
- // // ws.send(JSON.stringify(message));
914
- // // });
915
923
 
916
-
917
-
918
-
919
- // // // with mongo stream start
920
- // // //const fullDocumentQuery = {fullDocument: query};
921
- // // const fullDocumentQuery = that.cloneAsDotted("fullDocument.", query);
922
- // // console.log("fullDocumentQuery", JSON.stringify(fullDocumentQuery));
923
924
 
924
- // // const pipeline = [{ $match: fullDocumentQuery }];
925
- // // console.log("pipeline", JSON.stringify(pipeline));
925
+ // // message2Event.on(id_project+'.message.create', function (message) {
926
+ // // console.log('message2Event=', message);
927
+ // // ws.send(JSON.stringify(message));
928
+ // // });
926
929
 
927
- // // //const changeStream = Message.watch( pipeline, { fullDocument: 'updateLookup' });
928
- // // const changeStream = Message.watch( pipeline);
929
- // // //const changeStream = Message.watch();
930
-
931
- // // console.log("changeStream");
932
- // // changeStream.on('change', (change) => {
933
- // // console.log('change', change); // You could parse out the needed info and send only that data.
934
- // // ws.send(JSON.stringify(change.fullDocument));
935
- // // //io.emit('changeData', change);
936
- // // });
937
930
 
938
- // // // with mongo stream end
939
931
 
940
932
 
941
-
933
+ // // // with mongo stream start
934
+ // // //const fullDocumentQuery = {fullDocument: query};
935
+ // // const fullDocumentQuery = that.cloneAsDotted("fullDocument.", query);
936
+ // // console.log("fullDocumentQuery", JSON.stringify(fullDocumentQuery));
942
937
 
938
+ // // const pipeline = [{ $match: fullDocumentQuery }];
939
+ // // console.log("pipeline", JSON.stringify(pipeline));
943
940
 
941
+ // // //const changeStream = Message.watch( pipeline, { fullDocument: 'updateLookup' });
942
+ // // const changeStream = Message.watch( pipeline);
943
+ // // //const changeStream = Message.watch();
944
944
 
945
- // ws.on('message', function incoming(message) {
946
- // if (message.type === 'utf8') {
947
- // // process WebSocket message
948
-
949
- // }
950
- // console.log('received: %s', message);
951
-
952
- // });
945
+ // // console.log("changeStream");
946
+ // // changeStream.on('change', (change) => {
947
+ // // console.log('change', change); // You could parse out the needed info and send only that data.
948
+ // // ws.send(JSON.stringify(change.fullDocument));
949
+ // // //io.emit('changeData', change);
950
+ // // });
953
951
 
954
- // // ws.on('open', function open() {
955
- // // console.log('ws open');
956
- // // });
952
+ // // // with mongo stream end
953
+
954
+
955
+
956
+
957
+
958
+
959
+ // ws.on('message', function incoming(message) {
960
+ // if (message.type === 'utf8') {
961
+ // // process WebSocket message
962
+
963
+ // }
964
+ // console.log('received: %s', message);
965
+
966
+ // });
967
+
968
+ // // ws.on('open', function open() {
969
+ // // console.log('ws open');
970
+ // // });
971
+
972
+ // });
957
973
 
958
- // });
959
974
 
960
-
961
975
 
962
976
  }
963
977
 
@@ -977,7 +991,7 @@ class WebSocketServer {
977
991
  // ws.send(JSON.stringify(dataToSend));
978
992
  // });
979
993
  // }
980
-
994
+
981
995
  // });
982
996
  // }
983
997
  // }
@@ -996,8 +1010,8 @@ class WebSocketServer {
996
1010
  // that.clientsSubscriptions[id_project][event].push(ws);
997
1011
  // });
998
1012
  // }
999
-
1000
-
1013
+
1014
+
1001
1015
  // winston.debug('clientsSubscriptions=', this.clientsSubscriptions);
1002
1016
  // }
1003
1017
 
@@ -1021,9 +1035,9 @@ class WebSocketServer {
1021
1035
  // });
1022
1036
 
1023
1037
  // }
1024
-
1038
+
1025
1039
  // }
1026
-
1040
+
1027
1041
 
1028
1042
 
1029
1043
  // cloneAsDotted(prefix, origin) {