stations.js 14 KB

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