stations.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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(`Insufficient permissions.`);
  91. cache.hget('sessions', session.sessionId, next);
  92. },
  93. (session, next) => {
  94. if (!session) return next(`Insufficient permissions.`);
  95. db.models.user.findOne({_id: session.userId}, next);
  96. },
  97. (user, next) => {
  98. if (!user) return next(`Insufficient permissions.`);
  99. if (user.role === 'admin') return next(true);
  100. if (station.type === 'official') return next(`Insufficient permissions.`);
  101. if (station.owner === session.userId) return next(true);
  102. next(`Insufficient permissions.`);
  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 name
  124. *
  125. * @param session
  126. * @param stationName - the station name
  127. * @param cb
  128. */
  129. findByName: (session, stationName, cb) => {
  130. async.waterfall([
  131. (next) => {
  132. stations.getStationByName(stationName, 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_BY_NAME", `Finding station "${stationName}" failed. "${err}"`);
  142. return cb({'status': 'failure', 'message': err});
  143. }
  144. logger.success("STATIONS_FIND_BY_NAME", `Found station "${stationName}" 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 name
  184. *
  185. * @param session
  186. * @param stationName - the station name
  187. * @param cb
  188. * @return {{ status: String, userCount: Integer }}
  189. */
  190. join: (session, stationName, cb) => {
  191. async.waterfall([
  192. (next) => {
  193. stations.getStationByName(stationName, 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.${station._id}`);
  220. let data = {
  221. _id: station._id,
  222. type: station.type,
  223. currentSong: station.currentSong,
  224. startedAt: station.startedAt,
  225. paused: station.paused,
  226. timePaused: station.timePaused,
  227. description: station.description,
  228. displayName: station.displayName,
  229. privacy: station.privacy,
  230. partyMode: station.partyMode,
  231. owner: station.owner,
  232. privatePlaylist: station.privatePlaylist
  233. };
  234. next(null, data);
  235. },
  236. (data, next) => {
  237. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  238. utils.socketJoinSongRoom(session.socketId, `song.${data.currentSong.songId}`);
  239. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  240. songs.getSong(data.currentSong.songId, (err, song) => {
  241. if (!err && song) {
  242. data.currentSong.likes = song.likes;
  243. data.currentSong.dislikes = song.dislikes;
  244. } else {
  245. data.currentSong.likes = -1;
  246. data.currentSong.dislikes = -1;
  247. }
  248. next(null, data);
  249. });
  250. }
  251. ], (err, data) => {
  252. if (err) {
  253. err = utils.getError(err);
  254. logger.error("STATIONS_JOIN", `Joining station "${stationName}" failed. "${err}"`);
  255. return cb({'status': 'failure', 'message': err});
  256. }
  257. logger.success("STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  258. cb({status: 'success', data});
  259. });
  260. },
  261. /**
  262. * Votes to skip a station
  263. *
  264. * @param session
  265. * @param stationId - the station id
  266. * @param cb
  267. * @param userId
  268. */
  269. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  270. async.waterfall([
  271. (next) => {
  272. stations.getStation(stationId, next);
  273. },
  274. (station, next) => {
  275. if (!station) return next('Station not found.');
  276. if (!station.currentSong) return next('There is currently no song to skip.');
  277. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return next('You have already voted to skip this song.');
  278. next(null, station);
  279. },
  280. (station, next) => {
  281. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, next)
  282. },
  283. (res, next) => {
  284. stations.updateStation(stationId, next);
  285. },
  286. (station, next) => {
  287. if (!station) return next('Station not found.');
  288. next(null, station);
  289. }
  290. ], (err, station) => {
  291. if (err) {
  292. err = utils.getError(err);
  293. logger.error("STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  294. return cb({'status': 'failure', 'message': err});
  295. }
  296. logger.success("STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  297. cache.pub('station.voteSkipSong', stationId);
  298. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  299. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  300. });
  301. }),
  302. /**
  303. * Force skips a station
  304. *
  305. * @param session
  306. * @param stationId - the station id
  307. * @param cb
  308. */
  309. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  310. async.waterfall([
  311. (next) => {
  312. stations.getStation(stationId, next);
  313. },
  314. (station, next) => {
  315. if (!station) return next('Station not found.');
  316. next();
  317. }
  318. ], (err) => {
  319. if (err) {
  320. err = utils.getError(err);
  321. logger.error("STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  322. return cb({'status': 'failure', 'message': err});
  323. }
  324. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  325. stations.skipStation(stationId)();
  326. logger.success("STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  327. return cb({'status': 'success', 'message': 'Successfully skipped station.'});
  328. });
  329. }),
  330. /**
  331. * Leaves the user's current station
  332. *
  333. * @param session
  334. * @param stationId
  335. * @param cb
  336. * @return {{ status: String, userCount: Integer }}
  337. */
  338. leave: (session, stationId, cb) => {
  339. async.waterfall([
  340. (next) => {
  341. stations.getStation(stationId, next);
  342. },
  343. (station, next) => {
  344. if (!station) return next('Station not found.');
  345. next();
  346. },
  347. (next) => {
  348. cache.client.hincrby('station.userCounts', stationId, -1, next);
  349. }
  350. ], (err, userCount) => {
  351. if (err) {
  352. err = utils.getError(err);
  353. logger.error("STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  354. return cb({'status': 'failure', 'message': err});
  355. }
  356. logger.success("STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  357. utils.socketLeaveRooms(session);
  358. return cb({'status': 'success', 'message': 'Successfully left station.', userCount});
  359. });
  360. },
  361. /**
  362. * Updates a station's name
  363. *
  364. * @param session
  365. * @param stationId - the station id
  366. * @param newName - the new station name
  367. * @param cb
  368. */
  369. updateName: hooks.ownerRequired((session, stationId, newName, cb) => {
  370. async.waterfall([
  371. (next) => {
  372. db.models.station.update({_id: stationId}, {$set: {name: newName}}, next);
  373. },
  374. (res, next) => {
  375. stations.updateStation(stationId, next);
  376. }
  377. ], (err) => {
  378. if (err) {
  379. err = utils.getError(err);
  380. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newName}" failed. "${err}"`);
  381. return cb({'status': 'failure', 'message': err});
  382. }
  383. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newName}" successfully.`);
  384. return cb({'status': 'success', 'message': 'Successfully updated the name.'});
  385. });
  386. }),
  387. /**
  388. * Updates a station's display name
  389. *
  390. * @param session
  391. * @param stationId - the station id
  392. * @param newDisplayName - the new station display name
  393. * @param cb
  394. */
  395. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  396. async.waterfall([
  397. (next) => {
  398. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, next);
  399. },
  400. (res, next) => {
  401. stations.updateStation(stationId, next);
  402. }
  403. ], (err) => {
  404. if (err) {
  405. err = utils.getError(err);
  406. logger.error("STATIONS_UPDATE_DISPLAY_NAME", `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`);
  407. return cb({'status': 'failure', 'message': err});
  408. }
  409. logger.success("STATIONS_UPDATE_DISPLAY_NAME", `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`);
  410. return cb({'status': 'success', 'message': 'Successfully updated the display name.'});
  411. });
  412. }),
  413. /**
  414. * Updates a station's description
  415. *
  416. * @param session
  417. * @param stationId - the station id
  418. * @param newDescription - the new station description
  419. * @param cb
  420. */
  421. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  422. async.waterfall([
  423. (next) => {
  424. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, next);
  425. },
  426. (res, next) => {
  427. stations.updateStation(stationId, next);
  428. }
  429. ], (err) => {
  430. if (err) {
  431. err = utils.getError(err);
  432. logger.error("STATIONS_UPDATE_DESCRIPTION", `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`);
  433. return cb({'status': 'failure', 'message': err});
  434. }
  435. logger.success("STATIONS_UPDATE_DESCRIPTION", `Updated station "${stationId}" description to "${newDescription}" successfully.`);
  436. return cb({'status': 'success', 'message': 'Successfully updated the description.'});
  437. });
  438. }),
  439. /**
  440. * Updates a station's privacy
  441. *
  442. * @param session
  443. * @param stationId - the station id
  444. * @param newPrivacy - the new station privacy
  445. * @param cb
  446. */
  447. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  448. async.waterfall([
  449. (next) => {
  450. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, next);
  451. },
  452. (res, next) => {
  453. stations.updateStation(stationId, next);
  454. }
  455. ], (err) => {
  456. if (err) {
  457. err = utils.getError(err);
  458. logger.error("STATIONS_UPDATE_PRIVACY", `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`);
  459. return cb({'status': 'failure', 'message': err});
  460. }
  461. logger.success("STATIONS_UPDATE_PRIVACY", `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`);
  462. return cb({'status': 'success', 'message': 'Successfully updated the privacy.'});
  463. });
  464. }),
  465. /**
  466. * Updates a station's party mode
  467. *
  468. * @param session
  469. * @param stationId - the station id
  470. * @param newPartyMode - the new station party mode
  471. * @param cb
  472. */
  473. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  474. async.waterfall([
  475. (next) => {
  476. stations.getStation(stationId, next);
  477. },
  478. (station, next) => {
  479. if (!station) return next('Station not found.');
  480. if (station.partyMode === newPartyMode) return next('The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.'));
  481. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, next);
  482. },
  483. (res, next) => {
  484. stations.updateStation(stationId, next);
  485. }
  486. ], (err) => {
  487. if (err) {
  488. err = utils.getError(err);
  489. logger.error("STATIONS_UPDATE_PARTY_MODE", `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`);
  490. return cb({'status': 'failure', 'message': err});
  491. }
  492. logger.success("STATIONS_UPDATE_PARTY_MODE", `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`);
  493. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  494. stations.skipStation(stationId)();
  495. return cb({'status': 'success', 'message': 'Successfully updated the party mode.'});
  496. });
  497. }),
  498. /**
  499. * Pauses a station
  500. *
  501. * @param session
  502. * @param stationId - the station id
  503. * @param cb
  504. */
  505. pause: hooks.ownerRequired((session, stationId, cb) => {
  506. async.waterfall([
  507. (next) => {
  508. stations.getStation(stationId, next);
  509. },
  510. (station, next) => {
  511. if (!station) return next('Station not found.');
  512. if (station.paused) return next('That station was already paused.');
  513. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, 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_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  522. return cb({'status': 'failure', 'message': err});
  523. }
  524. logger.success("STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  525. cache.pub('station.pause', stationId);
  526. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  527. return cb({'status': 'success', 'message': 'Successfully paused.'});
  528. });
  529. }),
  530. /**
  531. * Resumes a station
  532. *
  533. * @param session
  534. * @param stationId - the station id
  535. * @param cb
  536. */
  537. resume: hooks.ownerRequired((session, stationId, cb) => {
  538. async.waterfall([
  539. (next) => {
  540. stations.getStation(stationId, next);
  541. },
  542. (station, next) => {
  543. if (!station) return next('Station not found.');
  544. if (!station.paused) return next('That station is not paused.');
  545. station.timePaused += (Date.now() - station.pausedAt);
  546. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, next);
  547. },
  548. (next) => {
  549. stations.updateStation(stationId, next);
  550. }
  551. ], (err) => {
  552. if (err) {
  553. err = utils.getError(err);
  554. logger.error("STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  555. return cb({'status': 'failure', 'message': err});
  556. }
  557. logger.success("STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  558. cache.pub('station.resume', stationId);
  559. return cb({'status': 'success', 'message': 'Successfully resumed.'});
  560. });
  561. }),
  562. /**
  563. * Removes a station
  564. *
  565. * @param session
  566. * @param stationId - the station id
  567. * @param cb
  568. */
  569. remove: hooks.ownerRequired((session, stationId, cb) => {
  570. async.waterfall([
  571. (next) => {
  572. db.models.station.remove({ _id: stationId }, err => next(err));
  573. },
  574. (next) => {
  575. cache.hdel('stations', stationId, err => next(err));
  576. }
  577. ], (err) => {
  578. if (err) {
  579. err = utils.getError(err);
  580. logger.error("STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  581. return cb({ 'status': 'failure', 'message': err });
  582. }
  583. logger.success("STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  584. cache.pub('station.remove', stationId);
  585. return cb({ 'status': 'success', 'message': 'Successfully removed.' });
  586. });
  587. }),
  588. /**
  589. * Create a station
  590. *
  591. * @param session
  592. * @param data - the station data
  593. * @param cb
  594. * @param userId
  595. */
  596. create: hooks.loginRequired((session, data, cb, userId) => {
  597. console.log(data);
  598. data.name = data.name.toLowerCase();
  599. 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"];
  600. async.waterfall([
  601. (next) => {
  602. if (!data) return next('Invalid data.');
  603. next();
  604. },
  605. (next) => {
  606. db.models.station.findOne({ $or: [{name: data.name}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  607. },
  608. (station, next) => {
  609. if (station) return next('A station with that name or display name already exists.');
  610. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  611. if (type === 'official') {
  612. db.models.user.findOne({_id: userId}, (err, user) => {
  613. if (err) return next(err);
  614. if (!user) return next('User not found.');
  615. if (user.role !== 'admin') return next('Admin required.');
  616. db.models.station.create({
  617. name,
  618. displayName,
  619. description,
  620. type,
  621. privacy: 'private',
  622. playlist,
  623. genres,
  624. blacklistedGenres,
  625. currentSong: stations.defaultSong
  626. }, next);
  627. });
  628. } else if (type === 'community') {
  629. if (blacklist.indexOf(name) !== -1) return next('That name is blacklisted. Please use a different name.');
  630. db.models.station.create({
  631. name,
  632. displayName,
  633. description,
  634. type,
  635. privacy: 'private',
  636. owner: userId,
  637. queue: [],
  638. currentSong: null
  639. }, next);
  640. }
  641. }
  642. ], (err, station) => {
  643. if (err) {
  644. console.log(err);
  645. err = utils.getError(err);
  646. logger.error("STATIONS_CREATE", `Creating station failed. "${err}"`);
  647. return cb({'status': 'failure', 'message': err});
  648. }
  649. logger.success("STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  650. cache.pub('station.create', station._id);
  651. return cb({'status': 'success', 'message': 'Successfully created station.'});
  652. });
  653. }),
  654. /**
  655. * Adds song to station queue
  656. *
  657. * @param session
  658. * @param stationId - the station id
  659. * @param songId - the song id
  660. * @param cb
  661. * @param userId
  662. */
  663. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  664. async.waterfall([
  665. (next) => {
  666. stations.getStation(stationId, next);
  667. },
  668. (station, next) => {
  669. if (!station) return next('Station not found.');
  670. if (station.type !== 'community') return next('That station is not a community station.');
  671. if (station.currentSong && station.currentSong.songId === songId) return next('That song is currently playing.');
  672. async.each(station.queue, (queueSong, next) => {
  673. if (queueSong.songId === songId) return next('That song is already in the queue.');
  674. next();
  675. }, (err) => {
  676. next(err, station);
  677. });
  678. },
  679. (station, next) => {
  680. songs.getSong(songId, (err, song) => {
  681. if (!err && song) return next(null, song);
  682. console.log(53, songId);
  683. utils.getSongFromYouTube(songId, (song) => {
  684. song.artists = [];
  685. song.skipDuration = 0;
  686. song.likes = -1;
  687. song.dislikes = -1;
  688. song.thumbnail = "empty";
  689. song.explicit = false;
  690. next(null, song);
  691. });
  692. });
  693. },
  694. (song, next) => {
  695. song.requestedBy = userId;
  696. db.models.station.update({_id: stationId}, {$push: {queue: song}}, next);
  697. },
  698. (res, next) => {
  699. stations.updateStation(stationId, next);
  700. }
  701. ], (err, station) => {
  702. if (err) {
  703. err = utils.getError(err);
  704. logger.error("STATIONS_ADD_SONG_TO_QUEUE", `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`);
  705. return cb({'status': 'failure', 'message': err});
  706. }
  707. logger.success("STATIONS_ADD_SONG_TO_QUEUE", `Added song "${songId}" to station "${stationId}" successfully.`);
  708. cache.pub('station.queueUpdate', stationId);
  709. return cb({'status': 'success', 'message': 'Successfully added song to queue.'});
  710. });
  711. }),
  712. /**
  713. * Removes song from station queue
  714. *
  715. * @param session
  716. * @param stationId - the station id
  717. * @param songId - the song id
  718. * @param cb
  719. * @param userId
  720. */
  721. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  722. async.waterfall([
  723. (next) => {
  724. if (!songId) return next('Invalid song id.');
  725. stations.getStation(stationId, next);
  726. },
  727. (station, next) => {
  728. if (!station) return next('Station not found.');
  729. if (station.type !== 'community') return next('Station is not a community station.');
  730. async.each(station.queue, (queueSong, next) => {
  731. if (queueSong.songId === songId) return next(true);
  732. next();
  733. }, (err) => {
  734. if (err === true) return next();
  735. next('Song is not currently in the queue.');
  736. });
  737. },
  738. (next) => {
  739. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, next);
  740. },
  741. (next) => {
  742. stations.updateStation(stationId, next);
  743. }
  744. ], (err, station) => {
  745. if (err) {
  746. err = utils.getError(err);
  747. logger.error("STATIONS_REMOVE_SONG_TO_QUEUE", `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`);
  748. return cb({'status': 'failure', 'message': err});
  749. }
  750. logger.success("STATIONS_REMOVE_SONG_TO_QUEUE", `Removed song "${songId}" from station "${stationId}" successfully.`);
  751. cache.pub('station.queueUpdate', stationId);
  752. return cb({'status': 'success', 'message': 'Successfully removed song from queue.'});
  753. });
  754. }),
  755. /**
  756. * Gets the queue from a station
  757. *
  758. * @param session
  759. * @param stationId - the station id
  760. * @param cb
  761. */
  762. getQueue: hooks.adminRequired((session, stationId, cb) => {
  763. async.waterfall([
  764. (next) => {
  765. stations.getStation(stationId, next);
  766. },
  767. (station, next) => {
  768. if (!station) return next('Station not found.');
  769. if (station.type !== 'community') return next('Station is not a community station.');
  770. next(null, station);
  771. }
  772. ], (err, station) => {
  773. if (err) {
  774. err = utils.getError(err);
  775. logger.error("STATIONS_GET_QUEUE", `Getting queue for station "${stationId}" failed. "${err}"`);
  776. return cb({'status': 'failure', 'message': err});
  777. }
  778. logger.success("STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  779. return cb({'status': 'success', 'message': 'Successfully got queue.', queue: station.queue});
  780. });
  781. }),
  782. /**
  783. * Selects a private playlist for a station
  784. *
  785. * @param session
  786. * @param stationId - the station id
  787. * @param playlistId - the private playlist id
  788. * @param cb
  789. * @param userId
  790. */
  791. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  792. async.waterfall([
  793. (next) => {
  794. stations.getStation(stationId, next);
  795. },
  796. (station, next) => {
  797. if (!station) return next('Station not found.');
  798. if (station.type !== 'community') return next('Station is not a community station.');
  799. if (station.privatePlaylist === playlistId) return next('That private playlist is already selected.');
  800. db.models.playlist.findOne({_id: playlistId}, next);
  801. },
  802. (playlist, next) => {
  803. if (!playlist) return next('Playlist not found.');
  804. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  805. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: currentSongIndex}}, next);
  806. },
  807. (res, next) => {
  808. stations.updateStation(stationId, next);
  809. }
  810. ], (err, station) => {
  811. if (err) {
  812. err = utils.getError(err);
  813. logger.error("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`);
  814. return cb({'status': 'failure', 'message': err});
  815. }
  816. logger.success("STATIONS_SELECT_PRIVATE_PLAYLIST", `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`);
  817. if (!station.partyMode) stations.skipStation(stationId)();
  818. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  819. return cb({'status': 'success', 'message': 'Successfully selected playlist.'});
  820. });
  821. }),
  822. };