stations.js 20 KB

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