stations.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. stations.skipStation(stationId)();
  166. }
  167. else {
  168. cb({ status: 'failure', message: `That station doesn't exist` });
  169. }
  170. });
  171. }),
  172. /**
  173. * Leaves the users current station
  174. *
  175. * @param session
  176. * @param stationId
  177. * @param cb
  178. * @return {{ status: String, userCount: Integer }}
  179. */
  180. leave: (session, stationId, cb) => {
  181. stations.getStation(stationId, (err, station) => {
  182. if (err && err !== true) {
  183. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  184. }
  185. if (session) session.stationId = null;
  186. else if (station) {
  187. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  188. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  189. utils.socketLeaveRooms(session);
  190. cb({ status: 'success', userCount });
  191. });
  192. } else {
  193. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  194. }
  195. });
  196. },
  197. lock: hooks.adminRequired((session, stationId, cb) => {
  198. stations.getStation(stationId, (err, station) => {
  199. if (err && err !== true) {
  200. return cb({ status: 'error', message: 'An error occurred while locking the station' });
  201. } else if (station) {
  202. // Add code to update Mongo and Redis
  203. cb({ status: 'success' });
  204. } else {
  205. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  206. }
  207. });
  208. }),
  209. unlock: hooks.adminRequired((session, stationId, cb) => {
  210. stations.getStation(stationId, (err, station) => {
  211. if (err && err !== true) {
  212. return cb({ status: 'error', message: 'An error occurred while unlocking 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. pause: hooks.adminRequired((session, stationId, cb) => {
  222. stations.getStation(stationId, (err, station) => {
  223. if (err && err !== true) {
  224. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  225. } else if (station) {
  226. if (!station.paused) {
  227. station.paused = true;
  228. station.pausedAt = Date.now();
  229. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  230. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  231. stations.updateStation(stationId, () => {
  232. cache.pub('station.pause', stationId);
  233. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  234. cb({ status: 'success' });
  235. });
  236. });
  237. } else {
  238. cb({ status: 'failure', message: 'That station was already paused.' });
  239. }
  240. cb({ status: 'success' });
  241. } else {
  242. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  243. }
  244. });
  245. }),
  246. resume: hooks.adminRequired((session, stationId, cb) => {
  247. stations.getStation(stationId, (err, station) => {
  248. if (err && err !== true) {
  249. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  250. } else if (station) {
  251. if (station.paused) {
  252. station.paused = false;
  253. station.timePaused += (Date.now() - station.pausedAt);
  254. console.log("&&&", station.timePaused, station.pausedAt, Date.now(), station.timePaused);
  255. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  256. stations.updateStation(stationId, (err, station) => {
  257. cache.pub('station.resume', stationId);
  258. cb({ status: 'success' });
  259. });
  260. });
  261. } else {
  262. cb({ status: 'failure', message: 'That station is not paused.' });
  263. }
  264. } else {
  265. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  266. }
  267. });
  268. }),
  269. remove: hooks.adminRequired((session, stationId, cb) => {
  270. db.models.station.remove({ _id: stationId });
  271. cache.hdel('stations', stationId, () => {
  272. return cb({ status: 'success', message: 'Station successfully removed' });
  273. });
  274. }),
  275. create: hooks.adminRequired((session, data, cb) => {
  276. async.waterfall([
  277. (next) => {
  278. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  279. },
  280. // check the cache for the station
  281. (next) => cache.hget('stations', data._id, next),
  282. // if the cached version exist
  283. (station, next) => {
  284. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  285. db.models.station.findOne({ _id: data._id }, next);
  286. },
  287. (station, next) => {
  288. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  289. const { _id, displayName, description, genres, playlist } = data;
  290. db.models.station.create({
  291. _id,
  292. displayName,
  293. description,
  294. type: "official",
  295. playlist,
  296. genres,
  297. currentSong: stations.defaultSong
  298. }, next);
  299. }
  300. ], (err, station) => {
  301. if (err) {console.log(err); return cb({ 'status': 'failure', 'message': 'Something went wrong.'});}
  302. cache.pub('station.create', data._id);
  303. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  304. });
  305. }),
  306. createCommunity: hooks.loginRequired((session, data, cb) => {
  307. async.waterfall([
  308. (next) => {
  309. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  310. },
  311. // check the cache for the station
  312. (next) => cache.hget('stations', data._id, next),
  313. // if the cached version exist
  314. (station, next) => {
  315. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  316. db.models.station.findOne({ _id: data._id }, next);
  317. },
  318. (station, next) => {
  319. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  320. const { _id, displayName, description } = data;
  321. db.models.station.create({
  322. _id,
  323. displayName,
  324. description,
  325. type: "community",
  326. queue: [],
  327. currentSong: null
  328. }, next);
  329. }
  330. ], (err, station) => {
  331. if (err) {console.log(err); throw err;}
  332. cache.pub('station.create', data._id);
  333. return cb({ 'status': 'success', 'message': 'Successfully created station.' });
  334. });
  335. }),
  336. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  337. stations.getStation(stationId, (err, station) => {
  338. if (err) return cb(err);
  339. if (station.type === 'community') {
  340. let has = false;
  341. station.queue.forEach((queueSong) => {
  342. if (queueSong._id === songId) {
  343. has = true;
  344. }
  345. });
  346. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  347. db.models.station.update({_id: stationId}, {$push: {queue: {_id: songId, title: "Title", duration: 100, requestedBy: userId}}}, (err) => {
  348. console.log(err);
  349. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  350. stations.updateStation(stationId, (err, station) => {
  351. if (err) return cb(err);
  352. if (station.currentSong === null || station.currentSong._id === undefined) {
  353. notifications.schedule(`stations.nextSong?id=${stationId}`, 1);
  354. }
  355. cache.pub('station.queueUpdate', stationId);
  356. cb({'status': 'success', 'message': 'Added that song to the queue.'});
  357. });
  358. });
  359. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  360. });
  361. }),
  362. removeFromQueue: hooks.adminRequired((session, stationId, songId, cb, userId) => {
  363. stations.getStation(stationId, (err, station) => {
  364. if (err) return cb(err);
  365. if (station.type === 'community') {
  366. let has = false;
  367. station.queue.forEach((queueSong) => {
  368. if (queueSong._id === songId) {
  369. has = true;
  370. }
  371. });
  372. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  373. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  374. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  375. stations.updateStation(stationId, (err, station) => {
  376. if (err) return cb(err);
  377. cache.pub('station.queueUpdate', stationId);
  378. });
  379. });
  380. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  381. });
  382. }),
  383. };