stations.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. owner: station.owner
  193. }
  194. });
  195. }
  196. }
  197. } else {
  198. cb({ status: 'failure', message: `That station doesn't exist` });
  199. }
  200. });
  201. },
  202. /**
  203. * Skips the users current station
  204. *
  205. * @param session
  206. * @param stationId - the station id
  207. * @param cb
  208. */
  209. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  210. stations.getStation(stationId, (err, station) => {
  211. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  212. if (!station.currentSong) return cb({ status: 'failure', message: 'There is currently no song to skip.' });
  213. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return cb({ status: 'failure', message: 'You have already voted to skip this song.' });
  214. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, (err) => {
  215. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  216. stations.updateStation(stationId, (err, station) => {
  217. cache.pub('station.voteSkipSong', stationId);
  218. if (station.currentSong && station.currentSong.skipVotes.length >= 1) {
  219. stations.skipStation(stationId)();
  220. }
  221. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  222. })
  223. });
  224. });
  225. }),
  226. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  227. stations.getStation(stationId, (err, station) => {
  228. if (err && err !== true) {
  229. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  230. }
  231. if (station) {
  232. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  233. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  234. stations.skipStation(stationId)();
  235. }
  236. else {
  237. cb({ status: 'failure', message: `That station doesn't exist` });
  238. }
  239. });
  240. }),
  241. /**
  242. * Leaves the users current station
  243. *
  244. * @param session
  245. * @param stationId
  246. * @param cb
  247. * @return {{ status: String, userCount: Integer }}
  248. */
  249. leave: (session, stationId, cb) => {
  250. stations.getStation(stationId, (err, station) => {
  251. if (err && err !== true) {
  252. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  253. }
  254. if (session) session.stationId = null;
  255. else if (station) {
  256. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  257. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  258. utils.socketLeaveRooms(session);
  259. cb({ status: 'success', userCount });
  260. });
  261. } else {
  262. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  263. }
  264. });
  265. },
  266. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  267. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, (err) => {
  268. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  269. stations.updateStation(stationId, () => {
  270. //TODO Pub/sub for displayName change
  271. cb({ status: 'success', message: 'Successfully updated the display name.' });
  272. })
  273. });
  274. }),
  275. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  276. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, (err) => {
  277. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  278. stations.updateStation(stationId, () => {
  279. //TODO Pub/sub for description change
  280. cb({ status: 'success', message: 'Successfully updated the description.' });
  281. })
  282. });
  283. }),
  284. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  285. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, (err) => {
  286. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  287. stations.updateStation(stationId, () => {
  288. //TODO Pub/sub for privacy change
  289. cb({ status: 'success', message: 'Successfully updated the privacy.' });
  290. })
  291. });
  292. }),
  293. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  294. stations.getStation(stationId, (err, station) => {
  295. if (err) return cb({ status: 'failure', message: err });
  296. if (station.partyMode === newPartyMode) return cb({ status: 'failure', message: 'The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.') });
  297. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, (err) => {
  298. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  299. stations.updateStation(stationId, () => {
  300. //TODO Pub/sub for privacy change
  301. stations.skipStation(stationId)();
  302. cb({ status: 'success', message: 'Successfully updated the party mode.' });
  303. })
  304. });
  305. });
  306. }),
  307. pause: hooks.ownerRequired((session, stationId, cb) => {
  308. stations.getStation(stationId, (err, station) => {
  309. if (err && err !== true) {
  310. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  311. } else if (station) {
  312. if (!station.paused) {
  313. station.paused = true;
  314. station.pausedAt = Date.now();
  315. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  316. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  317. stations.updateStation(stationId, () => {
  318. cache.pub('station.pause', stationId);
  319. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  320. cb({ status: 'success' });
  321. });
  322. });
  323. } else {
  324. cb({ status: 'failure', message: 'That station was already paused.' });
  325. }
  326. cb({ status: 'success' });
  327. } else {
  328. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  329. }
  330. });
  331. }),
  332. resume: hooks.ownerRequired((session, stationId, cb) => {
  333. stations.getStation(stationId, (err, station) => {
  334. if (err && err !== true) {
  335. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  336. } else if (station) {
  337. if (station.paused) {
  338. station.paused = false;
  339. station.timePaused += (Date.now() - station.pausedAt);
  340. console.log("&&&", station.timePaused, station.pausedAt, Date.now(), station.timePaused);
  341. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  342. stations.updateStation(stationId, (err, station) => {
  343. cache.pub('station.resume', stationId);
  344. cb({ status: 'success' });
  345. });
  346. });
  347. } else {
  348. cb({ status: 'failure', message: 'That station is not paused.' });
  349. }
  350. } else {
  351. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  352. }
  353. });
  354. }),
  355. remove: hooks.ownerRequired((session, stationId, cb) => {
  356. db.models.station.remove({ _id: stationId }, (err) => {
  357. console.log(err, stationId);
  358. if (err) return cb({status: 'failure', message: 'Something went wrong when deleting that station.'});
  359. cache.hdel('stations', stationId, () => {
  360. return cb({ status: 'success', message: 'Station successfully removed' });
  361. });
  362. });
  363. }),
  364. create: hooks.loginRequired((session, data, cb) => {
  365. data._id = data._id.toLowerCase();
  366. async.waterfall([
  367. (next) => {
  368. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  369. },
  370. (next) => {
  371. db.models.station.findOne({ $or: [{_id: data._id}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  372. },
  373. (station, next) => {
  374. if (station) return next({ 'status': 'failure', 'message': 'A station with that name or display name already exists' });
  375. const { _id, displayName, description, genres, playlist, type } = data;
  376. cache.hget('sessions', session.sessionId, (err, session) => {
  377. if (type == 'official') {
  378. db.models.user.findOne({_id: session.userId}, (err, user) => {
  379. if (err) return next({ 'status': 'failure', 'message': 'Something went wrong when getting your user info.' });
  380. if (!user) return next({ 'status': 'failure', 'message': 'User not found.' });
  381. if (user.role !== 'admin') return next({ 'status': 'failure', 'message': 'Admin required.' });
  382. db.models.station.create({
  383. _id,
  384. displayName,
  385. description,
  386. type,
  387. privacy: 'private',
  388. playlist,
  389. genres,
  390. currentSong: stations.defaultSong
  391. }, next);
  392. });
  393. } else if (type == 'community') {
  394. db.models.station.create({
  395. _id,
  396. displayName,
  397. description,
  398. type,
  399. privacy: 'private',
  400. owner: session.userId,
  401. queue: [],
  402. currentSong: null
  403. }, next);
  404. }
  405. });
  406. }
  407. ], (err, station) => {
  408. if (err) {
  409. console.error(err);
  410. return cb({ 'status': 'failure', 'message': 'Something went wrong.'});
  411. }
  412. cache.pub('station.create', data._id);
  413. cb({ 'status': 'success', 'message': 'Successfully created station.' });
  414. });
  415. }),
  416. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  417. stations.getStation(stationId, (err, station) => {
  418. if (err) return cb(err);
  419. if (station.type === 'community') {
  420. let has = false;
  421. station.queue.forEach((queueSong) => {
  422. if (queueSong._id === songId) {
  423. has = true;
  424. }
  425. });
  426. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  427. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing.'});
  428. songs.getSong(songId, (err, song) => {
  429. if (err) {
  430. utils.getSongFromYouTube(songId, (song) => {
  431. song.artists = [];
  432. song.skipDuration = 0;
  433. song.likes = -1;
  434. song.dislikes = -1;
  435. song.thumbnail = "empty";
  436. song.explicit = false;
  437. cont(song);
  438. });
  439. } else cont(song);
  440. function cont(song) {
  441. db.models.station.update({_id: stationId}, {$push: {queue: song}}, (err) => {
  442. console.log(err);
  443. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  444. stations.updateStation(stationId, (err, station) => {
  445. if (err) return cb(err);
  446. cache.pub('station.queueUpdate', stationId);
  447. cb({'status': 'success', 'message': 'Added that song to the queue.'});
  448. });
  449. });
  450. }
  451. });
  452. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  453. });
  454. }),
  455. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  456. stations.getStation(stationId, (err, station) => {
  457. if (err) return cb(err);
  458. if (station.type === 'community') {
  459. let has = false;
  460. station.queue.forEach((queueSong) => {
  461. if (queueSong._id === songId) {
  462. has = true;
  463. }
  464. });
  465. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  466. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  467. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  468. stations.updateStation(stationId, (err, station) => {
  469. if (err) return cb(err);
  470. cache.pub('station.queueUpdate', stationId);
  471. });
  472. });
  473. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  474. });
  475. }),
  476. getQueue: hooks.adminRequired((session, stationId, cb) => {
  477. stations.getStation(stationId, (err, station) => {
  478. if (err) return cb(err);
  479. if (!station) return cb({'status': 'failure', 'message': 'Station not found.'});
  480. if (station.type === 'community') {
  481. cb({'status': 'success', queue: station.queue});
  482. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  483. });
  484. }),
  485. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  486. stations.getStation(stationId, (err, station) => {
  487. if (err) return cb(err);
  488. if (station.type === 'community') {
  489. if (station.privatePlaylist === playlistId) return cb({'status': 'failure', 'message': 'That playlist is already selected.'});
  490. db.models.playlist.findOne({_id: playlistId}, (err, playlist) => {
  491. if (err) return cb(err);
  492. if (playlist) {
  493. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: 0}}, (err) => {
  494. if (err) return cb(err);
  495. stations.updateStation(stationId, (err, station) => {
  496. if (err) return cb(err);
  497. stations.skipStation(stationId)();
  498. cb({'status': 'success', 'message': 'Playlist selected.'});
  499. });
  500. });
  501. } else cb({'status': 'failure', 'message': 'Playlist not found.'});
  502. });
  503. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  504. });
  505. }),
  506. };