stations.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. return this.db.models.station.updateOne({_id: stationId}, {$pull: {queue: {_id: station.queue[0]._id}}}, (err) => {
  296. if (err) return next(err);
  297. next(null, station.queue[0], -12, station);
  298. });
  299. }
  300. if (station.type === 'community' && !station.partyMode) {
  301. return this.db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  302. if (err) return next(err);
  303. if (!playlist) return next(null, null, -13, station);
  304. playlist = playlist.songs;
  305. if (playlist.length > 0) {
  306. let currentSongIndex;
  307. if (station.currentSongIndex < playlist.length - 1) currentSongIndex = station.currentSongIndex + 1;
  308. else currentSongIndex = 0;
  309. let callback = (err, song) => {
  310. if (err) return next(err);
  311. if (song) return next(null, song, currentSongIndex, station);
  312. else {
  313. let song = playlist[currentSongIndex];
  314. let currentSong = {
  315. songId: song.songId,
  316. title: song.title,
  317. duration: song.duration,
  318. likes: -1,
  319. dislikes: -1
  320. };
  321. return next(null, currentSong, currentSongIndex, station);
  322. }
  323. };
  324. if (playlist[currentSongIndex]._id) this.songs.getSong(playlist[currentSongIndex]._id, callback);
  325. else this.songs.getSongFromId(playlist[currentSongIndex].songId, callback);
  326. } else return next(null, null, -14, station);
  327. });
  328. }
  329. if (station.type === 'official' && station.playlist.length === 0) {
  330. return this.calculateSongForStation(station, (err, playlist) => {
  331. if (err) return next(err);
  332. if (playlist.length === 0) return next(null, this.defaultSong, 0, station);
  333. else {
  334. this.songs.getSong(playlist[0], (err, song) => {
  335. if (err || !song) return next(null, this.defaultSong, 0, station);
  336. return next(null, song, 0, station);
  337. });
  338. }
  339. }, true);
  340. }
  341. if (station.type === 'official' && station.playlist.length > 0) {
  342. async.doUntil((next) => {
  343. if (station.currentSongIndex < station.playlist.length - 1) {
  344. this.songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  345. if (!err) return next(null, song, station.currentSongIndex + 1);
  346. else {
  347. station.currentSongIndex++;
  348. next(null, null, null);
  349. }
  350. });
  351. } else {
  352. this.calculateSongForStation(station, (err, newPlaylist) => {
  353. if (err) return next(null, this.defaultSong, 0);
  354. this.songs.getSong(newPlaylist[0], (err, song) => {
  355. if (err || !song) return next(null, this.defaultSong, 0);
  356. station.playlist = newPlaylist;
  357. next(null, song, 0);
  358. });
  359. }, true);
  360. }
  361. }, (song, currentSongIndex, next) => {
  362. if (!!song) return next(null, true, currentSongIndex);
  363. else return next(null, false);
  364. }, (err, song, currentSongIndex) => {
  365. return next(err, song, currentSongIndex, station);
  366. });
  367. }
  368. },
  369. (song, currentSongIndex, station, next) => {
  370. let $set = {};
  371. if (song === null) $set.currentSong = null;
  372. else if (song.likes === -1 && song.dislikes === -1) {
  373. $set.currentSong = {
  374. songId: song.songId,
  375. title: song.title,
  376. duration: song.duration,
  377. skipDuration: 0,
  378. likes: -1,
  379. dislikes: -1
  380. };
  381. } else {
  382. $set.currentSong = {
  383. songId: song.songId,
  384. title: song.title,
  385. artists: song.artists,
  386. duration: song.duration,
  387. likes: song.likes,
  388. dislikes: song.dislikes,
  389. skipDuration: song.skipDuration,
  390. thumbnail: song.thumbnail
  391. };
  392. }
  393. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  394. $set.startedAt = Date.now();
  395. $set.timePaused = 0;
  396. if (station.paused) $set.pausedAt = Date.now();
  397. next(null, $set, station);
  398. },
  399. ($set, station, next) => {
  400. this.db.models.station.updateOne({_id: station._id}, {$set}, (err) => {
  401. this.updateStation(station._id, (err, station) => {
  402. if (station.type === 'community' && station.partyMode === true)
  403. this.cache.pub('station.queueUpdate', stationId);
  404. next(null, station);
  405. }, true);
  406. });
  407. },
  408. ], async (err, station) => {
  409. if (!err) {
  410. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  411. station.currentSong.skipVotes = 0;
  412. }
  413. //TODO Pub/Sub this
  414. this.utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  415. currentSong: station.currentSong,
  416. startedAt: station.startedAt,
  417. paused: station.paused,
  418. timePaused: 0
  419. });
  420. if (station.privacy === 'public') this.utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  421. else {
  422. let sockets = await this.utils.getRoomSockets('home');
  423. for (let socketId in sockets) {
  424. let socket = sockets[socketId];
  425. let session = sockets[socketId].session;
  426. if (session.sessionId) {
  427. this.cache.hget('sessions', session.sessionId, (err, session) => {
  428. if (!err && session) {
  429. this.db.models.user.findOne({_id: session.userId}, (err, user) => {
  430. if (!err && user) {
  431. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  432. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  433. }
  434. });
  435. }
  436. });
  437. }
  438. }
  439. }
  440. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  441. this.utils.socketsJoinSongRoom(await this.utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong.songId}`);
  442. if (!station.paused) {
  443. this.notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000, null, station);
  444. }
  445. } else {
  446. this.utils.socketsLeaveSongRooms(await this.utils.getRoomSockets(`station.${station._id}`));
  447. }
  448. cb(null, station);
  449. } else {
  450. err = await this.utils.getError(err);
  451. this.logger.error('SKIP_STATION', `Skipping station "${stationId}" failed. "${err}"`);
  452. cb(err);
  453. }
  454. });
  455. }
  456. }
  457. async canUserViewStation(station, userId, cb) {
  458. try { await this._validateHook(); } catch { return; }
  459. async.waterfall([
  460. (next) => {
  461. if (station.privacy !== 'private') return next(true);
  462. if (!userId) return next("Not allowed");
  463. next();
  464. },
  465. (next) => {
  466. this.db.models.user.findOne({_id: userId}, next);
  467. },
  468. (user, next) => {
  469. if (!user) return next("Not allowed");
  470. if (user.role === 'admin') return next(true);
  471. if (station.type === 'official') return next("Not allowed");
  472. if (station.owner === userId) return next(true);
  473. next("Not allowed");
  474. }
  475. ], async (errOrResult) => {
  476. if (errOrResult === true || errOrResult === "Not allowed") return cb(null, (errOrResult === true) ? true : false);
  477. cb(await this.utils.getError(errOrResult));
  478. });
  479. }
  480. }