stations.js 16 KB

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