stations.js 20 KB

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