stations.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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. theme: station.theme
  323. };
  324. userList[session.socketId] = station._id;
  325. next(null, data);
  326. },
  327. (data, next) => {
  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. theme: 'blue'
  804. }, next);
  805. });
  806. } else if (type === 'community') {
  807. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  808. db.models.station.create({
  809. name,
  810. displayName,
  811. description,
  812. type,
  813. privacy: 'private',
  814. owner: session.userId,
  815. queue: [],
  816. currentSong: null,
  817. theme: 'blue'
  818. }, next);
  819. }
  820. }
  821. ], async (err, station) => {
  822. if (err) {
  823. err = await utils.getError(err);
  824. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  825. return cb({'status': 'failure', 'message': err});
  826. }
  827. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  828. cache.pub('station.create', station._id);
  829. return cb({'status': 'success', 'message': 'Successfully created station.'});
  830. });
  831. }),
  832. /**
  833. * Adds song to station queue
  834. *
  835. * @param session
  836. * @param stationId - the station id
  837. * @param songId - the song id
  838. * @param cb
  839. */
  840. addToQueue: hooks.loginRequired((session, stationId, songId, cb) => {
  841. async.waterfall([
  842. (next) => {
  843. stations.getStation(stationId, next);
  844. },
  845. (station, next) => {
  846. if (!station) return next('Station not found.');
  847. if (station.locked) {
  848. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  849. if (user.role !== 'admin' && station.owner !== session.userId) return next('Only owners and admins can add songs to a locked queue.');
  850. else return next(null, station);
  851. });
  852. } else {
  853. return next(null, station);
  854. }
  855. },
  856. (station, next) => {
  857. if (station.type !== 'community') return next('That station is not a community station.');
  858. stations.canUserViewStation(station, session.userId, (err, canView) => {
  859. if (err) return next(err);
  860. if (canView) return next(null, station);
  861. return next('Insufficient permissions.');
  862. });
  863. },
  864. (station, next) => {
  865. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  866. async.each(station.queue, (queueSong, next) => {
  867. if (queueSong.songId === songId) return next('That song is already in the queue.');
  868. next();
  869. }, (err) => {
  870. next(err, station);
  871. });
  872. },
  873. (station, next) => {
  874. songs.getSong(songId, (err, song) => {
  875. if (!err && song) return next(null, song, station);
  876. utils.getSongFromYouTube(songId, (song) => {
  877. song.artists = [];
  878. song.skipDuration = 0;
  879. song.likes = -1;
  880. song.dislikes = -1;
  881. song.thumbnail = "empty";
  882. song.explicit = false;
  883. next(null, song, station);
  884. });
  885. });
  886. },
  887. (song, station, next) => {
  888. let queue = station.queue;
  889. song.requestedBy = session.userId;
  890. queue.push(song);
  891. let totalDuration = 0;
  892. queue.forEach((song) => {
  893. totalDuration += song.duration;
  894. });
  895. if (totalDuration >= 3600 * 3) return next('The max length of the queue is 3 hours.');
  896. next(null, song, station);
  897. },
  898. (song, station, next) => {
  899. let queue = station.queue;
  900. if (queue.length === 0) return next(null, song, station);
  901. let totalDuration = 0;
  902. const userId = queue[queue.length - 1].requestedBy;
  903. station.queue.forEach((song) => {
  904. if (userId === song.requestedBy) {
  905. totalDuration += song.duration;
  906. }
  907. });
  908. if(totalDuration >= 900) return next('The max length of songs per user is 15 minutes.');
  909. next(null, song, station);
  910. },
  911. (song, station, next) => {
  912. let queue = station.queue;
  913. if (queue.length === 0) return next(null, song);
  914. let totalSongs = 0;
  915. const userId = queue[queue.length - 1].requestedBy;
  916. queue.forEach((song) => {
  917. if (userId === song.requestedBy) {
  918. totalSongs++;
  919. }
  920. });
  921. if (totalSongs <= 2) return next(null, song);
  922. if (totalSongs > 3) return next('The max amount of songs per user is 3, and only 2 in a row is allowed.');
  923. 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.');
  924. next(null, song);
  925. },
  926. (song, next) => {
  927. db.models.station.updateOne({_id: stationId}, {$push: {queue: song}}, {runValidators: true}, next);
  928. },
  929. (res, next) => {
  930. stations.updateStation(stationId, next);
  931. }
  932. ], async (err, station) => {
  933. if (err) {
  934. err = await utils.getError(err);
  935. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  936. return cb({'status': 'failure', 'message': err});
  937. }
  938. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  939. cache.pub('station.queueUpdate', stationId);
  940. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  941. });
  942. }),
  943. /**
  944. * Removes song from station queue
  945. *
  946. * @param session
  947. * @param stationId - the station id
  948. * @param songId - the song id
  949. * @param cb
  950. */
  951. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb) => {
  952. async.waterfall([
  953. (next) => {
  954. if (!songId) return next('Invalid song id.');
  955. stations.getStation(stationId, next);
  956. },
  957. (station, next) => {
  958. if (!station) return next('Station not found.');
  959. if (station.type !== 'community') return next('Station is not a community station.');
  960. async.each(station.queue, (queueSong, next) => {
  961. if (queueSong.songId === songId) return next(true);
  962. next();
  963. }, (err) => {
  964. if (err === true) return next();
  965. next('Song is not currently in the queue.');
  966. });
  967. },
  968. (next) => {
  969. db.models.station.updateOne({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  970. },
  971. (res, next) => {
  972. stations.updateStation(stationId, next);
  973. }
  974. ], async (err, station) => {
  975. if (err) {
  976. err = await utils.getError(err);
  977. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  978. return cb({'status': 'failure', 'message': err});
  979. }
  980. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  981. cache.pub('station.queueUpdate', stationId);
  982. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  983. });
  984. }),
  985. /**
  986. * Gets the queue from a station
  987. *
  988. * @param session
  989. * @param stationId - the station id
  990. * @param cb
  991. */
  992. getQueue: (session, stationId, cb) => {
  993. async.waterfall([
  994. (next) => {
  995. stations.getStation(stationId, next);
  996. },
  997. (station, next) => {
  998. if (!station) return next('Station not found.');
  999. if (station.type !== 'community') return next('Station is not a community station.');
  1000. next(null, station);
  1001. },
  1002. (station, next) => {
  1003. stations.canUserViewStation(station, session.userId, (err, canView) => {
  1004. if (err) return next(err);
  1005. if (canView) return next(null, station);
  1006. return next('Insufficient permissions.');
  1007. });
  1008. }
  1009. ], async (err, station) => {
  1010. if (err) {
  1011. err = await utils.getError(err);
  1012. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  1013. return cb({'status': 'failure', 'message': err});
  1014. }
  1015. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1016. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  1017. });
  1018. },
  1019. /**
  1020. * Selects a private playlist for a station
  1021. *
  1022. * @param session
  1023. * @param stationId - the station id
  1024. * @param playlistId - the private playlist id
  1025. * @param cb
  1026. */
  1027. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb) => {
  1028. async.waterfall([
  1029. (next) => {
  1030. stations.getStation(stationId, next);
  1031. },
  1032. (station, next) => {
  1033. if (!station) return next('Station not found.');
  1034. if (station.type !== 'community') return next('Station is not a community station.');
  1035. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  1036. db.models.playlist.findOne({_id: playlistId}, next);
  1037. },
  1038. (playlist, next) => {
  1039. if (!playlist) return next('Playlist not found.');
  1040. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  1041. db.models.station.updateOne({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, {runValidators: true}, next);
  1042. },
  1043. (res, next) => {
  1044. stations.updateStation(stationId, next);
  1045. }
  1046. ], async (err, station) => {
  1047. if (err) {
  1048. err = await utils.getError(err);
  1049. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  1050. return cb({'status': 'failure', 'message': err});
  1051. }
  1052. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  1053. notifications.unschedule(`stations.nextSong?id${stationId}`);
  1054. if (!station.partyMode) stations.skipStation(stationId)();
  1055. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  1056. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  1057. });
  1058. }),
  1059. favoriteStation: hooks.loginRequired((session, stationId, cb) => {
  1060. async.waterfall([
  1061. (next) => {
  1062. stations.getStation(stationId, next);
  1063. },
  1064. (station, next) => {
  1065. if (!station) return next('Station not found.');
  1066. stations.canUserViewStation(station, session.userId, (err, canView) => {
  1067. if (err) return next(err);
  1068. if (canView) return next();
  1069. return next('Insufficient permissions.');
  1070. });
  1071. },
  1072. (next) => {
  1073. db.models.user.updateOne({ _id: session.userId }, { $addToSet: { favoriteStations: stationId } }, next);
  1074. },
  1075. (res, next) => {
  1076. if (res.nModified === 0) return next("The station was already favorited.");
  1077. next();
  1078. }
  1079. ], async (err) => {
  1080. if (err) {
  1081. err = await utils.getError(err);
  1082. logger.error("FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  1083. return cb({'status': 'failure', 'message': err});
  1084. }
  1085. logger.success("FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  1086. cache.pub('user.favoritedStation', { userId: session.userId, stationId });
  1087. return cb({'status': 'success', 'message': 'Succesfully favorited station.'});
  1088. });
  1089. }),
  1090. unfavoriteStation: hooks.loginRequired((session, stationId, cb) => {
  1091. async.waterfall([
  1092. (next) => {
  1093. db.models.user.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  1094. },
  1095. (res, next) => {
  1096. if (res.nModified === 0) return next("The station wasn't favorited.");
  1097. next();
  1098. }
  1099. ], async (err) => {
  1100. if (err) {
  1101. err = await utils.getError(err);
  1102. logger.error("UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  1103. return cb({'status': 'failure', 'message': err});
  1104. }
  1105. logger.success("UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  1106. cache.pub('user.unfavoritedStation', { userId: session.userId, stationId });
  1107. return cb({'status': 'success', 'message': 'Succesfully unfavorited station.'});
  1108. });
  1109. }),
  1110. /**
  1111. * Updates a station's theme
  1112. *
  1113. * @param session
  1114. * @param stationId - the station id
  1115. * @param newTheme - the new station theme
  1116. * @param cb
  1117. */
  1118. updateTheme: hooks.ownerRequired((session, stationId, newTheme, cb) => {
  1119. async.waterfall([
  1120. (next) => {
  1121. db.models.station.updateOne({_id: stationId}, {$set: {theme: newTheme}}, {runValidators: true}, next);
  1122. },
  1123. (res, next) => {
  1124. stations.updateStation(stationId, next);
  1125. }
  1126. ], async (err) => {
  1127. if (err) {
  1128. err = await utils.getError(err);
  1129. logger.error("STATIONS_UPDATE_THEME", `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`);
  1130. return cb({'status': 'failure', 'message': err});
  1131. }
  1132. logger.success("STATIONS_UPDATE_THEME", `Updated station "${stationId}" theme to "${newTheme}" successfully.`);
  1133. return cb({'status': 'success', 'message': 'Successfully updated the theme.'});
  1134. });
  1135. }),
  1136. };