stations.js 13 KB

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