stations.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. }
  169. });
  170. });
  171. } else {
  172. cb({
  173. status: 'success',
  174. data: {
  175. type: station.type,
  176. currentSong: null,
  177. startedAt: station.startedAt,
  178. paused: station.paused,
  179. timePaused: station.timePaused,
  180. description: station.description,
  181. displayName: station.displayName,
  182. privacy: station.privacy
  183. }
  184. });
  185. }
  186. }
  187. } else {
  188. cb({ status: 'failure', message: `That station doesn't exist` });
  189. }
  190. });
  191. },
  192. /**
  193. * Skips the users current station
  194. *
  195. * @param session
  196. * @param stationId - the station id
  197. * @param cb
  198. * @return {{ status: String, skipCount: Integer }}
  199. */
  200. /*skip: (session, stationId, cb) => {
  201. if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
  202. stations.getStation(stationId, (err, station) => {
  203. if (err && err !== true) {
  204. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  205. }
  206. if (station) {
  207. cache.client.hincrby('station.skipCounts', session.stationId, 1, (err, skipCount) => {
  208. session.skippedSong = true;
  209. if (err) return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  210. cache.hget('station.userCounts', session.stationId, (err, userCount) => {
  211. cb({ status: 'success', skipCount });
  212. });
  213. });
  214. }
  215. else {
  216. cb({ status: 'failure', message: `That station doesn't exist` });
  217. }
  218. });
  219. },*/
  220. forceSkip: hooks.adminRequired((session, stationId, cb) => {
  221. stations.getStation(stationId, (err, station) => {
  222. if (err && err !== true) {
  223. return cb({ status: 'error', message: 'An error occurred while skipping the station' });
  224. }
  225. if (station) {
  226. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  227. //notifications.schedule(`stations.nextSong?id=${stationId}`, 100);
  228. stations.skipStation(stationId)();
  229. }
  230. else {
  231. cb({ status: 'failure', message: `That station doesn't exist` });
  232. }
  233. });
  234. }),
  235. /**
  236. * Leaves the users current station
  237. *
  238. * @param session
  239. * @param stationId
  240. * @param cb
  241. * @return {{ status: String, userCount: Integer }}
  242. */
  243. leave: (session, stationId, cb) => {
  244. stations.getStation(stationId, (err, station) => {
  245. if (err && err !== true) {
  246. return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  247. }
  248. if (session) session.stationId = null;
  249. else if (station) {
  250. cache.client.hincrby('station.userCounts', stationId, -1, (err, userCount) => {
  251. if (err) return cb({ status: 'error', message: 'An error occurred while leaving the station' });
  252. utils.socketLeaveRooms(session);
  253. cb({ status: 'success', userCount });
  254. });
  255. } else {
  256. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  257. }
  258. });
  259. },
  260. updateDisplayName: hooks.adminRequired((session, stationId, newDisplayName, cb) => {
  261. db.models.station.update({_id: stationId}, {$set: {displayName: newDisplayName}}, (err) => {
  262. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  263. stations.updateStation(stationId, () => {
  264. //TODO Pub/sub for displayName change
  265. cb({ status: 'success', message: 'Successfully updated the display name.' });
  266. })
  267. });
  268. }),
  269. updateDescription: hooks.adminRequired((session, stationId, newDescription, cb) => {
  270. db.models.station.update({_id: stationId}, {$set: {description: newDescription}}, (err) => {
  271. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  272. stations.updateStation(stationId, () => {
  273. //TODO Pub/sub for description change
  274. cb({ status: 'success', message: 'Successfully updated the description.' });
  275. })
  276. });
  277. }),
  278. updatePrivacy: hooks.adminRequired((session, stationId, newPrivacy, cb) => {
  279. db.models.station.update({_id: stationId}, {$set: {privacy: newPrivacy}}, (err) => {
  280. if (err) return cb({ status: 'failure', message: 'Something went wrong when saving the station.' });
  281. stations.updateStation(stationId, () => {
  282. //TODO Pub/sub for privacy change
  283. cb({ status: 'success', message: 'Successfully updated the privacy.' });
  284. })
  285. });
  286. }),
  287. pause: hooks.adminRequired((session, stationId, cb) => {
  288. stations.getStation(stationId, (err, station) => {
  289. if (err && err !== true) {
  290. return cb({ status: 'error', message: 'An error occurred while pausing the station' });
  291. } else if (station) {
  292. if (!station.paused) {
  293. station.paused = true;
  294. station.pausedAt = Date.now();
  295. db.models.station.update({_id: stationId}, {$set: {paused: true, pausedAt: Date.now()}}, () => {
  296. if (err) return cb({ status: 'failure', message: 'An error occurred while pausing the station.' });
  297. stations.updateStation(stationId, () => {
  298. cache.pub('station.pause', stationId);
  299. notifications.unschedule(`stations.nextSong?id=${stationId}`);
  300. cb({ status: 'success' });
  301. });
  302. });
  303. } else {
  304. cb({ status: 'failure', message: 'That station was already paused.' });
  305. }
  306. cb({ status: 'success' });
  307. } else {
  308. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  309. }
  310. });
  311. }),
  312. resume: hooks.adminRequired((session, stationId, cb) => {
  313. stations.getStation(stationId, (err, station) => {
  314. if (err && err !== true) {
  315. return cb({ status: 'error', message: 'An error occurred while resuming the station' });
  316. } else if (station) {
  317. if (station.paused) {
  318. station.paused = false;
  319. station.timePaused += (Date.now() - station.pausedAt);
  320. console.log("&&&", station.timePaused, station.pausedAt, Date.now(), station.timePaused);
  321. db.models.station.update({_id: stationId}, {$set: {paused: false}, $inc: {timePaused: Date.now() - station.pausedAt}}, () => {
  322. stations.updateStation(stationId, (err, station) => {
  323. cache.pub('station.resume', stationId);
  324. cb({ status: 'success' });
  325. });
  326. });
  327. } else {
  328. cb({ status: 'failure', message: 'That station is not paused.' });
  329. }
  330. } else {
  331. cb({ status: 'failure', message: `That station doesn't exist, it may have been deleted` });
  332. }
  333. });
  334. }),
  335. remove: hooks.adminRequired((session, stationId, cb) => {
  336. db.models.station.remove({ _id: stationId });
  337. cache.hdel('stations', stationId, () => {
  338. return cb({ status: 'success', message: 'Station successfully removed' });
  339. });
  340. }),
  341. create: hooks.adminRequired((session, data, cb) => {
  342. async.waterfall([
  343. (next) => {
  344. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  345. },
  346. // check the cache for the station
  347. (next) => cache.hget('stations', data._id, next),
  348. // if the cached version exist
  349. (station, next) => {
  350. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  351. db.models.station.findOne({ _id: data._id }, next);
  352. },
  353. (station, next) => {
  354. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  355. const { _id, displayName, description, genres, playlist } = data;
  356. db.models.station.create({
  357. _id,
  358. displayName,
  359. description,
  360. type: 'official',
  361. privacy: 'private',
  362. playlist,
  363. genres,
  364. currentSong: stations.defaultSong
  365. }, next);
  366. }
  367. ], (err, station) => {
  368. if (err) {console.log(err); return cb({ 'status': 'failure', 'message': 'Something went wrong.'});}
  369. cache.pub('station.create', data._id);
  370. return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
  371. });
  372. }),
  373. createCommunity: hooks.loginRequired((session, data, cb) => {
  374. async.waterfall([
  375. (next) => {
  376. return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
  377. },
  378. // check the cache for the station
  379. (next) => cache.hget('stations', data._id, next),
  380. // if the cached version exist
  381. (station, next) => {
  382. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  383. db.models.station.findOne({ _id: data._id }, next);
  384. },
  385. (station, next) => {
  386. cache.hget('sessions', session.sessionId, (err, session) => {
  387. next(null, station, session.userId);
  388. });
  389. },
  390. (station, userId, next) => {
  391. if (station) return next({ 'status': 'failure', 'message': 'A station with that id already exists' });
  392. const { _id, displayName, description } = data;
  393. db.models.station.create({
  394. _id,
  395. displayName,
  396. owner: userId,
  397. privacy: 'private',
  398. description,
  399. type: "community",
  400. queue: [],
  401. currentSong: null
  402. }, next);
  403. }
  404. ], (err, station) => {
  405. if (err) console.error(err);
  406. console.log(err, station);
  407. cache.pub('station.create', data._id);
  408. return cb({ 'status': 'success', 'message': 'Successfully created station.' });
  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.adminRequired((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. };