stations.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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(5);
  75. async.each(stations, (station, next2) => {
  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, () => {
  82. next()
  83. }, true);
  84. }
  85. ], (err) => {
  86. next2(err);
  87. });
  88. }, next);
  89. }
  90. ], async (err) => {
  91. if (err) {
  92. err = await this.utils.getError(err);
  93. reject(err);
  94. } else {
  95. resolve();
  96. }
  97. });
  98. });
  99. }
  100. async initializeStation(stationId, cb, bypassValidate = false) {
  101. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  102. if (typeof cb !== 'function') cb = ()=>{};
  103. async.waterfall([
  104. (next) => {
  105. this.getStation(stationId, next, true);
  106. },
  107. (station, next) => {
  108. if (!station) return next('Station not found.');
  109. this.notifications.unschedule(`stations.nextSong?id=${station._id}`);
  110. subscription = this.notifications.subscribe(`stations.nextSong?id=${station._id}`, this.skipStation(station._id), true, station);
  111. if (station.paused) return next(true, station);
  112. next(null, station);
  113. },
  114. (station, next) => {
  115. if (!station.currentSong) {
  116. return this.skipStation(station._id)((err, station) => {
  117. if (err) return next(err);
  118. return next(true, station);
  119. }, true);
  120. }
  121. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  122. if (isNaN(timeLeft)) timeLeft = -1;
  123. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  124. this.skipStation(station._id)((err, station) => {
  125. next(err, station);
  126. }, true);
  127. } else {
  128. this.notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft, null, station);
  129. next(null, station);
  130. }
  131. }
  132. ], (err, station) => {
  133. if (err && err !== true) return cb(err);
  134. cb(null, station);
  135. });
  136. }
  137. async calculateSongForStation(station, cb, bypassValidate = false) {
  138. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  139. let songList = [];
  140. async.waterfall([
  141. (next) => {
  142. if (station.genres.length === 0) return next();
  143. let genresDone = [];
  144. station.genres.forEach((genre) => {
  145. this.db.models.song.find({genres: genre}, (err, songs) => {
  146. if (!err) {
  147. songs.forEach((song) => {
  148. if (songList.indexOf(song._id) === -1) {
  149. let found = false;
  150. song.genres.forEach((songGenre) => {
  151. if (station.blacklistedGenres.indexOf(songGenre) !== -1) found = true;
  152. });
  153. if (!found) {
  154. songList.push(song._id);
  155. }
  156. }
  157. });
  158. }
  159. genresDone.push(genre);
  160. if (genresDone.length === station.genres.length) next();
  161. });
  162. });
  163. },
  164. (next) => {
  165. let playlist = [];
  166. songList.forEach(function(songId) {
  167. if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
  168. });
  169. station.playlist.filter((songId) => {
  170. if (songList.indexOf(songId) !== -1) playlist.push(songId);
  171. });
  172. this.utils.shuffle(playlist).then((playlist) => {
  173. next(null, playlist);
  174. });
  175. },
  176. (playlist, next) => {
  177. this.calculateOfficialPlaylistList(station._id, playlist, () => {
  178. next(null, playlist);
  179. }, true);
  180. },
  181. (playlist, next) => {
  182. this.db.models.station.updateOne({_id: station._id}, {$set: {playlist: playlist}}, {runValidators: true}, (err) => {
  183. this.updateStation(station._id, () => {
  184. next(err, playlist);
  185. }, true);
  186. });
  187. }
  188. ], (err, newPlaylist) => {
  189. cb(err, newPlaylist);
  190. });
  191. }
  192. // Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  193. async getStation(stationId, cb, bypassValidate = false) {
  194. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  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. async.waterfall([
  222. (next) => {
  223. this.db.models.station.findOne({ name: stationName }, next);
  224. },
  225. (station, next) => {
  226. if (station) {
  227. if (station.type === 'official') {
  228. this.calculateOfficialPlaylistList(station._id, station.playlist, ()=>{});
  229. }
  230. station = this.cache.schemas.station(station);
  231. this.cache.hset('stations', station._id, station);
  232. next(true, station);
  233. } else next('Station not found');
  234. },
  235. ], (err, station) => {
  236. if (err && err !== true) return cb(err);
  237. cb(null, station);
  238. });
  239. }
  240. async updateStation(stationId, cb, bypassValidate = false) {
  241. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  242. async.waterfall([
  243. (next) => {
  244. this.db.models.station.findOne({ _id: stationId }, next);
  245. },
  246. (station, next) => {
  247. if (!station) {
  248. this.cache.hdel('stations', stationId);
  249. return next('Station not found');
  250. }
  251. this.cache.hset('stations', stationId, station, next);
  252. }
  253. ], (err, station) => {
  254. if (err && err !== true) return cb(err);
  255. cb(null, station);
  256. });
  257. }
  258. async calculateOfficialPlaylistList(stationId, songList, cb, bypassValidate = false) {
  259. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  260. let lessInfoPlaylist = [];
  261. async.each(songList, (song, next) => {
  262. this.songs.getSong(song, (err, song) => {
  263. if (!err && song) {
  264. let newSong = {
  265. songId: song.songId,
  266. title: song.title,
  267. artists: song.artists,
  268. duration: song.duration
  269. };
  270. lessInfoPlaylist.push(newSong);
  271. }
  272. next();
  273. });
  274. }, () => {
  275. this.cache.hset("officialPlaylists", stationId, this.cache.schemas.officialPlaylist(stationId, lessInfoPlaylist), () => {
  276. this.cache.pub("station.newOfficialPlaylist", stationId);
  277. cb();
  278. });
  279. });
  280. }
  281. skipStation(stationId) {
  282. this.logger.info("STATION_SKIP", `Skipping station ${stationId}.`, false);
  283. return async (cb, bypassValidate = false) => {
  284. if (!bypassValidate) try { await this._validateHook(); } catch { return; }
  285. this.logger.stationIssue(`SKIP_STATION_CB - Station ID: ${stationId}.`);
  286. if (typeof cb !== 'function') cb = ()=>{};
  287. async.waterfall([
  288. (next) => {
  289. this.getStation(stationId, next, true);
  290. },
  291. (station, next) => {
  292. if (!station) return next('Station not found.');
  293. 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
  294. if (station.type === 'community' && station.partyMode && station.queue.length > 0) { // Community station with party mode enabled and songs in the queue
  295. if (station.paused) {
  296. return next(null, null, -19, station);
  297. } else {
  298. return this.db.models.station.updateOne({_id: stationId}, {$pull: {queue: {_id: station.queue[0]._id}}}, (err) => {
  299. if (err) return next(err);
  300. next(null, station.queue[0], -12, station);
  301. });
  302. }
  303. }
  304. if (station.type === 'community' && !station.partyMode) {
  305. return this.db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  306. if (err) return next(err);
  307. if (!playlist) return next(null, null, -13, station);
  308. playlist = playlist.songs;
  309. if (playlist.length > 0) {
  310. let currentSongIndex;
  311. if (station.currentSongIndex < playlist.length - 1) currentSongIndex = station.currentSongIndex + 1;
  312. else currentSongIndex = 0;
  313. let callback = (err, song) => {
  314. if (err) return next(err);
  315. if (song) return next(null, song, currentSongIndex, station);
  316. else {
  317. let song = playlist[currentSongIndex];
  318. let currentSong = {
  319. songId: song.songId,
  320. title: song.title,
  321. duration: song.duration,
  322. likes: -1,
  323. dislikes: -1
  324. };
  325. return next(null, currentSong, currentSongIndex, station);
  326. }
  327. };
  328. if (playlist[currentSongIndex]._id) this.songs.getSong(playlist[currentSongIndex]._id, callback);
  329. else this.songs.getSongFromId(playlist[currentSongIndex].songId, callback);
  330. } else return next(null, null, -14, station);
  331. });
  332. }
  333. if (station.type === 'official' && station.playlist.length === 0) {
  334. return this.calculateSongForStation(station, (err, playlist) => {
  335. if (err) return next(err);
  336. if (playlist.length === 0) return next(null, this.defaultSong, 0, station);
  337. else {
  338. this.songs.getSong(playlist[0], (err, song) => {
  339. if (err || !song) return next(null, this.defaultSong, 0, station);
  340. return next(null, song, 0, station);
  341. });
  342. }
  343. }, true);
  344. }
  345. if (station.type === 'official' && station.playlist.length > 0) {
  346. async.doUntil((next) => {
  347. if (station.currentSongIndex < station.playlist.length - 1) {
  348. this.songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  349. if (!err) return next(null, song, station.currentSongIndex + 1);
  350. else {
  351. station.currentSongIndex++;
  352. next(null, null, null);
  353. }
  354. });
  355. } else {
  356. this.calculateSongForStation(station, (err, newPlaylist) => {
  357. if (err) return next(null, this.defaultSong, 0);
  358. this.songs.getSong(newPlaylist[0], (err, song) => {
  359. if (err || !song) return next(null, this.defaultSong, 0);
  360. station.playlist = newPlaylist;
  361. next(null, song, 0);
  362. });
  363. }, true);
  364. }
  365. }, (song, currentSongIndex, next) => {
  366. if (!!song) return next(null, true, currentSongIndex);
  367. else return next(null, false);
  368. }, (err, song, currentSongIndex) => {
  369. return next(err, song, currentSongIndex, station);
  370. });
  371. }
  372. },
  373. (song, currentSongIndex, station, next) => {
  374. let $set = {};
  375. if (song === null) $set.currentSong = null;
  376. else if (song.likes === -1 && song.dislikes === -1) {
  377. $set.currentSong = {
  378. songId: song.songId,
  379. title: song.title,
  380. duration: song.duration,
  381. skipDuration: 0,
  382. likes: -1,
  383. dislikes: -1
  384. };
  385. } else {
  386. $set.currentSong = {
  387. songId: song.songId,
  388. title: song.title,
  389. artists: song.artists,
  390. duration: song.duration,
  391. likes: song.likes,
  392. dislikes: song.dislikes,
  393. skipDuration: song.skipDuration,
  394. thumbnail: song.thumbnail
  395. };
  396. }
  397. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  398. $set.startedAt = Date.now();
  399. $set.timePaused = 0;
  400. if (station.paused) $set.pausedAt = Date.now();
  401. next(null, $set, station);
  402. },
  403. ($set, station, next) => {
  404. this.db.models.station.updateOne({_id: station._id}, {$set}, (err) => {
  405. this.updateStation(station._id, (err, station) => {
  406. if (station.type === 'community' && station.partyMode === true)
  407. this.cache.pub('station.queueUpdate', stationId);
  408. next(null, station);
  409. }, true);
  410. });
  411. },
  412. ], async (err, station) => {
  413. if (!err) {
  414. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  415. station.currentSong.skipVotes = 0;
  416. }
  417. //TODO Pub/Sub this
  418. this.utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  419. currentSong: station.currentSong,
  420. startedAt: station.startedAt,
  421. paused: station.paused,
  422. timePaused: 0
  423. });
  424. if (station.privacy === 'public') this.utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  425. else {
  426. let sockets = await this.utils.getRoomSockets('home');
  427. for (let socketId in sockets) {
  428. let socket = sockets[socketId];
  429. let session = sockets[socketId].session;
  430. if (session.sessionId) {
  431. this.cache.hget('sessions', session.sessionId, (err, session) => {
  432. if (!err && session) {
  433. this.db.models.user.findOne({_id: session.userId}, (err, user) => {
  434. if (!err && user) {
  435. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  436. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  437. }
  438. });
  439. }
  440. });
  441. }
  442. }
  443. }
  444. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  445. this.utils.socketsJoinSongRoom(await this.utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong.songId}`);
  446. if (!station.paused) {
  447. this.notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000, null, station);
  448. }
  449. } else {
  450. this.utils.socketsLeaveSongRooms(await this.utils.getRoomSockets(`station.${station._id}`));
  451. }
  452. cb(null, station);
  453. } else {
  454. err = await this.utils.getError(err);
  455. this.logger.error('SKIP_STATION', `Skipping station "${stationId}" failed. "${err}"`);
  456. cb(err);
  457. }
  458. });
  459. }
  460. }
  461. async canUserViewStation(station, userId, cb) {
  462. try { await this._validateHook(); } catch { return; }
  463. async.waterfall([
  464. (next) => {
  465. if (station.privacy !== 'private') return next(true);
  466. if (!userId) return next("Not allowed");
  467. next();
  468. },
  469. (next) => {
  470. this.db.models.user.findOne({_id: userId}, next);
  471. },
  472. (user, next) => {
  473. if (!user) return next("Not allowed");
  474. if (user.role === 'admin') return next(true);
  475. if (station.type === 'official') return next("Not allowed");
  476. if (station.owner === userId) return next(true);
  477. next("Not allowed");
  478. }
  479. ], async (errOrResult) => {
  480. if (errOrResult === true || errOrResult === "Not allowed") return cb(null, (errOrResult === true) ? true : false);
  481. cb(await this.utils.getError(errOrResult));
  482. });
  483. }
  484. }