stations.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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.songId) === -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.songId);
  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. async.each(songList, (song, next) => {
  209. songs.getSongFromId(song, (err, song) => {
  210. if (!err && song) {
  211. let newSong = {
  212. songId: song.songId,
  213. title: song.title,
  214. artists: song.artists,
  215. duration: song.duration
  216. };
  217. lessInfoPlaylist.push(newSong);
  218. }
  219. next();
  220. });
  221. }, () => {
  222. cache.hset("officialPlaylists", stationId, cache.schemas.officialPlaylist(stationId, lessInfoPlaylist), () => {
  223. cache.pub("station.newOfficialPlaylist", stationId);
  224. cb();
  225. });
  226. });
  227. },
  228. skipStation: function(stationId) {
  229. console.log("SKIP!", stationId);
  230. let _this = this;
  231. return (cb) => {
  232. if (typeof cb !== 'function') cb = ()=>{};
  233. async.waterfall([
  234. (next) => {
  235. _this.getStation(stationId, next);
  236. },
  237. (station, next) => {
  238. if (!station) return next('Station not found.');
  239. if (station.type === 'community' && station.partyMode && station.queue.length === 0) return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  240. if (station.type === 'community' && station.partyMode && station.queue.length > 0) { // Community station with party mode enabled and songs in the queue
  241. return db.models.station.update({_id: stationId}, {$pull: {queue: {_id: station.queue[0]._id}}}, (err) => {
  242. if (err) return next(err);
  243. next(null, station.queue[0], -12, station);
  244. });
  245. }
  246. if (station.type === 'community' && !station.partyMode) {
  247. return db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  248. if (err) return next(err);
  249. if (!playlist) return next(null, null, -13, station);
  250. playlist = playlist.songs;
  251. if (playlist.length > 0) {
  252. let currentSongIndex;
  253. if (station.currentSongIndex < playlist.length - 1) currentSongIndex = station.currentSongIndex + 1;
  254. else currentSongIndex = 0;
  255. let callback = (err, song) => {
  256. if (err) return next(err);
  257. if (song) return next(null, song, currentSongIndex, station);
  258. else {
  259. let song = playlist[currentSongIndex];
  260. let currentSong = {
  261. songId: song.songId,
  262. title: song.title,
  263. duration: song.duration,
  264. likes: -1,
  265. dislikes: -1
  266. };
  267. return next(null, currentSong, currentSongIndex, station);
  268. }
  269. };
  270. if (playlist[currentSongIndex]._id) songs.getSong(playlist[currentSongIndex]._id, callback);
  271. else songs.getSongFromId(playlist[currentSongIndex].songId, callback);
  272. } else return next(null, null, -14, station);
  273. });
  274. }
  275. if (station.type === 'official' && station.playlist.length === 0) {
  276. return _this.calculateSongForStation(station, (err, playlist) => {
  277. if (err) return next(err);
  278. if (playlist.length === 0) return next(null, _this.defaultSong, 0, station);
  279. else {
  280. songs.getSong(playlist[0], (err, song) => {
  281. if (err || !song) return next(null, _this.defaultSong, 0, station);
  282. return next(null, song, 0, station);
  283. });
  284. }
  285. });
  286. }
  287. if (station.type === 'official' && station.playlist.length > 0) {
  288. async.doUntil((next) => {
  289. if (station.currentSongIndex < station.playlist.length - 1) {
  290. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  291. if (!err) return next(null, song, station.currentSongIndex + 1);
  292. else {
  293. station.currentSongIndex++;
  294. next(null, null);
  295. }
  296. });
  297. } else {
  298. _this.calculateSongForStation(station, (err, newPlaylist) => {
  299. if (err) return next(null, _this.defaultSong, 0);
  300. songs.getSongFromId(newPlaylist[0], (err, song) => {
  301. if (err || !song) return next(null, _this.defaultSong, 0);
  302. station.playlist = newPlaylist;
  303. next(null, song, 0);
  304. });
  305. });
  306. }
  307. }, (song) => {
  308. return !!song;
  309. }, (err, song, currentSongIndex) => {
  310. return next(err, song, currentSongIndex, station);
  311. });
  312. }
  313. },
  314. (song, currentSongIndex, station, next) => {
  315. let $set = {};
  316. if (song === null) $set.currentSong = null;
  317. else if (song.likes === -1 && song.dislikes === -1) {
  318. $set.currentSong = {
  319. songId: song.songId,
  320. title: song.title,
  321. duration: song.duration,
  322. likes: -1,
  323. dislikes: -1
  324. };
  325. } else {
  326. $set.currentSong = {
  327. songId: song.songId,
  328. title: song.title,
  329. artists: song.artists,
  330. duration: song.duration,
  331. likes: song.likes,
  332. dislikes: song.dislikes,
  333. skipDuration: song.skipDuration,
  334. thumbnail: song.thumbnail
  335. };
  336. }
  337. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  338. $set.startedAt = Date.now();
  339. $set.timePaused = 0;
  340. if (station.paused) $set.pausedAt = Date.now();
  341. next(null, $set, station);
  342. },
  343. ($set, station, next) => {
  344. db.models.station.update({_id: station._id}, {$set}, (err) => {
  345. _this.updateStation(station._id, (err, station) => {
  346. if (station.type === 'community' && station.partyMode === true)
  347. cache.pub('station.queueUpdate', stationId);
  348. next(null, station);
  349. });
  350. });
  351. },
  352. ], (err, station) => {
  353. if (!err) {
  354. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  355. station.currentSong.skipVotes = 0;
  356. }
  357. //TODO Pub/Sub this
  358. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  359. currentSong: station.currentSong,
  360. startedAt: station.startedAt,
  361. paused: station.paused,
  362. timePaused: 0
  363. });
  364. if (station.privacy === 'public') utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  365. else {
  366. let sockets = utils.getRoomSockets('home');
  367. for (let socketId in sockets) {
  368. let socket = sockets[socketId];
  369. let session = sockets[socketId].session;
  370. if (session.sessionId) {
  371. cache.hget('sessions', session.sessionId, (err, session) => {
  372. if (!err && session) {
  373. db.models.user.findOne({_id: session.userId}, (err, user) => {
  374. if (!err && user) {
  375. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  376. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  377. }
  378. });
  379. }
  380. });
  381. }
  382. }
  383. }
  384. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  385. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong.songId}`);
  386. if (!station.paused) {
  387. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  388. }
  389. } else {
  390. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`));
  391. }
  392. cb(null, station);
  393. } else {
  394. err = utils.getError(err);
  395. logger.error('SKIP_STATION', `Skipping station "${stationId}" failed. "${err}"`);
  396. cb(err);
  397. }
  398. });
  399. }
  400. },
  401. defaultSong: {
  402. songId: '60ItHLz5WEA',
  403. title: 'Faded - Alan Walker',
  404. duration: 212,
  405. likes: -1,
  406. dislikes: -1
  407. }
  408. };