queueSongs.js 5.2 KB

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