stations.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. const stations = require('../stations');
  11. const songs = require('../songs');
  12. const hooks = require('./hooks');
  13. cache.sub('station.locked', stationId => {
  14. io.io.to(`station.${stationId}`).emit("event:stations.locked");
  15. });
  16. cache.sub('station.unlocked', stationId => {
  17. io.io.to(`station.${stationId}`).emit("event:stations.unlocked");
  18. });
  19. cache.sub('station.pause', stationId => {
  20. io.io.to(`station.${stationId}`).emit("event:stations.pause");
  21. });
  22. cache.sub('station.resume', stationId => {
  23. stations.getStation(stationId, (err, station) => {
  24. io.io.to(`station.${stationId}`).emit("event:stations.resume", {timePaused: station.timePaused});
  25. });
  26. });
  27. cache.sub('station.queueUpdate', stationId => {
  28. stations.getStation(stationId, (err, station) => {
  29. if (!err) {
  30. io.io.to(`station.${stationId}`).emit("event:queue.update", station.queue);
  31. }
  32. });
  33. });
  34. cache.sub('station.create', stationId => {
  35. stations.initializeStation(stationId, (err, station) => {
  36. //TODO Emit to homepage and admin station page
  37. if (!err) {
  38. io.io.to('home').emit("event:stations.created", station);
  39. }
  40. });
  41. });
  42. module.exports = {
  43. /**
  44. * Get a list of all the stations
  45. *
  46. * @param session
  47. * @param cb
  48. * @return {{ status: String, stations: Array }}
  49. */
  50. index: (session, cb) => {
  51. // TODO: the logic should be a bit more personalized to the users preferred genres
  52. // and it should probably just a different cache table then 'stations'
  53. cache.hgetall('stations', (err, stations) => {
  54. if (err && err !== true) {
  55. return cb({
  56. status: 'error',
  57. message: 'An error occurred while obtaining the stations'
  58. });
  59. }
  60. let arr = [];
  61. for (let prop in stations) {
  62. arr.push(stations[prop]);
  63. }
  64. cb({ status: 'success', stations: arr });
  65. });
  66. },
  67. getPlaylist: (session, stationId, cb) => {
  68. let playlist = [];
  69. stations.getStation(stationId, (err, station) => {
  70. for (let s = 1; s < station.playlist.length; s++) {
  71. songs.getSong(station.playlist[s], (err, song) => {
  72. playlist.push(song);
  73. });
  74. }
  75. });
  76. cb({ status: 'success', data: playlist })
  77. },
  78. /**
  79. * Joins the station by its id
  80. *
  81. * @param session
  82. * @param stationId - the station id
  83. * @param cb
  84. * @return {{ status: String, userCount: Integer }}
  85. */
  86. join: (session, stationId, cb) => {
  87. stations.getStation(stationId, (err, station) => {
  88. if (err && err !== true) {
  89. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  90. }
  91. if (station) {
  92. //TODO Loop through all sockets, see if socket with same session exists, and if so leave all other station rooms and join this stationRoom
  93. /*cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
  94. if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });*/
  95. utils.socketJoinRoom(session.socketId, `station.${stationId}`);
  96. utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
  97. //TODO Emit to cache, listen on cache
  98. songs.getSong(station.currentSong._id, (err, song) => {
  99. if (!err && song) {
  100. station.currentSong.likes = song.likes;
  101. station.currentSong.dislikes = song.dislikes;
  102. } else {
  103. station.currentSong.likes = -1;
  104. station.currentSong.dislikes = -1;
  105. }
  106. cb({ status: 'success', currentSong: station.currentSong, startedAt: station.startedAt, paused: station.paused, timePaused: station.timePaused });
  107. });
  108. //});
  109. }
  110. else {
  111. cb({ status: 'failure', message: `That station doesn't exist` });
  112. }
  113. });
  114. },
  115. /**
  116. * Skips the users current station
  117. *
  118. * @param session
  119. * @param stationId - the station id
  120. * @param cb
  121. * @return {{ status: String, skipCount: Integer }}
  122. */
  123. /*skip: (session, stationId, cb) => {
  124. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  125. stations.getStation(stationId, (err, station) => {
  126. if (err && err !== true) {
  127. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  128. }
  129. if (station) {
  130. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  131. session.skippedSong = true;
  132. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  133. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  134. cb({ status: 'success', skipCount });
  135. });
  136. });
  137. }
  138. else {
  139. cb({ status: 'failure', message: `That station doesn't exist` });
  140. }
  141. });
  142. },*/
  143. forceSkip: hooks.adminRequired((session, stationId, cb) => {
  144. stations.getStation(stationId, (err, station) => {
  145. if (err && err !== true) {
  146. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  147. }
  148. if (station) {
  149. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  150. notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  151. }
  152. else {
  153. cb({ status: 'failure', message: `That station doesn't exist` });
  154. }
  155. });
  156. }),
  157. /**
  158. * Leaves the users current station
  159. *
  160. * @param session
  161. * @param stationId
  162. * @param cb
  163. * @return {{ status: String, userCount: Integer }}
  164. */
  165. leave: (session, stationId, cb) => {
  166. stations.getStation(stationId, (err, station) => {
  167. if (err && err !== true) {
  168. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  169. }
  170. if (session) session.stationId = null;
  171. else if (station) {
  172. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  173. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  174. utils.socketLeaveRooms(session);
  175. cb({ status: 'success', userCount });
  176. });
  177. } else {
  178. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  179. }
  180. });
  181. },
  182. lock: hooks.adminRequired((session, stationId, cb) => {
  183. stations.getStation(stationId, (err, station) => {
  184. if (err && err !== true) {
  185. return cb({ status: 'error', message: 'An error occurred while locking the station' });
  186. } else if (station) {
  187. // Add code to update Mongo and Redis
  188. cb({ status: 'success' });
  189. } else {
  190. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  191. }
  192. });
  193. }),
  194. unlock: hooks.adminRequired((session, stationId, cb) => {
  195. stations.getStation(stationId, (err, station) => {
  196. if (err && err !== true) {
  197. return cb({ status: 'error', message: 'An error occurred while unlocking the station' });
  198. } else if (station) {
  199. // Add code to update Mongo and Redis
  200. cb({ status: 'success' });
  201. } else {
  202. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  203. }
  204. });
  205. }),
  206. pause: hooks.adminRequired((session, stationId, cb) => {
  207. stations.getStation(stationId, (err, station) => {
  208. if (err && err !== true) {
  209. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  210. } else if (station) {
  211. if (!station.paused) {
  212. station.paused = true;
  213. station.pausedAt = Date.now();
  214. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  215. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  216. stations.updateStation(stationId, () => {
  217. cache.pub('station.pause', stationId);
  218. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  219. cb({ status: 'success' });
  220. });
  221. });
  222. } else {
  223. cb({ status: 'failure', message: 'That station was already paused.' });
  224. }
  225. cb({ status: 'success' });
  226. } else {
  227. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  228. }
  229. });
  230. }),
  231. resume: hooks.adminRequired((session, stationId, cb) => {
  232. stations.getStation(stationId, (err, station) => {
  233. if (err && err !== true) {
  234. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  235. } else if (station) {
  236. if (station.paused) {
  237. station.paused = false;
  238. station.timePaused += (Date.now() - station.pausedAt);
  239. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  240. stations.updateStation(stationId, (err, station) => {
  241. cache.pub('station.resume', stationId);
  242. cb({ status: 'success' });
  243. });
  244. });
  245. } else {
  246. cb({ status: 'failure', message: 'That station is not paused.' });
  247. }
  248. } else {
  249. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  250. }
  251. });
  252. }),
  253. remove: hooks.adminRequired((session, stationId, cb) => {
  254. db.models.station.remove({ _id: stationId });
  255. cache.hdel('stations', stationId, () => {
  256. return cb({ status: 'success', message: 'Station successfully removed' });
  257. });
  258. }),
  259. create: hooks.adminRequired((session, data, cb) => {
  260. async.waterfall([
  261. (next) => {
  262. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  263. },
  264. // check the cache for the station
  265. (next) => cache.hget('stations', data._id, next),
  266. // if the cached version exist
  267. (station, next) => {
  268. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  269. db.models.station.findOne({ _id: data._id }, next);
  270. },
  271. (station, next) => {
  272. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  273. const { _id, displayName, description, genres, playlist } = data;
  274. db.models.station.create({
  275. _id,
  276. displayName,
  277. description,
  278. type: "official",
  279. playlist,
  280. genres,
  281. currentSong: stations.defaultSong
  282. }, next);
  283. }
  284. ], (err, station) => {
  285. if (err) throw err;
  286. cache.pub('station.create', data._id);
  287. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  288. });
  289. }),
  290. createCommunity: hooks.loginRequired((session, data, cb) => {
  291. async.waterfall([
  292. (next) => {
  293. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  294. },
  295. // check the cache for the station
  296. (next) => cache.hget('stations', data._id, next),
  297. // if the cached version exist
  298. (station, next) => {
  299. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  300. db.models.station.findOne({ _id: data._id }, next);
  301. },
  302. (station, next) => {
  303. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  304. const { _id, displayName, description } = data;
  305. db.models.station.create({
  306. _id,
  307. displayName,
  308. description,
  309. type: "community",
  310. queue: [],
  311. currentSong: stations.defaultSong
  312. }, next);
  313. }
  314. ], (err, station) => {
  315. if (err) throw err;
  316. cache.pub('station.create', data._id);
  317. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  318. });
  319. }),
  320. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  321. stations.getStation(stationId, (err, station) => {
  322. if (err) return cb(err);
  323. if (station.type === 'community') {
  324. let has = false;
  325. station.queue.forEach((queueSong) => {
  326. if (queueSong.songId === songId) {
  327. has = true;
  328. }
  329. });
  330. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  331. db.models.update({_id: stationId}, {$push: {queue: {_id: songId, title: "Title", duration: 100, requestedBy: userId}}}, (err) => {
  332. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  333. stations.updateStation(stationId, (err, station) => {
  334. if (err) return cb(err);
  335. cache.pub('station.queueUpdate', stationId);
  336. });
  337. });
  338. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  339. });
  340. }),
  341. removeFromQueue: hooks.adminRequired((session, stationId, songId, cb, userId) => {
  342. stations.getStation(stationId, (err, station) => {
  343. if (err) return cb(err);
  344. if (station.type === 'community') {
  345. let has = false;
  346. station.queue.forEach((queueSong) => {
  347. if (queueSong._id === songId) {
  348. has = true;
  349. }
  350. });
  351. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  352. db.models.update({_id: stationId}, {$pull: {queue: {_id: songId}}}, (err) => {
  353. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  354. stations.updateStation(stationId, (err, station) => {
  355. if (err) return cb(err);
  356. cache.pub('station.queueUpdate', stationId);
  357. });
  358. });
  359. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  360. });
  361. }),
  362. };