stations.js 15 KB

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