stations.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. 'use strict';
  2. const async = require('async'),
  3. request = require('request'),
  4. config = require('config');
  5. const io = require('../io');
  6. const db = require('../db');
  7. const cache = require('../cache');
  8. const notifications = require('../notifications');
  9. const utils = require('../utils');
  10. /**
  11. * Loads a station into the cache, and sets up all the related logic
  12. *
  13. * @param {String} stationId - the id of the station
  14. * @param {Function} cb - gets called when this function completes
  15. */
  16. function initializeAndReturnStation (stationId, cb) {
  17. async.waterfall([
  18. // first check the cache for the station
  19. (next) => cache.hget('stations', stationId, next),
  20. // if the cached version exist
  21. (station, next) => {
  22. if (station) return next(true, station);
  23. db.models.station.findOne({ id: stationId }, next);
  24. },
  25. // if the station exists in the DB, add it to the cache
  26. (station, next) => {
  27. if (!station) return cb('Station by that id does not exist');
  28. station = cache.schemas.station(station);
  29. cache.hset('stations', station.id, station, (err) => next(err, station));
  30. }
  31. ], (err, station) => {
  32. if (err && err !== true) return cb(err);
  33. // get notified when the next song for this station should play, so that we can notify our sockets
  34. let notification = notifications.subscribe(`stations.nextSong?id=${station.id}`, () => {
  35. // get the station from the cache
  36. cache.hget('stations', station.id, (err, station) => {
  37. if (station) {
  38. // notify all the sockets on this station to go to the next song
  39. async.waterfall(io.sockets.clients().map((socket) => (next) => {
  40. // fetch the sockets session
  41. cache.hget('sessions', socket.sessionId, (err, session) => {
  42. if (session.stationId == station.id) {
  43. socket.emit('notification:stations.nextSong');
  44. }
  45. next();
  46. });
  47. }), (err) => {
  48. // schedule a notification to be dispatched when the next song ends
  49. notifications.schedule(`stations.nextSong?id=${station.id}`, 5000);
  50. });
  51. }
  52. // the station doesn't exist anymore, unsubscribe from it
  53. else {
  54. notifications.remove(notification);
  55. }
  56. });
  57. }, true);
  58. // will need to be added once station namespace thing is decided
  59. // function generatePlaylist(arr) {
  60. // station.playlist = [];
  61. // return arr.reduce((promise, id) => {
  62. // return promise.then(() => {
  63. // return globals.db.models.song.findOne({ id }, (err, song) => {
  64. // if (err) throw err;
  65. // station.playlist.push(song);
  66. // });
  67. // });
  68. // }, Promise.resolve());
  69. // }
  70. // generatePlaylist(station.playlist).then(() => {
  71. // cb(null, station);
  72. // });
  73. });
  74. }
  75. module.exports = {
  76. /**
  77. * Get a list of all the stations
  78. *
  79. * @param session
  80. * @param cb
  81. * @return {{ status: String, stations: Array }}
  82. */
  83. index: (session, cb) => {
  84. // TODO: the logic should be a bit more personalized to the users preferred genres
  85. // and it should probably just a different cache table then 'stations'
  86. cache.hgetall('stations', (err, stations) => {
  87. if (err && err !== true) {
  88. return cb({
  89. status: 'error',
  90. message: 'An error occurred while obtaining the stations'
  91. });
  92. }
  93. let arr = [];
  94. for (let prop in stations) {
  95. arr.push(stations[prop]);
  96. }
  97. cb({ status: 'success', stations: arr });
  98. });
  99. },
  100. /**
  101. * Joins the station by its id
  102. *
  103. * @param session
  104. * @param stationId - the station id
  105. * @param cb
  106. * @return {{ status: String, userCount: Integer }}
  107. */
  108. join: (session, stationId, cb) => {
  109. initializeAndReturnStation(stationId, (err, station) => {
  110. if (err && err !== true) {
  111. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  112. }
  113. if (station) {
  114. if (session) session.stationId = stationId;
  115. cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
  116. if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  117. cb({ status: 'success', userCount });
  118. });
  119. }
  120. else {
  121. cb({ status: 'failure', message: `That station doesn't exist` });
  122. }
  123. });
  124. },
  125. /**
  126. * Skips the users current station
  127. *
  128. * @param session
  129. * @param stationId - the station id
  130. * @param cb
  131. * @return {{ status: String, skipCount: Integer }}
  132. */
  133. skip: (session, stationId, cb) => {
  134. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  135. initializeAndReturnStation(stationId, (err, station) => {
  136. if (err && err !== true) {
  137. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  138. }
  139. if (station) {
  140. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  141. session.skippedSong = true;
  142. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  143. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  144. cb({ status: 'success', skipCount });
  145. });
  146. });
  147. }
  148. else {
  149. cb({ status: 'failure', message: `That station doesn't exist` });
  150. }
  151. });
  152. },
  153. /**
  154. * Leaves the users current station
  155. *
  156. * @param session
  157. * @param cb
  158. * @return {{ status: String, userCount: Integer }}
  159. */
  160. leave: (session, cb) => {
  161. let stationId = "edm";
  162. initializeAndReturnStation(stationId, (err, station) => {
  163. if (err && err !== true) {
  164. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  165. }
  166. if (session) session.stationId = null;
  167. else if (station) {
  168. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  169. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  170. cb({ status: 'success', userCount });
  171. });
  172. } else {
  173. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  174. }
  175. });
  176. },
  177. addSong: (session, station, song, cb) => {
  178. if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
  179. const params = [
  180. 'part=snippet,contentDetails,statistics,status',
  181. `id=${encodeURIComponent(song.id)}`,
  182. `key=${config.get('apis.youtube.key')}`
  183. ].join('&');
  184. request(`https://www.googleapis.com/youtube/v3/videos?${params}`, (err, res, body) => {
  185. if (err) {
  186. console.error(err);
  187. return cb({ status: 'error', message: 'Failed to find song from youtube' });
  188. }
  189. body = JSON.parse(body);
  190. const newSong = new db.models.song({
  191. id: body.items[0].id,
  192. title: body.items[0].snippet.title,
  193. duration: utils.convertTime(body.items[0].contentDetails.duration),
  194. thumbnail: body.items[0].snippet.thumbnails.high.url
  195. });
  196. // save the song to the database
  197. newSong.save(err => {
  198. if (err) {
  199. console.error(err);
  200. return cb({ status: 'error', message: 'Failed to save song from youtube to the database' });
  201. }
  202. // stations.getStation(station).playlist.push(newSong);
  203. // cb({ status: 'success', data: stations.getStation(station.playlist) });
  204. });
  205. });
  206. }
  207. };