stations.js 19 KB

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