stations.js 35 KB

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