-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathapp.js
173 lines (135 loc) · 5.95 KB
/
app.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
if (process.env.NODE_ENV === "production") {
require('nodetime').profile({
accountKey: 'a0df5534478dd2873fcc0789e958749f2a356908',
appName: 'InstaCab Dispatcher'
});
require("bugsnag").register("889ee967ff69e8a6def329190b410677");
}
var Dispatcher = require('./dispatch'),
// agent = require('webkit-devtools-agent'),
WebSocketServer = require('ws').Server,
express = require('express'),
inspect = require('util').inspect,
util = require('util'),
cors = require('cors'),
apiBackend = require('./backend'),
async = require('async'),
db = require('./mongo_client'),
amqpConsumer = require('./amqp_consumer');
var dispatcher = new Dispatcher();
dispatcher.load(function(err) {
if (err) return console.log(err);
var app = express();
var port = process.env.PORT || 9000;
var server = app.listen(port);
console.log(' [*] Dispatcher started on port %d', port);
// Websockets
var wss = new WebSocketServer({ server: server });
wss.on('connection', function(connection) {
connection.on('message', function(data) {
dispatcher.processMessage(data, connection);
});
connection.on('close', function() {
connection.removeAllListeners();
connection = null;
});
connection.on('error', function(reason, code){
console.log('socket error: reason ' + reason + ', code ' + code);
connection.removeAllListeners();
connection = null;
})
});
// Middleware
app.use(express.json());
app.use(cors());
app.use(app.router);
app.use(function(err, req, res, next) {
console.error(err.stack);
res.send('500', { messageType: 'Error', text: err.message });
});
// create index:
// key, unique, callback
db.collection('mobile_events').ensureIndex({ "location": "2d" }, false, function(err, replies){});
db.collection('driver_events').ensureIndex({ "location": "2d" }, false, function(err, replies){});
// Events
app.post('/mobile/event', function(req, resp) {
// console.log(req.body);
db.collection('mobile_events').insert( req.body, function(err, replies){
if (err) console.log(err);
});
resp.writeHead(200, { 'Content-Type': 'text/plain' });
resp.end();
if (req.body.eventName === "NearestCabRequest" && req.body.parameters.reason === "openApp") {
apiBackend.clientOpenApp(req.body.parameters.clientId || req.body.clientId);
}
});
var clientRepository = require('./models/client').repository;
// TODO: Это должен быть отдельный от Диспетчера Node.js процесс
// 1) Нужен набор служб который запускается как один организм в котором службы сотрудничают друг с другом
// 2) Нужен процесс который будет перезапускать умершие службы, да Forever должен справиться
// TODO: Это должно делаться через Redis, хранишь данные в Redis,
// потом читаешь их и кэшируешь в памяти через request-redis-cache, затем с Web интерфейса можешь
// обновить данные Клиента, Водителя в Redis и послать сигнал в Redis чтобы Диспетчер прочитал обновленные данные из Redis
//
// State management
app.put('/clients/:id', function(req, resp) {
clientRepository.get(req.body.id, function(err, client) {
if (err) return console.log(err);
client.update(req.body);
});
resp.end();
});
var filterClientIds = [ 29, 31, 35, 36, 49, 63, 60, 67 ];
// Query demand
app.get('/query/pings', function(req, resp) {
var filter = {
// location: {
// $near: [39.192151, 51.672448], // Center of the Voronezh
// $maxDistance: 80 * 1000 // 40 km
// },
eventName: 'NearestCabRequest',
'parameters.reason': 'openApp',
'parameters.clientId': { $nin: filterClientIds } // filter out Pavel Tisunov and Mikhail Zhizhenko
};
db.collection('mobile_events').find(filter).toArray(function(err, items) {
if (err) return resp.end(JSON.stringify({pings: ""}));
var pings = async.map(items, function(item, callback) {
callback(null, {
id: item._id,
clientId: item.parameters.clientId || item.clientId,
longitude: item.location[0] || 0,
latitude: item.location[1] || 0,
epoch: item.epoch,
verticalAccuracy: item.parameters.locationVerticalAccuracy,
horizontalAccuracy: item.parameters.locationHorizontalAccuracy
});
}, function(err, result) {
resp.end(JSON.stringify({pings: result}));
});
});
});
app.get('/query/pickup_requests', function(req, resp) {
var filter = {
// TODO: Сделать миграцию, позже переименовать в базе PickupRequest -> RequestVehicleRequest
eventName: { $in: ['RequestVehicleRequest', 'PickupRequest']},
'parameters.clientId': { $nin: filterClientIds } // filter out Pavel Tisunov and Mikhail Zhizhenko
};
// TODO: Сделать миграцию, перенести clientId из parameters.clientId в root.clientId
db.collection('mobile_events').find(filter).toArray(function(err, items) {
if (err) return resp.end(JSON.stringify({pickup_requests: ""}));
var pings = async.map(items, function(item, callback) {
callback(null, {
id: item._id,
clientId: item.parameters.clientId || item.clientId,
longitude: item.location[0],
latitude: item.location[1],
epoch: item.epoch,
verticalAccuracy: item.parameters.locationVerticalAccuracy,
horizontalAccuracy: item.parameters.locationHorizontalAccuracy
});
}, function(err, result) {
resp.end(JSON.stringify({pickup_requests: result}));
});
});
});
});