stations.js 19 KB

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