diff --git a/router/album.js b/router/album.js index 4d97485..d46f930 100644 --- a/router/album.js +++ b/router/album.js @@ -51,6 +51,12 @@ router.route("/filter/:term") res.json(result).status(200).end(); }); }) +router.route("/random/:count") + .get(passport.authenticate("jwt", { session: false }), (req, res) => { + database.albums.randomCovers(req.params.count, 64, (result) => { + res.json(result).status(200).end(); + }); + }) router.route("/:id") .get(checkGuest, (req, res) => { diff --git a/services/database/albums.js b/services/database/albums.js index 09c9e43..e8258cb 100644 --- a/services/database/albums.js +++ b/services/database/albums.js @@ -310,4 +310,29 @@ exports.empty = function (callback) { .toArray((err, result) => { callback(result.filter(f => !f.tracks || f.tracks.length == 0)); }); -}; \ No newline at end of file +}; + +exports.randomCovers = function (count, size, callback) { + dbo + .collection("albums") + .find({ "covers.cover64": { $exists: true } }) + .project({ "covers.cover64": true }) + .toArray((err, result) => { + let res = []; + if (result.length > count) { + let i = 0; + while (i < count) { + let rnd = randomNumber(0, result.length); + res.push(result[rnd]); + i++; + } + callback(res); + } else { + callback(result); + } + }) +} + +function randomNumber(min, max) { + return Math.floor(Math.random() * (max - min) + min); +} \ No newline at end of file