stations.js 15 KB

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