stations.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. let stationsLoaded = {};
  11. notifications.subscribe('station.locked', function(stationName) {
  12. io.to(`station.${stationName}`).emit("event:station.locked");
  13. });
  14. notifications.subscribe('station.unlocked', function(stationName) {
  15. io.to(`station.${stationName}`).emit("event:station.unlocked");
  16. });
  17. notifications.subscribe('station.pause', function(stationName) {
  18. io.to(`station.${stationName}`).emit("event:station.pause");
  19. });
  20. notifications.subscribe('station.resume', function(stationName) {
  21. io.to(`station.${stationName}`).emit("event:station.resume");
  22. });
  23. /**
  24. * Loads a station into the cache, and sets up all the related logic
  25. *
  26. * @param {String} stationId - the id of the station
  27. * @param {Function} cb - gets called when this function completes
  28. */
  29. function initializeAndReturnStation (stationId, cb) {
  30. async.waterfall([
  31. // first check the cache for the station
  32. (next) => cache.hget('stations', stationId, next),
  33. // if the cached version exist
  34. (station, next) => {
  35. if (station) return next(true, station);
  36. db.models.station.findOne({ id: stationId }, next);
  37. },
  38. // if the station exists in the DB, add it to the cache
  39. (station, next) => {
  40. if (!station) return cb('Station by that id does not exist');
  41. station = cache.schemas.station(station);
  42. cache.hset('stations', station.id, station, (err) => next(err, station));
  43. }
  44. ], (err, station) => {
  45. if (err && err !== true) return cb(err);
  46. // get notified when the next song for this station should play, so that we can notify our sockets
  47. if (stationsLoaded[stationId] === undefined) {
  48. stationsLoaded[stationId] = 1;
  49. let notification = notifications.subscribe(`stations.nextSong?id=${station.id}`, () => {
  50. // get the station from the cache
  51. cache.hget('stations', station.name, (err, station) => {
  52. if (station) {
  53. console.log(777);
  54. // notify all the sockets on this station to go to the next song
  55. io.to(`station.${stationId}`).emit("event:songs.next", {
  56. currentSong: station.currentSong,
  57. startedAt: station.startedAt,
  58. paused: station.paused,
  59. timePaused: 0
  60. });
  61. // schedule a notification to be dispatched when the next song ends
  62. notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
  63. }
  64. // the station doesn't exist anymore, unsubscribe from it
  65. else {
  66. console.log(888);
  67. notifications.remove(notification);
  68. delete stationsLoaded[stationId];
  69. }
  70. });
  71. }, true);
  72. if (!station.paused) {
  73. console.log(station);
  74. notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
  75. }
  76. }
  77. return cb(null, station);
  78. // will need to be added once station namespace thing is decided
  79. // function generatePlaylist(arr) {
  80. // station.playlist = [];
  81. // return arr.reduce((promise, id) => {
  82. // return promise.then(() => {
  83. // return globals.db.models.song.findOne({ id }, (err, song) => {
  84. // if (err) throw err;
  85. // station.playlist.push(song);
  86. // });
  87. // });
  88. // }, Promise.resolve());
  89. // }
  90. // generatePlaylist(station.playlist).then(() => {
  91. // cb(null, station);
  92. // });
  93. });
  94. }
  95. module.exports = {
  96. /**
  97. * Get a list of all the stations
  98. *
  99. * @param session
  100. * @param cb
  101. * @return {{ status: String, stations: Array }}
  102. */
  103. index: (session, cb) => {
  104. // TODO: the logic should be a bit more personalized to the users preferred genres
  105. // and it should probably just a different cache table then 'stations'
  106. cache.hgetall('stations', (err, stations) => {
  107. if (err && err !== true) {
  108. return cb({
  109. status: 'error',
  110. message: 'An error occurred while obtaining the stations'
  111. });
  112. }
  113. let arr = [];
  114. for (let prop in stations) {
  115. arr.push(stations[prop]);
  116. }
  117. cb({ status: 'success', stations: arr });
  118. });
  119. },
  120. /**
  121. * Joins the station by its id
  122. *
  123. * @param session
  124. * @param stationId - the station id
  125. * @param cb
  126. * @return {{ status: String, userCount: Integer }}
  127. */
  128. join: (session, stationId, cb) => {
  129. let ns = io.io.of("/");
  130. if (ns) {
  131. for (let id in ns.connected) {
  132. console.log(ns.connected[id]);
  133. console.log(ns.connected[id].testProp);
  134. }
  135. }
  136. initializeAndReturnStation(stationId, (err, station) => {
  137. if (err && err !== true) {
  138. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  139. }
  140. if (station) {
  141. if (session) session.stationId = stationId;
  142. //TODO Loop through all sockets, see if socket with same session exists, and if so leave all other station rooms and join this stationRoom
  143. cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
  144. if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  145. utils.socketJoinRoom(session);
  146. //TODO Emit to cache, listen on cache
  147. cb({ status: 'success', currentSong: station.currentSong, startedAt: station.startedAt, paused: station.paused, timePaused: station.timePaused });
  148. });
  149. }
  150. else {
  151. cb({ status: 'failure', message: `That station doesn't exist` });
  152. }
  153. });
  154. },
  155. /**
  156. * Skips the users current station
  157. *
  158. * @param session
  159. * @param stationId - the station id
  160. * @param cb
  161. * @return {{ status: String, skipCount: Integer }}
  162. */
  163. skip: (session, stationId, cb) => {
  164. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  165. initializeAndReturnStation(stationId, (err, station) => {
  166. if (err && err !== true) {
  167. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  168. }
  169. if (station) {
  170. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  171. session.skippedSong = true;
  172. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  173. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  174. cb({ status: 'success', skipCount });
  175. });
  176. });
  177. }
  178. else {
  179. cb({ status: 'failure', message: `That station doesn't exist` });
  180. }
  181. });
  182. },
  183. /**
  184. * Leaves the users current station
  185. *
  186. * @param session
  187. * @param cb
  188. * @return {{ status: String, userCount: Integer }}
  189. */
  190. leave: (session, cb) => {
  191. let stationId = "edm";
  192. initializeAndReturnStation(stationId, (err, station) => {
  193. if (err && err !== true) {
  194. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  195. }
  196. if (session) session.stationId = null;
  197. else if (station) {
  198. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  199. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  200. utils.socketLeaveRooms(session);
  201. cb({ status: 'success', userCount });
  202. });
  203. } else {
  204. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  205. }
  206. });
  207. },
  208. lock: (session, stationId, cb) => {
  209. //TODO Require admin
  210. initializeAndReturnStation(stationId, (err, station) => {
  211. if (err && err !== true) {
  212. return cb({ status: 'error', message: 'An error occurred while locking the station' });
  213. } else if (station) {
  214. // Add code to update Mongo and Redis
  215. cb({ status: 'success' });
  216. } else {
  217. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  218. }
  219. });
  220. },
  221. unlock: (session, stationId, cb) => {
  222. //TODO Require admin
  223. initializeAndReturnStation(stationId, (err, station) => {
  224. if (err && err !== true) {
  225. return cb({ status: 'error', message: 'An error occurred while unlocking the station' });
  226. } else if (station) {
  227. // Add code to update Mongo and Redis
  228. cb({ status: 'success' });
  229. } else {
  230. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  231. }
  232. });
  233. },
  234. };