forked from dorbenlulu/Binder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
173 lines (152 loc) · 7.08 KB
/
server.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
const dotenv = require('dotenv').config()
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const path = require("path");
const api = require("./server/routes/api.js");
const errorHandler = require('./server/middlewares/errorHandler/errorHandler')
const config = require('./config/config')
// const dbSetup = require('./server/db/dbSetup')
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const axios = require("axios")
const apiKey = process.env.GOOGLE_MAP_API_KEY //move through config
const controller = require('./server/middlewares/controllers/controller')
const queries = require('./server/db/queries')
const userIds = require('./dummyData').userIds
const PORT = 8080
const users = []
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'build')));
app.use("/", api);
app.use(errorHandler)
io.on('connection', function (socket) {
console.log('user has connected')
socket.on('userId', (user) => {
user.socketId = socket.id
users.push(user)
console.log(user.firstName)
users.forEach(u=>console.log('user name: '+u.firstName))
})
socket.on('GPSlocation', async (GPSlocation) => {
const nearLocations = await axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${GPSlocation.lat},${GPSlocation.lng}&radius=100&type=bar&key=${apiKey}`);
let places = nearLocations.data.results.map(itemName => ({ name: itemName.name, id: itemName.place_id, locationCoordinates: itemName.geometry.location }))
socket.emit(`locationsArry`, places);
})
socket.on('selectedLocation', (selectedLocation) => {
console.log('Selected location received: ' + selectedLocation)
let usersNearUser = []
let newUser = {}
users.forEach(u => {
if (u.location === selectedLocation) {
usersNearUser.push(u)
}
if (u.socketId === socket.id) {
u.location = selectedLocation
newUser = u
}
})
socket.emit(`usersNearMe`, usersNearUser)
usersNearUser.push(newUser)
console.log('newUser is ', newUser.firstName);
for (let i = 0; i < usersNearUser.length - 1; i++) {
const usersToSend = [...usersNearUser.filter(user => user.socketId != usersNearUser[i].socketId)]
io.to(`${usersNearUser[i].socketId}`).emit('usersNearMe', usersToSend);
}
})
socket.on('GPSlocation', async (GPSlocation) => {
const nearLocations = await axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${GPSlocation.lat},${GPSlocation.lng}&radius=100&type=bar&key=${apiKey}`);
let places = nearLocations.data.results.map(itemName => ({ name: itemName.name, id: itemName.place_id, locationCoordinates: itemName.geometry.location }))
let pictures=[]
for(let i=0 ; i<nearLocations.data.results.length; i++){
if(nearLocations.data.results[i].photos){
let photoCode= nearLocations.data.results[i].photos[0].photo_reference
const photoLocation = await axios.get(`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${photoCode}&key=AIzaSyBKizswmWAb46dJxdiVPZp1zpUjDxC55lM`);
delete photoLocation.data
pictures.push(photoLocation.request.res.responseUrl)
}
else{
pictures.push("https://images.squarespace-cdn.com/content/v1/53eba4e8e4b0d8c733bbd45a/1413767586813-7KBCWBJ538XXVKJ2DKXF/ke17ZwdGBToddI8pDm48kAR7vG2QfD3uW0H7YLf9VaYUqsxRUqqbr1mOJYKfIPR7LoDQ9mXPOjoJoqy81S2I8N_N4V1vUb5AoIIIbLZhVYxCRW4BPu10St3TBAUQYVKcT3f5-rKIYluIX58xa6tfcBn_TXvNu7kmrqqSJvyZGOaDbqGgO06TDcYHqFgl4xk9/BAR.jpg")
}
}
for(let i=0; i<places.length; i++){
places[i].picture=pictures[i]
}
socket.emit(`locationsArry`, places);
})
socket.on('reaction', (reactionObj) => {
io.to(`${reactionObj.destinationUser.socketId}`).emit('reaction recieved', reactionObj);
// for (let i = 0; i < users.length; i++) {
// if (users[i].socketId === reactionObj.destinationUser.socketId) {
// // console.log('users[i].notificationToken',users[i].notificationToken)
// const body = {
// content: {
// data: {
// message: "notification",
// },
// to: users[i].notificationToken
// },
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': 'key=AAAAz2kANlQ:APA91bFtwfVaUwO-d7CYV-BkeyqiXM93jaZtT4LeWZqrd6kXJbEefW-8yNZ8zHbKQA6X8aPZZoJlYKAcQ0IIfEkWOqN7qpvTyoWqBjBt2ZpyFJ7LgbTPQiExwkCjP-nFeqEYMhL7a8dI'
// }
// }
// axios.post('https://fcm.googleapis.com/fcm/send', body)
// .then( result => {
// res.end()
// })
// .catch( err => {
// // console.log('error')
// })
// }
// }
})
socket.on('out of range', function () {
let location
for (let i = 0; i < users.length; i++) {
if (users[i].socketId === socket.id) {
location = users[i].location
users[i].location = ""
console.log(`checking out user ${users[i].userId} from ${location}`)
}
}
for (let i = 0; i < users.length; i++) {
const usersToSend = [...users.filter(user => user.socketId != users[i].socketId && user.location == location)]
io.to(`${users[i].socketId}`).emit('usersNearMe', usersToSend);
}
})
socket.on('push notification token', (token) => {
console.log('token',token)
console.log('users',users)
for (let i = 0; i < users.length; i++) {
console.log('socketId',socket.id)
if (users[i].socketId === socket.id) {
users[i].notificationToken = token
console.log('userWithToken',users[i].notificationToken)
}
}
})
socket.on('disconnect', function () {
console.log('user disconnected');
let location
for (let i = 0; i < users.length; i++) {
if (users[i].socketId === socket.id) {
location = users[i].location
console.log(`deleting user ${users[i].userId}`)
users.splice(i, 1);
}
}
for (let i = 0; i < users.length; i++) {
const usersToSend = [...users.filter(user => user.socketId != users[i].socketId && user.location == location)]
io.to(`${users[i].socketId}`).emit('usersNearMe', usersToSend);
}
});
});
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// app.use((req, res) => res.sendFile(INDEX, { root: __dirname }))
http.listen(process.env.PORT || PORT, function () {
console.log('listening on *:8080');
});