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