· 7 years ago · Dec 18, 2018, 10:00 AM
1var Sequelize = require("sequelize");
2var Promise = Sequelize.Promise
3var moment = require('moment-timezone');
4
5//var Controllers = require(appRoot+"/controllers");///// Controllers
6var Libs = require(appRoot+"/libs");////////////////// Libraries
7var Services = require(appRoot+"/services");/////////// Services
8var Db = require(appRoot+"/models");////////////////// Db Models
9var Configs = require(appRoot+"/configs");///////////// Configs
10
11// io.configure(function () {
12
13// io.set('authorization', async (request, callback) => {
14
15// var cookie = parseCookie(request.headers.cookie);
16
17// if( !cookie && !cookie['connect.sid'] )
18// {
19// return callback(null, false);
20// }
21// else
22// {
23
24// sessionStore.get(utils.parseSignedCookie(cookie['connect.sid'], 'secret'), function (err, session) {
25// if ( err ) {
26// callback(err.message, false);
27// } else {
28// if ( session && session.username ) {
29// request.user = session.username;
30// callback(null, true);
31// } else {
32// callback(null, false);
33// }
34// }
35// });
36
37
38// }
39// });
40
41// });
42
43// io.use( async (socket, response, next) => {
44
45// if (socket.handshake.query && socket.handshake.query.access_token)
46// {
47
48// // jwt.verify(socket.handshake.query.token, 'SECRET_KEY', function(err, decoded) {
49// // if(err) return next(new Error('Authentication error'));
50// // socket.decoded = decoded;
51// // next();
52// // });
53
54// //console.log('11111111111111111111111111111111111111111');
55// next();
56
57// }
58// else
59// {
60// //console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
61// return response(new Error('Authentication error'));
62// //next(new Error('Authentication error'));
63// }
64
65// })
66
67io.on('connection', async (socket) => {
68try{
69
70socket.on('disconnect', async () => {
71
72 //console.log('DISCONNESSO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ', socket.id);
73
74 var update_ud = await Db.user_details.update(
75 {
76 socket_id: "",
77 updated_at: moment.utc().format('YYYY-MM-DD HH:mm:ss')
78 },
79 {
80 where: { socket_id: socket.id }
81 }
82 );
83
84});
85
86 //console.log('Socket ID trying Log --------------------------------------', socket.handshake.query, socket.id);
87/////////////////////// Authentication ///////////////////////////////////
88 if (socket.handshake.query && socket.handshake.query)
89 {
90
91 if(socket.handshake.query.access_token)
92 {/////////////////// App Token /////////////////////////////
93
94 var access_token = socket.handshake.query.access_token;
95
96 var AppDetail = await Db.user_details.findOne({ where: {access_token: access_token} });
97 if(!AppDetail)
98 {
99 return io.sockets.to(socket.id).emit("Error", { type: "AuthError", access_token });
100 }
101
102 var updated_at = await Libs.commonFunctions.currentUTC();
103
104 var UserUpdate = await Db.user_details.update(
105 {
106 socket_id: socket.id,
107 updated_at: updated_at
108 },
109 {
110 where: {access_token: access_token}
111 }
112 );
113
114 console.log('Socket Id Updated and Authenticated', access_token, socket.id);
115
116 }/////////////////// App Token /////////////////////////////
117 else
118 {/////////////////// Panels /////////////////////////////////////
119
120 var admin_access_token = socket.handshake.query.admin_access_token;
121
122 var PanelDetail = await Db.admin_user_detail_logins.findOne({ where: {access_token: admin_access_token} });
123 if(!PanelDetail)
124 {
125 return io.sockets.to(socket.id).emit("Error", { type: "AuthError", access_token });
126 }
127
128 //console.log('Panel Socket Authenticated', access_token, socket.id );
129
130 }/////////////////// Panels /////////////////////////////////////
131
132 }
133 else
134 {
135 //console.log('Socket Id Not Updated and Not Authenticated', access_token);
136 return io.sockets.to(socket.id).emit("Error", { type: "AuthError", AppDetail });
137 }
138/////////////////////// Authentication ///////////////////////////////////
139
140socket.on("CommonEvent", async (data, fn) => {
141try{
142 console.log('CommonEvent', data);
143 // return {awdd: "dadwd"});
144
145 if(!data.type)
146 return { success: 0, statusCode: 400, msg: "Socket event type is required"};
147
148 if(!data.access_token)
149 return { success: 0, statusCode: 400, msg: "Access Token is required"};
150
151 var AppDetail = await Db.user_details.findOne({ where: {access_token: data.access_token} });
152 if(!AppDetail)
153 return { success: 0, statusCode: 401, msg: "No device with this token found. Please login to continue" };
154
155 data.user_id=AppDetail.user_id;
156
157 // if(userDetail.blocked == '1')
158 // return {success: -2, statusCode: 403, msg: "Sorry, this service is currently not available to you. Please contact admin" });
159
160 data.created_at = moment.utc().format('YYYY-MM-DD HH:mm:ss');
161
162 var result = {success: 1, statusCode: 200, msg: "Common Event", data};
163
164 if(data.type == "UpdateData")
165 {
166 result = await UpdateData(data, AppDetail);
167 }
168 else if(data.type == "CustHomeMap")
169 {
170
171 //console.log("CustHomeMapppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp", data );
172
173 result = await CustHomeMap(data, AppDetail);
174 }
175 else if(data.type == "DCurrentOrders")
176 {
177 if(AppDetail.user_type_id == 1)
178 result = { success: 0, statusCode: 400, msg: "This facility is only available to Drivers" };
179 else
180 result = await DCurrentOrders(data, AppDetail);
181 }
182 else if(data.type == "CCurrentOrders")
183 {
184 result = await CCurrentOrders(data, AppDetail);
185 }
186 else if(data.type == "CustSingleOrder")
187 {
188 if(!data.order_token)
189 result = { success: 0, statusCode: 400, msg: "Sorry, order token is required" };
190 else
191 result = await CustSingleOrder(data, AppDetail);
192 }
193
194 return fn(result);
195
196 }
197catch(e)
198 {
199 //console.log("CommonEvent Error - "+e.message, data);
200 //return { success: 0, statusCode: 500, msg: e.message});
201 }
202});
203
204/////////////////// Panel Event //////////////////////////////////
205socket.on("PanelCommonEvent", async (data, fn) => {
206
207 var result;
208
209 //console.log("-----------------------------------------------------------------------------", data);
210
211 if(data.type == 'TrackDriver')
212 {/////////// Track Order //////////////////////
213 if(!data.order_id)
214 result = { success: 0, statusCode: 400, msg: "Sorry, order id is required" };
215 else
216 result = await PanelTrackOrder(data);
217 //return await AdminTracOrder(data));
218 }/////////// Track Order //////////////////////
219 else if(data.type == 'AdminDriverMap')
220 {/////////// Admin Drivers Map //////////////
221
222 if(!data.services)
223 data.services = [];
224
225 if(!data.supports)
226 data.supports = [];
227
228 if(!data.online)
229 data.online = 1;
230
231 data.category_ids = data.services.concat(data.supports);
232
233 if(data.category_ids.length == 0)
234 drivers = [];
235 else
236 drivers = await Services.driverListingServices.adminDriverMaps(data);
237
238 result = { success: 1, statusCode: 200, msg: "All Drivers", drivers, data };
239
240 }/////////// Admin Drivers Map //////////////
241 else if(data.type == 'OrgDriverMap')
242 {/////////// Admin Drivers Map //////////////
243
244 if(!data.services)
245 data.services = [];
246
247 if(!data.supports)
248 data.supports = [];
249
250 if(!data.online)
251 data.online = 1;
252
253 data.category_ids = data.services.concat(data.supports);
254
255 if(data.category_ids.length == 0)
256 drivers = [];
257 else
258 drivers = await Services.driverListingServices.orgDriverMaps(data);
259
260 result = { success: 1, statusCode: 200, msg: "All Drivers", drivers, data };
261
262 }/////////// Admin Drivers Map //////////////
263 else if(data.type == 'SingleDTrack')
264 {/////////// Single Driver Track //////////////
265
266 if(!data.user_detail_id)
267 result = { success: 0, statusCode: 400, msg: "Sorry, driver id is required" };
268 else
269 result = await PanelDTrackOrder(data.user_detail_id);
270
271 }/////////// Single Driver Track //////////////
272
273 return fn(result);
274
275});
276/////////////////// Panel Event //////////////////////////////////
277
278 }
279catch(e)
280 {
281 //console.log("PanelCommonEvent Error - "+e.message, data);
282 return ({ success: 0, statusCode: 500, msg: e.message});
283 }
284});
285
286/////////////// Single Driver Track ////////////////////////////////
287var PanelDTrackOrder = async (user_detail_id) => {
288
289 var driver = await Db.user_details.findOne({ where: { user_detail_id }, attributes: ["latitude", "longitude", "bearing"] });
290 if(!driver)
291 return { success: 0, statusCode: 400, msg: "Sorry, this driver is currently not available" }
292
293 return { success: 1, statusCode: 200, msg: "Single Details", driver };
294
295}
296
297///////////// Panel Track Order //////////////////////////////////
298var PanelTrackOrder = async (data) => {
299try{
300
301 var order = await Services.orderServices.PanelTrackOrder(data);
302
303 if(!order)
304 return { success: 0, statusCode: 200, msg: "Sorry, this order is currently not available" };
305
306 if(order.SRequest)
307 order.SRequest = JSON.parse(order.SRequest);
308
309 return { success: 1, statusCode: 200, msg: "Orders", order };
310
311 }
312catch(e)
313 {
314 return { success: 0, statusCode: 500, msg: e.message};
315 }
316}
317
318///////////// Update UserDevice Data ////////////////////////
319var UpdateData = async (data, AppDetail) => {
320try{
321
322 //console.log('Socket Data -/////////////////////////////////////////////////////////////////// ', data);
323// {socket_id: socket.id, type: "UpdateData", "access_token": "u39", "latitude":30.76, "longitude": 76.78, timezone: "Asia/Calcutta", fcm_id: "" }
324
325 var updated_data = {
326 //socket_id: data.socket_id,
327 updated_at: await Libs.commonFunctions.currentUTC()
328 };
329
330 if(data.latitude)
331 updated_data.latitude = data.latitude;
332 if(data.longitude)
333 updated_data.longitude = data.longitude;
334 if(data.timezone)
335 {
336 updated_data.timezone = data.timezone;
337 updated_data.timezonez = await Libs.commonFunctions.changeTimezoneFormat(data.timezone);
338 }
339 if(data.fcm_id)
340 updated_data.fcm_id = data.fcm_id;
341
342 // if(data.language_id)
343 // updated_data.language_id = data.language_id;
344
345 if(data.bearing)
346 updated_data.bearing = data.bearing;
347 //data.rotation = data.bearing ? data.bearing : order.CRequest.rotation;
348
349 var UserUpdate = await Db.user_details.update(
350 updated_data,
351 {
352 where: {user_detail_id: AppDetail.user_detail_id},
353 }
354 );
355
356 if(AppDetail.user_type_id != 1)
357 {
358 var AppDetail = await Services.userDetailServices.UserGetAppDetails(data);
359 }
360 else
361 {
362 var AppDetail = await Services.userDetailServices.ServiceDriverLoginDetails(data);
363 }
364
365 AppDetail = JSON.parse(JSON.stringify(AppDetail));
366 AppDetail.profile_pic_url = (AppDetail.profile_pic == '') ? '' : process.env.RESIZE_URL+AppDetail.profile_pic;
367
368////////////// Ratings ///////////////////////////
369 var ratings = await Services.userDetailServices.userRatings(AppDetail.user_type_id ,AppDetail.user_detail_id);
370
371 AppDetail.rating_count = parseInt(ratings[0].rating_count);
372 AppDetail.ratings_avg = parseInt(ratings[0].ratings_avg);
373////////////// Ratings ///////////////////////////
374
375 return { success: 1, statusCode: 200, msg: "Data updated successfully", AppDetail, Versioning: Configs.appData.Versioning };
376
377 }
378catch(e)
379 {
380 return { success: 0, statusCode: 500, msg: e.message};
381 }
382}
383
384/////////// Customer Home Map Drivers //////////////////////////
385var CustHomeMap = async (data, AppDetail) => {
386try{
387// {type: "custHomeMap", "access_token": "u39", "latitude":30.76, "longitude": 76.78, "category_id": 1, distance: 50 }
388 if(!data.category_id)
389 return { success: 0, statusCode: 400, msg: "Category Id is required"};
390 else if(!data.distance)
391 return { success: 0, statusCode: 400, msg: "Distance is required"};
392 if(!data.latitude)
393 return { success: 0, statusCode: 400, msg: "Latitude is required"};
394 if(!data.longitude)
395 return { success: 0, statusCode: 400, msg: "Longitude is required"};
396
397 if(data.category_id < 6)
398 {
399 data.user_type_id = 2;
400 data.category_type = "Service";
401 }
402 else
403 {
404 data.user_type_id = 3;
405 data.category_type = "Support";
406 }
407
408 // if(!data.distance)
409 // data.distance = 50;
410
411 data.past_5Mins = moment(data.created_at,'YYYY-MM-DD HH:mm:ss').subtract(2, 'days').format('YYYY-MM-DD HH:mm:ss');
412
413 var drivers = await Services.driverListingServices.userHomeMapDrivers(data);
414
415 var result = {
416 drivers
417 };
418
419 return {success: 1, statusCode: 200, msg: "Home map listings", result };
420
421 }
422catch(e)
423 {
424 return { success: 0, statusCode: 500, msg: e.message};
425 }
426}
427
428///////////////////// Custoemr Single Order Details //////////////////////////////
429var CustSingleOrder = async (data, AppDetail) => {
430 try{
431
432 //console.log('Customer Single Order', data);
433
434 data.user_detail_id = AppDetail.user_detail_id;
435 data.app_language_id = AppDetail.language_id;
436
437 var order = await Services.orderServices.customerSingleOrderDetails(data);
438 if(order.length == 0 || order[0].customer_user_detail_id != data.user_detail_id)
439 return { success: 0, statusCode: 400, msg: "Sorry, this order is currently not available", order };
440
441 return { success: 1, statusCode: 200, msg: "Customer tracks current orders", result: order[0] };
442
443 }
444 catch(e)
445 {
446 return { success: 0, statusCode: 500, msg: e.message};
447 }
448}
449
450///////////////////// Driver Current Rides Update ////////////////////////////////
451var DCurrentOrders = async (data, AppDetail) => {
452try{
453
454//console.log('Current Orders', data);
455
456// {type: "DCurrentOrders", "access_token": "u39", "latitude":30.76, "longitude": 76.78 }
457 var orders = await Db.orders.findAll({
458 where: {
459 driver_user_detail_id: AppDetail.user_detail_id,
460 order_status: { $in : ["Ongoing", "Accepted"]}// { /*$In: ["Ongoing", "Accepted"]*/ }
461 },
462 include: [
463
464 {
465 as: "CRequest",
466 model: Db.order_requests,
467 where: {
468 driver_user_detail_id: AppDetail.user_detail_id
469 }
470 },
471 {
472 model: Db.user_details,
473 as: "CustomerDetails"
474 }
475
476 ]
477
478 })
479 .then( (orders) => {
480
481 var promises = [];
482
483 orders = JSON.parse(JSON.stringify(orders));
484
485 orders.forEach(function(order) {
486
487 var full_track = JSON.parse(order.CRequest.full_track);
488 full_track.push({'Dt': data.created_at, 'latitude': data.latitude, 'longitude': data.longitude})
489 full_track = JSON.stringify(full_track);
490
491 data.rotation = data.bearing ? data.bearing : order.CRequest.rotation;
492 data.bearing = data.rotation;
493
494 promises.push(
495 Promise.all([
496
497 Db.sequelize.query("UPDATE user_details SET latitude="+data.latitude+", longitude="+data.longitude+", bearing='"+data.bearing+"', updated_at='"+data.created_at+"' WHERE user_detail_id="+AppDetail.user_detail_id+" "),
498 Db.sequelize.query("UPDATE order_requests SET driver_current_latitude="+data.latitude+", driver_current_longitude="+data.longitude+", full_track='"+full_track+"', rotation='"+data.rotation+"', updated_at= '"+data.created_at+"' WHERE order_request_id="+order.CRequest.order_request_id+" ")
499
500 ])
501 .spread(function() { // Maps results from the 2nd promise array
502
503
504 if(order.CustomerDetails.socket_id != '')
505 {///////////// Emit To customer ////////////////////
506
507 var socket_data = {
508 type: "CurrentOrders",
509 order_id: order.order_id,
510 driver_id: order.driver_id,
511 latitude: data.latitude,
512 longitude: data.longitude,
513 bearing: data.bearing ? data.bearing : 0.0,
514 polyline: data.polyline ? data.polyline : {},
515 order_status: order.order_status,
516 my_turn: order.my_turn
517 };
518
519 Libs.commonFunctions.emitToDevice("OrderEvent", order.CustomerDetails.socket_id, socket_data);
520
521 }///////////// Emit To customer ////////////////////
522
523 return order;
524
525 })
526 );
527
528 });
529
530 return Promise.all(promises);
531
532 });
533
534 var result = {
535 orders
536 };
537
538 ////console.log("Driver Current Orders");
539
540 return { success: 1, statusCode: 200, msg: "Driver update current orders", result };
541
542 }
543catch(e)
544 {
545 //console.log(e.message, 'DCurrentOrders Error');
546 return { success: 0, statusCode: 500, msg: e.message};
547 }
548}
549////////////////////// Event Emit to customer ///////////////////////////////////////////
550
551///////////////////// Customer Current Orders /////////////////////////////////////////
552var CCurrentOrders = async (data, AppDetail) => {
553try{
554 data.user_detail_id = AppDetail.user_detail_id;
555 data.app_language_id = AppDetail.language_id;
556
557 var orders = await Services.orderServices.customerCurrentOrders(data);
558
559 var result = {
560 orders
561 };
562
563 return { success: 1, statusCode: 200, msg: "Customer tracks current orders", result };
564
565 }
566catch(e)
567 {
568 //console.log(e.message, 'CCurrentOrders Error');
569 return { success: 0, statusCode: 500, msg: e.message};
570 }
571}
572/////////////////////