stations.js 16 KB

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