stations.js 30 KB

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