queueSongs.js 5.0 KB

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