-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
227 lines (194 loc) · 6.93 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
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
const mosca = require('mosca');
const ascoltatori = require('ascoltatori');
const HashMap = require('hashmap');
const callsMap = new HashMap();
const devicePendingMessages = new HashMap();
const User = require('./models/user');
const Calls = require('./models/call');
const Device = require('./models/device');
const dbConfig = require('./config/database');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.database);
//TODO in future whole logic should be moved from app.js
//mongodb://heroku_user:[email protected]:41068/intercom
var ascoltatore = {
//using ascoltatore
type: 'mongo',
url: 'mongodb://heroku_user:[email protected]:41068/intercom',
pubsubCollection: 'ascoltatori',
mongo: {}
};
var settings = {
http: {
port: 5080,
bundle: true,
static: './'
},
port: 5083,
backend: ascoltatore
};
var server = new mosca.Server(settings);
server.on('clientConnected', async function (client) {
console.log('client connected', client.id);
let device = await Device.findOne({"deviceId": client.id}).populate("user").exec().catch(err => err);
client.userId = device.user.username;
});
// fired when a message is received
server.on('published', async function (packet, client) {
console.log('Published', packet.topic);
try {
console.log('PublishedDATA', JSON.parse(packet.payload));
}
catch (err) {
console.log('PublishedDATA', packet.payload);
}
let topics = packet.topic.split("/");
switch (topics[0]) {
case "calls":
let message = JSON.parse(packet.payload);
let call;
if (message.messageType !== "callnew") {
try {
call = await Calls.findOne({callId: message.callId}).exec();
}
catch (err) {
console.log("Error");
return;
}
}
if (topics[1] === "ongoing") {
handelOngoingCallEvent(packet, client, message, call);
} else if (topics[1] === "server") {
handelGeneralCallEvent(packet, client, message, call);
}
break;
}
});
server.on('ready', setup);
function sendPendingCallIfExist(devideId) {
}
async function handelOngoingCallEvent(packet, client, message, call) {
switch (message.callEvent) {
case "answer":
//MAYBE WE CAN MAKE TOPIC FOR PRE_CALL_ESTABLISHMENT EVENTS SO WE WILL NOT MAKE FOR LOOP and it has other adavantages
call.status = "connected";
call.answeredDeviceId = client.id;
await call.save().catch(err => err);
for (let i = 0; i < call.remoteUserIds.length; i++) {
let callAnsweredMessage = getCallAnsweredMessage(message.callId, call.remoteUserIds[i]);
server.publish(callAnsweredMessage);
}
break;
case "hangup":
call.status = "terminated";
await call.save().catch(err => err);
break;
case "invite":
break;
}
}
async function handelGeneralCallEvent(packet, client, message, call) {
//first topic item is "calls"
switch (message.messageType) {
//calls/general/*
case "callnew":
//FIXME callId should be generated
let callId = message.rawCallId + "real";
call = new Calls({
callId: callId,
rawCallId: message.rawCallId,
callMakerUserId: client.userId,
recipientUsersIds: message.remoteUserIds,
status: 'connecting'
});
call.save(function (err) {
if (err) {
console.log(err)
} else {
console.log(`Successfully created new Call ${callId}`)
}
});
let callInfoMessage = getCallInfoMessage(client.id, callId, message.rawCallId);
server.publish(callInfoMessage);
for (let i = 0; i < message.remoteUserIds.length; i++) {
//FIXME client.id is device id but user id should be passed
let inviteMessage = getInviteMessage(client.id, message.remoteUserIds[i], message.callType, callId);
server.publish(inviteMessage);
}
break;
case "calldecline":
//if all call recipients sent decline we should notify caller
//FIXME check if all recipients sent decline
call.status = "terminated";
await call.save().catch(err => err);
let declineMessage = getDeclinedMessage(call.callerDeviceId, message.callId);
server.publish(declineMessage);
callsMap.delete(message.callId);
break;
case "callhangup":
call.status = "terminated";
await call.save().catch(err => err);
for (let i = 0; i < call.remoteUserIds.length; i++) {
let hangupMessage = getHangupMessage(message.callId, call.remoteUserIds[i]);
server.publish(hangupMessage);
}
break;
}
}
server.on('delivered', async function (packet, client) {
await Device.findOneAndUpdate({deviceId: client.id}, {lastTimeReceivedMessage: Date.now()}, {new: true}).catch(err => err);
});
server.on("subscribed", async function (topic, client) {
if (topic === "calls/device/" + client.id) {
let device = await Device.findOne({deviceId: client.id}).exec().catch(err => err);
let calls = await Calls.find().and([{status: "connecting"},
{recipientUsersIds: client.userId},
{lastTimeUpdated: {$gt: device.lastTimeReceivedMessage}}
]).exec().catch(err => err);
calls.forEach(function (call) {
let inviteMessage = getInviteDeviceMessage(call.callMakerUserId, client.id, "", call.callId);
server.publish(inviteMessage);
})
}
});
function getMqttMessage(topic, payload) {
return {
topic: topic,
payload: JSON.stringify(payload), // or a Buffer
qos: 0, // 0, 1, or 2
retain: false // or true
};
}
function getCallAnsweredMessage(callId, remoteUserId) {
return getMqttMessage(
'calls/user/' + remoteUserId,
{
messageType: "callanswered",
callId: callId
}
);
}
function getHangupMessage(callId, remoteUserId) {
return getMqttMessage(
'calls/user/' + remoteUserId,
{
messageType: "callhangup",
callId: callId
}
);
}
function getDeclinedMessage(callerDeviceId, callId) {
return getMqttMessage(
'calls/device/' + callerDeviceId,
{
messageType: "calldecline",
callId: callId
}
);
}
//Call invitation logic removed
// fired when the mqtt server is ready
function setup() {
console.log('Mosca server is up and running');
}