stations.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. cb(null, station);
  59. });
  60. }
  61. module.exports = {
  62. /**
  63. * Get a list of all the stations
  64. *
  65. * @param session
  66. * @param cb
  67. * @return {{ status: String, stations: Array }}
  68. */
  69. index: (session, cb) => {
  70. // TODO: the logic should be a bit more personalized to the users preferred genres
  71. // and it should probably just a different cache table then 'stations'
  72. cache.hgetall('stations', (err, stations) => {
  73. console.log('all', stations)
  74. if (err && err !== true) {
  75. return cb({
  76. status: 'error',
  77. message: 'An error occurred while obtaining the stations'
  78. });
  79. }
  80. let arr = [];
  81. for (let prop in stations) {
  82. arr.push(stations[prop]);
  83. }
  84. cb({ status: 'success', stations: arr });
  85. });
  86. },
  87. /**
  88. * Joins the station by its id
  89. *
  90. * @param session
  91. * @param stationId - the station id
  92. * @param cb
  93. * @return {{ status: String, userCount: Integer }}
  94. */
  95. join: (session, stationId, cb) => {
  96. initializeAndReturnStation(stationId, (err, station) => {
  97. if (err && err !== true) {
  98. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  99. }
  100. if (station) {
  101. if (session) session.stationId = stationId;
  102. cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
  103. if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  104. cb({ status: 'success', userCount });
  105. });
  106. }
  107. else {
  108. cb({ status: 'failure', message: `That station doesn't exist` });
  109. }
  110. });
  111. },
  112. /**
  113. * Skips the users current station
  114. *
  115. * @param session
  116. * @param stationId - the station id
  117. * @param cb
  118. * @return {{ status: String, skipCount: Integer }}
  119. */
  120. skip: (session, stationId, cb) => {
  121. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  122. initializeAndReturnStation(stationId, (err, station) => {
  123. if (err && err !== true) {
  124. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  125. }
  126. if (station) {
  127. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  128. session.skippedSong = true;
  129. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  130. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  131. cb({ status: 'success', skipCount });
  132. });
  133. });
  134. }
  135. else {
  136. cb({ status: 'failure', message: `That station doesn't exist` });
  137. }
  138. });
  139. },
  140. /**
  141. * Leaves the users current station
  142. *
  143. * @param session
  144. * @param cb
  145. * @return {{ status: String, userCount: Integer }}
  146. */
  147. leave: (session, cb) => {
  148. let stationId = "edm";
  149. initializeAndReturnStation(stationId, (err, station) => {
  150. if (err && err !== true) {
  151. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  152. }
  153. if (session) session.stationId = null;
  154. else if (station) {
  155. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  156. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  157. cb({ status: 'success', userCount });
  158. });
  159. } else {
  160. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  161. }
  162. });
  163. },
  164. addSong: (session, station, song, cb) => {
  165. // if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
  166. const params = [
  167. 'part=snippet,contentDetails,statistics,status',
  168. `id=${encodeURIComponent(song.id)}`,
  169. `key=${config.get('apis.youtube.key')}`
  170. ].join('&');
  171. request(`https://www.googleapis.com/youtube/v3/videos?${params}`, (err, res, body) => {
  172. if (err) {
  173. console.error(err);
  174. return cb({ status: 'error', message: 'Failed to find song from youtube' });
  175. }
  176. body = JSON.parse(body);
  177. const newSong = new db.models.song({
  178. id: body.items[0].id,
  179. title: body.items[0].snippet.title,
  180. duration: utils.convertTime(body.items[0].contentDetails.duration),
  181. thumbnail: body.items[0].snippet.thumbnails.high.url
  182. });
  183. // save the song to the database
  184. newSong.save(err => {
  185. if (err) {
  186. console.error(err);
  187. return cb({ status: 'error', message: 'Failed to save song from youtube to the database' });
  188. }
  189. // stations.getStation(station).playlist.push(newSong);
  190. // cb({ status: 'success', data: stations.getStation(station.playlist) });
  191. });
  192. });
  193. }
  194. };