-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
215 lines (178 loc) · 5.1 KB
/
index.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
var init = function()
{
// startup Restify server
var server = Restify.createServer({'name': 'madsonic-songservice'});
server.use(Restify.fullResponse());
server.use(Restify.bodyParser());
server.use(Restify.queryParser());
server.on("uncaughtException", onUncaughtException);
server.use(mainHandler);
server.get("/songs", getSongs);
server.get("/search", searchSongs);
server.listen(config.port, serverUpHandler);
Winston.info("Server listening through port " + config.port + ".");
}
var mainHandler = function(request, result, next)
{
// recreate url
Winston.verbose(request.method + ": " + request.url);
next();
};
var onUncaughtException = function(request, response, route, err)
{
Winston.error("Uncaught Exception:\n", err);
response.send(err); // Resume default behaviour.
}
var serverUpHandler = function()
{
Winston.log('info', 'Restify server up and running on port ' + config.port);
};
// ================== //
// HANDLER FUNCTIONS: //
// ================== //
var divideSongs = function(folders, size)
{
var result = [];
var folderObj = {};
for(i = 0; i < folders.length; i++)
{
folderObj[folders[i].id] = 0;
}
for(i = 0; i < size; i++)
{
var index = Math.floor((Math.random() * folders.length));
folderObj[folders[index].id]++;
}
for(i = 0; i < folders.length; i++)
{
if(folderObj[folders[i].id])
{
result.push({id: folders[i].id, size: folderObj[folders[i].id]});
};
}
return result;
};
var getSongs = function(request, response, next)
{
if(request.params.type === "random")
{
// random, by year
Winston.info("random songs");
getFolders(function(err, folders)
{
getRandomSongs(folders, request.params.fromYear, request.params.toYear, request.params.size, function(err, songs)
{
response.send(songs);
});
});
}
next();
};
var getFolders = function(callback)
{
var options = JSON.parse(JSON.stringify(_httpOptions));
options.url = config.api.madsonic.location;
var client = Restify.createJSONClient(options);
var endpoint = '/rest2/getMusicFolders.view';
endpoint += '?v=2.5.0&c=work-pc-rest&f=json&u=' + config.api.madsonic.user;
endpoint += '&p=' + config.api.madsonic.pass;
Winston.info("Calling API with url: " + endpoint);
client.get(endpoint, function(err, req, resp, object)
{
callback(err, object["madsonic-response"].musicFolders.musicFolder);
});
};
var getRandomSongs = function(folders, from, to, size, callback)
{
var options = JSON.parse(JSON.stringify(_httpOptions));
options.url = config.api.madsonic.location;
var client = Restify.createJSONClient(options);
var endpoint = '/rest2/getRandomSongs.view';
endpoint += '?v=2.5.0&c=work-pc-rest&f=json&u=' + config.api.madsonic.user;
endpoint += '&p=' + config.api.madsonic.pass;
// by year?
if(from)
{
endpoint += '&fromYear=' + from;
endpoint += '&toYear=' + to;
}
// determine division of songs per folder
var chosenFolders = divideSongs(folders, size);
var songs = [];
Async.each(chosenFolders, function(folder, callback)
{
Winston.info("Calling API with url: " + endpoint + "musicFolderId=" + folder.id + "&size=" + folder.size);
client.get(endpoint + "&musicFolderId=" + folder.id + "&size=" + folder.size, function(err, req, resp, object)
{
if(!err) songs.push.apply(songs, object["madsonic-response"].randomSongs.song);
callback(err);
});
},
function(err)
{
// shuffle array before returning
Shuffle(songs);
callback(err, songs);
});
};
var searchSongs = function(request, response, next)
{
// set vars
var query = {
artist: request.params.artist,
song: request.params.song
};
var searchQuery = query.artist + " " + query.song;
// prepare rest call
var options = JSON.parse(JSON.stringify(_httpOptions));
options.url = config.api.madsonic.location;
var client = Restify.createJSONClient(options);
var endpoint = '/rest2/searchID3.view';
endpoint += '?v=2.5.0&c=work-pc-rest&f=json&u=' + config.api.madsonic.user;
endpoint += '&p=' + config.api.madsonic.pass;
endpoint += '&query=' + encodeURIComponent(searchQuery);
// make rest call
Winston.info("Calling API with url: " + endpoint);
client.get(endpoint, function(err, req, resp, object)
{
// loop through songs and fond the correct one
var songs = object["madsonic-response"].searchResultID3.song;
var song;
var songFound = null;
var i = 0; iLen = songs.length;
for(i; i < iLen; i++)
{
song = songs[i];
if(song.artist.toLowerCase() == query.artist.toLowerCase() && song.title.toLowerCase() == query.song.toLowerCase())
{
songFound = song;
break;
}
};
// send response
if(!songFound) return response.send(404);
response.send(songFound);
});
next();
};
// init requirements:
var Async = require('async');
var Shuffle = require('shuffle-array');
var Restify = require('restify');
var Winston = require("./node_logging/logger.js")("madsonic-songservice");
// config
var config = require('./config.json');
Winston.info("Started with the following config:\n", JSON.stringify(config));
// init vars
var _httpOptions = {
headers: {
"Content-Type": "application/json"
},
retry: {
'retries': 0
},
agent: false
};
var _user = "admin";
var _pass = "admin";
init();