stations.js 39 KB

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