stations.js 16 KB

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