queueSongs.js 4.9 KB

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