stations.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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", { pausedAt: 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. pausedAt: station.pausedAt,
  331. description: station.description,
  332. displayName: station.displayName,
  333. privacy: station.privacy,
  334. locked: station.locked,
  335. partyMode: station.partyMode,
  336. owner: station.owner,
  337. privatePlaylist: station.privatePlaylist
  338. };
  339. userList[session.socketId] = station._id;
  340. next(null, data);
  341. },
  342. (data, next) => {
  343. data.userCount = usersPerStationCount[data._id] || 0;
  344. data.users = usersPerStation[data._id] || [];
  345. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  346. utils.socketJoinSongRoom(session.socketId, `song.${data.currentSong.songId}`);
  347. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  348. songs.getSongFromId(data.currentSong.songId, (err, song) => {
  349. if (!err && song) {
  350. data.currentSong.likes = song.likes;
  351. data.currentSong.dislikes = song.dislikes;
  352. } else {
  353. data.currentSong.likes = -1;
  354. data.currentSong.dislikes = -1;
  355. }
  356. next(null, data);
  357. });
  358. }
  359. ], (err, data) => {
  360. if (err) {
  361. err = utils.getError(err);
  362. logger.error("STATIONS_JOIN", `Joining station "${stationName}" failed. "${err}"`);
  363. return cb({'status': 'failure', 'message': err});
  364. }
  365. logger.success("STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  366. cb({status: 'success', data});
  367. });
  368. },
  369. /**
  370. * Toggles if a station is locked
  371. *
  372. * @param session
  373. * @param stationId - the station id
  374. * @param cb
  375. */
  376. toggleLock: hooks.ownerRequired((session, stationId, cb) => {
  377. async.waterfall([
  378. (next) => {
  379. stations.getStation(stationId, next);
  380. },
  381. (station, next) => {
  382. db.models.station.updateOne({ _id: stationId }, { $set: { locked: !station.locked} }, next);
  383. },
  384. (res, next) => {
  385. stations.updateStation(stationId, next);
  386. }
  387. ], (err, station) => {
  388. if (err) {
  389. err = utils.getError(err);
  390. logger.error("STATIONS_UPDATE_LOCKED_STATUS", `Toggling the queue lock for station "${stationId}" failed. "${err}"`);
  391. return cb({ status: 'failure', message: err });
  392. } else {
  393. logger.success("STATIONS_UPDATE_LOCKED_STATUS", `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`);
  394. cache.pub('station.queueLockToggled', {stationId, locked: station.locked});
  395. return cb({ status: 'success', data: station.locked });
  396. }
  397. });
  398. }),
  399. /**
  400. * Votes to skip a station
  401. *
  402. * @param session
  403. * @param stationId - the station id
  404. * @param cb
  405. * @param userId
  406. */
  407. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  408. async.waterfall([
  409. (next) => {
  410. stations.getStation(stationId, next);
  411. },
  412. (station, next) => {
  413. if (!station) return next('Station not found.');
  414. utils.canUserBeInStation(station, userId, (canBe) => {
  415. if (canBe) return next(null, station);
  416. return next('Insufficient permissions.');
  417. });
  418. },
  419. (station, next) => {
  420. if (!station.currentSong) return next('There is currently no song to skip.');
  421. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return next('You have already voted to skip this song.');
  422. next(null, station);
  423. },
  424. (station, next) => {
  425. db.models.station.updateOne({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, next)
  426. },
  427. (res, next) => {
  428. stations.updateStation(stationId, next);
  429. },
  430. (station, next) => {
  431. if (!station) return next('Station not found.');
  432. next(null, station);
  433. }
  434. ], (err, station) => {
  435. if (err) {
  436. err = utils.getError(err);
  437. logger.error("STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  438. return cb({'status': 'failure', 'message': err});
  439. }
  440. logger.success("STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  441. cache.pub('station.voteSkipSong', stationId);
  442. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  443. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  444. });
  445. }),
  446. /**
  447. * Force skips a station
  448. *
  449. * @param session
  450. * @param stationId - the station id
  451. * @param cb
  452. */
  453. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  454. async.waterfall([
  455. (next) => {
  456. stations.getStation(stationId, next);
  457. },
  458. (station, next) => {
  459. if (!station) return next('Station not found.');
  460. next();
  461. }
  462. ], (err) => {
  463. if (err) {
  464. err = utils.getError(err);
  465. logger.error("STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  466. return cb({'status': 'failure', 'message': err});
  467. }
  468. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  469. stations.skipStation(stationId)();
  470. logger.success("STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  471. return cb({'status': 'success', 'message': 'Successfully skipped station.'});
  472. });
  473. }),
  474. /**
  475. * Leaves the user's current station
  476. *
  477. * @param session
  478. * @param stationId
  479. * @param cb
  480. * @return {{ status: String, userCount: Integer }}
  481. */
  482. leave: (session, stationId, cb) => {
  483. async.waterfall([
  484. (next) => {
  485. stations.getStation(stationId, next);
  486. },
  487. (station, next) => {
  488. if (!station) return next('Station not found.');
  489. next();
  490. }
  491. ], (err, userCount) => {
  492. if (err) {
  493. err = utils.getError(err);
  494. logger.error("STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  495. return cb({'status': 'failure', 'message': err});
  496. }
  497. logger.success("STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  498. utils.socketLeaveRooms(session);
  499. delete userList[session.socketId];
  500. return cb({'status': 'success', 'message': 'Successfully left station.', userCount});
  501. });
  502. },
  503. /**
  504. * Updates a station's name
  505. *
  506. * @param session
  507. * @param stationId - the station id
  508. * @param newName - the new station name
  509. * @param cb
  510. */
  511. updateName: hooks.ownerRequired((session, stationId, newName, cb) => {
  512. async.waterfall([
  513. (next) => {
  514. db.models.station.updateOne({_id: stationId}, {$set: {name: newName}}, {runValidators: true}, next);
  515. },
  516. (res, next) => {
  517. stations.updateStation(stationId, next);
  518. }
  519. ], (err) => {
  520. if (err) {
  521. err = utils.getError(err);
  522. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newName}" failed. "${err}"`);
  523. return cb({'status': 'failure', 'message': err});
  524. }
  525. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newName}" successfully.`);
  526. return cb({'status': 'success', 'message': 'Successfully updated the name.'});
  527. });
  528. }),
  529. /**
  530. * Updates a station's display name
  531. *
  532. * @param session
  533. * @param stationId - the station id
  534. * @param newDisplayName - the new station display name
  535. * @param cb
  536. */
  537. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  538. async.waterfall([
  539. (next) => {
  540. db.models.station.updateOne({_id: stationId}, {$set: {displayName: newDisplayName}}, {runValidators: true}, next);
  541. },
  542. (res, next) => {
  543. stations.updateStation(stationId, next);
  544. }
  545. ], (err) => {
  546. if (err) {
  547. err = utils.getError(err);
  548. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`);
  549. return cb({'status': 'failure', 'message': err});
  550. }
  551. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`);
  552. return cb({'status': 'success', 'message': 'Successfully updated the display name.'});
  553. });
  554. }),
  555. /**
  556. * Updates a station's description
  557. *
  558. * @param session
  559. * @param stationId - the station id
  560. * @param newDescription - the new station description
  561. * @param cb
  562. */
  563. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  564. async.waterfall([
  565. (next) => {
  566. db.models.station.updateOne({_id: stationId}, {$set: {description: newDescription}}, {runValidators: true}, next);
  567. },
  568. (res, next) => {
  569. stations.updateStation(stationId, next);
  570. }
  571. ], (err) => {
  572. if (err) {
  573. err = utils.getError(err);
  574. logger.error("STATIONS_UPDATE_DESCRIPTION", `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`);
  575. return cb({'status': 'failure', 'message': err});
  576. }
  577. logger.success("STATIONS_UPDATE_DESCRIPTION", `Updated station "${stationId}" description to "${newDescription}" successfully.`);
  578. return cb({'status': 'success', 'message': 'Successfully updated the description.'});
  579. });
  580. }),
  581. /**
  582. * Updates a station's privacy
  583. *
  584. * @param session
  585. * @param stationId - the station id
  586. * @param newPrivacy - the new station privacy
  587. * @param cb
  588. */
  589. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  590. async.waterfall([
  591. (next) => {
  592. db.models.station.updateOne({_id: stationId}, {$set: {privacy: newPrivacy}}, {runValidators: true}, next);
  593. },
  594. (res, next) => {
  595. stations.updateStation(stationId, next);
  596. }
  597. ], (err) => {
  598. if (err) {
  599. err = utils.getError(err);
  600. logger.error("STATIONS_UPDATE_PRIVACY", `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`);
  601. return cb({'status': 'failure', 'message': err});
  602. }
  603. logger.success("STATIONS_UPDATE_PRIVACY", `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`);
  604. return cb({'status': 'success', 'message': 'Successfully updated the privacy.'});
  605. });
  606. }),
  607. /**
  608. * Updates a station's genres
  609. *
  610. * @param session
  611. * @param stationId - the station id
  612. * @param newGenres - the new station genres
  613. * @param cb
  614. */
  615. updateGenres: hooks.ownerRequired((session, stationId, newGenres, cb) => {
  616. async.waterfall([
  617. (next) => {
  618. db.models.station.updateOne({_id: stationId}, {$set: {genres: newGenres}}, {runValidators: true}, next);
  619. },
  620. (res, next) => {
  621. stations.updateStation(stationId, next);
  622. }
  623. ], (err) => {
  624. if (err) {
  625. err = utils.getError(err);
  626. logger.error("STATIONS_UPDATE_GENRES", `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`);
  627. return cb({'status': 'failure', 'message': err});
  628. }
  629. logger.success("STATIONS_UPDATE_GENRES", `Updated station "${stationId}" genres to "${newGenres}" successfully.`);
  630. return cb({'status': 'success', 'message': 'Successfully updated the genres.'});
  631. });
  632. }),
  633. /**
  634. * Updates a station's blacklisted genres
  635. *
  636. * @param session
  637. * @param stationId - the station id
  638. * @param newBlacklistedGenres - the new station blacklisted genres
  639. * @param cb
  640. */
  641. updateBlacklistedGenres: hooks.ownerRequired((session, stationId, newBlacklistedGenres, cb) => {
  642. async.waterfall([
  643. (next) => {
  644. db.models.station.updateOne({_id: stationId}, {$set: {blacklistedGenres: newBlacklistedGenres}}, {runValidators: true}, next);
  645. },
  646. (res, next) => {
  647. stations.updateStation(stationId, next);
  648. }
  649. ], (err) => {
  650. if (err) {
  651. err = utils.getError(err);
  652. logger.error("STATIONS_UPDATE_BLACKLISTED_GENRES", `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`);
  653. return cb({'status': 'failure', 'message': err});
  654. }
  655. logger.success("STATIONS_UPDATE_BLACKLISTED_GENRES", `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`);
  656. return cb({'status': 'success', 'message': 'Successfully updated the blacklisted genres.'});
  657. });
  658. }),
  659. /**
  660. * Updates a station's party mode
  661. *
  662. * @param session
  663. * @param stationId - the station id
  664. * @param newPartyMode - the new station party mode
  665. * @param cb
  666. */
  667. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  668. async.waterfall([
  669. (next) => {
  670. stations.getStation(stationId, next);
  671. },
  672. (station, next) => {
  673. if (!station) return next('Station not found.');
  674. if (station.partyMode === newPartyMode) return next('The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.'));
  675. db.models.station.updateOne({_id: stationId}, {$set: {partyMode: newPartyMode}}, {runValidators: true}, next);
  676. },
  677. (res, next) => {
  678. stations.updateStation(stationId, next);
  679. }
  680. ], (err) => {
  681. if (err) {
  682. err = utils.getError(err);
  683. logger.error("STATIONS_UPDATE_PARTY_MODE", `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`);
  684. return cb({'status': 'failure', 'message': err});
  685. }
  686. logger.success("STATIONS_UPDATE_PARTY_MODE", `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`);
  687. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  688. stations.skipStation(stationId)();
  689. return cb({'status': 'success', 'message': 'Successfully updated the party mode.'});
  690. });
  691. }),
  692. /**
  693. * Pauses a station
  694. *
  695. * @param session
  696. * @param stationId - the station id
  697. * @param cb
  698. */
  699. pause: hooks.ownerRequired((session, stationId, cb) => {
  700. async.waterfall([
  701. (next) => {
  702. stations.getStation(stationId, next);
  703. },
  704. (station, next) => {
  705. if (!station) return next('Station not found.');
  706. if (station.paused) return next('That station was already paused.');
  707. db.models.station.updateOne({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, next);
  708. },
  709. (res, next) => {
  710. stations.updateStation(stationId, next);
  711. }
  712. ], (err) => {
  713. if (err) {
  714. err = utils.getError(err);
  715. logger.error("STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  716. return cb({'status': 'failure', 'message': err});
  717. }
  718. logger.success("STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  719. cache.pub('station.pause', stationId);
  720. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  721. return cb({'status': 'success', 'message': 'Successfully paused.'});
  722. });
  723. }),
  724. /**
  725. * Resumes a station
  726. *
  727. * @param session
  728. * @param stationId - the station id
  729. * @param cb
  730. */
  731. resume: hooks.ownerRequired((session, stationId, cb) => {
  732. async.waterfall([
  733. (next) => {
  734. stations.getStation(stationId, next);
  735. },
  736. (station, next) => {
  737. if (!station) return next('Station not found.');
  738. if (!station.paused) return next('That station is not paused.');
  739. station.timePaused += (Date.now() - station.pausedAt);
  740. db.models.station.updateOne({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, next);
  741. },
  742. (res, next) => {
  743. stations.updateStation(stationId, next);
  744. }
  745. ], (err) => {
  746. if (err) {
  747. err = utils.getError(err);
  748. logger.error("STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  749. return cb({'status': 'failure', 'message': err});
  750. }
  751. logger.success("STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  752. cache.pub('station.resume', stationId);
  753. return cb({'status': 'success', 'message': 'Successfully resumed.'});
  754. });
  755. }),
  756. /**
  757. * Removes a station
  758. *
  759. * @param session
  760. * @param stationId - the station id
  761. * @param cb
  762. */
  763. remove: hooks.ownerRequired((session, stationId, cb) => {
  764. async.waterfall([
  765. (next) => {
  766. db.models.station.deleteOne({ _id: stationId }, err => next(err));
  767. },
  768. (next) => {
  769. cache.hdel('stations', stationId, err => next(err));
  770. }
  771. ], (err) => {
  772. if (err) {
  773. err = utils.getError(err);
  774. logger.error("STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  775. return cb({ 'status': 'failure', 'message': err });
  776. }
  777. logger.success("STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  778. cache.pub('station.remove', stationId);
  779. return cb({ 'status': 'success', 'message': 'Successfully removed.' });
  780. });
  781. }),
  782. /**
  783. * Create a station
  784. *
  785. * @param session
  786. * @param data - the station data
  787. * @param cb
  788. * @param userId
  789. */
  790. create: hooks.loginRequired((session, data, cb, userId) => {
  791. data.name = data.name.toLowerCase();
  792. 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"];
  793. async.waterfall([
  794. (next) => {
  795. if (!data) return next('Invalid data.');
  796. next();
  797. },
  798. (next) => {
  799. db.models.station.findOne({ $or: [{name: data.name}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  800. },
  801. (station, next) => {
  802. if (station) return next('A station with that name or display name already exists.');
  803. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  804. if (type === 'official') {
  805. db.models.user.findOne({_id: userId}, (err, user) => {
  806. if (err) return next(err);
  807. if (!user) return next('User not found.');
  808. if (user.role !== 'admin') return next('Admin required.');
  809. db.models.station.create({
  810. name,
  811. displayName,
  812. description,
  813. type,
  814. privacy: 'private',
  815. playlist,
  816. genres,
  817. blacklistedGenres,
  818. currentSong: stations.defaultSong
  819. }, next);
  820. });
  821. } else if (type === 'community') {
  822. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  823. db.models.station.create({
  824. name,
  825. displayName,
  826. description,
  827. type,
  828. privacy: 'private',
  829. owner: userId,
  830. queue: [],
  831. currentSong: null
  832. }, next);
  833. }
  834. }
  835. ], (err, station) => {
  836. if (err) {
  837. err = utils.getError(err);
  838. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  839. return cb({'status': 'failure', 'message': err});
  840. }
  841. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  842. cache.pub('station.create', station._id);
  843. return cb({'status': 'success', 'message': 'Successfully created station.'});
  844. });
  845. }),
  846. /**
  847. * Adds song to station queue
  848. *
  849. * @param session
  850. * @param stationId - the station id
  851. * @param songId - the song id
  852. * @param cb
  853. * @param userId
  854. */
  855. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  856. async.waterfall([
  857. (next) => {
  858. stations.getStation(stationId, next);
  859. },
  860. (station, next) => {
  861. if (!station) return next('Station not found.');
  862. if (station.locked) {
  863. db.models.user.findOne({ _id: userId }, (err, user) => {
  864. if (user.role !== 'admin' && station.owner !== userId) return next('Only owners and admins can add songs to a locked queue.');
  865. else return next(null, station);
  866. });
  867. } else {
  868. return next(null, station);
  869. }
  870. },
  871. (station, next) => {
  872. if (station.type !== 'community') return next('That station is not a community station.');
  873. utils.canUserBeInStation(station, userId, (canBe) => {
  874. if (canBe) return next(null, station);
  875. return next('Insufficient permissions.');
  876. });
  877. },
  878. (station, next) => {
  879. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  880. async.each(station.queue, (queueSong, next) => {
  881. if (queueSong.songId === songId) return next('That song is already in the queue.');
  882. next();
  883. }, (err) => {
  884. next(err, station);
  885. });
  886. },
  887. (station, next) => {
  888. songs.getSong(songId, (err, song) => {
  889. if (!err && song) return next(null, song, station);
  890. utils.getSongFromYouTube(songId, (song) => {
  891. song.artists = [];
  892. song.skipDuration = 0;
  893. song.likes = -1;
  894. song.dislikes = -1;
  895. song.thumbnail = "empty";
  896. song.explicit = false;
  897. next(null, song, station);
  898. });
  899. });
  900. },
  901. (song, station, next) => {
  902. let queue = station.queue;
  903. song.requestedBy = userId;
  904. queue.push(song);
  905. let totalDuration = 0;
  906. queue.forEach((song) => {
  907. totalDuration += song.duration;
  908. });
  909. if (totalDuration >= 3600 * 3) return next('The max length of the queue is 3 hours.');
  910. next(null, song, station);
  911. },
  912. (song, station, next) => {
  913. let queue = station.queue;
  914. if (queue.length === 0) return next(null, song, station);
  915. let totalDuration = 0;
  916. const userId = queue[queue.length - 1].requestedBy;
  917. station.queue.forEach((song) => {
  918. if (userId === song.requestedBy) {
  919. totalDuration += song.duration;
  920. }
  921. });
  922. if(totalDuration >= 900) return next('The max length of songs per user is 15 minutes.');
  923. next(null, song, station);
  924. },
  925. (song, station, next) => {
  926. let queue = station.queue;
  927. if (queue.length === 0) return next(null, song);
  928. let totalSongs = 0;
  929. const userId = queue[queue.length - 1].requestedBy;
  930. queue.forEach((song) => {
  931. if (userId === song.requestedBy) {
  932. totalSongs++;
  933. }
  934. });
  935. if (totalSongs <= 2) return next(null, song);
  936. if (totalSongs > 3) return next('The max amount of songs per user is 3, and only 2 in a row is allowed.');
  937. 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.');
  938. next(null, song);
  939. },
  940. (song, next) => {
  941. db.models.station.updateOne({_id: stationId}, {$push: {queue: song}}, {runValidators: true}, next);
  942. },
  943. (res, next) => {
  944. stations.updateStation(stationId, next);
  945. }
  946. ], (err, station) => {
  947. if (err) {
  948. err = utils.getError(err);
  949. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  950. return cb({'status': 'failure', 'message': err});
  951. }
  952. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  953. cache.pub('station.queueUpdate', stationId);
  954. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  955. });
  956. }),
  957. /**
  958. * Removes song from station queue
  959. *
  960. * @param session
  961. * @param stationId - the station id
  962. * @param songId - the song id
  963. * @param cb
  964. * @param userId
  965. */
  966. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  967. async.waterfall([
  968. (next) => {
  969. if (!songId) return next('Invalid song id.');
  970. stations.getStation(stationId, next);
  971. },
  972. (station, next) => {
  973. if (!station) return next('Station not found.');
  974. if (station.type !== 'community') return next('Station is not a community station.');
  975. async.each(station.queue, (queueSong, next) => {
  976. if (queueSong.songId === songId) return next(true);
  977. next();
  978. }, (err) => {
  979. if (err === true) return next();
  980. next('Song is not currently in the queue.');
  981. });
  982. },
  983. (next) => {
  984. db.models.station.updateOne({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  985. },
  986. (res, next) => {
  987. stations.updateStation(stationId, next);
  988. }
  989. ], (err, station) => {
  990. if (err) {
  991. err = utils.getError(err);
  992. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  993. return cb({'status': 'failure', 'message': err});
  994. }
  995. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  996. cache.pub('station.queueUpdate', stationId);
  997. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  998. });
  999. }),
  1000. /**
  1001. * Gets the queue from a station
  1002. *
  1003. * @param session
  1004. * @param stationId - the station id
  1005. * @param cb
  1006. */
  1007. getQueue: (session, stationId, cb) => {
  1008. async.waterfall([
  1009. (next) => {
  1010. stations.getStation(stationId, next);
  1011. },
  1012. (station, next) => {
  1013. if (!station) return next('Station not found.');
  1014. if (station.type !== 'community') return next('Station is not a community station.');
  1015. next(null, station);
  1016. },
  1017. (station, next) => {
  1018. utils.canUserBeInStation(station, session.userId, (canBe) => {
  1019. if (canBe) return next(null, station);
  1020. return next('Insufficient permissions.');
  1021. });
  1022. }
  1023. ], (err, station) => {
  1024. if (err) {
  1025. err = utils.getError(err);
  1026. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  1027. return cb({'status': 'failure', 'message': err});
  1028. }
  1029. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1030. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  1031. });
  1032. },
  1033. /**
  1034. * Selects a private playlist for a station
  1035. *
  1036. * @param session
  1037. * @param stationId - the station id
  1038. * @param playlistId - the private playlist id
  1039. * @param cb
  1040. * @param userId
  1041. */
  1042. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  1043. async.waterfall([
  1044. (next) => {
  1045. stations.getStation(stationId, next);
  1046. },
  1047. (station, next) => {
  1048. if (!station) return next('Station not found.');
  1049. if (station.type !== 'community') return next('Station is not a community station.');
  1050. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  1051. db.models.playlist.findOne({_id: playlistId}, next);
  1052. },
  1053. (playlist, next) => {
  1054. if (!playlist) return next('Playlist not found.');
  1055. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  1056. db.models.station.updateOne({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, {runValidators: true}, next);
  1057. },
  1058. (res, next) => {
  1059. stations.updateStation(stationId, next);
  1060. }
  1061. ], (err, station) => {
  1062. if (err) {
  1063. err = utils.getError(err);
  1064. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  1065. return cb({'status': 'failure', 'message': err});
  1066. }
  1067. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  1068. notifications.unschedule(`stations.nextSong?id${stationId}`);
  1069. if (!station.partyMode) stations.skipStation(stationId)();
  1070. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  1071. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  1072. });
  1073. }),
  1074. };