stations.js 20 KB

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