stations.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. //logger.info("UPDATE_STATION_USER_COUNT", `Updating user count of ${stationId}.`);
  71. cache.pub('station.updateUserCount', stationId);
  72. });
  73. stationsUpdated.forEach((stationId) => {
  74. //logger.info("UPDATE_STATION_USER_LIST", `Updating user list of ${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.queueLockToggled', data => {
  109. utils.emitToRoom(`station.${data.stationId}`, "event:queueLockToggled", data.locked)
  110. });
  111. cache.sub('station.updatePartyMode', data => {
  112. utils.emitToRoom(`station.${data.stationId}`, "event:partyMode.updated", data.partyMode);
  113. });
  114. cache.sub('privatePlaylist.selected', data => {
  115. utils.emitToRoom(`station.${data.stationId}`, "event:privatePlaylist.selected", data.playlistId);
  116. });
  117. cache.sub('station.pause', stationId => {
  118. utils.emitToRoom(`station.${stationId}`, "event:stations.pause");
  119. });
  120. cache.sub('station.resume', stationId => {
  121. stations.getStation(stationId, (err, station) => {
  122. utils.emitToRoom(`station.${stationId}`, "event:stations.resume", { timePaused: station.timePaused });
  123. });
  124. });
  125. cache.sub('station.queueUpdate', stationId => {
  126. stations.getStation(stationId, (err, station) => {
  127. if (!err) utils.emitToRoom(`station.${stationId}`, "event:queue.update", station.queue);
  128. });
  129. });
  130. cache.sub('station.voteSkipSong', stationId => {
  131. utils.emitToRoom(`station.${stationId}`, "event:song.voteSkipSong");
  132. });
  133. cache.sub('station.remove', stationId => {
  134. utils.emitToRoom(`station.${stationId}`, 'event:stations.remove');
  135. utils.emitToRoom('admin.stations', 'event:admin.station.removed', stationId);
  136. });
  137. cache.sub('station.create', stationId => {
  138. stations.initializeStation(stationId, (err, station) => {
  139. station.userCount = usersPerStationCount[stationId] || 0;
  140. if (err) console.error(err);
  141. utils.emitToRoom('admin.stations', 'event:admin.station.added', station);
  142. // TODO If community, check if on whitelist
  143. if (station.privacy === 'public') utils.emitToRoom('home', "event:stations.created", station);
  144. else {
  145. let sockets = utils.getRoomSockets('home');
  146. for (let socketId in sockets) {
  147. let socket = sockets[socketId];
  148. let session = sockets[socketId].session;
  149. if (session.sessionId) {
  150. cache.hget('sessions', session.sessionId, (err, session) => {
  151. if (!err && session) {
  152. db.models.user.findOne({_id: session.userId}, (err, user) => {
  153. if (user.role === 'admin') socket.emit("event:stations.created", station);
  154. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:stations.created", station);
  155. });
  156. }
  157. });
  158. }
  159. }
  160. }
  161. });
  162. });
  163. module.exports = {
  164. /**
  165. * Get a list of all the stations
  166. *
  167. * @param session
  168. * @param cb
  169. * @return {{ status: String, stations: Array }}
  170. */
  171. index: (session, cb) => {
  172. async.waterfall([
  173. (next) => {
  174. cache.hgetall('stations', next);
  175. },
  176. (stations, next) => {
  177. let resultStations = [];
  178. for (let id in stations) {
  179. resultStations.push(stations[id]);
  180. }
  181. next(null, stations);
  182. },
  183. (stations, next) => {
  184. let resultStations = [];
  185. async.each(stations, (station, next) => {
  186. async.waterfall([
  187. (next) => {
  188. if (station.privacy === 'public') return next(true);
  189. if (!session.sessionId) return next(`Insufficient permissions.`);
  190. cache.hget('sessions', session.sessionId, next);
  191. },
  192. (session, next) => {
  193. if (!session) return next(`Insufficient permissions.`);
  194. db.models.user.findOne({_id: session.userId}, next);
  195. },
  196. (user, next) => {
  197. if (!user) return next(`Insufficient permissions.`);
  198. if (user.role === 'admin') return next(true);
  199. if (station.type === 'official') return next(`Insufficient permissions.`);
  200. if (station.owner === session.userId) return next(true);
  201. next(`Insufficient permissions.`);
  202. }
  203. ], (err) => {
  204. station.userCount = usersPerStationCount[station._id] || 0;
  205. if (err === true) resultStations.push(station);
  206. next();
  207. });
  208. }, () => {
  209. next(null, resultStations);
  210. });
  211. }
  212. ], (err, stations) => {
  213. if (err) {
  214. err = utils.getError(err);
  215. logger.error("STATIONS_INDEX", `Indexing stations failed. "${err}"`);
  216. return cb({'status': 'failure', 'message': err});
  217. }
  218. logger.success("STATIONS_INDEX", `Indexing stations successful.`, false);
  219. return cb({'status': 'success', 'stations': stations});
  220. });
  221. },
  222. /**
  223. * Finds a station by name
  224. *
  225. * @param session
  226. * @param stationName - the station name
  227. * @param cb
  228. */
  229. findByName: (session, stationName, cb) => {
  230. async.waterfall([
  231. (next) => {
  232. stations.getStationByName(stationName, next);
  233. },
  234. (station, next) => {
  235. if (!station) return next('Station not found.');
  236. next(null, station);
  237. }
  238. ], (err, station) => {
  239. if (err) {
  240. err = utils.getError(err);
  241. logger.error("STATIONS_FIND_BY_NAME", `Finding station "${stationName}" failed. "${err}"`);
  242. return cb({'status': 'failure', 'message': err});
  243. }
  244. logger.success("STATIONS_FIND_BY_NAME", `Found station "${stationName}" successfully.`, false);
  245. cb({status: 'success', data: station});
  246. });
  247. },
  248. /**
  249. * Gets the official playlist for a station
  250. *
  251. * @param session
  252. * @param stationId - the station id
  253. * @param cb
  254. */
  255. getPlaylist: (session, stationId, cb) => {
  256. async.waterfall([
  257. (next) => {
  258. stations.getStation(stationId, next);
  259. },
  260. (station, next) => {
  261. if (!station) return next('Station not found.');
  262. else if (station.type !== 'official') return next('This is not an official station.');
  263. else next();
  264. },
  265. (next) => {
  266. cache.hget('officialPlaylists', stationId, next);
  267. },
  268. (playlist, next) => {
  269. if (!playlist) return next('Playlist not found.');
  270. next(null, playlist);
  271. }
  272. ], (err, playlist) => {
  273. if (err) {
  274. err = utils.getError(err);
  275. logger.error("STATIONS_GET_PLAYLIST", `Getting playlist for station "${stationId}" failed. "${err}"`);
  276. return cb({ status: 'failure', message: err });
  277. } else {
  278. logger.success("STATIONS_GET_PLAYLIST", `Got playlist for station "${stationId}" successfully.`, false);
  279. cb({ status: 'success', data: playlist.songs });
  280. }
  281. });
  282. },
  283. /**
  284. * Joins the station by its name
  285. *
  286. * @param session
  287. * @param stationName - the station name
  288. * @param cb
  289. * @return {{ status: String, userCount: Integer }}
  290. */
  291. join: (session, stationName, cb) => {
  292. async.waterfall([
  293. (next) => {
  294. stations.getStationByName(stationName, next);
  295. },
  296. (station, next) => {
  297. if (!station) return next('Station not found.');
  298. async.waterfall([
  299. (next) => {
  300. if (station.privacy !== 'private') return next(true);
  301. if (!session.userId) return next('An error occurred while joining the station.');
  302. next();
  303. },
  304. (next) => {
  305. db.models.user.findOne({_id: session.userId}, next);
  306. },
  307. (user, next) => {
  308. if (!user) return next('An error occurred while joining the station.');
  309. if (user.role === 'admin') return next(true);
  310. if (station.type === 'official') return next('An error occurred while joining the station.');
  311. if (station.owner === session.userId) return next(true);
  312. next('An error occurred while joining the station.');
  313. }
  314. ], (err) => {
  315. if (err === true) return next(null, station);
  316. next(utils.getError(err));
  317. });
  318. },
  319. (station, next) => {
  320. utils.socketJoinRoom(session.socketId, `station.${station._id}`);
  321. let data = {
  322. _id: station._id,
  323. type: station.type,
  324. currentSong: station.currentSong,
  325. startedAt: station.startedAt,
  326. paused: station.paused,
  327. timePaused: station.timePaused,
  328. description: station.description,
  329. displayName: station.displayName,
  330. privacy: station.privacy,
  331. locked: station.locked,
  332. partyMode: station.partyMode,
  333. owner: station.owner,
  334. privatePlaylist: station.privatePlaylist
  335. };
  336. userList[session.socketId] = station._id;
  337. next(null, data);
  338. },
  339. (data, next) => {
  340. data.userCount = usersPerStationCount[data._id] || 0;
  341. data.users = usersPerStation[data._id] || [];
  342. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  343. utils.socketJoinSongRoom(session.socketId, `song.${data.currentSong.songId}`);
  344. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  345. songs.getSongFromId(data.currentSong.songId, (err, song) => {
  346. if (!err && song) {
  347. data.currentSong.likes = song.likes;
  348. data.currentSong.dislikes = song.dislikes;
  349. } else {
  350. data.currentSong.likes = -1;
  351. data.currentSong.dislikes = -1;
  352. }
  353. next(null, data);
  354. });
  355. }
  356. ], (err, data) => {
  357. if (err) {
  358. err = utils.getError(err);
  359. logger.error("STATIONS_JOIN", `Joining station "${stationName}" failed. "${err}"`);
  360. return cb({'status': 'failure', 'message': err});
  361. }
  362. logger.success("STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  363. cb({status: 'success', data});
  364. });
  365. },
  366. /**
  367. * Toggles if a station is locked
  368. *
  369. * @param session
  370. * @param stationId - the station id
  371. * @param cb
  372. */
  373. toggleLock: hooks.ownerRequired((session, stationId, cb) => {
  374. async.waterfall([
  375. (next) => {
  376. stations.getStation(stationId, next);
  377. },
  378. (station, next) => {
  379. db.models.station.update({ _id: stationId }, { $set: { locked: !station.locked} }, next);
  380. },
  381. (res, next) => {
  382. stations.updateStation(stationId, next);
  383. }
  384. ], (err, station) => {
  385. if (err) {
  386. err = utils.getError(err);
  387. logger.error("STATIONS_UPDATE_LOCKED_STATUS", `Toggling the queue lock for station "${stationId}" failed. "${err}"`);
  388. return cb({ status: 'failure', message: err });
  389. } else {
  390. logger.success("STATIONS_UPDATE_LOCKED_STATUS", `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`);
  391. cache.pub('station.queueLockToggled', {stationId, locked: station.locked});
  392. return cb({ status: 'success', data: station.locked });
  393. }
  394. });
  395. }),
  396. /**
  397. * Votes to skip a station
  398. *
  399. * @param session
  400. * @param stationId - the station id
  401. * @param cb
  402. * @param userId
  403. */
  404. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  405. async.waterfall([
  406. (next) => {
  407. stations.getStation(stationId, next);
  408. },
  409. (station, next) => {
  410. if (!station) return next('Station not found.');
  411. utils.canUserBeInStation(station, userId, (canBe) => {
  412. if (canBe) return next(null, station);
  413. return next('Insufficient permissions.');
  414. });
  415. },
  416. (station, next) => {
  417. if (!station.currentSong) return next('There is currently no song to skip.');
  418. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return next('You have already voted to skip this song.');
  419. next(null, station);
  420. },
  421. (station, next) => {
  422. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, next)
  423. },
  424. (res, next) => {
  425. stations.updateStation(stationId, next);
  426. },
  427. (station, next) => {
  428. if (!station) return next('Station not found.');
  429. next(null, station);
  430. }
  431. ], (err, station) => {
  432. if (err) {
  433. err = utils.getError(err);
  434. logger.error("STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  435. return cb({'status': 'failure', 'message': err});
  436. }
  437. logger.success("STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  438. cache.pub('station.voteSkipSong', stationId);
  439. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  440. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  441. });
  442. }),
  443. /**
  444. * Force skips a station
  445. *
  446. * @param session
  447. * @param stationId - the station id
  448. * @param cb
  449. */
  450. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  451. async.waterfall([
  452. (next) => {
  453. stations.getStation(stationId, next);
  454. },
  455. (station, next) => {
  456. if (!station) return next('Station not found.');
  457. next();
  458. }
  459. ], (err) => {
  460. if (err) {
  461. err = utils.getError(err);
  462. logger.error("STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  463. return cb({'status': 'failure', 'message': err});
  464. }
  465. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  466. stations.skipStation(stationId)();
  467. logger.success("STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  468. return cb({'status': 'success', 'message': 'Successfully skipped station.'});
  469. });
  470. }),
  471. /**
  472. * Leaves the user's current station
  473. *
  474. * @param session
  475. * @param stationId
  476. * @param cb
  477. * @return {{ status: String, userCount: Integer }}
  478. */
  479. leave: (session, stationId, cb) => {
  480. async.waterfall([
  481. (next) => {
  482. stations.getStation(stationId, next);
  483. },
  484. (station, next) => {
  485. if (!station) return next('Station not found.');
  486. next();
  487. }
  488. ], (err, userCount) => {
  489. if (err) {
  490. err = utils.getError(err);
  491. logger.error("STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  492. return cb({'status': 'failure', 'message': err});
  493. }
  494. logger.success("STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  495. utils.socketLeaveRooms(session);
  496. delete userList[session.socketId];
  497. return cb({'status': 'success', 'message': 'Successfully left station.', userCount});
  498. });
  499. },
  500. /**
  501. * Updates a station's name
  502. *
  503. * @param session
  504. * @param stationId - the station id
  505. * @param newName - the new station name
  506. * @param cb
  507. */
  508. updateName: hooks.ownerRequired((session, stationId, newName, cb) => {
  509. async.waterfall([
  510. (next) => {
  511. db.models.station.update({_id: stationId}, {$set: {name: newName}}, {runValidators: true}, next);
  512. },
  513. (res, next) => {
  514. stations.updateStation(stationId, next);
  515. }
  516. ], (err) => {
  517. if (err) {
  518. err = utils.getError(err);
  519. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newName}" failed. "${err}"`);
  520. return cb({'status': 'failure', 'message': err});
  521. }
  522. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newName}" successfully.`);
  523. return cb({'status': 'success', 'message': 'Successfully updated the name.'});
  524. });
  525. }),
  526. /**
  527. * Updates a station's display name
  528. *
  529. * @param session
  530. * @param stationId - the station id
  531. * @param newDisplayName - the new station display name
  532. * @param cb
  533. */
  534. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  535. async.waterfall([
  536. (next) => {
  537. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, {runValidators: true}, next);
  538. },
  539. (res, next) => {
  540. stations.updateStation(stationId, next);
  541. }
  542. ], (err) => {
  543. if (err) {
  544. err = utils.getError(err);
  545. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`);
  546. return cb({'status': 'failure', 'message': err});
  547. }
  548. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`);
  549. return cb({'status': 'success', 'message': 'Successfully updated the display name.'});
  550. });
  551. }),
  552. /**
  553. * Updates a station's description
  554. *
  555. * @param session
  556. * @param stationId - the station id
  557. * @param newDescription - the new station description
  558. * @param cb
  559. */
  560. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  561. async.waterfall([
  562. (next) => {
  563. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, {runValidators: true}, next);
  564. },
  565. (res, next) => {
  566. stations.updateStation(stationId, next);
  567. }
  568. ], (err) => {
  569. if (err) {
  570. err = utils.getError(err);
  571. logger.error("STATIONS_UPDATE_DESCRIPTION", `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`);
  572. return cb({'status': 'failure', 'message': err});
  573. }
  574. logger.success("STATIONS_UPDATE_DESCRIPTION", `Updated station "${stationId}" description to "${newDescription}" successfully.`);
  575. return cb({'status': 'success', 'message': 'Successfully updated the description.'});
  576. });
  577. }),
  578. /**
  579. * Updates a station's privacy
  580. *
  581. * @param session
  582. * @param stationId - the station id
  583. * @param newPrivacy - the new station privacy
  584. * @param cb
  585. */
  586. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  587. async.waterfall([
  588. (next) => {
  589. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, {runValidators: true}, next);
  590. },
  591. (res, next) => {
  592. stations.updateStation(stationId, next);
  593. }
  594. ], (err) => {
  595. if (err) {
  596. err = utils.getError(err);
  597. logger.error("STATIONS_UPDATE_PRIVACY", `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`);
  598. return cb({'status': 'failure', 'message': err});
  599. }
  600. logger.success("STATIONS_UPDATE_PRIVACY", `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`);
  601. return cb({'status': 'success', 'message': 'Successfully updated the privacy.'});
  602. });
  603. }),
  604. /**
  605. * Updates a station's party mode
  606. *
  607. * @param session
  608. * @param stationId - the station id
  609. * @param newPartyMode - the new station party mode
  610. * @param cb
  611. */
  612. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  613. async.waterfall([
  614. (next) => {
  615. stations.getStation(stationId, next);
  616. },
  617. (station, next) => {
  618. if (!station) return next('Station not found.');
  619. if (station.partyMode === newPartyMode) return next('The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.'));
  620. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, {runValidators: true}, next);
  621. },
  622. (res, next) => {
  623. stations.updateStation(stationId, next);
  624. }
  625. ], (err) => {
  626. if (err) {
  627. err = utils.getError(err);
  628. logger.error("STATIONS_UPDATE_PARTY_MODE", `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`);
  629. return cb({'status': 'failure', 'message': err});
  630. }
  631. logger.success("STATIONS_UPDATE_PARTY_MODE", `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`);
  632. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  633. stations.skipStation(stationId)();
  634. return cb({'status': 'success', 'message': 'Successfully updated the party mode.'});
  635. });
  636. }),
  637. /**
  638. * Pauses a station
  639. *
  640. * @param session
  641. * @param stationId - the station id
  642. * @param cb
  643. */
  644. pause: hooks.ownerRequired((session, stationId, cb) => {
  645. async.waterfall([
  646. (next) => {
  647. stations.getStation(stationId, next);
  648. },
  649. (station, next) => {
  650. if (!station) return next('Station not found.');
  651. if (station.paused) return next('That station was already paused.');
  652. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, next);
  653. },
  654. (res, next) => {
  655. stations.updateStation(stationId, next);
  656. }
  657. ], (err) => {
  658. if (err) {
  659. err = utils.getError(err);
  660. logger.error("STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  661. return cb({'status': 'failure', 'message': err});
  662. }
  663. logger.success("STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  664. cache.pub('station.pause', stationId);
  665. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  666. return cb({'status': 'success', 'message': 'Successfully paused.'});
  667. });
  668. }),
  669. /**
  670. * Resumes a station
  671. *
  672. * @param session
  673. * @param stationId - the station id
  674. * @param cb
  675. */
  676. resume: hooks.ownerRequired((session, stationId, cb) => {
  677. async.waterfall([
  678. (next) => {
  679. stations.getStation(stationId, next);
  680. },
  681. (station, next) => {
  682. if (!station) return next('Station not found.');
  683. if (!station.paused) return next('That station is not paused.');
  684. station.timePaused += (Date.now() - station.pausedAt);
  685. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, next);
  686. },
  687. (res, next) => {
  688. stations.updateStation(stationId, next);
  689. }
  690. ], (err) => {
  691. if (err) {
  692. err = utils.getError(err);
  693. logger.error("STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  694. return cb({'status': 'failure', 'message': err});
  695. }
  696. logger.success("STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  697. cache.pub('station.resume', stationId);
  698. return cb({'status': 'success', 'message': 'Successfully resumed.'});
  699. });
  700. }),
  701. /**
  702. * Removes a station
  703. *
  704. * @param session
  705. * @param stationId - the station id
  706. * @param cb
  707. */
  708. remove: hooks.ownerRequired((session, stationId, cb) => {
  709. async.waterfall([
  710. (next) => {
  711. db.models.station.remove({ _id: stationId }, err => next(err));
  712. },
  713. (next) => {
  714. cache.hdel('stations', stationId, err => next(err));
  715. }
  716. ], (err) => {
  717. if (err) {
  718. err = utils.getError(err);
  719. logger.error("STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  720. return cb({ 'status': 'failure', 'message': err });
  721. }
  722. logger.success("STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  723. cache.pub('station.remove', stationId);
  724. return cb({ 'status': 'success', 'message': 'Successfully removed.' });
  725. });
  726. }),
  727. /**
  728. * Create a station
  729. *
  730. * @param session
  731. * @param data - the station data
  732. * @param cb
  733. * @param userId
  734. */
  735. create: hooks.loginRequired((session, data, cb, userId) => {
  736. data.name = data.name.toLowerCase();
  737. 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"];
  738. async.waterfall([
  739. (next) => {
  740. if (!data) return next('Invalid data.');
  741. next();
  742. },
  743. (next) => {
  744. db.models.station.findOne({ $or: [{name: data.name}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  745. },
  746. (station, next) => {
  747. if (station) return next('A station with that name or display name already exists.');
  748. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  749. if (type === 'official') {
  750. db.models.user.findOne({_id: userId}, (err, user) => {
  751. if (err) return next(err);
  752. if (!user) return next('User not found.');
  753. if (user.role !== 'admin') return next('Admin required.');
  754. db.models.station.create({
  755. name,
  756. displayName,
  757. description,
  758. type,
  759. privacy: 'private',
  760. playlist,
  761. genres,
  762. blacklistedGenres,
  763. currentSong: stations.defaultSong
  764. }, next);
  765. });
  766. } else if (type === 'community') {
  767. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  768. db.models.station.create({
  769. name,
  770. displayName,
  771. description,
  772. type,
  773. privacy: 'private',
  774. owner: userId,
  775. queue: [],
  776. currentSong: null
  777. }, next);
  778. }
  779. }
  780. ], (err, station) => {
  781. if (err) {
  782. err = utils.getError(err);
  783. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  784. return cb({'status': 'failure', 'message': err});
  785. }
  786. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  787. cache.pub('station.create', station._id);
  788. return cb({'status': 'success', 'message': 'Successfully created station.'});
  789. });
  790. }),
  791. /**
  792. * Adds song to station queue
  793. *
  794. * @param session
  795. * @param stationId - the station id
  796. * @param songId - the song id
  797. * @param cb
  798. * @param userId
  799. */
  800. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  801. async.waterfall([
  802. (next) => {
  803. stations.getStation(stationId, next);
  804. },
  805. (station, next) => {
  806. if (!station) return next('Station not found.');
  807. if (station.locked) {
  808. db.models.user.findOne({ _id: userId }, (err, user) => {
  809. if (user.role !== 'admin' && station.owner !== userId) return next('Only owners and admins can add songs to a locked queue.');
  810. else return next(null, station);
  811. });
  812. } else {
  813. return next(null, station);
  814. }
  815. },
  816. (station, next) => {
  817. if (station.type !== 'community') return next('That station is not a community station.');
  818. utils.canUserBeInStation(station, userId, (canBe) => {
  819. if (canBe) return next(null, station);
  820. return next('Insufficient permissions.');
  821. });
  822. },
  823. (station, next) => {
  824. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  825. async.each(station.queue, (queueSong, next) => {
  826. if (queueSong.songId === songId) return next('That song is already in the queue.');
  827. next();
  828. }, (err) => {
  829. next(err, station);
  830. });
  831. },
  832. (station, next) => {
  833. songs.getSong(songId, (err, song) => {
  834. if (!err && song) return next(null, song, station);
  835. utils.getSongFromYouTube(songId, (song) => {
  836. song.artists = [];
  837. song.skipDuration = 0;
  838. song.likes = -1;
  839. song.dislikes = -1;
  840. song.thumbnail = "empty";
  841. song.explicit = false;
  842. next(null, song, station);
  843. });
  844. });
  845. },
  846. (song, station, next) => {
  847. let queue = station.queue;
  848. song.requestedBy = userId;
  849. queue.push(song);
  850. let totalDuration = 0;
  851. queue.forEach((song) => {
  852. totalDuration += song.duration;
  853. });
  854. if (totalDuration >= 3600 * 3) return next('The max length of the queue is 3 hours.');
  855. next(null, song, station);
  856. },
  857. (song, station, next) => {
  858. let queue = station.queue;
  859. if (queue.length === 0) return next(null, song, station);
  860. let totalDuration = 0;
  861. const userId = queue[queue.length - 1].requestedBy;
  862. station.queue.forEach((song) => {
  863. if (userId === song.requestedBy) {
  864. totalDuration += song.duration;
  865. }
  866. });
  867. if(totalDuration >= 900) return next('The max length of songs per user is 15 minutes.');
  868. next(null, song, station);
  869. },
  870. (song, station, next) => {
  871. let queue = station.queue;
  872. if (queue.length === 0) return next(null, song);
  873. let totalSongs = 0;
  874. const userId = queue[queue.length - 1].requestedBy;
  875. queue.forEach((song) => {
  876. if (userId === song.requestedBy) {
  877. totalSongs++;
  878. }
  879. });
  880. if (totalSongs <= 2) return next(null, song);
  881. if (totalSongs > 3) return next('The max amount of songs per user is 3, and only 2 in a row is allowed.');
  882. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return next('The max amount of songs per user is 3, and only 2 in a row is allowed.');
  883. next(null, song);
  884. },
  885. (song, next) => {
  886. db.models.station.update({_id: stationId}, {$push: {queue: song}}, {runValidators: true}, next);
  887. },
  888. (res, next) => {
  889. stations.updateStation(stationId, next);
  890. }
  891. ], (err, station) => {
  892. if (err) {
  893. err = utils.getError(err);
  894. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  895. return cb({'status': 'failure', 'message': err});
  896. }
  897. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  898. cache.pub('station.queueUpdate', stationId);
  899. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  900. });
  901. }),
  902. /**
  903. * Removes song from station queue
  904. *
  905. * @param session
  906. * @param stationId - the station id
  907. * @param songId - the song id
  908. * @param cb
  909. * @param userId
  910. */
  911. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  912. async.waterfall([
  913. (next) => {
  914. if (!songId) return next('Invalid song id.');
  915. stations.getStation(stationId, next);
  916. },
  917. (station, next) => {
  918. if (!station) return next('Station not found.');
  919. if (station.type !== 'community') return next('Station is not a community station.');
  920. async.each(station.queue, (queueSong, next) => {
  921. if (queueSong.songId === songId) return next(true);
  922. next();
  923. }, (err) => {
  924. if (err === true) return next();
  925. next('Song is not currently in the queue.');
  926. });
  927. },
  928. (next) => {
  929. db.models.station.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  930. },
  931. (res, next) => {
  932. stations.updateStation(stationId, next);
  933. }
  934. ], (err, station) => {
  935. if (err) {
  936. err = utils.getError(err);
  937. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  938. return cb({'status': 'failure', 'message': err});
  939. }
  940. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  941. cache.pub('station.queueUpdate', stationId);
  942. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  943. });
  944. }),
  945. /**
  946. * Gets the queue from a station
  947. *
  948. * @param session
  949. * @param stationId - the station id
  950. * @param cb
  951. */
  952. getQueue: (session, stationId, cb) => {
  953. async.waterfall([
  954. (next) => {
  955. stations.getStation(stationId, next);
  956. },
  957. (station, next) => {
  958. if (!station) return next('Station not found.');
  959. if (station.type !== 'community') return next('Station is not a community station.');
  960. next(null, station);
  961. },
  962. (station, next) => {
  963. utils.canUserBeInStation(station, session.userId, (canBe) => {
  964. if (canBe) return next(null, station);
  965. return next('Insufficient permissions.');
  966. });
  967. }
  968. ], (err, station) => {
  969. if (err) {
  970. err = utils.getError(err);
  971. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  972. return cb({'status': 'failure', 'message': err});
  973. }
  974. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  975. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  976. });
  977. },
  978. /**
  979. * Selects a private playlist for a station
  980. *
  981. * @param session
  982. * @param stationId - the station id
  983. * @param playlistId - the private playlist id
  984. * @param cb
  985. * @param userId
  986. */
  987. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  988. async.waterfall([
  989. (next) => {
  990. stations.getStation(stationId, next);
  991. },
  992. (station, next) => {
  993. if (!station) return next('Station not found.');
  994. if (station.type !== 'community') return next('Station is not a community station.');
  995. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  996. db.models.playlist.findOne({_id: playlistId}, next);
  997. },
  998. (playlist, next) => {
  999. if (!playlist) return next('Playlist not found.');
  1000. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  1001. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, {runValidators: true}, next);
  1002. },
  1003. (res, next) => {
  1004. stations.updateStation(stationId, next);
  1005. }
  1006. ], (err, station) => {
  1007. if (err) {
  1008. err = utils.getError(err);
  1009. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  1010. return cb({'status': 'failure', 'message': err});
  1011. }
  1012. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  1013. notifications.unschedule(`stations.nextSong?id${stationId}`);
  1014. if (!station.partyMode) stations.skipStation(stationId)();
  1015. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  1016. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  1017. });
  1018. }),
  1019. };