stations.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. 'use strict';
  2. const async = require('async'),
  3. request = require('request'),
  4. config = require('config'),
  5. _ = require('underscore')._;
  6. const io = require('../io');
  7. const db = require('../db');
  8. const cache = require('../cache');
  9. const notifications = require('../notifications');
  10. const utils = require('../utils');
  11. const logger = require('../logger');
  12. const stations = require('../stations');
  13. const songs = require('../songs');
  14. const hooks = require('./hooks');
  15. let userList = {};
  16. let usersPerStation = {};
  17. let usersPerStationCount = {};
  18. setInterval(() => {
  19. let stationsCountUpdated = [];
  20. let stationsUpdated = [];
  21. let oldUsersPerStation = usersPerStation;
  22. usersPerStation = {};
  23. let oldUsersPerStationCount = usersPerStationCount;
  24. usersPerStationCount = {};
  25. async.each(Object.keys(userList), function(socketId, next) {
  26. let socket = utils.socketFromSession(socketId);
  27. let stationId = userList[socketId];
  28. if (!socket || Object.keys(socket.rooms).indexOf(`station.${stationId}`) === -1) {
  29. if (stationsCountUpdated.indexOf(stationId) === -1) stationsCountUpdated.push(stationId);
  30. if (stationsUpdated.indexOf(stationId) === -1) stationsUpdated.push(stationId);
  31. delete userList[socketId];
  32. return next();
  33. }
  34. if (!usersPerStationCount[stationId]) usersPerStationCount[stationId] = 0;
  35. usersPerStationCount[stationId]++;
  36. if (!usersPerStation[stationId]) usersPerStation[stationId] = [];
  37. async.waterfall([
  38. (next) => {
  39. if (!socket.session || !socket.session.sessionId) return next('No session found.');
  40. cache.hget('sessions', socket.session.sessionId, next);
  41. },
  42. (session, next) => {
  43. if (!session) return next('Session not found.');
  44. db.models.user.findOne({_id: session.userId}, next);
  45. },
  46. (user, next) => {
  47. if (!user) return next('User not found.');
  48. if (usersPerStation[stationId].indexOf(user.username) !== -1) return next('User already in the list.');
  49. next(null, user.username);
  50. }
  51. ], (err, username) => {
  52. if (!err) {
  53. usersPerStation[stationId].push(username);
  54. }
  55. next();
  56. });
  57. //TODO Code to show users
  58. }, (err) => {
  59. for (let stationId in usersPerStationCount) {
  60. if (oldUsersPerStationCount[stationId] !== usersPerStationCount[stationId]) {
  61. if (stationsCountUpdated.indexOf(stationId) === -1) stationsCountUpdated.push(stationId);
  62. }
  63. }
  64. for (let stationId in usersPerStation) {
  65. if (_.difference(usersPerStation[stationId], oldUsersPerStation[stationId]).length > 0 || _.difference(oldUsersPerStation[stationId], usersPerStation[stationId]).length > 0) {
  66. if (stationsUpdated.indexOf(stationId) === -1) stationsUpdated.push(stationId);
  67. }
  68. }
  69. stationsCountUpdated.forEach((stationId) => {
  70. console.log("Updating count of ", stationId);
  71. cache.pub('station.updateUserCount', stationId);
  72. });
  73. stationsUpdated.forEach((stationId) => {
  74. console.log("Updating ", stationId);
  75. cache.pub('station.updateUsers', stationId);
  76. });
  77. //console.log("Userlist", usersPerStation);
  78. });
  79. }, 3000);
  80. cache.sub('station.updateUsers', stationId => {
  81. let list = usersPerStation[stationId] || [];
  82. utils.emitToRoom(`station.${stationId}`, "event:users.updated", list);
  83. });
  84. cache.sub('station.updateUserCount', stationId => {
  85. let count = usersPerStationCount[stationId] || 0;
  86. utils.emitToRoom(`station.${stationId}`, "event:userCount.updated", count);
  87. stations.getStation(stationId, (err, station) => {
  88. if (station.privacy === 'public') utils.emitToRoom('home', "event:userCount.updated", stationId, count);
  89. else {
  90. let sockets = utils.getRoomSockets('home');
  91. for (let socketId in sockets) {
  92. let socket = sockets[socketId];
  93. let session = sockets[socketId].session;
  94. if (session.sessionId) {
  95. cache.hget('sessions', session.sessionId, (err, session) => {
  96. if (!err && session) {
  97. db.models.user.findOne({_id: session.userId}, (err, user) => {
  98. if (user.role === 'admin') socket.emit("event:userCount.updated", stationId, count);
  99. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:userCount.updated", stationId, count);
  100. });
  101. }
  102. });
  103. }
  104. }
  105. }
  106. })
  107. });
  108. cache.sub('station.updatePartyMode', data => {
  109. utils.emitToRoom(`station.${data.stationId}`, "event:partyMode.updated", data.partyMode);
  110. });
  111. cache.sub('privatePlaylist.selected', data => {
  112. utils.emitToRoom(`station.${data.stationId}`, "event:privatePlaylist.selected", data.playlistId);
  113. });
  114. cache.sub('station.pause', stationId => {
  115. utils.emitToRoom(`station.${stationId}`, "event:stations.pause");
  116. });
  117. cache.sub('station.resume', stationId => {
  118. stations.getStation(stationId, (err, station) => {
  119. utils.emitToRoom(`station.${stationId}`, "event:stations.resume", { timePaused: station.timePaused });
  120. });
  121. });
  122. cache.sub('station.queueUpdate', stationId => {
  123. stations.getStation(stationId, (err, station) => {
  124. if (!err) utils.emitToRoom(`station.${stationId}`, "event:queue.update", station.queue);
  125. });
  126. });
  127. cache.sub('station.voteSkipSong', stationId => {
  128. utils.emitToRoom(`station.${stationId}`, "event:song.voteSkipSong");
  129. });
  130. cache.sub('station.remove', stationId => {
  131. utils.emitToRoom(`station.${stationId}`, 'event:stations.remove');
  132. utils.emitToRoom('admin.stations', 'event:admin.station.removed', stationId);
  133. });
  134. cache.sub('station.create', stationId => {
  135. stations.initializeStation(stationId, (err, station) => {
  136. station.userCount = usersPerStationCount[stationId] || 0;
  137. if (err) console.error(err);
  138. utils.emitToRoom('admin.stations', 'event:admin.station.added', station);
  139. // TODO If community, check if on whitelist
  140. if (station.privacy === 'public') utils.emitToRoom('home', "event:stations.created", station);
  141. else {
  142. let sockets = utils.getRoomSockets('home');
  143. for (let socketId in sockets) {
  144. let socket = sockets[socketId];
  145. let session = sockets[socketId].session;
  146. if (session.sessionId) {
  147. cache.hget('sessions', session.sessionId, (err, session) => {
  148. if (!err && session) {
  149. db.models.user.findOne({_id: session.userId}, (err, user) => {
  150. if (user.role === 'admin') socket.emit("event:stations.created", station);
  151. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:stations.created", station);
  152. });
  153. }
  154. });
  155. }
  156. }
  157. }
  158. });
  159. });
  160. module.exports = {
  161. /**
  162. * Get a list of all the stations
  163. *
  164. * @param session
  165. * @param cb
  166. * @return {{ status: String, stations: Array }}
  167. */
  168. index: (session, cb) => {
  169. async.waterfall([
  170. (next) => {
  171. cache.hgetall('stations', next);
  172. },
  173. (stations, next) => {
  174. let resultStations = [];
  175. for (let id in stations) {
  176. resultStations.push(stations[id]);
  177. }
  178. next(null, stations);
  179. },
  180. (stations, next) => {
  181. let resultStations = [];
  182. async.each(stations, (station, next) => {
  183. async.waterfall([
  184. (next) => {
  185. if (station.privacy === 'public') return next(true);
  186. if (!session.sessionId) return next(`Insufficient permissions.`);
  187. cache.hget('sessions', session.sessionId, next);
  188. },
  189. (session, next) => {
  190. if (!session) return next(`Insufficient permissions.`);
  191. db.models.user.findOne({_id: session.userId}, next);
  192. },
  193. (user, next) => {
  194. if (!user) return next(`Insufficient permissions.`);
  195. if (user.role === 'admin') return next(true);
  196. if (station.type === 'official') return next(`Insufficient permissions.`);
  197. if (station.owner === session.userId) return next(true);
  198. next(`Insufficient permissions.`);
  199. }
  200. ], (err) => {
  201. station.userCount = usersPerStationCount[station._id] || 0;
  202. if (err === true) resultStations.push(station);
  203. next();
  204. });
  205. }, () => {
  206. next(null, resultStations);
  207. });
  208. }
  209. ], (err, stations) => {
  210. if (err) {
  211. err = utils.getError(err);
  212. logger.error("STATIONS_INDEX", `Indexing stations failed. "${err}"`);
  213. return cb({'status': 'failure', 'message': err});
  214. }
  215. logger.success("STATIONS_INDEX", `Indexing stations successful.`);
  216. return cb({'status': 'success', 'stations': stations});
  217. });
  218. },
  219. /**
  220. * Finds a station by name
  221. *
  222. * @param session
  223. * @param stationName - the station name
  224. * @param cb
  225. */
  226. findByName: (session, stationName, cb) => {
  227. async.waterfall([
  228. (next) => {
  229. stations.getStationByName(stationName, next);
  230. },
  231. (station, next) => {
  232. if (!station) return next('Station not found.');
  233. next(null, station);
  234. }
  235. ], (err, station) => {
  236. if (err) {
  237. err = utils.getError(err);
  238. logger.error("STATIONS_FIND_BY_NAME", `Finding station "${stationName}" failed. "${err}"`);
  239. return cb({'status': 'failure', 'message': err});
  240. }
  241. logger.success("STATIONS_FIND_BY_NAME", `Found station "${stationName}" successfully.`);
  242. cb({status: 'success', data: station});
  243. });
  244. },
  245. /**
  246. * Gets the official playlist for a station
  247. *
  248. * @param session
  249. * @param stationId - the station id
  250. * @param cb
  251. */
  252. getPlaylist: (session, stationId, cb) => {
  253. async.waterfall([
  254. (next) => {
  255. stations.getStation(stationId, next);
  256. },
  257. (station, next) => {
  258. if (!station) return next('Station not found.');
  259. if (station.type !== 'official') return next('This is not an official station.');
  260. next();
  261. },
  262. (next) => {
  263. cache.hget("officialPlaylists", stationId, next);
  264. },
  265. (playlist, next) => {
  266. if (!playlist) return next('Playlist not found.');
  267. next(null, playlist);
  268. }
  269. ], (err, playlist) => {
  270. if (err) {
  271. err = utils.getError(err);
  272. logger.error("STATIONS_GET_PLAYLIST", `Getting playlist for station "${stationId}" failed. "${err}"`);
  273. return cb({'status': 'failure', 'message': err});
  274. }
  275. logger.success("STATIONS_GET_PLAYLIST", `Got playlist for station "${stationId}" successfully.`);
  276. cb({status: 'success', data: playlist.songs})
  277. });
  278. },
  279. /**
  280. * Joins the station by its name
  281. *
  282. * @param session
  283. * @param stationName - the station name
  284. * @param cb
  285. * @return {{ status: String, userCount: Integer }}
  286. */
  287. join: (session, stationName, cb) => {
  288. async.waterfall([
  289. (next) => {
  290. stations.getStationByName(stationName, next);
  291. },
  292. (station, next) => {
  293. if (!station) return next('Station not found.');
  294. async.waterfall([
  295. (next) => {
  296. if (station.privacy !== 'private') return next(true);
  297. if (!session.userId) return next('An error occurred while joining the station.');
  298. next();
  299. },
  300. (next) => {
  301. db.models.user.findOne({_id: session.userId}, next);
  302. },
  303. (user, next) => {
  304. if (!user) return next('An error occurred while joining the station.');
  305. if (user.role === 'admin') return next(true);
  306. if (station.type === 'official') return next('An error occurred while joining the station.');
  307. if (station.owner === session.userId) return next(true);
  308. next('An error occurred while joining the station.');
  309. }
  310. ], (err) => {
  311. if (err === true) return next(null, station);
  312. next(utils.getError(err));
  313. });
  314. },
  315. (station, next) => {
  316. utils.socketJoinRoom(session.socketId, `station.${station._id}`);
  317. let data = {
  318. _id: station._id,
  319. type: station.type,
  320. currentSong: station.currentSong,
  321. startedAt: station.startedAt,
  322. paused: station.paused,
  323. timePaused: station.timePaused,
  324. description: station.description,
  325. displayName: station.displayName,
  326. privacy: station.privacy,
  327. partyMode: station.partyMode,
  328. owner: station.owner,
  329. privatePlaylist: station.privatePlaylist
  330. };
  331. userList[session.socketId] = station._id;
  332. next(null, data);
  333. },
  334. (data, next) => {
  335. data.userCount = usersPerStationCount[data._id] || 0;
  336. data.users = usersPerStation[data._id] || [];
  337. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  338. utils.socketJoinSongRoom(session.socketId, `song.${data.currentSong.songId}`);
  339. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  340. songs.getSongFromId(data.currentSong.songId, (err, song) => {
  341. if (!err && song) {
  342. data.currentSong.likes = song.likes;
  343. data.currentSong.dislikes = song.dislikes;
  344. } else {
  345. data.currentSong.likes = -1;
  346. data.currentSong.dislikes = -1;
  347. }
  348. next(null, data);
  349. });
  350. }
  351. ], (err, data) => {
  352. if (err) {
  353. err = utils.getError(err);
  354. logger.error("STATIONS_JOIN", `Joining station "${stationName}" failed. "${err}"`);
  355. return cb({'status': 'failure', 'message': err});
  356. }
  357. logger.success("STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  358. cb({status: 'success', data});
  359. });
  360. },
  361. /**
  362. * Votes to skip a station
  363. *
  364. * @param session
  365. * @param stationId - the station id
  366. * @param cb
  367. * @param userId
  368. */
  369. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  370. async.waterfall([
  371. (next) => {
  372. stations.getStation(stationId, next);
  373. },
  374. (station, next) => {
  375. if (!station) return next('Station not found.');
  376. if (!station.currentSong) return next('There is currently no song to skip.');
  377. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return next('You have already voted to skip this song.');
  378. next(null, station);
  379. },
  380. (station, next) => {
  381. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, next)
  382. },
  383. (res, next) => {
  384. stations.updateStation(stationId, next);
  385. },
  386. (station, next) => {
  387. if (!station) return next('Station not found.');
  388. next(null, station);
  389. }
  390. ], (err, station) => {
  391. if (err) {
  392. err = utils.getError(err);
  393. logger.error("STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  394. return cb({'status': 'failure', 'message': err});
  395. }
  396. logger.success("STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  397. cache.pub('station.voteSkipSong', stationId);
  398. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  399. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  400. });
  401. }),
  402. /**
  403. * Force skips a station
  404. *
  405. * @param session
  406. * @param stationId - the station id
  407. * @param cb
  408. */
  409. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  410. async.waterfall([
  411. (next) => {
  412. stations.getStation(stationId, next);
  413. },
  414. (station, next) => {
  415. if (!station) return next('Station not found.');
  416. next();
  417. }
  418. ], (err) => {
  419. if (err) {
  420. err = utils.getError(err);
  421. logger.error("STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  422. return cb({'status': 'failure', 'message': err});
  423. }
  424. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  425. stations.skipStation(stationId)();
  426. logger.success("STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  427. return cb({'status': 'success', 'message': 'Successfully skipped station.'});
  428. });
  429. }),
  430. /**
  431. * Leaves the user's current station
  432. *
  433. * @param session
  434. * @param stationId
  435. * @param cb
  436. * @return {{ status: String, userCount: Integer }}
  437. */
  438. leave: (session, stationId, cb) => {
  439. async.waterfall([
  440. (next) => {
  441. stations.getStation(stationId, next);
  442. },
  443. (station, next) => {
  444. if (!station) return next('Station not found.');
  445. next();
  446. },
  447. (next) => {
  448. cache.client.hincrby('station.userCounts', stationId, -1, next);
  449. }
  450. ], (err, userCount) => {
  451. if (err) {
  452. err = utils.getError(err);
  453. logger.error("STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  454. return cb({'status': 'failure', 'message': err});
  455. }
  456. logger.success("STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  457. utils.socketLeaveRooms(session);
  458. delete userList[session.socketId];
  459. return cb({'status': 'success', 'message': 'Successfully left station.', userCount});
  460. });
  461. },
  462. /**
  463. * Updates a station's name
  464. *
  465. * @param session
  466. * @param stationId - the station id
  467. * @param newName - the new station name
  468. * @param cb
  469. */
  470. updateName: hooks.ownerRequired((session, stationId, newName, cb) => {
  471. async.waterfall([
  472. (next) => {
  473. db.models.station.update({_id: stationId}, {$set: {name: newName}}, {runValidators: true}, next);
  474. },
  475. (res, next) => {
  476. stations.updateStation(stationId, next);
  477. }
  478. ], (err) => {
  479. if (err) {
  480. err = utils.getError(err);
  481. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newName}" failed. "${err}"`);
  482. return cb({'status': 'failure', 'message': err});
  483. }
  484. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newName}" successfully.`);
  485. return cb({'status': 'success', 'message': 'Successfully updated the name.'});
  486. });
  487. }),
  488. /**
  489. * Updates a station's display name
  490. *
  491. * @param session
  492. * @param stationId - the station id
  493. * @param newDisplayName - the new station display name
  494. * @param cb
  495. */
  496. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  497. async.waterfall([
  498. (next) => {
  499. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, {runValidators: true}, next);
  500. },
  501. (res, next) => {
  502. stations.updateStation(stationId, next);
  503. }
  504. ], (err) => {
  505. if (err) {
  506. err = utils.getError(err);
  507. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`);
  508. return cb({'status': 'failure', 'message': err});
  509. }
  510. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`);
  511. return cb({'status': 'success', 'message': 'Successfully updated the display name.'});
  512. });
  513. }),
  514. /**
  515. * Updates a station's description
  516. *
  517. * @param session
  518. * @param stationId - the station id
  519. * @param newDescription - the new station description
  520. * @param cb
  521. */
  522. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  523. async.waterfall([
  524. (next) => {
  525. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, {runValidators: true}, next);
  526. },
  527. (res, next) => {
  528. stations.updateStation(stationId, next);
  529. }
  530. ], (err) => {
  531. if (err) {
  532. err = utils.getError(err);
  533. logger.error("STATIONS_UPDATE_DESCRIPTION", `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`);
  534. return cb({'status': 'failure', 'message': err});
  535. }
  536. logger.success("STATIONS_UPDATE_DESCRIPTION", `Updated station "${stationId}" description to "${newDescription}" successfully.`);
  537. return cb({'status': 'success', 'message': 'Successfully updated the description.'});
  538. });
  539. }),
  540. /**
  541. * Updates a station's privacy
  542. *
  543. * @param session
  544. * @param stationId - the station id
  545. * @param newPrivacy - the new station privacy
  546. * @param cb
  547. */
  548. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  549. async.waterfall([
  550. (next) => {
  551. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, {runValidators: true}, next);
  552. },
  553. (res, next) => {
  554. stations.updateStation(stationId, next);
  555. }
  556. ], (err) => {
  557. if (err) {
  558. err = utils.getError(err);
  559. logger.error("STATIONS_UPDATE_PRIVACY", `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`);
  560. return cb({'status': 'failure', 'message': err});
  561. }
  562. logger.success("STATIONS_UPDATE_PRIVACY", `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`);
  563. return cb({'status': 'success', 'message': 'Successfully updated the privacy.'});
  564. });
  565. }),
  566. /**
  567. * Updates a station's party mode
  568. *
  569. * @param session
  570. * @param stationId - the station id
  571. * @param newPartyMode - the new station party mode
  572. * @param cb
  573. */
  574. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  575. async.waterfall([
  576. (next) => {
  577. stations.getStation(stationId, next);
  578. },
  579. (station, next) => {
  580. if (!station) return next('Station not found.');
  581. if (station.partyMode === newPartyMode) return next('The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.'));
  582. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, {runValidators: true}, next);
  583. },
  584. (res, next) => {
  585. stations.updateStation(stationId, next);
  586. }
  587. ], (err) => {
  588. if (err) {
  589. err = utils.getError(err);
  590. logger.error("STATIONS_UPDATE_PARTY_MODE", `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`);
  591. return cb({'status': 'failure', 'message': err});
  592. }
  593. logger.success("STATIONS_UPDATE_PARTY_MODE", `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`);
  594. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  595. stations.skipStation(stationId)();
  596. return cb({'status': 'success', 'message': 'Successfully updated the party mode.'});
  597. });
  598. }),
  599. /**
  600. * Pauses a station
  601. *
  602. * @param session
  603. * @param stationId - the station id
  604. * @param cb
  605. */
  606. pause: hooks.ownerRequired((session, stationId, cb) => {
  607. async.waterfall([
  608. (next) => {
  609. stations.getStation(stationId, next);
  610. },
  611. (station, next) => {
  612. if (!station) return next('Station not found.');
  613. if (station.paused) return next('That station was already paused.');
  614. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, next);
  615. },
  616. (res, next) => {
  617. stations.updateStation(stationId, next);
  618. }
  619. ], (err) => {
  620. if (err) {
  621. err = utils.getError(err);
  622. logger.error("STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  623. return cb({'status': 'failure', 'message': err});
  624. }
  625. logger.success("STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  626. cache.pub('station.pause', stationId);
  627. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  628. return cb({'status': 'success', 'message': 'Successfully paused.'});
  629. });
  630. }),
  631. /**
  632. * Resumes a station
  633. *
  634. * @param session
  635. * @param stationId - the station id
  636. * @param cb
  637. */
  638. resume: hooks.ownerRequired((session, stationId, cb) => {
  639. async.waterfall([
  640. (next) => {
  641. stations.getStation(stationId, next);
  642. },
  643. (station, next) => {
  644. if (!station) return next('Station not found.');
  645. if (!station.paused) return next('That station is not paused.');
  646. station.timePaused += (Date.now() - station.pausedAt);
  647. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, next);
  648. },
  649. (res, next) => {
  650. stations.updateStation(stationId, next);
  651. }
  652. ], (err) => {
  653. if (err) {
  654. err = utils.getError(err);
  655. logger.error("STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  656. return cb({'status': 'failure', 'message': err});
  657. }
  658. logger.success("STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  659. cache.pub('station.resume', stationId);
  660. return cb({'status': 'success', 'message': 'Successfully resumed.'});
  661. });
  662. }),
  663. /**
  664. * Removes a station
  665. *
  666. * @param session
  667. * @param stationId - the station id
  668. * @param cb
  669. */
  670. remove: hooks.ownerRequired((session, stationId, cb) => {
  671. async.waterfall([
  672. (next) => {
  673. db.models.station.remove({ _id: stationId }, err => next(err));
  674. },
  675. (next) => {
  676. cache.hdel('stations', stationId, err => next(err));
  677. }
  678. ], (err) => {
  679. if (err) {
  680. err = utils.getError(err);
  681. logger.error("STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  682. return cb({ 'status': 'failure', 'message': err });
  683. }
  684. logger.success("STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  685. cache.pub('station.remove', stationId);
  686. return cb({ 'status': 'success', 'message': 'Successfully removed.' });
  687. });
  688. }),
  689. /**
  690. * Create a station
  691. *
  692. * @param session
  693. * @param data - the station data
  694. * @param cb
  695. * @param userId
  696. */
  697. create: hooks.loginRequired((session, data, cb, userId) => {
  698. data.name = data.name.toLowerCase();
  699. let blacklist = ["country", "edm", "musare", "hip-hop", "rap", "top-hits", "todays-hits", "old-school", "christmas", "about", "support", "staff", "help", "news", "terms", "privacy", "profile", "c", "community", "tos", "login", "register", "p", "official", "o", "trap", "faq", "team", "donate", "buy", "shop", "forums", "explore", "settings", "admin", "auth", "reset_password"];
  700. async.waterfall([
  701. (next) => {
  702. if (!data) return next('Invalid data.');
  703. next();
  704. },
  705. (next) => {
  706. db.models.station.findOne({ $or: [{name: data.name}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  707. },
  708. (station, next) => {
  709. if (station) return next('A station with that name or display name already exists.');
  710. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  711. if (type === 'official') {
  712. db.models.user.findOne({_id: userId}, (err, user) => {
  713. if (err) return next(err);
  714. if (!user) return next('User not found.');
  715. if (user.role !== 'admin') return next('Admin required.');
  716. db.models.station.create({
  717. name,
  718. displayName,
  719. description,
  720. type,
  721. privacy: 'private',
  722. playlist,
  723. genres,
  724. blacklistedGenres,
  725. currentSong: stations.defaultSong
  726. }, next);
  727. });
  728. } else if (type === 'community') {
  729. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  730. db.models.station.create({
  731. name,
  732. displayName,
  733. description,
  734. type,
  735. privacy: 'private',
  736. owner: userId,
  737. queue: [],
  738. currentSong: null
  739. }, next);
  740. }
  741. }
  742. ], (err, station) => {
  743. if (err) {
  744. err = utils.getError(err);
  745. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  746. return cb({'status': 'failure', 'message': err});
  747. }
  748. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  749. cache.pub('station.create', station._id);
  750. return cb({'status': 'success', 'message': 'Successfully created station.'});
  751. });
  752. }),
  753. /**
  754. * Adds song to station queue
  755. *
  756. * @param session
  757. * @param stationId - the station id
  758. * @param songId - the song id
  759. * @param cb
  760. * @param userId
  761. */
  762. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  763. async.waterfall([
  764. (next) => {
  765. stations.getStation(stationId, next);
  766. },
  767. (station, next) => {
  768. if (!station) return next('Station not found.');
  769. if (station.type !== 'community') return next('That station is not a community station.');
  770. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  771. async.each(station.queue, (queueSong, next) => {
  772. if (queueSong.songId === songId) return next('That song is already in the queue.');
  773. next();
  774. }, (err) => {
  775. next(err, station);
  776. });
  777. },
  778. (station, next) => {
  779. songs.getSong(songId, (err, song) => {
  780. if (!err && song) return next(null, song);
  781. utils.getSongFromYouTube(songId, (song) => {
  782. song.artists = [];
  783. song.skipDuration = 0;
  784. song.likes = -1;
  785. song.dislikes = -1;
  786. song.thumbnail = "empty";
  787. song.explicit = false;
  788. next(null, song);
  789. });
  790. });
  791. },
  792. (song, next) => {
  793. song.requestedBy = userId;
  794. db.models.station.update({_id: stationId}, {$push: {queue: song}}, {runValidators: true}, next);
  795. },
  796. (res, next) => {
  797. stations.updateStation(stationId, next);
  798. }
  799. ], (err, station) => {
  800. if (err) {
  801. err = utils.getError(err);
  802. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  803. return cb({'status': 'failure', 'message': err});
  804. }
  805. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  806. cache.pub('station.queueUpdate', stationId);
  807. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  808. });
  809. }),
  810. /**
  811. * Removes song from station queue
  812. *
  813. * @param session
  814. * @param stationId - the station id
  815. * @param songId - the song id
  816. * @param cb
  817. * @param userId
  818. */
  819. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  820. async.waterfall([
  821. (next) => {
  822. if (!songId) return next('Invalid song id.');
  823. stations.getStation(stationId, next);
  824. },
  825. (station, next) => {
  826. if (!station) return next('Station not found.');
  827. if (station.type !== 'community') return next('Station is not a community station.');
  828. async.each(station.queue, (queueSong, next) => {
  829. if (queueSong.songId === songId) return next(true);
  830. next();
  831. }, (err) => {
  832. if (err === true) return next();
  833. next('Song is not currently in the queue.');
  834. });
  835. },
  836. (next) => {
  837. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  838. },
  839. (next) => {
  840. stations.updateStation(stationId, next);
  841. }
  842. ], (err, station) => {
  843. if (err) {
  844. err = utils.getError(err);
  845. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  846. return cb({'status': 'failure', 'message': err});
  847. }
  848. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  849. cache.pub('station.queueUpdate', stationId);
  850. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  851. });
  852. }),
  853. /**
  854. * Gets the queue from a station
  855. *
  856. * @param session
  857. * @param stationId - the station id
  858. * @param cb
  859. */
  860. getQueue: hooks.adminRequired((session, stationId, cb) => {
  861. async.waterfall([
  862. (next) => {
  863. stations.getStation(stationId, next);
  864. },
  865. (station, next) => {
  866. if (!station) return next('Station not found.');
  867. if (station.type !== 'community') return next('Station is not a community station.');
  868. next(null, station);
  869. }
  870. ], (err, station) => {
  871. if (err) {
  872. err = utils.getError(err);
  873. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  874. return cb({'status': 'failure', 'message': err});
  875. }
  876. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  877. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  878. });
  879. }),
  880. /**
  881. * Selects a private playlist for a station
  882. *
  883. * @param session
  884. * @param stationId - the station id
  885. * @param playlistId - the private playlist id
  886. * @param cb
  887. * @param userId
  888. */
  889. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  890. async.waterfall([
  891. (next) => {
  892. stations.getStation(stationId, next);
  893. },
  894. (station, next) => {
  895. if (!station) return next('Station not found.');
  896. if (station.type !== 'community') return next('Station is not a community station.');
  897. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  898. db.models.playlist.findOne({_id: playlistId}, next);
  899. },
  900. (playlist, next) => {
  901. if (!playlist) return next('Playlist not found.');
  902. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  903. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, {runValidators: true}, next);
  904. },
  905. (res, next) => {
  906. stations.updateStation(stationId, next);
  907. }
  908. ], (err, station) => {
  909. if (err) {
  910. err = utils.getError(err);
  911. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  912. return cb({'status': 'failure', 'message': err});
  913. }
  914. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  915. notifications.unschedule(`stations.nextSong?id${stationId}`);
  916. if (!station.partyMode) stations.skipStation(stationId)();
  917. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  918. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  919. });
  920. }),
  921. };