stations.js 21 KB

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