stations.js 14 KB

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