stations.js 32 KB

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