stations.js 16 KB

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