stations.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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.pause', stationId => {
  14. utils.emitToRoom(`station.${stationId}`, "event:stations.pause");
  15. });
  16. cache.sub('station.resume', stationId => {
  17. stations.getStation(stationId, (err, station) => {
  18. utils.emitToRoom(`station.${stationId}`, "event:stations.resume", {timePaused: station.timePaused});
  19. });
  20. });
  21. cache.sub('station.queueUpdate', stationId => {
  22. stations.getStation(stationId, (err, station) => {
  23. if (!err) {
  24. utils.emitToRoom(`station.${stationId}`, "event:queue.update", station.queue);
  25. }
  26. });
  27. });
  28. cache.sub('station.voteSkipSong', stationId => {
  29. utils.emitToRoom(`station.${stationId}`, "event:song.voteSkipSong");
  30. });
  31. cache.sub('station.create', stationId => {
  32. stations.initializeStation(stationId, (err, station) => {
  33. console.log("*************", err, station);
  34. //TODO Emit to admin station page
  35. // TODO If community, check if on whitelist
  36. console.log("*************", station.privacy);
  37. if (station.privacy === 'public') utils.emitToRoom('home', "event:stations.created", station);
  38. else {
  39. let sockets = utils.getRoomSockets('home');
  40. console.log("*************", sockets.length);
  41. for (let socketId in sockets) {
  42. let socket = sockets[socketId];
  43. let session = sockets[socketId].session;
  44. console.log("*************", session);
  45. if (session.sessionId) {
  46. cache.hget('sessions', session.sessionId, (err, session) => {
  47. console.log("*************", err, session);
  48. if (!err && session) {
  49. console.log("*************");
  50. db.models.user.findOne({_id: session.userId}, (err, user) => {
  51. console.log("*************", err, user.role, station.type, station.owner, session.userId);
  52. if (user.role === 'admin') socket.emit("event:stations.created", station);
  53. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:stations.created", station);
  54. });
  55. }
  56. });
  57. }
  58. }
  59. }
  60. });
  61. });
  62. module.exports = {
  63. /**
  64. * Get a list of all the stations
  65. *
  66. * @param session
  67. * @param cb
  68. * @return {{ status: String, stations: Array }}
  69. */
  70. index: (session, cb) => {
  71. cache.hgetall('stations', (err, stations) => {
  72. if (err && err !== true) {
  73. return cb({
  74. status: 'error',
  75. message: 'An error occurred while obtaining the stations'
  76. });
  77. }
  78. let arr = [];
  79. let done = 0;
  80. for (let prop in stations) {
  81. // TODO If community, check if on whitelist
  82. let station = stations[prop];
  83. console.log(station)
  84. if (station.privacy === 'public') add(true, station);
  85. else if (!session.sessionId) add(false);
  86. else {
  87. cache.hget('sessions', session.sessionId, (err, session) => {
  88. if (err || !session) {
  89. add(false);
  90. } else {
  91. db.models.user.findOne({_id: session.userId}, (err, user) => {
  92. if (err || !user) add(false);
  93. else if (user.role === 'admin') add(true, station);
  94. else if (station.type === 'official') add(false);
  95. else if (station.owner === session.userId) add(true, station);
  96. else add(false);
  97. });
  98. }
  99. });
  100. }
  101. }
  102. function add(add, station) {
  103. console.log("ADD!", add, station);
  104. if (add) arr.push(station);
  105. done++;
  106. if (done === Object.keys(stations).length) {
  107. console.log("DONE!", done);
  108. cb({ status: 'success', stations: arr });
  109. }
  110. }
  111. });
  112. },
  113. getPlaylist: (session, stationId, cb) => {
  114. let playlist = [];
  115. stations.getStation(stationId, (err, station) => {
  116. for (let s = 1; s < station.playlist.length; s++) {
  117. songs.getSong(station.playlist[s], (err, song) => {
  118. playlist.push(song);
  119. });
  120. }
  121. });
  122. cb({ status: 'success', data: playlist })
  123. },
  124. /**
  125. * Joins the station by its id
  126. *
  127. * @param session
  128. * @param stationId - the station id
  129. * @param cb
  130. * @return {{ status: String, userCount: Integer }}
  131. */
  132. join: (session, stationId, cb) => {
  133. stations.getStation(stationId, (err, station) => {
  134. if (err && err !== true) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  135. if (station) {
  136. if (station.privacy !== 'private') {
  137. func();
  138. } else {
  139. // TODO If community, check if on whitelist
  140. if (!session.userId) return cb({ status: 'error', message: 'An error occurred while joining the station1' });
  141. db.models.user.findOne({_id: session.userId}, (err, user) => {
  142. if (err || !user) return cb({ status: 'error', message: 'An error occurred while joining the station2' });
  143. if (user.role === 'admin') return func();
  144. if (station.type === 'official') return cb({ status: 'error', message: 'An error occurred while joining the station3' });
  145. if (station.owner === session.userId) return func();
  146. return cb({ status: 'error', message: 'An error occurred while joining the station4' });
  147. });
  148. }
  149. function func() {
  150. utils.socketJoinRoom(session.socketId, `station.${stationId}`);
  151. if (station.currentSong) {
  152. utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
  153. //TODO Emit to cache, listen on cache
  154. songs.getSong(station.currentSong._id, (err, song) => {
  155. if (!err && song) {
  156. station.currentSong.likes = song.likes;
  157. station.currentSong.dislikes = song.dislikes;
  158. } else {
  159. station.currentSong.likes = -1;
  160. station.currentSong.dislikes = -1;
  161. }
  162. station.currentSong.skipVotes = station.currentSong.skipVotes.length;
  163. cb({
  164. status: 'success',
  165. data: {
  166. type: station.type,
  167. currentSong: station.currentSong,
  168. startedAt: station.startedAt,
  169. paused: station.paused,
  170. timePaused: station.timePaused,
  171. description: station.description,
  172. displayName: station.displayName,
  173. privacy: station.privacy,
  174. partyMode: station.partyMode,
  175. owner: station.owner,
  176. privatePlaylist: station.privatePlaylist
  177. }
  178. });
  179. });
  180. } else {
  181. cb({
  182. status: 'success',
  183. data: {
  184. type: station.type,
  185. currentSong: null,
  186. startedAt: station.startedAt,
  187. paused: station.paused,
  188. timePaused: station.timePaused,
  189. description: station.description,
  190. displayName: station.displayName,
  191. privacy: station.privacy,
  192. partyMode: station.partyMode,
  193. owner: station.owner
  194. }
  195. });
  196. }
  197. }
  198. } else {
  199. cb({ status: 'failure', message: `That station doesn't exist` });
  200. }
  201. });
  202. },
  203. /**
  204. * Skips the users current station
  205. *
  206. * @param session
  207. * @param stationId - the station id
  208. * @param cb
  209. */
  210. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  211. stations.getStation(stationId, (err, station) => {
  212. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  213. if (!station.currentSong) return cb({ status: 'failure', message: 'There is currently no song to skip.' });
  214. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return cb({ status: 'failure', message: 'You have already voted to skip this song.' });
  215. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, (err) => {
  216. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  217. stations.updateStation(stationId, (err, station) => {
  218. cache.pub('station.voteSkipSong', stationId);
  219. if (station.currentSong && station.currentSong.skipVotes.length >= 1) {
  220. stations.skipStation(stationId)();
  221. }
  222. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  223. })
  224. });
  225. });
  226. }),
  227. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  228. stations.getStation(stationId, (err, station) => {
  229. if (err && err !== true) {
  230. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  231. }
  232. if (station) {
  233. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  234. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  235. stations.skipStation(stationId)();
  236. }
  237. else {
  238. cb({ status: 'failure', message: `That station doesn't exist` });
  239. }
  240. });
  241. }),
  242. /**
  243. * Leaves the users current station
  244. *
  245. * @param session
  246. * @param stationId
  247. * @param cb
  248. * @return {{ status: String, userCount: Integer }}
  249. */
  250. leave: (session, stationId, cb) => {
  251. stations.getStation(stationId, (err, station) => {
  252. if (err && err !== true) {
  253. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  254. }
  255. if (session) session.stationId = null;
  256. else if (station) {
  257. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  258. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  259. utils.socketLeaveRooms(session);
  260. cb({ status: 'success', userCount });
  261. });
  262. } else {
  263. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  264. }
  265. });
  266. },
  267. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  268. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, (err) => {
  269. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  270. stations.updateStation(stationId, () => {
  271. //TODO Pub/sub for displayName change
  272. cb({ status: 'success', message: 'Successfully updated the display name.' });
  273. })
  274. });
  275. }),
  276. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  277. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, (err) => {
  278. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  279. stations.updateStation(stationId, () => {
  280. //TODO Pub/sub for description change
  281. cb({ status: 'success', message: 'Successfully updated the description.' });
  282. })
  283. });
  284. }),
  285. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  286. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, (err) => {
  287. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  288. stations.updateStation(stationId, () => {
  289. //TODO Pub/sub for privacy change
  290. cb({ status: 'success', message: 'Successfully updated the privacy.' });
  291. })
  292. });
  293. }),
  294. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  295. stations.getStation(stationId, (err, station) => {
  296. if (err) return cb({ status: 'failure', message: err });
  297. if (station.partyMode === newPartyMode) return cb({ status: 'failure', message: 'The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.') });
  298. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, (err) => {
  299. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  300. stations.updateStation(stationId, () => {
  301. //TODO Pub/sub for privacy change
  302. stations.skipStation(stationId)();
  303. cb({ status: 'success', message: 'Successfully updated the party mode.' });
  304. })
  305. });
  306. });
  307. }),
  308. pause: hooks.ownerRequired((session, stationId, cb) => {
  309. stations.getStation(stationId, (err, station) => {
  310. if (err && err !== true) {
  311. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  312. } else if (station) {
  313. if (!station.paused) {
  314. station.paused = true;
  315. station.pausedAt = Date.now();
  316. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  317. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  318. stations.updateStation(stationId, () => {
  319. cache.pub('station.pause', stationId);
  320. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  321. cb({ status: 'success' });
  322. });
  323. });
  324. } else {
  325. cb({ status: 'failure', message: 'That station was already paused.' });
  326. }
  327. cb({ status: 'success' });
  328. } else {
  329. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  330. }
  331. });
  332. }),
  333. resume: hooks.ownerRequired((session, stationId, cb) => {
  334. stations.getStation(stationId, (err, station) => {
  335. if (err && err !== true) {
  336. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  337. } else if (station) {
  338. if (station.paused) {
  339. station.paused = false;
  340. station.timePaused += (Date.now() - station.pausedAt);
  341. console.log("&&&", station.timePaused, station.pausedAt, Date.now(), station.timePaused);
  342. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  343. stations.updateStation(stationId, (err, station) => {
  344. cache.pub('station.resume', stationId);
  345. cb({ status: 'success' });
  346. });
  347. });
  348. } else {
  349. cb({ status: 'failure', message: 'That station is not paused.' });
  350. }
  351. } else {
  352. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  353. }
  354. });
  355. }),
  356. remove: hooks.ownerRequired((session, stationId, cb) => {
  357. db.models.station.remove({ _id: stationId }, (err) => {
  358. console.log(err, stationId);
  359. if (err) return cb({status: 'failure', message: 'Something went wrong when deleting that station.'});
  360. cache.hdel('stations', stationId, () => {
  361. return cb({ status: 'success', message: 'Station successfully removed' });
  362. });
  363. });
  364. }),
  365. create: hooks.loginRequired((session, data, cb) => {
  366. data._id = data._id.toLowerCase();
  367. async.waterfall([
  368. (next) => {
  369. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  370. },
  371. (next) => {
  372. db.models.station.findOne({ $or: [{_id: data._id}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  373. },
  374. (station, next) => {
  375. if (station) return next({ 'status': 'failure', 'message': 'A station with that name or display name already exists' });
  376. const { _id, displayName, description, genres, playlist, type } = data;
  377. cache.hget('sessions', session.sessionId, (err, session) => {
  378. if (type == 'official') {
  379. db.models.user.findOne({_id: session.userId}, (err, user) => {
  380. if (err) return next({ 'status': 'failure', 'message': 'Something went wrong when getting your user info.' });
  381. if (!user) return next({ 'status': 'failure', 'message': 'User not found.' });
  382. if (user.role !== 'admin') return next({ 'status': 'failure', 'message': 'Admin required.' });
  383. db.models.station.create({
  384. _id,
  385. displayName,
  386. description,
  387. type,
  388. privacy: 'private',
  389. playlist,
  390. genres,
  391. currentSong: stations.defaultSong
  392. }, next);
  393. });
  394. } else if (type == 'community') {
  395. db.models.station.create({
  396. _id,
  397. displayName,
  398. description,
  399. type,
  400. privacy: 'private',
  401. owner: session.userId,
  402. queue: [],
  403. currentSong: null
  404. }, next);
  405. }
  406. });
  407. }
  408. ], (err, station) => {
  409. if (err) {
  410. console.error(err);
  411. return cb({ 'status': 'failure', 'message': 'Something went wrong.'});
  412. }
  413. cache.pub('station.create', data._id);
  414. cb({ 'status': 'success', 'message': 'Successfully created station.' });
  415. });
  416. }),
  417. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  418. stations.getStation(stationId, (err, station) => {
  419. if (err) return cb(err);
  420. if (station.type === 'community') {
  421. let has = false;
  422. station.queue.forEach((queueSong) => {
  423. if (queueSong._id === songId) {
  424. has = true;
  425. }
  426. });
  427. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  428. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing.'});
  429. songs.getSong(songId, (err, song) => {
  430. if (err) {
  431. utils.getSongFromYouTube(songId, (song) => {
  432. song.artists = [];
  433. song.skipDuration = 0;
  434. song.likes = -1;
  435. song.dislikes = -1;
  436. song.thumbnail = "empty";
  437. song.explicit = false;
  438. cont(song);
  439. });
  440. } else cont(song);
  441. function cont(song) {
  442. db.models.station.update({_id: stationId}, {$push: {queue: song}}, (err) => {
  443. console.log(err);
  444. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  445. stations.updateStation(stationId, (err, station) => {
  446. if (err) return cb(err);
  447. cache.pub('station.queueUpdate', stationId);
  448. cb({'status': 'success', 'message': 'Added that song to the queue.'});
  449. });
  450. });
  451. }
  452. });
  453. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  454. });
  455. }),
  456. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  457. stations.getStation(stationId, (err, station) => {
  458. if (err) return cb(err);
  459. if (station.type === 'community') {
  460. let has = false;
  461. station.queue.forEach((queueSong) => {
  462. if (queueSong._id === songId) {
  463. has = true;
  464. }
  465. });
  466. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  467. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  468. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  469. stations.updateStation(stationId, (err, station) => {
  470. if (err) return cb(err);
  471. cache.pub('station.queueUpdate', stationId);
  472. });
  473. });
  474. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  475. });
  476. }),
  477. getQueue: hooks.adminRequired((session, stationId, cb) => {
  478. stations.getStation(stationId, (err, station) => {
  479. if (err) return cb(err);
  480. if (!station) return cb({'status': 'failure', 'message': 'Station not found.'});
  481. if (station.type === 'community') {
  482. cb({'status': 'success', queue: station.queue});
  483. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  484. });
  485. }),
  486. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  487. stations.getStation(stationId, (err, station) => {
  488. if (err) return cb(err);
  489. if (station.type === 'community') {
  490. if (station.privatePlaylist === playlistId) return cb({'status': 'failure', 'message': 'That playlist is already selected.'});
  491. db.models.playlist.findOne({_id: playlistId}, (err, playlist) => {
  492. if (err) return cb(err);
  493. if (playlist) {
  494. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: 0}}, (err) => {
  495. if (err) return cb(err);
  496. stations.updateStation(stationId, (err, station) => {
  497. if (err) return cb(err);
  498. stations.skipStation(stationId)();
  499. cb({'status': 'success', 'message': 'Playlist selected.'});
  500. });
  501. });
  502. } else cb({'status': 'failure', 'message': 'Playlist not found.'});
  503. });
  504. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  505. });
  506. }),
  507. };