stations.js 16 KB

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