stations.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. 'use strict';
  2. const cache = require('./cache');
  3. const db = require('./db');
  4. const io = require('./io');
  5. const utils = require('./utils');
  6. const logger = require('./logger');
  7. const songs = require('./songs');
  8. const notifications = require('./notifications');
  9. const async = require('async');
  10. //TEMP
  11. cache.sub('station.pause', (stationId) => {
  12. notifications.remove(`stations.nextSong?id=${stationId}`);
  13. });
  14. cache.sub('station.resume', (stationId) => {
  15. module.exports.initializeStation(stationId)
  16. });
  17. cache.sub('station.queueUpdate', (stationId) => {
  18. module.exports.getStation(stationId, (err, station) => {
  19. if (!station.currentSong && station.queue.length > 0) {
  20. module.exports.initializeStation(stationId);
  21. }
  22. });
  23. });
  24. cache.sub('station.newOfficialPlaylist', (stationId) => {
  25. cache.hget("officialPlaylists", stationId, (err, playlistObj) => {
  26. if (!err && playlistObj) {
  27. utils.emitToRoom(`station.${stationId}`, "event:newOfficialPlaylist", playlistObj.songs);
  28. }
  29. })
  30. });
  31. module.exports = {
  32. init: function(cb) {
  33. async.waterfall([
  34. (next) => {
  35. cache.hgetall('stations', next);
  36. },
  37. (stations, next) => {
  38. if (!stations) return next();
  39. let stationIds = Object.keys(stations);
  40. async.each(stationIds, (stationId, next) => {
  41. db.models.station.findOne({_id: stationId}, (err, station) => {
  42. if (err) next(err);
  43. else if (!station) {
  44. cache.hdel('stations', stationId, next);
  45. } else next();
  46. });
  47. }, next);
  48. },
  49. (next) => {
  50. db.models.station.find({}, next);
  51. },
  52. (stations, next) => {
  53. async.each(stations, (station, next) => {
  54. async.waterfall([
  55. (next) => {
  56. cache.hset('stations', station._id, cache.schemas.station(station), next);
  57. },
  58. (station, next) => {
  59. this.initializeStation(station._id, next);
  60. }
  61. ], (err) => {
  62. next(err);
  63. });
  64. }, next);
  65. }
  66. ], (err) => {
  67. if (err) {
  68. console.log(`FAILED TO INITIALIZE STATIONS. ABORTING. "${err.message}"`);
  69. process.exit();
  70. } else cb();
  71. });
  72. },
  73. initializeStation: function(stationId, cb) {
  74. if (typeof cb !== 'function') cb = ()=>{};
  75. let _this = this;
  76. _this.getStation(stationId, (err, station) => {
  77. if (!err) {
  78. if (station) {
  79. let notification = notifications.subscribe(`stations.nextSong?id=${station._id}`, _this.skipStation(station._id), true);
  80. if (!station.paused ) {
  81. /*if (!station.startedAt) {
  82. station.startedAt = Date.now();
  83. station.timePaused = 0;
  84. cache.hset('stations', stationId, station);
  85. }*/
  86. if (station.currentSong) {
  87. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  88. if (isNaN(timeLeft)) timeLeft = -1;
  89. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  90. this.skipStation(station._id)((err, station) => {
  91. cb(err, station);
  92. });
  93. } else {
  94. notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft);
  95. cb(null, station);
  96. }
  97. } else {
  98. _this.skipStation(station._id)((err, station) => {
  99. cb(err, station);
  100. });
  101. }
  102. } else {
  103. notifications.unschedule(`stations.nextSong?id${station._id}`);
  104. cb(null, station);
  105. }
  106. } else cb("Station not found");
  107. } else cb(err);
  108. });
  109. },
  110. calculateSongForStation: function(station, cb) {
  111. let _this = this;
  112. let songList = [];
  113. async.waterfall([
  114. (next) => {
  115. let genresDone = [];
  116. station.genres.forEach((genre) => {
  117. db.models.song.find({genres: genre}, (err, songs) => {
  118. if (!err) {
  119. songs.forEach((song) => {
  120. if (songList.indexOf(song._id) === -1) {
  121. let found = false;
  122. song.genres.forEach((songGenre) => {
  123. if (station.blacklistedGenres.indexOf(songGenre) !== -1) found = true;
  124. });
  125. if (!found) {
  126. songList.push(song._id);
  127. }
  128. }
  129. });
  130. }
  131. genresDone.push(genre);
  132. if (genresDone.length === station.genres.length) next();
  133. });
  134. });
  135. },
  136. (next) => {
  137. let playlist = [];
  138. songList.forEach(function(songId) {
  139. if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
  140. });
  141. station.playlist.filter((songId) => {
  142. if (songList.indexOf(songId) !== -1) playlist.push(songId);
  143. });
  144. _this.calculateOfficialPlaylistList(station._id, playlist, () => {
  145. next(null, playlist);
  146. });
  147. },
  148. (playlist, next) => {
  149. db.models.station.update({_id: station._id}, {$set: {playlist: playlist}}, (err) => {
  150. _this.updateStation(station._id, () => {
  151. next(err, playlist);
  152. });
  153. });
  154. }
  155. ], (err, newPlaylist) => {
  156. cb(err, newPlaylist);
  157. });
  158. },
  159. // Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  160. getStation: function(stationId, cb) {
  161. let _this = this;
  162. async.waterfall([
  163. (next) => {
  164. cache.hget('stations', stationId, next);
  165. },
  166. (station, next) => {
  167. if (station) return next(true, station);
  168. db.models.station.findOne({ _id: stationId }, next);
  169. },
  170. (station, next) => {
  171. if (station) {
  172. if (station.type === 'official') {
  173. _this.calculateOfficialPlaylistList(station._id, station.playlist, ()=>{});
  174. }
  175. station = cache.schemas.station(station);
  176. cache.hset('stations', stationId, station);
  177. next(true, station);
  178. } else next('Station not found');
  179. },
  180. ], (err, station) => {
  181. if (err && err !== true) cb(err);
  182. cb(null, station);
  183. });
  184. },
  185. updateStation: function(stationId, cb) {
  186. let _this = this;
  187. async.waterfall([
  188. (next) => {
  189. db.models.station.findOne({ _id: stationId }, next);
  190. },
  191. (station, next) => {
  192. if (!station) return next('Station not found');
  193. cache.hset('stations', stationId, station, next);
  194. }
  195. ], (err, station) => {
  196. if (err && err !== true) return cb(err);
  197. cb(null, station);
  198. });
  199. },
  200. calculateOfficialPlaylistList: (stationId, songList, cb) => {
  201. let lessInfoPlaylist = [];
  202. function getSongInfo(index) {
  203. if (songList.length > index) {
  204. songs.getSong(songList[index], (err, song) => {
  205. if (!err && song) {
  206. let newSong = {
  207. _id: song._id,
  208. title: song.title,
  209. artists: song.artists,
  210. duration: song.duration
  211. };
  212. lessInfoPlaylist.push(newSong);
  213. }
  214. getSongInfo(index + 1);
  215. })
  216. } else {
  217. cache.hset("officialPlaylists", stationId, cache.schemas.officialPlaylist(stationId, lessInfoPlaylist), () => {
  218. cache.pub("station.newOfficialPlaylist", stationId);
  219. cb();
  220. });
  221. }
  222. }
  223. getSongInfo(0);
  224. },
  225. skipStation: function(stationId) {
  226. console.log("SKIP!", stationId);
  227. let _this = this;
  228. return (cb) => {
  229. if (typeof cb !== 'function') cb = ()=>{};
  230. _this.getStation(stationId, (err, station) => {
  231. if (station) {
  232. // notify all the sockets on this station to go to the next song
  233. async.waterfall([
  234. (next) => {
  235. if (station.type === "official") {
  236. if (station.playlist.length > 0) {
  237. function setCurrentSong() {
  238. if (station.currentSongIndex < station.playlist.length - 1) {
  239. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  240. if (!err) {
  241. let $set = {};
  242. $set.currentSong = {
  243. _id: song._id,
  244. title: song.title,
  245. artists: song.artists,
  246. duration: song.duration,
  247. likes: song.likes,
  248. dislikes: song.dislikes,
  249. skipDuration: song.skipDuration,
  250. thumbnail: song.thumbnail
  251. };
  252. $set.startedAt = Date.now();
  253. $set.timePaused = 0;
  254. $set.currentSongIndex = station.currentSongIndex + 1;
  255. next(null, $set);
  256. } else {
  257. db.models.station.update({ _id: station._id }, { $inc: { currentSongIndex: 1 } }, (err) => {
  258. _this.updateStation(station._id, () => {
  259. setCurrentSong();
  260. });
  261. });
  262. }
  263. });
  264. } else {
  265. db.models.station.update({_id: station._id}, {$set: {currentSongIndex: 0}}, (err) => {
  266. _this.updateStation(station._id, (err, station) => {
  267. _this.calculateSongForStation(station, (err, newPlaylist) => {
  268. if (!err) {
  269. songs.getSong(newPlaylist[0], (err, song) => {
  270. let $set = {};
  271. if (song) {
  272. $set.currentSong = {
  273. _id: song._id,
  274. title: song.title,
  275. artists: song.artists,
  276. duration: song.duration,
  277. likes: song.likes,
  278. dislikes: song.dislikes,
  279. skipDuration: song.skipDuration,
  280. thumbnail: song.thumbnail
  281. };
  282. station.playlist = newPlaylist;
  283. } else $set.currentSong = _this.defaultSong;
  284. $set.startedAt = Date.now();
  285. $set.timePaused = 0;
  286. next(null, $set);
  287. });
  288. } else {
  289. let $set = {};
  290. $set.currentSong = _this.defaultSong;
  291. $set.startedAt = Date.now();
  292. $set.timePaused = 0;
  293. next(null, $set);
  294. }
  295. })
  296. });
  297. });
  298. }
  299. }
  300. setCurrentSong();
  301. } else {
  302. _this.calculateSongForStation(station, (err, playlist) => {
  303. if (!err && playlist.length === 0) {
  304. let $set = {};
  305. $set.currentSongIndex = 0;
  306. $set.currentSong = _this.defaultSong;
  307. $set.startedAt = Date.now();
  308. $set.timePaused = 0;
  309. next(null, $set);
  310. } else {
  311. songs.getSong(playlist[0], (err, song) => {
  312. let $set = {};
  313. if (!err) {
  314. $set.currentSong = {
  315. _id: song._id,
  316. title: song.title,
  317. artists: song.artists,
  318. duration: song.duration,
  319. likes: song.likes,
  320. dislikes: song.dislikes,
  321. skipDuration: song.skipDuration,
  322. thumbnail: song.thumbnail
  323. };
  324. } else {
  325. $set.currentSong = _this.defaultSong;
  326. }
  327. $set.currentSongIndex = 0;
  328. $set.startedAt = Date.now();
  329. $set.timePaused = 0;
  330. next(null, $set);
  331. });
  332. }
  333. });
  334. }
  335. } else {
  336. if (station.partyMode === true) if (station.queue.length > 0) {
  337. db.models.station.update({ _id: stationId }, { $pull: { queue: { _id: station.queue[0]._id } } }, (err) => {
  338. if (err) return next(err);
  339. let $set = {};
  340. $set.currentSong = station.queue[0];
  341. $set.startedAt = Date.now();
  342. $set.timePaused = 0;
  343. if (station.paused) $set.pausedAt = Date.now();
  344. next(null, $set);
  345. });
  346. } else next(null, {currentSong: null});
  347. else {
  348. db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  349. if (err || !playlist) return next(null, {currentSong: null});
  350. playlist = playlist.songs;
  351. if (playlist.length > 0) {
  352. let $set = {};
  353. if (station.currentSongIndex < playlist.length - 1) $set.currentSongIndex = station.currentSongIndex + 1;
  354. else $set.currentSongIndex = 0;
  355. songs.getSong(playlist[$set.currentSongIndex]._id, (err, song) => {
  356. if (!err && song) {
  357. $set.currentSong = {
  358. _id: song._id,
  359. title: song.title,
  360. artists: song.artists,
  361. duration: song.duration,
  362. likes: song.likes,
  363. dislikes: song.dislikes,
  364. skipDuration: song.skipDuration,
  365. thumbnail: song.thumbnail
  366. };
  367. } else {
  368. let song = playlist[$set.currentSongIndex];
  369. $set.currentSong = {
  370. _id: song._id,
  371. title: song.title,
  372. duration: song.duration,
  373. likes: -1,
  374. dislikes: -1
  375. };
  376. }
  377. $set.startedAt = Date.now();
  378. $set.timePaused = 0;
  379. next(null, $set);
  380. });
  381. } else next(null, {currentSong: null});
  382. });
  383. }
  384. }
  385. },
  386. ($set, next) => {
  387. db.models.station.update({_id: station._id}, {$set}, (err) => {
  388. _this.updateStation(station._id, (err, station) => {
  389. if (station.type === 'community' && station.partyMode === true)
  390. cache.pub('station.queueUpdate', stationId);
  391. next(null, station);
  392. });
  393. });
  394. },
  395. ], (err, station) => {
  396. if (!err) {
  397. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  398. station.currentSong.skipVotes = 0;
  399. }
  400. //TODO Pub/Sub this
  401. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  402. currentSong: station.currentSong,
  403. startedAt: station.startedAt,
  404. paused: station.paused,
  405. timePaused: 0
  406. });
  407. if (station.privacy === 'public') utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  408. else {
  409. let sockets = utils.getRoomSockets('home');
  410. for (let socketId in sockets) {
  411. let socket = sockets[socketId];
  412. let session = sockets[socketId].session;
  413. if (session.sessionId) {
  414. cache.hget('sessions', session.sessionId, (err, session) => {
  415. if (!err && session) {
  416. db.models.user.findOne({_id: session.userId}, (err, user) => {
  417. if (!err && user) {
  418. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  419. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  420. }
  421. });
  422. }
  423. });
  424. }
  425. }
  426. }
  427. console.log(
  428. Date.now(),
  429. (station) ? station._id : "STATION_NULL",
  430. station.currentSong !== null && station.currentSong._id !== undefined,
  431. station.currentSong !== null,
  432. (station.currentSong) ? station.currentSong._id !== undefined : "CURRENTSONG_NULL"
  433. );
  434. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  435. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  436. if (!station.paused) {
  437. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  438. }
  439. } else {
  440. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`));
  441. }
  442. cb(null, station);
  443. } else cb(err);
  444. });
  445. }
  446. // the station doesn't exist anymore, unsubscribe from it
  447. else {
  448. cb("Station not found.");
  449. }
  450. });
  451. }
  452. },
  453. defaultSong: {
  454. _id: '60ItHLz5WEA',
  455. title: 'Faded - Alan Walker',
  456. duration: 212,
  457. likes: -1,
  458. dislikes: -1
  459. }
  460. };