stations.js 26 KB

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