queueSongs.js 5.3 KB

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