stations.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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) {
  132. return cb({ status: 'error', message: 'An error occurred while joining the station' });
  133. }
  134. if (station) {
  135. if (station.privacy !== 'private') {
  136. func();
  137. } else {
  138. // TODO If community, check if on whitelist
  139. if (!session.userId) return cb({ status: 'error', message: 'An error occurred while joining the station1' });
  140. db.models.user.findOne({_id: session.userId}, (err, user) => {
  141. if (err || !user) return cb({ status: 'error', message: 'An error occurred while joining the station2' });
  142. if (user.role === 'admin') return func();
  143. if (station.type === 'official') return cb({ status: 'error', message: 'An error occurred while joining the station3' });
  144. if (station.owner === session.userId) return func();
  145. return cb({ status: 'error', message: 'An error occurred while joining the station4' });
  146. });
  147. }
  148. function func() {
  149. utils.socketJoinRoom(session.socketId, `station.${stationId}`);
  150. if (station.currentSong) {
  151. utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
  152. //TODO Emit to cache, listen on cache
  153. songs.getSong(station.currentSong._id, (err, song) => {
  154. if (!err && song) {
  155. station.currentSong.likes = song.likes;
  156. station.currentSong.dislikes = song.dislikes;
  157. } else {
  158. station.currentSong.likes = -1;
  159. station.currentSong.dislikes = -1;
  160. }
  161. cb({
  162. status: 'success',
  163. data: {
  164. type: station.type,
  165. currentSong: station.currentSong,
  166. startedAt: station.startedAt,
  167. paused: station.paused,
  168. timePaused: station.timePaused,
  169. description: station.description,
  170. displayName: station.displayName,
  171. privacy: station.privacy,
  172. partyMode: station.partyMode,
  173. owner: station.owner,
  174. privatePlaylist: station.privatePlaylist
  175. }
  176. });
  177. });
  178. } else {
  179. cb({
  180. status: 'success',
  181. data: {
  182. type: station.type,
  183. currentSong: null,
  184. startedAt: station.startedAt,
  185. paused: station.paused,
  186. timePaused: station.timePaused,
  187. description: station.description,
  188. displayName: station.displayName,
  189. privacy: station.privacy,
  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. * @return {{ status: String, skipCount: Integer }}
  207. */
  208. /*skip: (session, stationId, cb) => {
  209. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  210. stations.getStation(stationId, (err, station) => {
  211. if (err && err !== true) {
  212. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  213. }
  214. if (station) {
  215. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  216. session.skippedSong = true;
  217. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  218. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  219. cb({ status: 'success', skipCount });
  220. });
  221. });
  222. }
  223. else {
  224. cb({ status: 'failure', message: `That station doesn't exist` });
  225. }
  226. });
  227. },*/
  228. forceSkip: hooks.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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.csOwnerRequired((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. return cb({ status: 'success', message: 'Station successfully removed' });
  363. });
  364. });
  365. }),
  366. create: hooks.adminRequired((session, data, cb) => {
  367. async.waterfall([
  368. (next) => {
  369. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  370. },
  371. // check the cache for the station
  372. (next) => cache.hget('stations', data._id, next),
  373. // if the cached version exist
  374. (station, next) => {
  375. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  376. db.models.station.findOne({ _id: data._id }, next);
  377. },
  378. (station, next) => {
  379. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  380. const { _id, displayName, description, genres, playlist } = data;
  381. db.models.station.create({
  382. _id,
  383. displayName,
  384. description,
  385. type: 'official',
  386. privacy: 'private',
  387. playlist,
  388. genres,
  389. currentSong: stations.defaultSong,
  390. partyMode: true
  391. }, next);
  392. }
  393. ], (err, station) => {
  394. if (err) {console.log(err); return cb({ 'status': 'failure', 'message': 'Something went wrong.'});}
  395. cache.pub('station.create', data._id);
  396. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  397. });
  398. }),
  399. createCommunity: hooks.loginRequired((session, data, cb) => {
  400. async.waterfall([
  401. (next) => {
  402. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  403. },
  404. // check the cache for the station
  405. (next) => {
  406. data._id = data._id.toLowerCase();
  407. cache.hget('stations', data._id, next)
  408. },
  409. // if the cached version exist
  410. (station, next) => {
  411. if (station) return next({ 'status': 'failure', 'message': 'A station with that name already exists' });
  412. db.models.station.findOne({$or: [{_id: data._id}, {displayName: new RegExp(`^${data.displayName}$`, 'i')}] }, next);
  413. },
  414. (station, next) => {
  415. cache.hget('sessions', session.sessionId, (err, session) => {
  416. next(null, station, session.userId);
  417. });
  418. },
  419. (station, userId, next) => {
  420. if (station) return next({ 'status': 'failure', 'message': 'A station with that name or display name already exists' });
  421. const { _id, displayName, description } = data;
  422. db.models.station.create({
  423. _id,
  424. displayName,
  425. owner: userId,
  426. privacy: 'private',
  427. description,
  428. type: "community",
  429. queue: [],
  430. currentSong: null
  431. }, next);
  432. }
  433. ], (err, station) => {
  434. if (err) return cb(err);
  435. console.log(err, station);
  436. cache.pub('station.create', data._id);
  437. return cb({ 'status': 'success', 'message': 'Successfully created station.' });
  438. });
  439. }),
  440. addToQueue: hooks.loginRequired((session, stationId, songId, cb, userId) => {
  441. stations.getStation(stationId, (err, station) => {
  442. if (err) return cb(err);
  443. if (station.type === 'community') {
  444. let has = false;
  445. station.queue.forEach((queueSong) => {
  446. if (queueSong._id === songId) {
  447. has = true;
  448. }
  449. });
  450. if (has) return cb({'status': 'failure', 'message': 'That song has already been added to the queue.'});
  451. if (station.currentSong && station.currentSong._id === songId) return cb({'status': 'failure', 'message': 'That song is currently playing.'});
  452. songs.getSong(songId, (err, song) => {
  453. if (err) {
  454. utils.getSongFromYouTube(songId, (song) => {
  455. song.artists = [];
  456. song.skipDuration = 0;
  457. song.likes = -1;
  458. song.dislikes = -1;
  459. song.thumbnail = "empty";
  460. song.explicit = false;
  461. cont(song);
  462. });
  463. } else cont(song);
  464. function cont(song) {
  465. db.models.station.update({_id: stationId}, {$push: {queue: song}}, (err) => {
  466. console.log(err);
  467. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  468. stations.updateStation(stationId, (err, station) => {
  469. if (err) return cb(err);
  470. cache.pub('station.queueUpdate', stationId);
  471. cb({'status': 'success', 'message': 'Added that song to the queue.'});
  472. });
  473. });
  474. }
  475. });
  476. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  477. });
  478. }),
  479. removeFromQueue: hooks.csOwnerRequired((session, stationId, songId, cb, userId) => {
  480. stations.getStation(stationId, (err, station) => {
  481. if (err) return cb(err);
  482. if (station.type === 'community') {
  483. let has = false;
  484. station.queue.forEach((queueSong) => {
  485. if (queueSong._id === songId) {
  486. has = true;
  487. }
  488. });
  489. if (!has) return cb({'status': 'failure', 'message': 'That song is not in the queue.'});
  490. db.models.update({_id: stationId}, {$pull: {queue: {songId: songId}}}, (err) => {
  491. if (err) return cb({'status': 'failure', 'message': 'Something went wrong.'});
  492. stations.updateStation(stationId, (err, station) => {
  493. if (err) return cb(err);
  494. cache.pub('station.queueUpdate', stationId);
  495. });
  496. });
  497. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  498. });
  499. }),
  500. getQueue: hooks.adminRequired((session, stationId, cb) => {
  501. stations.getStation(stationId, (err, station) => {
  502. if (err) return cb(err);
  503. if (!station) return cb({'status': 'failure', 'message': 'Station not found.'});
  504. if (station.type === 'community') {
  505. cb({'status': 'success', queue: station.queue});
  506. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  507. });
  508. }),
  509. selectPrivatePlaylist: hooks.csOwnerRequired((session, stationId, playlistId, cb, userId) => {
  510. stations.getStation(stationId, (err, station) => {
  511. if (err) return cb(err);
  512. if (station.type === 'community') {
  513. if (station.privatePlaylist === playlistId) return cb({'status': 'failure', 'message': 'That playlist is already selected.'});
  514. db.models.playlist.findOne({_id: playlistId}, (err, playlist) => {
  515. if (err) return cb(err);
  516. if (playlist) {
  517. db.models.station.update({_id: stationId}, {$set: {privatePlaylist: playlistId, currentSongIndex: 0}}, (err) => {
  518. if (err) return cb(err);
  519. stations.updateStation(stationId, (err, station) => {
  520. if (err) return cb(err);
  521. stations.skipStation(stationId)();
  522. cb({'status': 'success', 'message': 'Playlist selected.'});
  523. });
  524. });
  525. } else cb({'status': 'failure', 'message': 'Playlist not found.'});
  526. });
  527. } else cb({'status': 'failure', 'message': 'That station is not a community station.'});
  528. });
  529. }),
  530. };