stations.js 21 KB

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