2
0

stations.js 35 KB

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