stations.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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) return cb({ status: 'failure', message: 'Station not found..' });
  121. if (station.type === 'official') {
  122. cache.hget("officialPlaylists", stationId, (err, playlist) => {
  123. if (err) return cb({ status: 'failure', message: 'Something went wrong when getting the playlist.' });
  124. if (!playlist) return cb({ status: 'failure', message: 'Playlist not found.' });
  125. cb({ status: 'success', data: playlist.songs })
  126. })
  127. } else cb({ status: 'failure', message: 'This is not an official station.' })
  128. });
  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') joinStation();
  143. else {
  144. // TODO If community, check if on whitelist
  145. if (!session.userId) return cb({ status: 'error', message: 'An error occurred while joining the station1' });
  146. db.models.user.findOne({_id: session.userId}, (err, user) => {
  147. if (err || !user) return cb({ status: 'error', message: 'An error occurred while joining the station2' });
  148. if (user.role === 'admin') return joinStation();
  149. if (station.type === 'official') return cb({ status: 'error', message: 'An error occurred while joining the station3' });
  150. if (station.owner === session.userId) return joinStation();
  151. return cb({ status: 'error', message: 'An error occurred while joining the station4' });
  152. });
  153. }
  154. function joinStation() {
  155. utils.socketJoinRoom(session.socketId, `station.${stationId}`);
  156. if (station.currentSong) {
  157. utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
  158. //TODO Emit to cache, listen on cache
  159. songs.getSong(station.currentSong._id, (err, song) => {
  160. if (!err && song) {
  161. station.currentSong.likes = song.likes;
  162. station.currentSong.dislikes = song.dislikes;
  163. } else {
  164. station.currentSong.likes = -1;
  165. station.currentSong.dislikes = -1;
  166. }
  167. station.currentSong.skipVotes = station.currentSong.skipVotes.length;
  168. cb({
  169. status: 'success',
  170. data: {
  171. type: station.type,
  172. currentSong: station.currentSong,
  173. startedAt: station.startedAt,
  174. paused: station.paused,
  175. timePaused: station.timePaused,
  176. description: station.description,
  177. displayName: station.displayName,
  178. privacy: station.privacy,
  179. partyMode: station.partyMode,
  180. owner: station.owner,
  181. privatePlaylist: station.privatePlaylist
  182. }
  183. });
  184. });
  185. } else {
  186. cb({
  187. status: 'success',
  188. data: {
  189. type: station.type,
  190. currentSong: null,
  191. startedAt: station.startedAt,
  192. paused: station.paused,
  193. timePaused: station.timePaused,
  194. description: station.description,
  195. displayName: station.displayName,
  196. privacy: station.privacy,
  197. partyMode: station.partyMode,
  198. owner: station.owner,
  199. privatePlaylist: station.privatePlaylist
  200. }
  201. });
  202. }
  203. }
  204. } else {
  205. cb({ status: 'failure', message: `That station doesn't exist` });
  206. }
  207. });
  208. },
  209. /**
  210. * Skips the users current station
  211. *
  212. * @param session
  213. * @param stationId - the station id
  214. * @param cb
  215. */
  216. voteSkip: hooks.loginRequired((session, stationId, cb, userId) => {
  217. stations.getStation(stationId, (err, station) => {
  218. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  219. if (!station.currentSong) return cb({ status: 'failure', message: 'There is currently no song to skip.' });
  220. if (station.currentSong.skipVotes.indexOf(userId) !== -1) return cb({ status: 'failure', message: 'You have already voted to skip this song.' });
  221. db.models.station.update({_id: stationId}, {$push: {"currentSong.skipVotes": userId}}, (err) => {
  222. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  223. stations.updateStation(stationId, (err, station) => {
  224. cache.pub('station.voteSkipSong', stationId);
  225. if (station.currentSong && station.currentSong.skipVotes.length >= 3) stations.skipStation(stationId)();
  226. cb({ status: 'success', message: 'Successfully voted to skip the song.' });
  227. })
  228. });
  229. });
  230. }),
  231. forceSkip: hooks.ownerRequired((session, stationId, cb) => {
  232. stations.getStation(stationId, (err, station) => {
  233. if (err && err !== true) {
  234. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  235. }
  236. if (station) {
  237. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  238. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  239. stations.skipStation(stationId)();
  240. }
  241. else {
  242. cb({ status: 'failure', message: `That station doesn't exist` });
  243. }
  244. });
  245. }),
  246. /**
  247. * Leaves the users current station
  248. *
  249. * @param session
  250. * @param stationId
  251. * @param cb
  252. * @return {{ status: String, userCount: Integer }}
  253. */
  254. leave: (session, stationId, cb) => {
  255. stations.getStation(stationId, (err, station) => {
  256. if (err && err !== true) {
  257. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  258. }
  259. if (session) session.stationId = null;
  260. else if (station) {
  261. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  262. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  263. utils.socketLeaveRooms(session);
  264. cb({ status: 'success', userCount });
  265. });
  266. } else {
  267. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  268. }
  269. });
  270. },
  271. updateDisplayName: hooks.ownerRequired((session, stationId, newDisplayName, cb) => {
  272. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, (err) => {
  273. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  274. stations.updateStation(stationId, () => {
  275. //TODO Pub/sub for displayName change
  276. cb({ status: 'success', message: 'Successfully updated the display name.' });
  277. })
  278. });
  279. }),
  280. updateDescription: hooks.ownerRequired((session, stationId, newDescription, cb) => {
  281. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, (err) => {
  282. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  283. stations.updateStation(stationId, () => {
  284. //TODO Pub/sub for description change
  285. cb({ status: 'success', message: 'Successfully updated the description.' });
  286. })
  287. });
  288. }),
  289. updatePrivacy: hooks.ownerRequired((session, stationId, newPrivacy, cb) => {
  290. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, (err) => {
  291. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  292. stations.updateStation(stationId, () => {
  293. //TODO Pub/sub for privacy change
  294. cb({ status: 'success', message: 'Successfully updated the privacy.' });
  295. })
  296. });
  297. }),
  298. updatePartyMode: hooks.ownerRequired((session, stationId, newPartyMode, cb) => {
  299. stations.getStation(stationId, (err, station) => {
  300. if (err) return cb({ status: 'failure', message: err });
  301. if (station.partyMode === newPartyMode) return cb({ status: 'failure', message: 'The party mode was already ' + ((newPartyMode) ? 'enabled.' : 'disabled.') });
  302. db.models.station.update({_id: stationId}, {$set: {partyMode: newPartyMode}}, (err) => {
  303. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  304. stations.updateStation(stationId, () => {
  305. //TODO Pub/sub for privacy change
  306. cache.pub('station.updatePartyMode', {stationId: stationId, partyMode: newPartyMode});
  307. stations.skipStation(stationId)();
  308. cb({ status: 'success', message: 'Successfully updated the party mode.' });
  309. })
  310. });
  311. });
  312. }),
  313. pause: hooks.ownerRequired((session, stationId, cb) => {
  314. stations.getStation(stationId, (err, station) => {
  315. if (err && err !== true) {
  316. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  317. } else if (station) {
  318. if (!station.paused) {
  319. station.paused = true;
  320. station.pausedAt = Date.now();
  321. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  322. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  323. stations.updateStation(stationId, () => {
  324. cache.pub('station.pause', stationId);
  325. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  326. cb({ status: 'success' });
  327. });
  328. });
  329. } else {
  330. cb({ status: 'failure', message: 'That station was already paused.' });
  331. }
  332. cb({ status: 'success' });
  333. } else {
  334. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  335. }
  336. });
  337. }),
  338. resume: hooks.ownerRequired((session, stationId, cb) => {
  339. stations.getStation(stationId, (err, station) => {
  340. if (err && err !== true) return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  341. else if (station) {
  342. if (station.paused) {
  343. station.paused = false;
  344. station.timePaused += (Date.now() - station.pausedAt);
  345. db.models.station.update({ _id: stationId }, { $set: { paused: false }, $inc: { timePaused: Date.now() - station.pausedAt } }, () => {
  346. stations.updateStation(stationId, (err, station) => {
  347. cache.pub('station.resume', stationId);
  348. cb({ status: 'success' });
  349. });
  350. });
  351. } else cb({ status: 'failure', message: 'That station is not paused.' });
  352. } else cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  353. });
  354. }),
  355. remove: hooks.ownerRequired((session, stationId, cb) => {
  356. db.models.station.remove({ _id: stationId }, (err) => {
  357. if (err) return cb({ status: 'failure', message: 'Something went wrong when deleting that station' });
  358. cache.hdel('stations', stationId, () => {
  359. cache.pub('station.remove', stationId);
  360. return cb({ status: 'success', message: 'Station successfully removed' });
  361. });
  362. });
  363. }),
  364. create: hooks.loginRequired((session, data, cb) => {
  365. data._id = data._id.toLowerCase();
  366. 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"];
  367. async.waterfall([
  368. (next) => {
  369. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  370. },
  371. (next) => {
  372. db.models.station.findOne({ $or: [{_id: data._id}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  373. },
  374. (station, next) => {
  375. if (station) return next({ 'status': 'failure', 'message': 'A station with that name or display name already exists' });
  376. const { _id, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  377. cache.hget('sessions', session.sessionId, (err, session) => {
  378. if (type === 'official') {
  379. db.models.user.findOne({_id: session.userId}, (err, user) => {
  380. if (err) return next({ 'status': 'failure', 'message': 'Something went wrong when getting your user info.' });
  381. if (!user) return next({ 'status': 'failure', 'message': 'User not found.' });
  382. if (user.role !== 'admin') return next({ 'status': 'failure', 'message': 'Admin required.' });
  383. db.models.station.create({
  384. _id,
  385. displayName,
  386. description,
  387. type,
  388. privacy: 'private',
  389. playlist,
  390. genres,
  391. blacklistedGenres,
  392. currentSong: stations.defaultSong
  393. }, next);
  394. });
  395. } else if (type === 'community') {
  396. if (blacklist.indexOf(_id) !== -1) return next({ 'status': 'failure', 'message': 'That id is blacklisted. Please use a different id.' });
  397. db.models.station.create({
  398. _id,
  399. displayName,
  400. description,
  401. type,
  402. privacy: 'private',
  403. owner: session.userId,
  404. queue: [],
  405. currentSong: null
  406. }, next);
  407. }
  408. });
  409. }
  410. ], (err, station) => {
  411. if (err) {
  412. console.error(err);
  413. return cb({ 'status': 'failure', 'message': err.message});
  414. } else {
  415. cache.pub('station.create', data._id);
  416. cb({ 'status': 'success', 'message': 'Successfully created station' });
  417. }
  418. });
  419. }),
  420. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  421. stations.getStation(stationId, (err, station) => {
  422. if (err) return cb(err);
  423. if (station.type === 'community') {
  424. let has = false;
  425. station.queue.forEach(queueSong => {
  426. if (queueSong._id === songId) has = true;
  427. });
  428. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue'});
  429. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing'});
  430. songs.getSong(songId, (err, song) => {
  431. if (err) {
  432. utils.getSongFromYouTube(songId, (song) => {
  433. song.artists = [];
  434. song.skipDuration = 0;
  435. song.likes = -1;
  436. song.dislikes = -1;
  437. song.thumbnail = "empty";
  438. song.explicit = false;
  439. cont(song);
  440. });
  441. } else cont(song);
  442. function cont(song) {
  443. song.requestedBy = userId;
  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. let currentSongIndex = (playlist.songs.length > 0) ? playlist.songs.length - 1 : 0;
  496. db.models.station.update({_id: stationId}, { $set: { privatePlaylist: playlistId, currentSongIndex: currentSongIndex } }, (err) => {
  497. if (err) return cb(err);
  498. stations.updateStation(stationId, (err, station) => {
  499. if (err) return cb(err);
  500. if (!station.partyMode) stations.skipStation(stationId)();
  501. cache.pub('privatePlaylist.selected', {playlistId, stationId});
  502. cb({'status': 'success', 'message': 'Playlist selected.'});
  503. });
  504. });
  505. } else cb({'status': 'failure', 'message': 'Playlist not found.'});
  506. });
  507. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  508. });
  509. }),
  510. };