stations.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. data: {
  108. type: station.type,
  109. currentSong: station.currentSong,
  110. startedAt: station.startedAt,
  111. paused: station.paused,
  112. timePaused: station.timePaused
  113. }
  114. });
  115. });
  116. } else {
  117. cb({
  118. status: 'success',
  119. data: {
  120. type: station.type,
  121. currentSong: null,
  122. startedAt: station.startedAt,
  123. paused: station.paused,
  124. timePaused: station.timePaused
  125. }
  126. });
  127. }
  128. //});
  129. }
  130. else {
  131. cb({ status: 'failure', message: `That station doesn't exist` });
  132. }
  133. });
  134. },
  135. /**
  136. * Skips the users current station
  137. *
  138. * @param session
  139. * @param stationId - the station id
  140. * @param cb
  141. * @return {{ status: String, skipCount: Integer }}
  142. */
  143. /*skip: (session, stationId, cb) => {
  144. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  145. stations.getStation(stationId, (err, station) => {
  146. if (err && err !== true) {
  147. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  148. }
  149. if (station) {
  150. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  151. session.skippedSong = true;
  152. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  153. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  154. cb({ status: 'success', skipCount });
  155. });
  156. });
  157. }
  158. else {
  159. cb({ status: 'failure', message: `That station doesn't exist` });
  160. }
  161. });
  162. },*/
  163. forceSkip: hooks.adminRequired((session, stationId, cb) => {
  164. stations.getStation(stationId, (err, station) => {
  165. if (err && err !== true) {
  166. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  167. }
  168. if (station) {
  169. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  170. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  171. stations.skipStation(stationId)();
  172. }
  173. else {
  174. cb({ status: 'failure', message: `That station doesn't exist` });
  175. }
  176. });
  177. }),
  178. /**
  179. * Leaves the users current station
  180. *
  181. * @param session
  182. * @param stationId
  183. * @param cb
  184. * @return {{ status: String, userCount: Integer }}
  185. */
  186. leave: (session, stationId, cb) => {
  187. stations.getStation(stationId, (err, station) => {
  188. if (err && err !== true) {
  189. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  190. }
  191. if (session) session.stationId = null;
  192. else if (station) {
  193. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  194. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  195. utils.socketLeaveRooms(session);
  196. cb({ status: 'success', userCount });
  197. });
  198. } else {
  199. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  200. }
  201. });
  202. },
  203. lock: hooks.adminRequired((session, stationId, cb) => {
  204. stations.getStation(stationId, (err, station) => {
  205. if (err && err !== true) {
  206. return cb({ status: 'error', message: 'An error occurred while locking the station' });
  207. } else if (station) {
  208. // Add code to update Mongo and Redis
  209. cb({ status: 'success' });
  210. } else {
  211. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  212. }
  213. });
  214. }),
  215. unlock: hooks.adminRequired((session, stationId, cb) => {
  216. stations.getStation(stationId, (err, station) => {
  217. if (err && err !== true) {
  218. return cb({ status: 'error', message: 'An error occurred while unlocking the station' });
  219. } else if (station) {
  220. // Add code to update Mongo and Redis
  221. cb({ status: 'success' });
  222. } else {
  223. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  224. }
  225. });
  226. }),
  227. pause: hooks.adminRequired((session, stationId, cb) => {
  228. stations.getStation(stationId, (err, station) => {
  229. if (err && err !== true) {
  230. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  231. } else if (station) {
  232. if (!station.paused) {
  233. station.paused = true;
  234. station.pausedAt = Date.now();
  235. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  236. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  237. stations.updateStation(stationId, () => {
  238. cache.pub('station.pause', stationId);
  239. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  240. cb({ status: 'success' });
  241. });
  242. });
  243. } else {
  244. cb({ status: 'failure', message: 'That station was already paused.' });
  245. }
  246. cb({ status: 'success' });
  247. } else {
  248. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  249. }
  250. });
  251. }),
  252. resume: hooks.adminRequired((session, stationId, cb) => {
  253. stations.getStation(stationId, (err, station) => {
  254. if (err && err !== true) {
  255. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  256. } else if (station) {
  257. if (station.paused) {
  258. station.paused = false;
  259. station.timePaused += (Date.now() - station.pausedAt);
  260. console.log("&&&", station.timePaused, station.pausedAt, Date.now(), station.timePaused);
  261. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  262. stations.updateStation(stationId, (err, station) => {
  263. cache.pub('station.resume', stationId);
  264. cb({ status: 'success' });
  265. });
  266. });
  267. } else {
  268. cb({ status: 'failure', message: 'That station is not paused.' });
  269. }
  270. } else {
  271. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  272. }
  273. });
  274. }),
  275. remove: hooks.adminRequired((session, stationId, cb) => {
  276. db.models.station.remove({ _id: stationId });
  277. cache.hdel('stations', stationId, () => {
  278. return cb({ status: 'success', message: 'Station successfully removed' });
  279. });
  280. }),
  281. create: hooks.adminRequired((session, data, cb) => {
  282. async.waterfall([
  283. (next) => {
  284. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  285. },
  286. // check the cache for the station
  287. (next) => cache.hget('stations', data._id, next),
  288. // if the cached version exist
  289. (station, next) => {
  290. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  291. db.models.station.findOne({ _id: data._id }, next);
  292. },
  293. (station, next) => {
  294. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  295. const { _id, displayName, description, genres, playlist } = data;
  296. db.models.station.create({
  297. _id,
  298. displayName,
  299. description,
  300. type: "official",
  301. playlist,
  302. genres,
  303. currentSong: stations.defaultSong
  304. }, next);
  305. }
  306. ], (err, station) => {
  307. if (err) {console.log(err); return cb({ 'status': 'failure', 'message': 'Something went wrong.'});}
  308. cache.pub('station.create', data._id);
  309. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  310. });
  311. }),
  312. createCommunity: hooks.loginRequired((session, data, cb) => {
  313. async.waterfall([
  314. (next) => {
  315. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  316. },
  317. // check the cache for the station
  318. (next) => cache.hget('stations', data._id, next),
  319. // if the cached version exist
  320. (station, next) => {
  321. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  322. db.models.station.findOne({ _id: data._id }, next);
  323. },
  324. (station, next) => {
  325. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  326. const { _id, displayName, description } = data;
  327. db.models.station.create({
  328. _id,
  329. displayName,
  330. description,
  331. type: "community",
  332. queue: [],
  333. currentSong: null
  334. }, next);
  335. }
  336. ], (err, station) => {
  337. if (err) {console.log(err); throw err;}
  338. cache.pub('station.create', data._id);
  339. return cb({ 'status': 'success', 'message': 'Successfully created station.' });
  340. });
  341. }),
  342. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  343. stations.getStation(stationId, (err, station) => {
  344. if (err) return cb(err);
  345. if (station.type === 'community') {
  346. let has = false;
  347. station.queue.forEach((queueSong) => {
  348. if (queueSong._id === songId) {
  349. has = true;
  350. }
  351. });
  352. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  353. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing.'});
  354. songs.getSong(songId, (err, song) => {
  355. if (err) {
  356. utils.getSongFromYouTube(songId, (song) => {
  357. song.artists = [];
  358. song.skipDuration = 0;
  359. song.likes = -1;
  360. song.dislikes = -1;
  361. song.thumbnail = "empty";
  362. song.explicit = false;
  363. cont(song);
  364. });
  365. } else cont(song);
  366. function cont(song) {
  367. db.models.station.update({_id: stationId}, {$push: {queue: song}}, (err) => {
  368. console.log(err);
  369. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  370. stations.updateStation(stationId, (err, station) => {
  371. if (err) return cb(err);
  372. cache.pub('station.queueUpdate', stationId);
  373. cb({'status': 'success', 'message': 'Added that song to the queue.'});
  374. });
  375. });
  376. }
  377. });
  378. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  379. });
  380. }),
  381. removeFromQueue: hooks.adminRequired((session, stationId, songId, cb, userId) => {
  382. stations.getStation(stationId, (err, station) => {
  383. if (err) return cb(err);
  384. if (station.type === 'community') {
  385. let has = false;
  386. station.queue.forEach((queueSong) => {
  387. if (queueSong._id === songId) {
  388. has = true;
  389. }
  390. });
  391. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  392. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  393. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  394. stations.updateStation(stationId, (err, station) => {
  395. if (err) return cb(err);
  396. cache.pub('station.queueUpdate', stationId);
  397. });
  398. });
  399. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  400. });
  401. }),
  402. getQueue: hooks.adminRequired((session, stationId, cb) => {
  403. stations.getStation(stationId, (err, station) => {
  404. if (err) return cb(err);
  405. if (!station) return cb({'status': 'failure', 'message': 'Station not found.'});
  406. if (station.type === 'community') {
  407. cb({'status': 'success', queue: station.queue});
  408. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  409. });
  410. }),
  411. };