-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
234 lines (220 loc) · 7.65 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
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
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var utils = require('util');
var querystring = require('querystring');
//var serverAddress = '10.1.155.146';
var serverPort = process.env.PORT || 5000;
var usersIds = [ '22316098' ];
var usersTracks = {};
//====================================================================================
//
// Just a helper function to convert to radians
//
//====================================================================================
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
//====================================================================================
//
// Converts the tracks from this user into something that the browser will understand
// Basically comma separated format: `track1,lat1,lng1...trackn,latn,lngn`
//
//====================================================================================
function convertTracksToSend(user_id) {
var tracksStrings = '';
var tracks = usersTracks[user_id];
for (var i=0; i<tracks.length; i++) {
var track = tracks[i];
var str = track.id + ',' + track.lat + ',' + track.lng + ',';
tracksStrings += str;
}
return tracksStrings;
}
//====================================================================================
//
// Converts the tracks from this user into something that the browser will understand
// Basically comma separated format: `track1,lat1,lng1...trackn,latn,lngn`
//
//====================================================================================
function getClosestTrackToMarker(user_id, lat, lng) {
var tracks = usersTracks[user_id];
if(tracks === undefined) {
return {};
}
var shortestDistance = 1000000;
var outputHash = {};
for (var i=0; i<tracks.length; i++) {
var track = tracks[i];
var lat2 = parseFloat(lat);
var lat1 = parseFloat(track.lat);
var lon2 = parseFloat(lng);
var lon1 = parseFloat(track.lng);
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
if (d < shortestDistance) {
shortestDistance = d;
outputHash['distance'] = d;
outputHash['trackToSend'] = track.stream_url;
outputHash['trackPermalink'] = track.permalink;
}
}
outputHash.distance *= 1000.0;
outputHash.trackToSend = outputHash.trackToSend + '?client_id=YOUR_CLIENT_ID';
return outputHash;
}
//====================================================================================
//
// Gets individual info from all the tracks from a user and stores them in the global hash
//
//====================================================================================
function getTracksInfo(user_id, data) {
var userTracks = [];
var tracksSoFar = 0;
var nrTracks = data.length;
for (var i=0; i<data.length; i++) {
var track_path = '/tracks/' + data[i].id + '.json?client_id=YOUR_CLIENT_ID';
var options2 = {
host: 'api.soundcloud.com',
port: 80,
path: track_path
};
//Let's fetch all the tracks from the user
http.get(options2, function(resp2) {
var b2 = new Buffer(0);
resp2.on('data', function(d2) {
b2 += d2;
});
resp2.on('end', function() {
var str2 = b2.toString();
var data2 = JSON.parse(str2);
tracksSoFar++;
console.log("So far: " + tracksSoFar + "(" + nrTracks + ")" + " for user: " + user_id);
//Convert the tags into something that is easy to parse
geo_pos = data2.tag_list.split(' ');
if(geo_pos[0].split('=')[0] == 'lat') {
data2.lat = geo_pos[0].split('=')[1];
data2.lng = geo_pos[1].split('=')[1];
} else {
data2.lng = geo_pos[0].split('=')[1];
data2.lat = geo_pos[1].split('=')[1];
}
userTracks.push(data2);
if(tracksSoFar == nrTracks) {
console.log("Got all tracks for user: " + user_id);
usersTracks[user_id] = userTracks;
}
})
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
}
//====================================================================================
//
// Gets all the tracks related to a user
//
//====================================================================================
function getAllTracks(user_id) {
//Let's send out plain text
var options = {
host: 'api.soundcloud.com',
port: 80,
path: '/users/' + user_id + '/tracks.json?client_id=YOUR_CLIENT_ID'
};
//Let's fetch all the tracks from the user
http.get(options, function(resp) {
var b = new Buffer(0);
resp.on('data', function(d) {
b += d;
});
resp.on('end', function() {
var str = b.toString();
var data = JSON.parse(str);
getTracksInfo(user_id, data);
})
}).on('error', function(e) {
console.log("Got error: " + e.message);
res.write(JSON.stringify({ error: e.message }));
res.end();
});
}
//==========================================================================
//Update all the tracks for all the registered users
function updateTracks() {
for(var i=0; i<usersIds.length; i++) {
getAllTracks(usersIds[i]);
}
setTimeout(updateTracks, 60000);
}
updateTracks();
//==========================================================================
/*
* Handler for server static files
*
*/
function handleStaticFile(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
if (uri == '/') {
filename = './static/index.html';
}
path.exists(filename, function(exists) {
if(!exists) {
res.writeHead(404, {'Content-Type': 'text/plain', 'Cache-Control': 'no-cache' });
res.write("404 Not Found\n");
res.end();
return;
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
res.writeHead(500, {'Content-Type': 'text/plain', 'Cache-Control': 'no-cache' });
res.write(err + "\n");
res.end();
return;
}
var ext = filename.substr(filename.lastIndexOf('.') + 1);
var mimeType = 'text/html';
if(ext == 'js') {
mimeType = 'application/javascript';
}
//Set the proper file type header
res.writeHead(200, {'Content-Type': mimeType, 'Cache-Control': 'no-cache' });
res.write(file, "binary");
res.end();
});
});
}
//==========================================================================
//==========================================================================
//==========================================================================
var serverHTTP = http.createServer(function (req, res) {
req.parsedUrl = url.parse(req.url);
req.parsedUrl.parsedQuery = querystring.parse(req.parsedUrl.query || '');
console.log("Request for pathname: " + req.parsedUrl.pathname);
switch (req.parsedUrl.pathname) {
case '/getAllLocations':
res.writeHead(200, {'Content-Type': 'text/plain', 'Cache-Control': 'no-cache' });
var out = convertTracksToSend(usersIds[0]);
res.end(out);
break;
case '/getLocation':
res.writeHead(200, {'Content-Type': 'text/plain', 'Cache-Control': 'no-cache' });
var out = getClosestTrackToMarker(usersIds[0], req.parsedUrl.parsedQuery.lat, req.parsedUrl.parsedQuery.lng);
res.end(JSON.stringify(out));
break;
default:
handleStaticFile(req, res);
}
//}).listen(serverPort,serverAddress);
}).listen(serverPort);