stations.js 36 KB

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