| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537 | 
							- 'use strict';
 
- const coreClass = require("../core");
 
- const async = require('async');
 
- let subscription = null;
 
- module.exports = class extends coreClass {
 
- 	constructor(name, moduleManager) {
 
- 		super(name, moduleManager);
 
- 		this.dependsOn = ["cache", "db", "utils"];
 
- 	}
 
- 	initialize() {
 
- 		return new Promise(async (resolve, reject) => {
 
- 			this.setStage(1);
 
- 			this.cache = this.moduleManager.modules["cache"];
 
- 			this.db = this.moduleManager.modules["db"];
 
- 			this.utils = this.moduleManager.modules["utils"];
 
- 			this.songs = this.moduleManager.modules["songs"];
 
- 			this.notifications = this.moduleManager.modules["notifications"];
 
- 			this.defaultSong = {
 
- 				songId: '60ItHLz5WEA',
 
- 				title: 'Faded - Alan Walker',
 
- 				duration: 212,
 
- 				skipDuration: 0,
 
- 				likes: -1,
 
- 				dislikes: -1
 
- 			};
 
- 			//TEMP
 
- 			this.cache.sub('station.pause', async (stationId) => {
 
- 				try { await this._validateHook(); } catch { return; }
 
- 				this.notifications.remove(`stations.nextSong?id=${stationId}`);
 
- 			});
 
- 			this.cache.sub('station.resume', async (stationId) => {
 
- 				try { await this._validateHook(); } catch { return; }
 
- 				this.initializeStation(stationId)
 
- 			});
 
- 			this.cache.sub('station.queueUpdate', async (stationId) => {
 
- 				try { await this._validateHook(); } catch { return; }
 
- 				this.getStation(stationId, (err, station) => {
 
- 					if (!station.currentSong && station.queue.length > 0) {
 
- 						this.initializeStation(stationId);
 
- 					}
 
- 				});
 
- 			});
 
- 			this.cache.sub('station.newOfficialPlaylist', async (stationId) => {
 
- 				try { await this._validateHook(); } catch { return; }
 
- 				this.cache.hget("officialPlaylists", stationId, (err, playlistObj) => {
 
- 					if (!err && playlistObj) {
 
- 						this.utils.emitToRoom(`station.${stationId}`, "event:newOfficialPlaylist", playlistObj.songs);
 
- 					}
 
- 				})
 
- 			});
 
- 			async.waterfall([
 
- 				(next) => {
 
- 					this.setStage(2);
 
- 					this.cache.hgetall('stations', next);
 
- 				},
 
- 	
 
- 				(stations, next) => {
 
- 					this.setStage(3);
 
- 					if (!stations) return next();
 
- 					let stationIds = Object.keys(stations);
 
- 					async.each(stationIds, (stationId, next) => {
 
- 						this.db.models.station.findOne({_id: stationId}, (err, station) => {
 
- 							if (err) next(err);
 
- 							else if (!station) {
 
- 								this.cache.hdel('stations', stationId, next);
 
- 							} else next();
 
- 						});
 
- 					}, next);
 
- 				},
 
- 	
 
- 				(next) => {
 
- 					this.setStage(4);
 
- 					this.db.models.station.find({}, next);
 
- 				},
 
- 	
 
- 				(stations, next) => {
 
- 					this.setStage(5);
 
- 					async.each(stations, (station, next2) => {
 
- 						async.waterfall([
 
- 							(next) => {
 
- 								this.cache.hset('stations', station._id, this.cache.schemas.station(station), next);
 
- 							},
 
- 	
 
- 							(station, next) => {
 
- 								this.initializeStation(station._id, () => {
 
- 									next()
 
- 								}, true);
 
- 							}
 
- 						], (err) => {
 
- 							next2(err);
 
- 						});
 
- 					}, next);
 
- 				}
 
- 			], async (err) => {
 
- 				if (err) {
 
- 					err = await this.utils.getError(err);
 
- 					reject(err);
 
- 				} else {
 
- 					resolve();
 
- 				}
 
- 			});
 
- 		});
 
- 	}
 
- 	async initializeStation(stationId, cb, bypassValidate = false) {
 
- 		if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 		if (typeof cb !== 'function') cb = ()=>{};
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				this.getStation(stationId, next, true);
 
- 			},
 
- 			(station, next) => {
 
- 				if (!station) return next('Station not found.');
 
- 				this.notifications.unschedule(`stations.nextSong?id=${station._id}`);
 
- 				subscription = this.notifications.subscribe(`stations.nextSong?id=${station._id}`, this.skipStation(station._id), true, station);
 
- 				if (station.paused) return next(true, station);
 
- 				next(null, station);
 
- 			},
 
- 			(station, next) => {
 
- 				if (!station.currentSong) {
 
- 					return this.skipStation(station._id)((err, station) => {
 
- 						if (err) return next(err);
 
- 						return next(true, station);
 
- 					}, true);
 
- 				}
 
- 				let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
 
- 				if (isNaN(timeLeft)) timeLeft = -1;
 
- 				if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
 
- 					this.skipStation(station._id)((err, station) => {
 
- 						next(err, station);
 
- 					}, true);
 
- 				} else {
 
- 					this.notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft, null, station);
 
- 					next(null, station);
 
- 				}
 
- 			}
 
- 		], (err, station) => {
 
- 			if (err && err !== true) return cb(err);
 
- 			cb(null, station);
 
- 		});
 
- 	}
 
- 	async calculateSongForStation(station, cb, bypassValidate = false) {
 
- 		if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 		let songList = [];
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				if (station.genres.length === 0) return next();
 
- 				let genresDone = [];
 
- 				station.genres.forEach((genre) => {
 
- 					this.db.models.song.find({genres: genre}, (err, songs) => {
 
- 						if (!err) {
 
- 							songs.forEach((song) => {
 
- 								if (songList.indexOf(song._id) === -1) {
 
- 									let found = false;
 
- 									song.genres.forEach((songGenre) => {
 
- 										if (station.blacklistedGenres.indexOf(songGenre) !== -1) found = true;
 
- 									});
 
- 									if (!found) {
 
- 										songList.push(song._id);
 
- 									}
 
- 								}
 
- 							});
 
- 						}
 
- 						genresDone.push(genre);
 
- 						if (genresDone.length === station.genres.length) next();
 
- 					});
 
- 				});
 
- 			},
 
- 			(next) => {
 
- 				let playlist = [];
 
- 				songList.forEach(function(songId) {
 
- 					if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
 
- 				});
 
- 				station.playlist.filter((songId) => {
 
- 					if (songList.indexOf(songId) !== -1) playlist.push(songId);
 
- 				});
 
- 				this.utils.shuffle(playlist).then((playlist) => {
 
- 					next(null, playlist);
 
- 				});
 
- 			},
 
- 			(playlist, next) => {
 
- 				this.calculateOfficialPlaylistList(station._id, playlist, () => {
 
- 					next(null, playlist);
 
- 				}, true);
 
- 			},
 
- 			(playlist, next) => {
 
- 				this.db.models.station.updateOne({_id: station._id}, {$set: {playlist: playlist}}, {runValidators: true}, (err) => {
 
- 					this.updateStation(station._id, () => {
 
- 						next(err, playlist);
 
- 					}, true);
 
- 				});
 
- 			}
 
- 		], (err, newPlaylist) => {
 
- 			cb(err, newPlaylist);
 
- 		});
 
- 	}
 
- 	// Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
 
- 	async getStation(stationId, cb, bypassValidate = false) {
 
- 		if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				this.cache.hget('stations', stationId, next);
 
- 			},
 
- 			(station, next) => {
 
- 				if (station) return next(true, station);
 
- 				this.db.models.station.findOne({ _id: stationId }, next);
 
- 			},
 
- 			(station, next) => {
 
- 				if (station) {
 
- 					if (station.type === 'official') {
 
- 						this.calculateOfficialPlaylistList(station._id, station.playlist, () => {});
 
- 					}
 
- 					station = this.cache.schemas.station(station);
 
- 					this.cache.hset('stations', stationId, station);
 
- 					next(true, station);
 
- 				} else next('Station not found');
 
- 			},
 
- 		], (err, station) => {
 
- 			if (err && err !== true) return cb(err);
 
- 			cb(null, station);
 
- 		});
 
- 	}
 
- 	// Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
 
- 	async getStationByName(stationName, cb) {
 
- 		try { await this._validateHook(); } catch { return; }
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				this.db.models.station.findOne({ name: stationName }, next);
 
- 			},
 
- 			(station, next) => {
 
- 				if (station) {
 
- 					if (station.type === 'official') {
 
- 						this.calculateOfficialPlaylistList(station._id, station.playlist, ()=>{});
 
- 					}
 
- 					station = this.cache.schemas.station(station);
 
- 					this.cache.hset('stations', station._id, station);
 
- 					next(true, station);
 
- 				} else next('Station not found');
 
- 			},
 
- 		], (err, station) => {
 
- 			if (err && err !== true) return cb(err);
 
- 			cb(null, station);
 
- 		});
 
- 	}
 
- 	async updateStation(stationId, cb, bypassValidate = false) {
 
- 		if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				this.db.models.station.findOne({ _id: stationId }, next);
 
- 			},
 
- 			(station, next) => {
 
- 				if (!station) {
 
- 					this.cache.hdel('stations', stationId);
 
- 					return next('Station not found');
 
- 				}
 
- 				this.cache.hset('stations', stationId, station, next);
 
- 			}
 
- 		], (err, station) => {
 
- 			if (err && err !== true) return cb(err);
 
- 			cb(null, station);
 
- 		});
 
- 	}
 
- 	async calculateOfficialPlaylistList(stationId, songList, cb, bypassValidate = false) {
 
- 		if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 		let lessInfoPlaylist = [];
 
- 		async.each(songList, (song, next) => {
 
- 			this.songs.getSong(song, (err, song) => {
 
- 				if (!err && song) {
 
- 					let newSong = {
 
- 						songId: song.songId,
 
- 						title: song.title,
 
- 						artists: song.artists,
 
- 						duration: song.duration
 
- 					};
 
- 					lessInfoPlaylist.push(newSong);
 
- 				}
 
- 				next();
 
- 			});
 
- 		}, () => {
 
- 			this.cache.hset("officialPlaylists", stationId, this.cache.schemas.officialPlaylist(stationId, lessInfoPlaylist), () => {
 
- 				this.cache.pub("station.newOfficialPlaylist", stationId);
 
- 				cb();
 
- 			});
 
- 		});
 
- 	}
 
- 	skipStation(stationId) {
 
- 		this.logger.info("STATION_SKIP", `Skipping station ${stationId}.`, false);
 
- 		return async (cb, bypassValidate = false) => {
 
- 			if (!bypassValidate) try { await this._validateHook(); } catch { return; }
 
- 			this.logger.stationIssue(`SKIP_STATION_CB - Station ID: ${stationId}.`);
 
- 			if (typeof cb !== 'function') cb = ()=>{};
 
- 			async.waterfall([
 
- 				(next) => {
 
- 					this.getStation(stationId, next, true);
 
- 				},
 
- 				(station, next) => {
 
- 					if (!station) return next('Station not found.');
 
- 					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
 
- 					if (station.type === 'community' && station.partyMode && station.queue.length > 0) { // Community station with party mode enabled and songs in the queue
 
- 						return this.db.models.station.updateOne({_id: stationId}, {$pull: {queue: {_id: station.queue[0]._id}}}, (err) => {
 
- 							if (err) return next(err);
 
- 							next(null, station.queue[0], -12, station);
 
- 						});
 
- 					}
 
- 					if (station.type === 'community' && !station.partyMode) {
 
- 						return this.db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
 
- 							if (err) return next(err);
 
- 							if (!playlist) return next(null, null, -13, station);
 
- 							playlist = playlist.songs;
 
- 							if (playlist.length > 0) {
 
- 								let currentSongIndex;
 
- 								if (station.currentSongIndex < playlist.length - 1) currentSongIndex = station.currentSongIndex + 1;
 
- 								else currentSongIndex = 0;
 
- 								let callback = (err, song) => {
 
- 									if (err) return next(err);
 
- 									if (song) return next(null, song, currentSongIndex, station);
 
- 									else {
 
- 										let song = playlist[currentSongIndex];
 
- 										let currentSong = {
 
- 											songId: song.songId,
 
- 											title: song.title,
 
- 											duration: song.duration,
 
- 											likes: -1,
 
- 											dislikes: -1
 
- 										};
 
- 										return next(null, currentSong, currentSongIndex, station);
 
- 									}
 
- 								};
 
- 								if (playlist[currentSongIndex]._id) this.songs.getSong(playlist[currentSongIndex]._id, callback);
 
- 								else this.songs.getSongFromId(playlist[currentSongIndex].songId, callback);
 
- 							} else return next(null, null, -14, station);
 
- 						});
 
- 					}
 
- 					if (station.type === 'official' && station.playlist.length === 0) {
 
- 						return this.calculateSongForStation(station, (err, playlist) => {
 
- 							if (err) return next(err);
 
- 							if (playlist.length === 0) return next(null, this.defaultSong, 0, station);
 
- 							else {
 
- 								this.songs.getSong(playlist[0], (err, song) => {
 
- 									if (err || !song) return next(null, this.defaultSong, 0, station);
 
- 									return next(null, song, 0, station);
 
- 								});
 
- 							}
 
- 						}, true);
 
- 					}
 
- 					if (station.type === 'official' && station.playlist.length > 0) {
 
- 						async.doUntil((next) => {
 
- 							if (station.currentSongIndex < station.playlist.length - 1) {
 
- 								this.songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
 
- 									if (!err) return next(null, song, station.currentSongIndex + 1);
 
- 									else {
 
- 										station.currentSongIndex++;
 
- 										next(null, null, null);
 
- 									}
 
- 								});
 
- 							} else {
 
- 								this.calculateSongForStation(station, (err, newPlaylist) => {
 
- 									if (err) return next(null, this.defaultSong, 0);
 
- 									this.songs.getSong(newPlaylist[0], (err, song) => {
 
- 										if (err || !song) return next(null, this.defaultSong, 0);
 
- 										station.playlist = newPlaylist;
 
- 										next(null, song, 0);
 
- 									});
 
- 								}, true);
 
- 							}
 
- 						}, (song, currentSongIndex, next) => {
 
- 							if (!!song) return next(null, true, currentSongIndex);
 
- 							else return next(null, false);
 
- 						}, (err, song, currentSongIndex) => {
 
- 							return next(err, song, currentSongIndex, station);
 
- 						});
 
- 					}
 
- 				},
 
- 				(song, currentSongIndex, station, next) => {
 
- 					let $set = {};
 
- 					if (song === null) $set.currentSong = null;
 
- 					else if (song.likes === -1 && song.dislikes === -1) {
 
- 						$set.currentSong = {
 
- 							songId: song.songId,
 
- 							title: song.title,
 
- 							duration: song.duration,
 
- 							skipDuration: 0,
 
- 							likes: -1,
 
- 							dislikes: -1
 
- 						};
 
- 					} else {
 
- 						$set.currentSong = {
 
- 							songId: song.songId,
 
- 							title: song.title,
 
- 							artists: song.artists,
 
- 							duration: song.duration,
 
- 							likes: song.likes,
 
- 							dislikes: song.dislikes,
 
- 							skipDuration: song.skipDuration,
 
- 							thumbnail: song.thumbnail
 
- 						};
 
- 					}
 
- 					if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
 
- 					$set.startedAt = Date.now();
 
- 					$set.timePaused = 0;
 
- 					if (station.paused) $set.pausedAt = Date.now();
 
- 					next(null, $set, station);
 
- 				},
 
- 				($set, station, next) => {
 
- 					this.db.models.station.updateOne({_id: station._id}, {$set}, (err) => {
 
- 						this.updateStation(station._id, (err, station) => {
 
- 							if (station.type === 'community' && station.partyMode === true)
 
- 								this.cache.pub('station.queueUpdate', stationId);
 
- 							next(null, station);
 
- 						}, true);
 
- 					});
 
- 				},
 
- 			], async (err, station) => {
 
- 				if (!err) {
 
- 					if (station.currentSong !== null && station.currentSong.songId !== undefined) {
 
- 						station.currentSong.skipVotes = 0;
 
- 					}
 
- 					//TODO Pub/Sub this
 
- 					this.utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
 
- 						currentSong: station.currentSong,
 
- 						startedAt: station.startedAt,
 
- 						paused: station.paused,
 
- 						timePaused: 0
 
- 					});
 
- 					if (station.privacy === 'public') this.utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
 
- 					else {
 
- 						let sockets = await this.utils.getRoomSockets('home');
 
- 						for (let socketId in sockets) {
 
- 							let socket = sockets[socketId];
 
- 							let session = sockets[socketId].session;
 
- 							if (session.sessionId) {
 
- 								this.cache.hget('sessions', session.sessionId, (err, session) => {
 
- 									if (!err && session) {
 
- 										this.db.models.user.findOne({_id: session.userId}, (err, user) => {
 
- 											if (!err && user) {
 
- 												if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
 
- 												else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
 
- 											}
 
- 										});
 
- 									}
 
- 								});
 
- 							}
 
- 						}
 
- 					}
 
- 					if (station.currentSong !== null && station.currentSong.songId !== undefined) {
 
- 						this.utils.socketsJoinSongRoom(await this.utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong.songId}`);
 
- 						if (!station.paused) {
 
- 							this.notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000, null, station);
 
- 						}
 
- 					} else {
 
- 						this.utils.socketsLeaveSongRooms(await this.utils.getRoomSockets(`station.${station._id}`));
 
- 					}
 
- 					cb(null, station);
 
- 				} else {
 
- 					err = await this.utils.getError(err);
 
- 					this.logger.error('SKIP_STATION', `Skipping station "${stationId}" failed. "${err}"`);
 
- 					cb(err);
 
- 				}
 
- 			});
 
- 		}
 
- 	}
 
- 	async canUserViewStation(station, userId, cb) {
 
- 		try { await this._validateHook(); } catch { return; }
 
- 		async.waterfall([
 
- 			(next) => {
 
- 				if (station.privacy !== 'private') return next(true);
 
- 				if (!userId) return next("Not allowed");
 
- 				next();
 
- 			},
 
- 			
 
- 			(next) => {
 
- 				this.db.models.user.findOne({_id: userId}, next);
 
- 			},
 
- 			
 
- 			(user, next) => {
 
- 				if (!user) return next("Not allowed");
 
- 				if (user.role === 'admin') return next(true);
 
- 				if (station.type === 'official') return next("Not allowed");
 
- 				if (station.owner === userId) return next(true);
 
- 				next("Not allowed");
 
- 			}
 
- 		], async (errOrResult) => {
 
- 			if (errOrResult === true || errOrResult === "Not allowed") return cb(null, (errOrResult === true) ? true : false);
 
- 			cb(await this.utils.getError(errOrResult));
 
- 		});
 
- 	}
 
- }
 
 
  |