songs.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const db = require('../db');
  3. module.exports = {
  4. index: (session, cb) => {
  5. db.models.song.find({}, (err, songs) => {
  6. if (err) throw err;
  7. cb(songs);
  8. });
  9. },
  10. update: (session, id, song, cb) => {
  11. //TODO Require admin/login
  12. db.models.song.findOneAndUpdate({ id: id }, song, { upsert: true }, (err, updatedSong) => {
  13. if (err) throw err;
  14. cb(updatedSong);
  15. });
  16. },
  17. remove: (session, id, cb) => {
  18. //TODO Require admin/login
  19. db.models.song.find({ id: id }).remove().exec();
  20. },
  21. add: (session, id, cb) => {
  22. //TODO Require admin/login
  23. // if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
  24. const params = [
  25. 'part=snippet,contentDetails,statistics,status',
  26. `id=${encodeURIComponent(id)}`,
  27. `key=${config.get('apis.youtube.key')}`
  28. ].join('&');
  29. request(`https://www.googleapis.com/youtube/v3/videos?${params}`, (err, res, body) => {
  30. if (err) {
  31. console.error(err);
  32. return cb({ status: 'error', message: 'Failed to find song from youtube' });
  33. }
  34. body = JSON.parse(body);
  35. const newSong = new db.models.song({
  36. id: body.items[0].id,
  37. title: body.items[0].snippet.title,
  38. duration: utils.convertTime(body.items[0].contentDetails.duration),
  39. thumbnail: body.items[0].snippet.thumbnails.high.url
  40. });
  41. // save the song to the database
  42. newSong.save(err => {
  43. if (err) {
  44. console.error(err);
  45. return cb({ status: 'error', message: 'Failed to save song from youtube to the database' });
  46. }
  47. // stations.getStation(station).playlist.push(newSong);
  48. // cb({ status: 'success', data: stations.getStation(station.playlist) });
  49. });
  50. });
  51. }
  52. };