queueSongs.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. 'use strict';
  2. const db = require('../db');
  3. const utils = require('../utils');
  4. const notifications = require('../notifications');
  5. const cache = require('../cache');
  6. const async = require('async');
  7. const config = require('config');
  8. const request = require('request');
  9. notifications.subscribe('queue.newSong', songId => {
  10. io.to('admin.queue').emit('event:song.new', { songId });
  11. });
  12. notifications.subscribe('queue.removedSong', songId => {
  13. io.to('admin.queue').emit('event:song.removed', { songId });
  14. });
  15. notifications.subscribe('queue.updatedSong', songId => {
  16. //TODO Retrieve new Song object
  17. io.to('admin.queue').emit('event:song.updated', { songId });
  18. });
  19. module.exports = {
  20. index: (session, cb) => {
  21. //TODO Require admin/login
  22. db.models.queueSong.find({}, (err, songs) => {
  23. if (err) throw err;
  24. cb(songs);
  25. });
  26. },
  27. update: (session, _id, updatedSong, cb) => {
  28. //TODO Require admin/login
  29. //TODO Check if id and updatedSong is valid
  30. db.models.queueSong.findOne({ _id }, (err, currentSong) => {
  31. if (err) throw err;
  32. // TODO Check if new id, if any, is already in use in queue or on rotation
  33. let updated = false;
  34. for (let prop in updatedSong) if (updatedSong[prop] !== currentSong[prop]) currentSong[prop] = updatedSong[prop]; updated = true;
  35. if (!updated) return cb({ status: 'error', message: 'No properties changed' });
  36. else {
  37. currentSong.save(err => {
  38. if (err) throw err;
  39. return cb({ status: 'success', message: 'Successfully updated the queued song' });
  40. });
  41. }
  42. });
  43. },
  44. remove: (session, _id, cb) => {
  45. // TODO Require admin/login
  46. db.models.queueSong.find({ _id }).remove().exec();
  47. return cb({ status: 'success', message: 'Song was removed successfully' });
  48. },
  49. add: (session, id, cb) => {
  50. //TODO Require login
  51. //TODO Check if id is valid
  52. //TODO Check if id is already in queue/rotation
  53. // if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
  54. let requestedAt = Date.now();
  55. async.waterfall([
  56. // Get YouTube data from id
  57. (next) => {
  58. const youtubeParams = [
  59. 'part=snippet,contentDetails,statistics,status',
  60. `id=${encodeURIComponent(id)}`,
  61. `key=${config.get('apis.youtube.key')}`
  62. ].join('&');
  63. request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  64. if (err) {
  65. console.error(err);
  66. return next('Failed to find song from YouTube');
  67. }
  68. body = JSON.parse(body);
  69. //TODO Clean up duration converter
  70. let dur = body.items[0].contentDetails.duration;
  71. dur = dur.replace('PT', '');
  72. let durInSec = 0;
  73. dur = dur.replace(/([\d]*)H/, function(v, v2) {
  74. v2 = Number(v2);
  75. durInSec = (v2 * 60 * 60)
  76. return '';
  77. });
  78. dur = dur.replace(/([\d]*)M/, function(v, v2) {
  79. v2 = Number(v2);
  80. durInSec = (v2 * 60)
  81. return '';
  82. });
  83. dur = dur.replace(/([\d]*)S/, function(v, v2) {
  84. v2 = Number(v2);
  85. durInSec += v2;
  86. return '';
  87. });
  88. let newSong = {
  89. _id: body.items[0].id,
  90. title: body.items[0].snippet.title,
  91. artists: [],
  92. genres: [],
  93. duration: durInSec,
  94. skipDuration: 0,
  95. thumbnail: 'default.png',
  96. explicit: false,
  97. requestedBy: 'temp',
  98. requestedAt: requestedAt
  99. };
  100. next(null, newSong);
  101. });
  102. },
  103. (newSong, next) => {
  104. const spotifyParams = [
  105. `q=${encodeURIComponent(newSong.title)}`,
  106. `type=track`
  107. ].join('&');
  108. request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
  109. if (err) {
  110. console.error(err);
  111. return next('Failed to find song from Spotify');
  112. }
  113. body = JSON.parse(body);
  114. durationArtistLoop:
  115. for (let i in body) {
  116. let items = body[i].items;
  117. for (let j in items) {
  118. let item = items[j];
  119. let hasArtist = false;
  120. for (let k = 0; k < item.artists.length; k++) {
  121. let artist = item.artists[k];
  122. if (newSong.title.indexOf(artist.name) !== -1) {
  123. hasArtist = true;
  124. }
  125. }
  126. if (hasArtist && newSong.title.indexOf(item.name) !== -1) {
  127. newSong.duration = item.duration_ms / 1000;
  128. newSong.artists = item.artists.map(artist => {
  129. return artist.name;
  130. });
  131. newSong.title = item.name;
  132. newSong.explicit = item.explicit;
  133. newSong.thumbnail = item.album.images[1].url;
  134. break durationArtistLoop;
  135. }
  136. }
  137. }
  138. next(null, newSong);
  139. });
  140. },
  141. (newSong, next) => {
  142. const song = new db.models.queueSong(newSong);
  143. // check if song already exists
  144. song.save(err => {
  145. if (err) {
  146. console.error(err);
  147. return next('Failed to add song to database');
  148. }
  149. //stations.getStation(station).playlist.push(newSong);
  150. next(null, newSong);
  151. });
  152. }
  153. ],
  154. (err, newSong) => {
  155. if (err) return cb({ status: 'error', message: err });
  156. cache.pub('queue.newSong', newSong._id);
  157. return cb({ status: 'success', message: 'Successfully added that song to the queue' });
  158. });
  159. }
  160. };