-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
192 lines (155 loc) · 6.16 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
var bodyParser = require('body-parser');
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let app = express();
let router = express.Router();
// Database ========================================
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
db.defaults({users: []}).write();
// =================================================
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(function (req, res, next) {
var send = res.send;
res.send = function (body) {
console.log(req.method, req.url, "\r\nRequest => ", JSON.stringify(req.body, undefined, 4), "\r\nResponse => ", body, "\r\n=========================================================================");
send.call(this, body);
};
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.header("Access-Control-Max-Age","1800");
next()
});
// ============================================================ //
const config = {
kavenegarApiToken: process.env["npm_package_config_kavenegar_api_token"],
apnCertificateFile: process.env["npm_package_config_apn_certificate_file"],
apnTopic: process.env["npm_package_config_apn_topic"],
apnCertificatePassword: process.env["npm_package_config_apn_certificate_password"],
firebaseProjectFile: process.env["npm_package_config_firebase_project_file"],
firebaseDatabaseURL: process.env["npm_package_config_firebase_database_url"]
};
console.log("Kavenegar Backend Sample Config : ", JSON.stringify(config, undefined, 4));
// ============================================================ //
let axios = require('axios');
const httpClient = axios.create({
baseURL: 'https://api.kavenegar.io/user/v1/',
timeout: 10000,
headers: {'Authorization': "Bearer " + config.kavenegarApiToken}
});
// Firebase Messaging Config =============================================================== //
const firebaseAdmin = require('firebase-admin');
if (config.firebaseProjectFile) {
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(require(config.firebaseProjectFile)),
databaseURL: config.firebaseDatabaseURL
});
}
// Apple Messaging Config =============================================================== //
const apn = require('apn');
var appleApnProvider = null;
if (config.apnCertificateFile) {
appleApnProvider = new apn.Provider({
pfx: config.apnCertificateFile,
passphrase: config.apnCertificatePassword,
production: false
});
}
// ===========================================================//
app.get('/', function (req, res) {
res.send(db.get("users").value());
});
app.post("/calls", function (req, res) {
var deviceId = req.header("authorization");
var caller = db.get("users").find({deviceId: deviceId}).value();
var receptor = db.get("users").find({username: req.body.receptor}).value();
if (caller == null || receptor == null) {
res.status(500).send({status: "local_invalid_caller_or_receptor"});
return;
}
const payload = {
caller: {
username: caller.username,
displayName: caller.displayName,
platform: caller.platform
},
receptor: {
username: receptor.username,
displayName: receptor.displayName,
platform: receptor.platform
}
};
httpClient.post("calls", payload).then((response) => {
const data = response.data;
console.log("Response of kavenegar :", data);
const notificationToken = receptor.notificationToken;
sendNotification(data.receptor.username, notificationToken, {
callId: data.id,
accessToken: data.receptor.accessToken
}, receptor.platform);
res.send({
callId: data.id,
accessToken: data.caller.accessToken
});
}).catch(reason => {
if (reason.response) {
res.status(500).send(reason.response.data);
}
else {
res.status(500).send({status: reason.toString()});
}
});
});
app.post("/authorize", function (req, res) {
const payload = {
deviceId: req.body.deviceId,
notificationToken: req.body.notificationToken,
username: req.body.username,
displayName: req.body.displayName,
platform: req.body.platform
};
if (payload.deviceId == null || payload.notificationToken == null || payload.username == null || payload.platform == null) {
res.status(422).send({"status": "local_invalid_parameters"});
return;
}
db.get("users").remove({username: payload.username}).write(); // remove old data with this token
db.get("users").push(payload).write();
res.send({
"apiToken": payload.deviceId
});
});
function sendNotification(username, token, payload, platform) {
console.log("Send Notification To ", username, token, payload, platform);
if (platform === "android" || platform === "web") {
const message = {
data: {
action: 'call',
payload: JSON.stringify(payload)
},
token: token
};
firebaseAdmin.messaging().send(message).then((response) => {
console.log('Firebase push notification sent message:', response);
}).catch((error) => {
console.log('Firebase error sending message:', error);
});
}
else {
const notification = new apn.Notification();
notification.topic = config.apnTopic + ".voip";
notification.body = JSON.stringify(payload);
notification.badge = 10;
appleApnProvider.send(notification, token).then((result) => {
console.log("Apple push notification result : ", result);
});
}
}
module.exports = app;