stations.js 17 KB

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