stations.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. console.log(err, stations);
  211. if (err) {
  212. err = utils.getError(err);
  213. logger.error("STATIONS_INDEX", `Indexing stations failed. "${err}"`);
  214. return cb({'status': 'failure', 'message': err});
  215. }
  216. logger.success("STATIONS_INDEX", `Indexing stations successful.`);
  217. return cb({'status': 'success', 'stations': stations});
  218. });
  219. },
  220. /**
  221. * Finds a station by name
  222. *
  223. * @param session
  224. * @param stationName - the station name
  225. * @param cb
  226. */
  227. findByName: (session, stationName, cb) => {
  228. async.waterfall([
  229. (next) => {
  230. stations.getStationByName(stationName, next);
  231. },
  232. (station, next) => {
  233. if (!station) return next('Station not found.');
  234. next(null, station);
  235. }
  236. ], (err, station) => {
  237. if (err) {
  238. err = utils.getError(err);
  239. logger.error("STATIONS_FIND_BY_NAME", `Finding station "${stationName}" failed. "${err}"`);
  240. return cb({'status': 'failure', 'message': err});
  241. }
  242. logger.success("STATIONS_FIND_BY_NAME", `Found station "${stationName}" successfully.`);
  243. cb({status: 'success', data: station});
  244. });
  245. },
  246. /**
  247. * Gets the official playlist for a station
  248. *
  249. * @param session
  250. * @param stationId - the station id
  251. * @param cb
  252. */
  253. getPlaylist: (session, stationId, cb) => {
  254. async.waterfall([
  255. (next) => {
  256. stations.getStation(stationId, next);
  257. },
  258. (station, next) => {
  259. if (!station) return next('Station not found.');
  260. if (station.type !== 'official') return next('This is not an official station.');
  261. next();
  262. },
  263. (next) => {
  264. cache.hget("officialPlaylists", stationId, next);
  265. },
  266. (playlist, next) => {
  267. if (!playlist) return next('Playlist not found.');
  268. next(null, playlist);
  269. }
  270. ], (err, playlist) => {
  271. if (err) {
  272. err = utils.getError(err);
  273. logger.error("STATIONS_GET_PLAYLIST", `Getting playlist for station "${stationId}" failed. "${err}"`);
  274. return cb({'status': 'failure', 'message': err});
  275. }
  276. logger.success("STATIONS_GET_PLAYLIST", `Got playlist for station "${stationId}" successfully.`);
  277. cb({status: 'success', data: playlist.songs})
  278. });
  279. },
  280. /**
  281. * Joins the station by its name
  282. *
  283. * @param session
  284. * @param stationName - the station name
  285. * @param cb
  286. * @return {{ status: String, userCount: Integer }}
  287. */
  288. join: (session, stationName, cb) => {
  289. async.waterfall([
  290. (next) => {
  291. stations.getStationByName(stationName, next);
  292. },
  293. (station, next) => {
  294. if (!station) return next('Station not found.');
  295. async.waterfall([
  296. (next) => {
  297. if (station.privacy !== 'private') return next(true);
  298. if (!session.userId) return next('An error occurred while joining the station.');
  299. next();
  300. },
  301. (next) => {
  302. db.models.user.findOne({_id: session.userId}, next);
  303. },
  304. (user, next) => {
  305. if (!user) return next('An error occurred while joining the station.');
  306. if (user.role === 'admin') return next(true);
  307. if (station.type === 'official') return next('An error occurred while joining the station.');
  308. if (station.owner === session.userId) return next(true);
  309. next('An error occurred while joining the station.');
  310. }
  311. ], (err) => {
  312. if (err === true) return next(null, station);
  313. next(utils.getError(err));
  314. });
  315. },
  316. (station, next) => {
  317. utils.socketJoinRoom(session.socketId, `station.${station._id}`);
  318. let data = {
  319. _id: station._id,
  320. type: station.type,
  321. currentSong: station.currentSong,
  322. startedAt: station.startedAt,
  323. paused: station.paused,
  324. timePaused: station.timePaused,
  325. description: station.description,
  326. displayName: station.displayName,
  327. privacy: station.privacy,
  328. partyMode: station.partyMode,
  329. owner: station.owner,
  330. privatePlaylist: station.privatePlaylist
  331. };
  332. userList[session.socketId] = station._id;
  333. next(null, data);
  334. },
  335. (data, next) => {
  336. data.userCount = usersPerStationCount[data._id] || 0;
  337. data.users = usersPerStation[data._id] || [];
  338. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  339. utils.socketJoinSongRoom(session.socketId, `song.${data.currentSong.songId}`);
  340. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  341. songs.getSong(data.currentSong.songId, (err, song) => {
  342. if (!err && song) {
  343. data.currentSong.likes = song.likes;
  344. data.currentSong.dislikes = song.dislikes;
  345. } else {
  346. data.currentSong.likes = -1;
  347. data.currentSong.dislikes = -1;
  348. }
  349. next(null, data);
  350. });
  351. }
  352. ], (err, data) => {
  353. if (err) {
  354. err = utils.getError(err);
  355. logger.error("STATIONS_JOIN", `Joining station "${stationName}" failed. "${err}"`);
  356. return cb({'status': 'failure', 'message': err});
  357. }
  358. logger.success("STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  359. cb({status: 'success', data});
  360. });
  361. },
  362. /**
  363. * Votes to skip a station
  364. *
  365. * @param session
  366. * @param stationId - the station id
  367. * @param cb
  368. * @param userId
  369. */
  370. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  371. async.waterfall([
  372. (next) => {
  373. stations.getStation(stationId, next);
  374. },
  375. (station, next) => {
  376. if (!station) return next('Station not found.');
  377. if (!station.currentSong) return next('There is currently no song to skip.');
  378. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return next('You have already voted to skip this song.');
  379. next(null, station);
  380. },
  381. (station, next) => {
  382. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, next)
  383. },
  384. (res, next) => {
  385. stations.updateStation(stationId, next);
  386. },
  387. (station, next) => {
  388. if (!station) return next('Station not found.');
  389. next(null, station);
  390. }
  391. ], (err, station) => {
  392. if (err) {
  393. err = utils.getError(err);
  394. logger.error("STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  395. return cb({'status': 'failure', 'message': err});
  396. }
  397. logger.success("STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  398. cache.pub('station.voteSkipSong', stationId);
  399. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  400. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  401. });
  402. }),
  403. /**
  404. * Force skips a station
  405. *
  406. * @param session
  407. * @param stationId - the station id
  408. * @param cb
  409. */
  410. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  411. async.waterfall([
  412. (next) => {
  413. stations.getStation(stationId, next);
  414. },
  415. (station, next) => {
  416. if (!station) return next('Station not found.');
  417. next();
  418. }
  419. ], (err) => {
  420. if (err) {
  421. err = utils.getError(err);
  422. logger.error("STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  423. return cb({'status': 'failure', 'message': err});
  424. }
  425. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  426. stations.skipStation(stationId)();
  427. logger.success("STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  428. return cb({'status': 'success', 'message': 'Successfully skipped station.'});
  429. });
  430. }),
  431. /**
  432. * Leaves the user's current station
  433. *
  434. * @param session
  435. * @param stationId
  436. * @param cb
  437. * @return {{ status: String, userCount: Integer }}
  438. */
  439. leave: (session, stationId, cb) => {
  440. async.waterfall([
  441. (next) => {
  442. stations.getStation(stationId, next);
  443. },
  444. (station, next) => {
  445. if (!station) return next('Station not found.');
  446. next();
  447. },
  448. (next) => {
  449. cache.client.hincrby('station.userCounts', stationId, -1, next);
  450. }
  451. ], (err, userCount) => {
  452. if (err) {
  453. err = utils.getError(err);
  454. logger.error("STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  455. return cb({'status': 'failure', 'message': err});
  456. }
  457. logger.success("STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  458. utils.socketLeaveRooms(session);
  459. delete userList[session.socketId];
  460. return cb({'status': 'success', 'message': 'Successfully left station.', userCount});
  461. });
  462. },
  463. /**
  464. * Updates a station's name
  465. *
  466. * @param session
  467. * @param stationId - the station id
  468. * @param newName - the new station name
  469. * @param cb
  470. */
  471. updateName: hooks.ownerRequired((session, stationId, newName, cb) => {
  472. async.waterfall([
  473. (next) => {
  474. db.models.station.update({_id: stationId}, {$set: {name: newName}}, {runValidators: true}, next);
  475. },
  476. (res, next) => {
  477. stations.updateStation(stationId, next);
  478. }
  479. ], (err) => {
  480. if (err) {
  481. err = utils.getError(err);
  482. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newName}" failed. "${err}"`);
  483. return cb({'status': 'failure', 'message': err});
  484. }
  485. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newName}" successfully.`);
  486. return cb({'status': 'success', 'message': 'Successfully updated the name.'});
  487. });
  488. }),
  489. /**
  490. * Updates a station's display name
  491. *
  492. * @param session
  493. * @param stationId - the station id
  494. * @param newDisplayName - the new station display name
  495. * @param cb
  496. */
  497. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  498. async.waterfall([
  499. (next) => {
  500. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, {runValidators: true}, next);
  501. },
  502. (res, next) => {
  503. stations.updateStation(stationId, next);
  504. }
  505. ], (err) => {
  506. if (err) {
  507. err = utils.getError(err);
  508. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`);
  509. return cb({'status': 'failure', 'message': err});
  510. }
  511. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`);
  512. return cb({'status': 'success', 'message': 'Successfully updated the display name.'});
  513. });
  514. }),
  515. /**
  516. * Updates a station's description
  517. *
  518. * @param session
  519. * @param stationId - the station id
  520. * @param newDescription - the new station description
  521. * @param cb
  522. */
  523. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  524. async.waterfall([
  525. (next) => {
  526. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, {runValidators: true}, next);
  527. },
  528. (res, next) => {
  529. stations.updateStation(stationId, next);
  530. }
  531. ], (err) => {
  532. if (err) {
  533. err = utils.getError(err);
  534. logger.error("STATIONS_UPDATE_DESCRIPTION", `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`);
  535. return cb({'status': 'failure', 'message': err});
  536. }
  537. logger.success("STATIONS_UPDATE_DESCRIPTION", `Updated station "${stationId}" description to "${newDescription}" successfully.`);
  538. return cb({'status': 'success', 'message': 'Successfully updated the description.'});
  539. });
  540. }),
  541. /**
  542. * Updates a station's privacy
  543. *
  544. * @param session
  545. * @param stationId - the station id
  546. * @param newPrivacy - the new station privacy
  547. * @param cb
  548. */
  549. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  550. async.waterfall([
  551. (next) => {
  552. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, {runValidators: true}, next);
  553. },
  554. (res, next) => {
  555. stations.updateStation(stationId, next);
  556. }
  557. ], (err) => {
  558. if (err) {
  559. err = utils.getError(err);
  560. logger.error("STATIONS_UPDATE_PRIVACY", `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`);
  561. return cb({'status': 'failure', 'message': err});
  562. }
  563. logger.success("STATIONS_UPDATE_PRIVACY", `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`);
  564. return cb({'status': 'success', 'message': 'Successfully updated the privacy.'});
  565. });
  566. }),
  567. /**
  568. * Updates a station's party mode
  569. *
  570. * @param session
  571. * @param stationId - the station id
  572. * @param newPartyMode - the new station party mode
  573. * @param cb
  574. */
  575. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  576. async.waterfall([
  577. (next) => {
  578. stations.getStation(stationId, next);
  579. },
  580. (station, next) => {
  581. if (!station) return next('Station not found.');
  582. if (station.partyMode === newPartyMode) return next('The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.'));
  583. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, {runValidators: true}, next);
  584. },
  585. (res, next) => {
  586. stations.updateStation(stationId, next);
  587. }
  588. ], (err) => {
  589. if (err) {
  590. err = utils.getError(err);
  591. logger.error("STATIONS_UPDATE_PARTY_MODE", `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`);
  592. return cb({'status': 'failure', 'message': err});
  593. }
  594. logger.success("STATIONS_UPDATE_PARTY_MODE", `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`);
  595. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  596. stations.skipStation(stationId)();
  597. return cb({'status': 'success', 'message': 'Successfully updated the party mode.'});
  598. });
  599. }),
  600. /**
  601. * Pauses a station
  602. *
  603. * @param session
  604. * @param stationId - the station id
  605. * @param cb
  606. */
  607. pause: hooks.ownerRequired((session, stationId, cb) => {
  608. async.waterfall([
  609. (next) => {
  610. stations.getStation(stationId, next);
  611. },
  612. (station, next) => {
  613. if (!station) return next('Station not found.');
  614. if (station.paused) return next('That station was already paused.');
  615. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, next);
  616. },
  617. (res, next) => {
  618. stations.updateStation(stationId, next);
  619. }
  620. ], (err) => {
  621. if (err) {
  622. err = utils.getError(err);
  623. logger.error("STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  624. return cb({'status': 'failure', 'message': err});
  625. }
  626. logger.success("STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  627. cache.pub('station.pause', stationId);
  628. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  629. return cb({'status': 'success', 'message': 'Successfully paused.'});
  630. });
  631. }),
  632. /**
  633. * Resumes a station
  634. *
  635. * @param session
  636. * @param stationId - the station id
  637. * @param cb
  638. */
  639. resume: hooks.ownerRequired((session, stationId, cb) => {
  640. async.waterfall([
  641. (next) => {
  642. stations.getStation(stationId, next);
  643. },
  644. (station, next) => {
  645. if (!station) return next('Station not found.');
  646. if (!station.paused) return next('That station is not paused.');
  647. station.timePaused += (Date.now() - station.pausedAt);
  648. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, next);
  649. },
  650. (res, next) => {
  651. stations.updateStation(stationId, next);
  652. }
  653. ], (err) => {
  654. if (err) {
  655. err = utils.getError(err);
  656. logger.error("STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  657. return cb({'status': 'failure', 'message': err});
  658. }
  659. logger.success("STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  660. cache.pub('station.resume', stationId);
  661. return cb({'status': 'success', 'message': 'Successfully resumed.'});
  662. });
  663. }),
  664. /**
  665. * Removes a station
  666. *
  667. * @param session
  668. * @param stationId - the station id
  669. * @param cb
  670. */
  671. remove: hooks.ownerRequired((session, stationId, cb) => {
  672. async.waterfall([
  673. (next) => {
  674. db.models.station.remove({ _id: stationId }, err => next(err));
  675. },
  676. (next) => {
  677. cache.hdel('stations', stationId, err => next(err));
  678. }
  679. ], (err) => {
  680. if (err) {
  681. err = utils.getError(err);
  682. logger.error("STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  683. return cb({ 'status': 'failure', 'message': err });
  684. }
  685. logger.success("STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  686. cache.pub('station.remove', stationId);
  687. return cb({ 'status': 'success', 'message': 'Successfully removed.' });
  688. });
  689. }),
  690. /**
  691. * Create a station
  692. *
  693. * @param session
  694. * @param data - the station data
  695. * @param cb
  696. * @param userId
  697. */
  698. create: hooks.loginRequired((session, data, cb, userId) => {
  699. console.log(data);
  700. data.name = data.name.toLowerCase();
  701. 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"];
  702. async.waterfall([
  703. (next) => {
  704. if (!data) return next('Invalid data.');
  705. next();
  706. },
  707. (next) => {
  708. db.models.station.findOne({ $or: [{name: data.name}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  709. },
  710. (station, next) => {
  711. if (station) return next('A station with that name or display name already exists.');
  712. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  713. if (type === 'official') {
  714. db.models.user.findOne({_id: userId}, (err, user) => {
  715. if (err) return next(err);
  716. if (!user) return next('User not found.');
  717. if (user.role !== 'admin') return next('Admin required.');
  718. db.models.station.create({
  719. name,
  720. displayName,
  721. description,
  722. type,
  723. privacy: 'private',
  724. playlist,
  725. genres,
  726. blacklistedGenres,
  727. currentSong: stations.defaultSong
  728. }, next);
  729. });
  730. } else if (type === 'community') {
  731. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  732. db.models.station.create({
  733. name,
  734. displayName,
  735. description,
  736. type,
  737. privacy: 'private',
  738. owner: userId,
  739. queue: [],
  740. currentSong: null
  741. }, next);
  742. }
  743. }
  744. ], (err, station) => {
  745. if (err) {
  746. console.log(err);
  747. err = utils.getError(err);
  748. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  749. return cb({'status': 'failure', 'message': err});
  750. }
  751. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  752. cache.pub('station.create', station._id);
  753. return cb({'status': 'success', 'message': 'Successfully created station.'});
  754. });
  755. }),
  756. /**
  757. * Adds song to station queue
  758. *
  759. * @param session
  760. * @param stationId - the station id
  761. * @param songId - the song id
  762. * @param cb
  763. * @param userId
  764. */
  765. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  766. async.waterfall([
  767. (next) => {
  768. stations.getStation(stationId, next);
  769. },
  770. (station, next) => {
  771. if (!station) return next('Station not found.');
  772. if (station.type !== 'community') return next('That station is not a community station.');
  773. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  774. async.each(station.queue, (queueSong, next) => {
  775. if (queueSong.songId === songId) return next('That song is already in the queue.');
  776. next();
  777. }, (err) => {
  778. next(err, station);
  779. });
  780. },
  781. (station, next) => {
  782. songs.getSong(songId, (err, song) => {
  783. if (!err && song) return next(null, song);
  784. console.log(53, songId);
  785. utils.getSongFromYouTube(songId, (song) => {
  786. song.artists = [];
  787. song.skipDuration = 0;
  788. song.likes = -1;
  789. song.dislikes = -1;
  790. song.thumbnail = "empty";
  791. song.explicit = false;
  792. next(null, song);
  793. });
  794. });
  795. },
  796. (song, next) => {
  797. song.requestedBy = userId;
  798. db.models.station.update({_id: stationId}, {$push: {queue: song}}, next);
  799. },
  800. (res, next) => {
  801. stations.updateStation(stationId, next);
  802. }
  803. ], (err, station) => {
  804. if (err) {
  805. err = utils.getError(err);
  806. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  807. return cb({'status': 'failure', 'message': err});
  808. }
  809. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  810. cache.pub('station.queueUpdate', stationId);
  811. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  812. });
  813. }),
  814. /**
  815. * Removes song from station queue
  816. *
  817. * @param session
  818. * @param stationId - the station id
  819. * @param songId - the song id
  820. * @param cb
  821. * @param userId
  822. */
  823. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  824. async.waterfall([
  825. (next) => {
  826. if (!songId) return next('Invalid song id.');
  827. stations.getStation(stationId, next);
  828. },
  829. (station, next) => {
  830. if (!station) return next('Station not found.');
  831. if (station.type !== 'community') return next('Station is not a community station.');
  832. async.each(station.queue, (queueSong, next) => {
  833. if (queueSong.songId === songId) return next(true);
  834. next();
  835. }, (err) => {
  836. if (err === true) return next();
  837. next('Song is not currently in the queue.');
  838. });
  839. },
  840. (next) => {
  841. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  842. },
  843. (next) => {
  844. stations.updateStation(stationId, next);
  845. }
  846. ], (err, station) => {
  847. if (err) {
  848. err = utils.getError(err);
  849. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  850. return cb({'status': 'failure', 'message': err});
  851. }
  852. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  853. cache.pub('station.queueUpdate', stationId);
  854. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  855. });
  856. }),
  857. /**
  858. * Gets the queue from a station
  859. *
  860. * @param session
  861. * @param stationId - the station id
  862. * @param cb
  863. */
  864. getQueue: hooks.adminRequired((session, stationId, cb) => {
  865. async.waterfall([
  866. (next) => {
  867. stations.getStation(stationId, next);
  868. },
  869. (station, next) => {
  870. if (!station) return next('Station not found.');
  871. if (station.type !== 'community') return next('Station is not a community station.');
  872. next(null, station);
  873. }
  874. ], (err, station) => {
  875. if (err) {
  876. err = utils.getError(err);
  877. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  878. return cb({'status': 'failure', 'message': err});
  879. }
  880. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  881. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  882. });
  883. }),
  884. /**
  885. * Selects a private playlist for a station
  886. *
  887. * @param session
  888. * @param stationId - the station id
  889. * @param playlistId - the private playlist id
  890. * @param cb
  891. * @param userId
  892. */
  893. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  894. async.waterfall([
  895. (next) => {
  896. stations.getStation(stationId, next);
  897. },
  898. (station, next) => {
  899. if (!station) return next('Station not found.');
  900. if (station.type !== 'community') return next('Station is not a community station.');
  901. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  902. db.models.playlist.findOne({_id: playlistId}, next);
  903. },
  904. (playlist, next) => {
  905. if (!playlist) return next('Playlist not found.');
  906. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  907. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, {runValidators: true}, next);
  908. },
  909. (res, next) => {
  910. stations.updateStation(stationId, next);
  911. }
  912. ], (err, station) => {
  913. if (err) {
  914. err = utils.getError(err);
  915. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  916. return cb({'status': 'failure', 'message': err});
  917. }
  918. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  919. if (!station.partyMode) stations.skipStation(stationId)();
  920. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  921. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  922. });
  923. }),
  924. };