stations.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. async.each(songList, (song, next) => {
  209. songs.getSong(song, (err, song) => {
  210. if (!err && song) {
  211. let newSong = {
  212. _id: song._id,
  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. songs.getSong(playlist[currentSongIndex]._id, (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. _id: song._id,
  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. } else return next(null, null, -14, station);
  271. });
  272. }
  273. if (station.type === 'official' && station.playlist.length === 0) {
  274. return _this.calculateSongForStation(station, (err, playlist) => {
  275. if (err) return next(err);
  276. if (playlist.length === 0) return next(null, _this.defaultSong, 0, station);
  277. else {
  278. songs.getSong(playlist[0], (err, song) => {
  279. if (err || !song) return next(null, _this.defaultSong, 0, station);
  280. return next(null, song, 0, station);
  281. });
  282. }
  283. });
  284. }
  285. if (station.type === 'official' && station.playlist.length > 0) {
  286. async.doUntil((next) => {
  287. if (station.currentSongIndex < station.playlist.length - 1) {
  288. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  289. if (!err) return next(null, song, station.currentSongIndex + 1);
  290. else {
  291. station.currentSongIndex++;
  292. next(null, null);
  293. }
  294. });
  295. } else {
  296. _this.calculateSongForStation(station, (err, newPlaylist) => {
  297. if (err) return next(null, _this.defaultSong, 0);
  298. songs.getSong(newPlaylist[0], (err, song) => {
  299. if (err || !song) return next(null, _this.defaultSong, 0);
  300. station.playlist = newPlaylist;
  301. next(null, song, 0);
  302. });
  303. });
  304. }
  305. }, (song) => {
  306. return !!song;
  307. }, (err, song, currentSongIndex) => {
  308. return next(err, song, currentSongIndex, station);
  309. });
  310. }
  311. },
  312. (song, currentSongIndex, station, next) => {
  313. let $set = {};
  314. if (song === null) $set.currentSong = null;
  315. else if (song.likes === -1 && song.dislikes === -1) {
  316. $set.currentSong = {
  317. _id: song._id,
  318. title: song.title,
  319. duration: song.duration,
  320. likes: -1,
  321. dislikes: -1
  322. };
  323. } else {
  324. $set.currentSong = {
  325. _id: song._id,
  326. title: song.title,
  327. artists: song.artists,
  328. duration: song.duration,
  329. likes: song.likes,
  330. dislikes: song.dislikes,
  331. skipDuration: song.skipDuration,
  332. thumbnail: song.thumbnail
  333. };
  334. }
  335. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  336. $set.startedAt = Date.now();
  337. $set.timePaused = 0;
  338. if (station.paused) $set.pausedAt = Date.now();
  339. next(null, $set, station);
  340. },
  341. ($set, station, next) => {
  342. db.models.station.update({_id: station._id}, {$set}, (err) => {
  343. _this.updateStation(station._id, (err, station) => {
  344. if (station.type === 'community' && station.partyMode === true)
  345. cache.pub('station.queueUpdate', stationId);
  346. next(null, station);
  347. });
  348. });
  349. },
  350. ], (err, station) => {
  351. if (!err) {
  352. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  353. station.currentSong.skipVotes = 0;
  354. }
  355. //TODO Pub/Sub this
  356. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  357. currentSong: station.currentSong,
  358. startedAt: station.startedAt,
  359. paused: station.paused,
  360. timePaused: 0
  361. });
  362. if (station.privacy === 'public') utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  363. else {
  364. let sockets = utils.getRoomSockets('home');
  365. for (let socketId in sockets) {
  366. let socket = sockets[socketId];
  367. let session = sockets[socketId].session;
  368. if (session.sessionId) {
  369. cache.hget('sessions', session.sessionId, (err, session) => {
  370. if (!err && session) {
  371. db.models.user.findOne({_id: session.userId}, (err, user) => {
  372. if (!err && user) {
  373. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  374. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  375. }
  376. });
  377. }
  378. });
  379. }
  380. }
  381. }
  382. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  383. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  384. if (!station.paused) {
  385. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  386. }
  387. } else {
  388. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`));
  389. }
  390. cb(null, station);
  391. } else {
  392. err = utils.getError(err);
  393. logger.error('SKIP_STATION', `Skipping station "${stationId}" failed. "${err}"`);
  394. cb(err);
  395. }
  396. });
  397. }
  398. },
  399. defaultSong: {
  400. _id: '60ItHLz5WEA',
  401. title: 'Faded - Alan Walker',
  402. duration: 212,
  403. likes: -1,
  404. dislikes: -1
  405. }
  406. };