stations.js 19 KB

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