-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
275 lines (251 loc) · 7.36 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const port = process.env.PORT || 5012;
const fs = require("fs");
const server = require("http").createServer(app);
const DATABASE_URL ="mongodb://nJijaQgenesiszoaq:[email protected]:24812/genesismatrimony";
//const DATABASE_URL = "mongodb://localhost:27017";
const cors = require('cors')
const connectdb = require("./db/connect.js");
const jwt = require("jsonwebtoken");
const handleSuccess = require("./HandleFunction/handleSuccess.js");
const mime = require("mime");
const handleErr = require("./HandleFunction/HandleErr");
const path = require("path");
const UserApi = require('./routes/userApi.js');
const CommunityApi = require('./routes/communityApi');
const PreferenceApi = require('./routes/preferenceApi');
const ChatApi = require('./routes/chatApi.js');
const Chat = require('./models/chat');
const AdminApi = require('./routes/adminApi.js');
const io = require('socket.io')(server, {
path: '/custom',
reconnection: true,
reconnectionAttempts: 3,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
randomizationFactor: 0.5,
timeout: 20000,
autoConnect: true,
query: {},
// options of the Engine.IO io
upgrade: true,
forceJSONP: false,
jsonp: true,
forceBase64: false,
enablesXDR: false,
timestampRequests: true,
timestampParam: 't',
policyPort: 843,
transports: ['polling', 'websocket'],
transportOptions: {},
rememberUpgrade: false,
onlyBinaryUpgrades: false,
requestTimeout: 0,
protocols: [],
// options for Node.js
agent: false,
pfx: null,
key: null,
passphrase: null,
cert: null,
ca: null,
ciphers: [],
rejectUnauthorized: false,
perMessageDeflate: true,
forceNode: false,
localAddress: null,
});
const corsOptions = {
origin: 'https://metrimony.tech-east.com.pk'
};
connectdb(DATABASE_URL);
app.use(cors())
app.use(bodyParser.json({limit: '50mb'}));
app.use(express.json());
app.use(express.static(path.join(__dirname, "/uploads/")));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//Get File
// app.get("/api/getFile:path", (req, res) => {
// try {
// var file = __dirname + "/uploads/" + req.params.path;
// var filename = path.basename(file);
// var mimetype = mime.getType(file);
// //console.log('file->', file)
// res.setHeader("Content-disposition", "attachment; filename=" + filename);
// res.setHeader("Content-type", mimetype);
// var filestream = fs.createReadStream(file);
// filestream.pipe(res);
// } catch (error) {
// return res.json(handleErr(error));
// }
// });
// app.get('/api/getFile:path', (req, res) => {
// if (req.params.path !== undefined && req.params.path !== "undefined" && req.params.path !== null) {
// try {
// var file = __dirname + '/uploads/' + req.params.path;
// var filename = path.basename(file);
// var mimetype = mime.getType(file);
// // console.log('file->', file)
// res.setHeader('Content-disposition', 'attachment; filename=' + filename);
// res.setHeader('Content-type', mimetype);
// var filestream = fs.createReadStream(file);
// filestream.pipe(res);
// } catch (error) {
// return res.json(handleErr(error))
// }
// }
// else {
// return res.json(handleErr('Image path is required'))
// }
// })
app.get('/api/getFile:path', (req, res) => {
if (req.params.path !== undefined && req.params.path !== "undefined" && req.params.path !== null) {
var file = __dirname + '/uploads/' + req.params.path;
try {
if (fs.existsSync(file)) {
var filename = path.basename(file);
var mimetype = mime.getType(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
} else {
res.json(handleErr('File not found'))
}
} catch (error) {
res.json(handleErr(error))
}
}
else {
res.json(handleErr('Image path is required'))
}
})
app.use('/user' , UserApi);
app.use('/community' , CommunityApi);
app.use('/preference' , PreferenceApi);
app.use('/chat' , ChatApi);
app.use('/admin' , AdminApi);
io.engine.on("connection_error", (err) => {
console.log(err);
});
io.on('connection', (socket) => {
io.emit('connecteddd', {
message: "yahoooo"
})
socket.on('newMessageDone', (data) => {
console.log('oidhfsdf===>', data)
io.emit('messageSentSuccess', "Han mehdi mill gya hai");
})
socket.on('newMessage', (data) => {
console.log(data)
if (data.id && data.messageType !== undefined && data.messageSender !== undefined && data.sender !== undefined) {
let { id, messageType, messageSender, sender } = data
let message = {}
if (messageType === 0) {
if (data.text) {
message = {
text: data.text,
messageType,
messageSender,
sender
}
}
else {
let response = {
data: "Message text is required",
message: "Failed"
}
return io.emit('messageSent', response)
}
}
else if (messageType === 1) {
if (data.filePath) {
message = {
filePath: data.filePath,
messageType,
messageSender,
sender
}
}
else {
let response = {
data: "File path is required",
message: "Failed"
}
return io.emit('messageSent', response)
}
}
else if (messageType === 2) {
if (data.purchaseOffer) {
message = {
purchaseOffer: data.purchaseOffer,
messageType,
messageSender,
sender,
offerStatus: "pending"
}
}
else {
let response = {
data: "Purchase offer is required",
message: "Failed"
}
return io.emit('messageSent', response)
}
}
Chat.findByIdAndUpdate(id, { $push: { messages: message }, lastMessage: new Date() }, { new: true })
.populate([
{
path: "sender",
model: "users"
},
{
path: "receiver",
model: "users"
}
]).exec((err, chat) => {
if (err) {
let response = {
message: "Failed",
data: err
}
io.emit('messageSent', response)
}
else {
let response = {
message: "Success",
data: chat
}
io.emit('messageSent', response)
}
})
}
else {
let response = {
data: "Message details are required",
message: "Failed"
}
io.emit('messageSent', response)
}
})
/**
{
"id":"6284f25814b90659f96ad204",
"messageId":"62878337d21e8c0537d4bf07"
}
*/
//Accept Offer request
});
app.get("/", cors(corsOptions),(req, res) => {
res.send("<h1>hello from Genesis Backend</h1>");
});
server.listen(port, () => {
console.log("Server listening at port %d", port);
});