-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
310 lines (253 loc) · 8.01 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*jshint node:true*/
console.log('[app.js] Application setup beginning.');
var Express = require('express'),
Util = require('util'),
Wikidot = require('./public/js/wikidot'),
Scoring = require('./public/js/scoring'),
Calendar = require('./public/js/calendar'),
Timespan = require('./public/js/timespan'),
Jasmine = require('./public/js/jasmine'),
Recalculate = require('./public/js/recalculate'),
Q = require('q'),
_ = require('underscore');
// setup middleware
var app = Express();
app.use(Express.static(__dirname + '/public')); //setup static public directory
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views
app.engine('html', require('ejs').renderFile);
//TODO Refactor routing definitions out to a middleware routes.js
//TODO Routes = require('./public/js/routes');
//TODO Routes.apply(app);
// render index page
app.get('/', function(request,response) {
console.log(
'/',
'_songs: %s; _calendar: %s; _artists: %s',
roughSizeOfObject(_songs),roughSizeOfObject(_calendar),roughSizeOfObject(_artists)
);
res.render("index.html");
});
//TODO songChart.html
app.get('/artistChart', function(request,response) {
response.render("artistChart.html");
});
var deferred = Q.defer();
// Utility functions.
function roughSizeOfObject( object ) {
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
function pushSong(pArray,pSlug,pSong) {
if (pArray[pSlug]) {
pArray[pSlug].push(pSong);
} else {
pArray[pSlug] = [pSong];
}
}
// Cache the songs that have been downloaded.
var _songs = {};
var _calendar = new Calendar();
var _artists = {};
// p: { 'fullname': fullname of page to get, 'callback': function to process the received content }
function getPage(p) {
var fullname = p.fullname;
Wikidot.getPage(fullname, function(error,content) {
if (error) {
setImmediate(getPage,p); // requeue this
return;
}
p.callback(content);
}); // Wikidot.getPage
}
app.get('/scores/artist/:slug', function(request,response) {
response.json(_artists[request.params.slug]);
});
// Rank filter: All songs with projected peak at or above the given rank.
rankFn = function(someRank) { return function(song) { return parseFloat(song.peakrank) <= parseFloat(someRank); }; };
app.get('/scores/rank/:rank', function(request,response) {
subset = _.filter(_songs, rankFn(request.params.rank));
response.json(subset);
});
// Duration filter: All songs with projected duration at or above a given number.
durationFn = function(someAmount) { return function(song) { return parseFloat(song.months) >= parseFloat(someAmount); }; };
app.get('/scores/duration/:duration', function(request,response) {
subset = _.filter(_songs, durationFn(request.params.duration));
response.json(subset);
});
//TODO Generalize and add support for multiple fields.
function orderFnFn(field) {
var sign = 1;
if (field.substr(0,1) == "-") {
field = field.substr(1);
sign = -1;
}
return function(entity) {
return sign*entity[field];
}
}
app.get('/songs', function(request,response) {
console.log('/songs',request.query);
// Get post parameters.
var decade = request.query.decade;
var year = request.query.year;
var month = request.query.month;
var refresh = false; // disabled for now - request.query.refresh;
var top = request.query.top; // default: all
orderField = request.query.sortField ? request.query.sortField : "-score";
if (refresh) {
q = Q.fcall(getSongPageList);
} else {
q = Q.fcall(function() { return; } );
}
q.then(function() {
content = {};
//TODO Option to return highest-peaking songs.
//TODO Option to return highest-debuting songs.
//TODO Option to return only those songs for a particular artist.
if (decade) {
content = _calendar.get().byDecade(decade);
} else if (year) {
if (month) {
content = _calendar.get().byMonth(year,month);
} else {
content = _calendar.get().byYear(year);
}
}
//TODO Filter songs by criteria given.
if (content) {
content = _.sortBy(content,orderFnFn(orderField));
for (var index in content) {
song = content[index];
song.rank = parseInt(index)+1;
}
if (top) {
content = _.first(content,top);
}
console.log('Returning songs.',content.length);
} else {
console.log('No songs to return!');
}
response.json(content);
})
.catch(function (error) {
console.log('ERROR',error);
response.json({}); //TODO Make this more robust.
})
.done();
});
app.get('/artists', function(request,response) {
console.log('/artists');
var top
= request.query.top ? request.query.top : 100;
var orderField
= request.query.sortField ? request.query.sortField : "-score";
var refresh = false; // disabled for now - request.query.reload;
if (refresh) {
q = Q.fcall(getSongPageList);
} else {
q = Q.fcall(function() { return; } );
}
q.then(function() {
content = _.map(
_artists,
function (songArray, artistSlug) {
return {
slug: artistSlug,
songCount: songArray.length,
score: Scoring.songCollectionScore(songArray)
};
}
); // _.map
if (content) {
content = _.sortBy(content,orderFnFn(orderField));
for (var index in content) {
entity = content[index];
entity.rank = parseInt(index)+1;
}
if (top) {
content = _.first(content,top);
}
console.log('Returning artists.',content.length);
} else {
console.log('No artists to return!');
}
response.json(content);
})
.catch(function (error) {
console.log('ERROR',error);
response.json({}); //TODO Make this more robust.
})
.done();
});
function getPagesPromise(list) {
var promises = list.map(function(slug) {
return Q.nfcall(Wikidot.getPage, slug);
});
return Q.all(promises);
}
app.get('/page/:fullname', function(request,response) {
console.log('/page',request.params.fullname);
getPagesPromise([request.params.fullname])
.then(
function(returnValue) {
response.json(returnValue[0]); // Wikidot returns an array, but angular $resource.get expects an object.
}
)
.fail(function (error) {
console.log('ERROR',error);
response.json({}); //TODO Make this more robust.
})
.done();
});
app.get('/runJasmine', function(request,response) {
console.log('/jasmine');
response.json(Jasmine.run());
});
app.get('/recalculate', Recalculate);
// There are many useful environment variables available in process.env.
// VCAP_APPLICATION contains useful information about a deployed application.
var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}");
// TODO: Get application information and use it in your app.
Wikidot.username = process.env.WIKIDOT_USERNAME;
Wikidot.apiKey = process.env.WIKIDOT_APIKEY;
Wikidot.site = process.env.WIKIDOT_SITE;
// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.
var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
// TODO: Get service credentials and communicate with bluemix services.
// Start server
// The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application:
var host = (process.env.VCAP_APP_HOST || 'localhost');
// The port on the DEA for communication with the application:
var port = (process.env.VCAP_APP_PORT || 3000);
app.listen(port, host);
// All done.
console.log('[app.js] Application setup complete.');
// ================================================================================