stations.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 stations = require('../stations');
  11. const songs = require('../songs');
  12. const hooks = require('./hooks');
  13. cache.sub('station.updatePartyMode', data => {
  14. utils.emitToRoom(`station.${data.stationId}`, "event:partyMode.updated", data.partyMode);
  15. });
  16. cache.sub('privatePlaylist.selected', data => {
  17. utils.emitToRoom(`station.${data.stationId}`, "event:privatePlaylist.selected", data.playlistId);
  18. });
  19. cache.sub('station.pause', stationId => {
  20. utils.emitToRoom(`station.${stationId}`, "event:stations.pause");
  21. });
  22. cache.sub('station.resume', stationId => {
  23. stations.getStation(stationId, (err, station) => {
  24. utils.emitToRoom(`station.${stationId}`, "event:stations.resume", { timePaused: station.timePaused });
  25. });
  26. });
  27. cache.sub('station.queueUpdate', stationId => {
  28. stations.getStation(stationId, (err, station) => {
  29. if (!err) {
  30. utils.emitToRoom(`station.${stationId}`, "event:queue.update", station.queue);
  31. }
  32. });
  33. });
  34. cache.sub('station.voteSkipSong', stationId => {
  35. utils.emitToRoom(`station.${stationId}`, "event:song.voteSkipSong");
  36. });
  37. cache.sub('station.remove', stationId => {
  38. utils.emitToRoom('admin.stations', 'event:admin.station.removed', stationId);
  39. });
  40. cache.sub('station.create', stationId => {
  41. stations.initializeStation(stationId, (err, station) => {
  42. if (err) console.error(err);
  43. utils.emitToRoom('admin.stations', 'event:admin.station.added', station);
  44. // TODO If community, check if on whitelist
  45. if (station.privacy === 'public') utils.emitToRoom('home', "event:stations.created", station);
  46. else {
  47. let sockets = utils.getRoomSockets('home');
  48. for (let socketId in sockets) {
  49. let socket = sockets[socketId];
  50. let session = sockets[socketId].session;
  51. if (session.sessionId) {
  52. cache.hget('sessions', session.sessionId, (err, session) => {
  53. if (!err && session) {
  54. db.models.user.findOne({_id: session.userId}, (err, user) => {
  55. if (user.role === 'admin') socket.emit("event:stations.created", station);
  56. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:stations.created", station);
  57. });
  58. }
  59. });
  60. }
  61. }
  62. }
  63. });
  64. });
  65. module.exports = {
  66. /**
  67. * Get a list of all the stations
  68. *
  69. * @param session
  70. * @param cb
  71. * @return {{ status: String, stations: Array }}
  72. */
  73. index: (session, cb) => {
  74. cache.hgetall('stations', (err, stations) => {
  75. if (err && err !== true) {
  76. return cb({
  77. status: 'error',
  78. message: 'An error occurred while obtaining the stations'
  79. });
  80. }
  81. let arr = [];
  82. let done = 0;
  83. for (let prop in stations) {
  84. // TODO If community, check if on whitelist
  85. let station = stations[prop];
  86. if (station.privacy === 'public') add(true, station);
  87. else if (!session.sessionId) add(false);
  88. else {
  89. cache.hget('sessions', session.sessionId, (err, session) => {
  90. if (err || !session) {
  91. add(false);
  92. } else {
  93. db.models.user.findOne({_id: session.userId}, (err, user) => {
  94. if (err || !user) add(false);
  95. else if (user.role === 'admin') add(true, station);
  96. else if (station.type === 'official') add(false);
  97. else if (station.owner === session.userId) add(true, station);
  98. else add(false);
  99. });
  100. }
  101. });
  102. }
  103. }
  104. function add(add, station) {
  105. if (add) arr.push(station);
  106. done++;
  107. if (done === Object.keys(stations).length) {
  108. cb({ status: 'success', stations: arr });
  109. }
  110. }
  111. });
  112. },
  113. find: (session, stationId, cb) => {
  114. stations.getStation(stationId, (err, station) => {
  115. if (err) cb({ status: 'error', message: err });
  116. else if (station) cb({ status: 'success', data: station });
  117. });
  118. },
  119. getPlaylist: (session, stationId, cb) => {
  120. let playlist = [];
  121. stations.getStation(stationId, (err, station) => {
  122. for (let s = 1; s < station.playlist.length; s++) {
  123. songs.getSong(station.playlist[s], (err, song) => {
  124. playlist.push(song);
  125. });
  126. }
  127. });
  128. cb({ status: 'success', data: playlist })
  129. },
  130. /**
  131. * Joins the station by its id
  132. *
  133. * @param session
  134. * @param stationId - the station id
  135. * @param cb
  136. * @return {{ status: String, userCount: Integer }}
  137. */
  138. join: (session, stationId, cb) => {
  139. stations.getStation(stationId, (err, station) => {
  140. if (err && err !== true) return cb({ status: 'error', message: 'An error occurred while joining the station' });
  141. if (station) {
  142. if (station.privacy !== 'private') {
  143. func();
  144. } else {
  145. // TODO If community, check if on whitelist
  146. if (!session.userId) return cb({ status: 'error', message: 'An error occurred while joining the station1' });
  147. db.models.user.findOne({_id: session.userId}, (err, user) => {
  148. if (err || !user) return cb({ status: 'error', message: 'An error occurred while joining the station2' });
  149. if (user.role === 'admin') return func();
  150. if (station.type === 'official') return cb({ status: 'error', message: 'An error occurred while joining the station3' });
  151. if (station.owner === session.userId) return func();
  152. return cb({ status: 'error', message: 'An error occurred while joining the station4' });
  153. });
  154. }
  155. function func() {
  156. utils.socketJoinRoom(session.socketId, `station.${stationId}`);
  157. if (station.currentSong) {
  158. utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
  159. //TODO Emit to cache, listen on cache
  160. songs.getSong(station.currentSong._id, (err, song) => {
  161. if (!err && song) {
  162. station.currentSong.likes = song.likes;
  163. station.currentSong.dislikes = song.dislikes;
  164. } else {
  165. station.currentSong.likes = -1;
  166. station.currentSong.dislikes = -1;
  167. }
  168. station.currentSong.skipVotes = station.currentSong.skipVotes.length;
  169. cb({
  170. status: 'success',
  171. data: {
  172. type: station.type,
  173. currentSong: station.currentSong,
  174. startedAt: station.startedAt,
  175. paused: station.paused,
  176. timePaused: station.timePaused,
  177. description: station.description,
  178. displayName: station.displayName,
  179. privacy: station.privacy,
  180. partyMode: station.partyMode,
  181. owner: station.owner,
  182. privatePlaylist: station.privatePlaylist
  183. }
  184. });
  185. });
  186. } else {
  187. cb({
  188. status: 'success',
  189. data: {
  190. type: station.type,
  191. currentSong: null,
  192. startedAt: station.startedAt,
  193. paused: station.paused,
  194. timePaused: station.timePaused,
  195. description: station.description,
  196. displayName: station.displayName,
  197. privacy: station.privacy,
  198. partyMode: station.partyMode,
  199. owner: station.owner,
  200. privatePlaylist: station.privatePlaylist
  201. }
  202. });
  203. }
  204. }
  205. } else {
  206. cb({ status: 'failure', message: `That station doesn't exist` });
  207. }
  208. });
  209. },
  210. /**
  211. * Skips the users current station
  212. *
  213. * @param session
  214. * @param stationId - the station id
  215. * @param cb
  216. */
  217. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  218. stations.getStation(stationId, (err, station) => {
  219. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  220. if (!station.currentSong) return cb({ status: 'failure', message: 'There is currently no song to skip.' });
  221. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return cb({ status: 'failure', message: 'You have already voted to skip this song.' });
  222. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, (err) => {
  223. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  224. stations.updateStation(stationId, (err, station) => {
  225. cache.pub('station.voteSkipSong', stationId);
  226. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  227. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  228. })
  229. });
  230. });
  231. }),
  232. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  233. stations.getStation(stationId, (err, station) => {
  234. if (err && err !== true) {
  235. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  236. }
  237. if (station) {
  238. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  239. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  240. stations.skipStation(stationId)();
  241. }
  242. else {
  243. cb({ status: 'failure', message: `That station doesn't exist` });
  244. }
  245. });
  246. }),
  247. /**
  248. * Leaves the users current station
  249. *
  250. * @param session
  251. * @param stationId
  252. * @param cb
  253. * @return {{ status: String, userCount: Integer }}
  254. */
  255. leave: (session, stationId, cb) => {
  256. stations.getStation(stationId, (err, station) => {
  257. if (err && err !== true) {
  258. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  259. }
  260. if (session) session.stationId = null;
  261. else if (station) {
  262. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  263. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  264. utils.socketLeaveRooms(session);
  265. cb({ status: 'success', userCount });
  266. });
  267. } else {
  268. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  269. }
  270. });
  271. },
  272. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  273. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, (err) => {
  274. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  275. stations.updateStation(stationId, () => {
  276. //TODO Pub/sub for displayName change
  277. cb({ status: 'success', message: 'Successfully updated the display name.' });
  278. })
  279. });
  280. }),
  281. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  282. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, (err) => {
  283. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  284. stations.updateStation(stationId, () => {
  285. //TODO Pub/sub for description change
  286. cb({ status: 'success', message: 'Successfully updated the description.' });
  287. })
  288. });
  289. }),
  290. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  291. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, (err) => {
  292. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  293. stations.updateStation(stationId, () => {
  294. //TODO Pub/sub for privacy change
  295. cb({ status: 'success', message: 'Successfully updated the privacy.' });
  296. })
  297. });
  298. }),
  299. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  300. stations.getStation(stationId, (err, station) => {
  301. if (err) return cb({ status: 'failure', message: err });
  302. if (station.partyMode === newPartyMode) return cb({ status: 'failure', message: 'The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.') });
  303. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, (err) => {
  304. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  305. stations.updateStation(stationId, () => {
  306. //TODO Pub/sub for privacy change
  307. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  308. stations.skipStation(stationId)();
  309. cb({ status: 'success', message: 'Successfully updated the party mode.' });
  310. })
  311. });
  312. });
  313. }),
  314. pause: hooks.ownerRequired((session, stationId, cb) => {
  315. stations.getStation(stationId, (err, station) => {
  316. if (err && err !== true) {
  317. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  318. } else if (station) {
  319. if (!station.paused) {
  320. station.paused = true;
  321. station.pausedAt = Date.now();
  322. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  323. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  324. stations.updateStation(stationId, () => {
  325. cache.pub('station.pause', stationId);
  326. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  327. cb({ status: 'success' });
  328. });
  329. });
  330. } else {
  331. cb({ status: 'failure', message: 'That station was already paused.' });
  332. }
  333. cb({ status: 'success' });
  334. } else {
  335. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  336. }
  337. });
  338. }),
  339. resume: hooks.ownerRequired((session, stationId, cb) => {
  340. stations.getStation(stationId, (err, station) => {
  341. if (err && err !== true) return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  342. else if (station) {
  343. if (station.paused) {
  344. station.paused = false;
  345. station.timePaused += (Date.now() - station.pausedAt);
  346. db.models.station.update({ _id: stationId }, { $set: { paused: false }, $inc: { timePaused: Date.now() - station.pausedAt } }, () => {
  347. stations.updateStation(stationId, (err, station) => {
  348. cache.pub('station.resume', stationId);
  349. cb({ status: 'success' });
  350. });
  351. });
  352. } else cb({ status: 'failure', message: 'That station is not paused.' });
  353. } else cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  354. });
  355. }),
  356. remove: hooks.ownerRequired((session, stationId, cb) => {
  357. db.models.station.remove({ _id: stationId }, (err) => {
  358. if (err) return cb({ status: 'failure', message: 'Something went wrong when deleting that station' });
  359. cache.hdel('stations', stationId, () => {
  360. cache.pub('station.remove', stationId);
  361. return cb({ status: 'success', message: 'Station successfully removed' });
  362. });
  363. });
  364. }),
  365. create: hooks.loginRequired((session, data, cb) => {
  366. data._id = data._id.toLowerCase();
  367. 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"];
  368. async.waterfall([
  369. (next) => {
  370. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  371. },
  372. (next) => {
  373. db.models.station.findOne({ $or: [{_id: data._id}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  374. },
  375. (station, next) => {
  376. if (station) return next({ 'status': 'failure', 'message': 'A station with that name or display name already exists' });
  377. const { _id, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  378. cache.hget('sessions', session.sessionId, (err, session) => {
  379. if (type === 'official') {
  380. db.models.user.findOne({_id: session.userId}, (err, user) => {
  381. if (err) return next({ 'status': 'failure', 'message': 'Something went wrong when getting your user info.' });
  382. if (!user) return next({ 'status': 'failure', 'message': 'User not found.' });
  383. if (user.role !== 'admin') return next({ 'status': 'failure', 'message': 'Admin required.' });
  384. db.models.station.create({
  385. _id,
  386. displayName,
  387. description,
  388. type,
  389. privacy: 'private',
  390. playlist,
  391. genres,
  392. blacklistedGenres,
  393. currentSong: stations.defaultSong
  394. }, next);
  395. });
  396. } else if (type === 'community') {
  397. if (blacklist.indexOf(_id) !== -1) return next({ 'status': 'failure', 'message': 'That id is blacklisted. Please use a different id.' });
  398. db.models.station.create({
  399. _id,
  400. displayName,
  401. description,
  402. type,
  403. privacy: 'private',
  404. owner: session.userId,
  405. queue: [],
  406. currentSong: null
  407. }, next);
  408. }
  409. });
  410. }
  411. ], (err, station) => {
  412. if (err) {
  413. console.error(err);
  414. return cb({ 'status': 'failure', 'message': err.message});
  415. } else {
  416. cache.pub('station.create', data._id);
  417. cb({ 'status': 'success', 'message': 'Successfully created station' });
  418. }
  419. });
  420. }),
  421. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  422. stations.getStation(stationId, (err, station) => {
  423. if (err) return cb(err);
  424. if (station.type === 'community') {
  425. let has = false;
  426. station.queue.forEach(queueSong => {
  427. if (queueSong._id === songId) has = true;
  428. });
  429. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue'});
  430. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing'});
  431. songs.getSong(songId, (err, song) => {
  432. if (err) {
  433. utils.getSongFromYouTube(songId, (song) => {
  434. song.artists = [];
  435. song.skipDuration = 0;
  436. song.likes = -1;
  437. song.dislikes = -1;
  438. song.thumbnail = "empty";
  439. song.explicit = false;
  440. cont(song);
  441. });
  442. } else cont(song);
  443. function cont(song) {
  444. db.models.station.update({ _id: stationId }, { $push: { queue: song } }, (err) => {
  445. if (err) return cb({'status': 'failure', 'message': 'Something went wrong'});
  446. stations.updateStation(stationId, (err, station) => {
  447. if (err) return cb(err);
  448. cache.pub('station.queueUpdate', stationId);
  449. cb({ 'status': 'success', 'message': 'Added that song to the queue' });
  450. });
  451. });
  452. }
  453. });
  454. } else cb({'status': 'failure', 'message': 'That station is not a community station'});
  455. });
  456. }),
  457. removeFromQueue: hooks.ownerRequired((session, stationId, songId, cb, userId) => {
  458. stations.getStation(stationId, (err, station) => {
  459. if (err) return cb(err);
  460. if (station.type === 'community') {
  461. let has = false;
  462. station.queue.forEach((queueSong) => {
  463. if (queueSong._id === songId) {
  464. has = true;
  465. }
  466. });
  467. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  468. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  469. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  470. stations.updateStation(stationId, (err, station) => {
  471. if (err) return cb(err);
  472. cache.pub('station.queueUpdate', stationId);
  473. });
  474. });
  475. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  476. });
  477. }),
  478. getQueue: hooks.adminRequired((session, stationId, cb) => {
  479. stations.getStation(stationId, (err, station) => {
  480. if (err) return cb(err);
  481. if (!station) return cb({'status': 'failure', 'message': 'Station not found.'});
  482. if (station.type === 'community') {
  483. cb({'status': 'success', queue: station.queue});
  484. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  485. });
  486. }),
  487. selectPrivatePlaylist: hooks.ownerRequired((session, stationId, playlistId, cb, userId) => {
  488. stations.getStation(stationId, (err, station) => {
  489. if (err) return cb(err);
  490. if (station.type === 'community') {
  491. if (station.privatePlaylist === playlistId) return cb({'status': 'failure', 'message': 'That playlist is already selected.'});
  492. db.models.playlist.findOne({_id: playlistId}, (err, playlist) => {
  493. if (err) return cb(err);
  494. if (playlist) {
  495. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: 0}}, (err) => {
  496. if (err) return cb(err);
  497. stations.updateStation(stationId, (err, station) => {
  498. if (err) return cb(err);
  499. if (!station.partyMode) {
  500. stations.skipStation(stationId)();
  501. }
  502. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  503. cb({'status': 'success', 'message': 'Playlist selected.'});
  504. });
  505. });
  506. } else cb({'status': 'failure', 'message': 'Playlist not found.'});
  507. });
  508. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  509. });
  510. }),
  511. };