stations.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. io.to(`station.${stationId}`).emit("event:songs.next", {
  40. currentSong: station.currentSong,
  41. startedAt: station.startedAt,
  42. paused: station.paused,
  43. timePaused: 0
  44. });
  45. // schedule a notification to be dispatched when the next song ends
  46. notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
  47. }
  48. // the station doesn't exist anymore, unsubscribe from it
  49. else {
  50. notifications.remove(notification);
  51. }
  52. });
  53. }, true);
  54. // will need to be added once station namespace thing is decided
  55. // function generatePlaylist(arr) {
  56. // station.playlist = [];
  57. // return arr.reduce((promise, id) => {
  58. // return promise.then(() => {
  59. // return globals.db.models.song.findOne({ id }, (err, song) => {
  60. // if (err) throw err;
  61. // station.playlist.push(song);
  62. // });
  63. // });
  64. // }, Promise.resolve());
  65. // }
  66. // generatePlaylist(station.playlist).then(() => {
  67. // cb(null, station);
  68. // });
  69. });
  70. }
  71. module.exports = {
  72. /**
  73. * Get a list of all the stations
  74. *
  75. * @param session
  76. * @param cb
  77. * @return {{ status: String, stations: Array }}
  78. */
  79. index: (session, cb) => {
  80. // TODO: the logic should be a bit more personalized to the users preferred genres
  81. // and it should probably just a different cache table then 'stations'
  82. cache.hgetall('stations', (err, stations) => {
  83. if (err && err !== true) {
  84. return cb({
  85. status: 'error',
  86. message: 'An error occurred while obtaining the stations'
  87. });
  88. }
  89. let arr = [];
  90. for (let prop in stations) {
  91. arr.push(stations[prop]);
  92. }
  93. cb({ status: 'success', stations: arr });
  94. });
  95. },
  96. /**
  97. * Joins the station by its id
  98. *
  99. * @param session
  100. * @param stationId - the station id
  101. * @param cb
  102. * @return {{ status: String, userCount: Integer }}
  103. */
  104. join: (session, stationId, cb) => {
  105. io.io.to("SomeRoom").emit("SomeRoomMessage");
  106. io.io.emit("SomeRoomMessage");
  107. initializeAndReturnStation(stationId, (err, station) => {
  108. if (err && err !== true) {
  109. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  110. }
  111. if (station) {
  112. if (session) session.stationId = stationId;
  113. //TODO Loop through all sockets, see if socket with same sessionid exists, and if so leave all other station rooms and join this stationRoom
  114. cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
  115. if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  116. utils.socketJoinRoom(sessionId);
  117. //TODO Emit to cache, listen on cache
  118. cb({ status: 'success', userCount });
  119. });
  120. }
  121. else {
  122. cb({ status: 'failure', message: `That station doesn't exist` });
  123. }
  124. });
  125. },
  126. /**
  127. * Skips the users current station
  128. *
  129. * @param session
  130. * @param stationId - the station id
  131. * @param cb
  132. * @return {{ status: String, skipCount: Integer }}
  133. */
  134. skip: (session, stationId, cb) => {
  135. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  136. initializeAndReturnStation(stationId, (err, station) => {
  137. if (err && err !== true) {
  138. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  139. }
  140. if (station) {
  141. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  142. session.skippedSong = true;
  143. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  144. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  145. cb({ status: 'success', skipCount });
  146. });
  147. });
  148. }
  149. else {
  150. cb({ status: 'failure', message: `That station doesn't exist` });
  151. }
  152. });
  153. },
  154. /**
  155. * Leaves the users current station
  156. *
  157. * @param session
  158. * @param cb
  159. * @return {{ status: String, userCount: Integer }}
  160. */
  161. leave: (session, cb) => {
  162. let stationId = "edm";
  163. initializeAndReturnStation(stationId, (err, station) => {
  164. if (err && err !== true) {
  165. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  166. }
  167. if (session) session.stationId = null;
  168. else if (station) {
  169. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  170. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  171. utils.socketLeaveRooms(sessionId);
  172. cb({ status: 'success', userCount });
  173. });
  174. } else {
  175. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  176. }
  177. });
  178. },
  179. addSong: (session, station, song, cb) => {
  180. if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
  181. const params = [
  182. 'part=snippet,contentDetails,statistics,status',
  183. `id=${encodeURIComponent(song.id)}`,
  184. `key=${config.get('apis.youtube.key')}`
  185. ].join('&');
  186. request(`https://www.googleapis.com/youtube/v3/videos?${params}`, (err, res, body) => {
  187. if (err) {
  188. console.error(err);
  189. return cb({ status: 'error', message: 'Failed to find song from youtube' });
  190. }
  191. body = JSON.parse(body);
  192. const newSong = new db.models.song({
  193. id: body.items[0].id,
  194. title: body.items[0].snippet.title,
  195. duration: utils.convertTime(body.items[0].contentDetails.duration),
  196. thumbnail: body.items[0].snippet.thumbnails.high.url
  197. });
  198. // save the song to the database
  199. newSong.save(err => {
  200. if (err) {
  201. console.error(err);
  202. return cb({ status: 'error', message: 'Failed to save song from youtube to the database' });
  203. }
  204. //TODO Emit to cache, and listen on cache
  205. // stations.getStation(station).playlist.push(newSong);
  206. // cb({ status: 'success', data: stations.getStation(station.playlist) });
  207. });
  208. });
  209. }
  210. };