Переглянути джерело

Cleaned code up a bit with Stations/Songs

theflametrooper 8 роки тому
батько
коміт
9de02f0dd6

+ 1 - 1
backend/index.js

@@ -85,6 +85,6 @@ async.waterfall([
 		console.error('An error occurred while initializing the backend server');
 		console.error(err);
 	} else {
-		console.log('Backend server has been successfully started');
+		console.info('Backend server has been successfully started');
 	}
 });

+ 11 - 18
backend/logic/actions/queueSongs.js

@@ -3,6 +3,7 @@
 const db = require('../db');
 const utils = require('../utils');
 const notifications = require('../notifications');
+const cache = require('../cache');
 const async = require('async');
 const config = require('config');
 const request = require('request');
@@ -45,12 +46,12 @@ module.exports = {
 					updated = true;
 				}
 			}
-			if (!updated) return cb({ status: 'failure', message: 'No properties changed.' });
+			if (!updated) return cb({ status: 'failure', message: 'No properties changed' });
 
 			queueSong.save((err) => {
-				if (err) return cb({ status: 'failure', message: 'Couldn\'t save to Database.' });
+				if (err) return cb({ status: 'failure', message: 'Couldn\'t save to Database' });
 
-				return cb({ status: 'success', message: 'Successfully updated the queueSong object.' });
+				return cb({ status: 'success', message: 'Successfully updated the queueSong object' });
 			});
 
 		});
@@ -72,7 +73,6 @@ module.exports = {
 		async.waterfall([
 			// Get YouTube data from id
 			(next) => {
-				console.log(111, id);
 				const youtubeParams = [
 					'part=snippet,contentDetails,statistics,status',
 					`id=${encodeURIComponent(id)}`,
@@ -89,7 +89,6 @@ module.exports = {
 					body = JSON.parse(body);
 
 					//TODO Clean up duration converter
-					console.log(body);
 					let dur = body.items[0].contentDetails.duration;
 					dur = dur.replace("PT", "");
 					let durInSec = 0;
@@ -126,7 +125,6 @@ module.exports = {
 				});
 			},
 			(newSong, next) => {
-				console.log(222);
 				const spotifyParams = [
 					`q=${encodeURIComponent(newSong.title)}`,
 					`type=track`
@@ -145,6 +143,7 @@ module.exports = {
 					for (let i in body) {
 						let items = body[i].items;
 						for (let j in items) {
+
 							let item = items[j];
 							let hasArtist = false;
 							for (let k = 0; k < item.artists.length; k++) {
@@ -155,7 +154,7 @@ module.exports = {
 							}
 							if (hasArtist && newSong.title.indexOf(item.name) !== -1) {
 								newSong.duration = item.duration_ms / 1000;
-								newSong.artists = item.map(artist => {
+								newSong.artists = item.artists.map(artist => {
 									return artist.name;
 								});
 								newSong.title = item.name;
@@ -163,6 +162,7 @@ module.exports = {
 								newSong.thumbnail = item.album.images[1].url;
 								break durationArtistLoop;
 							}
+
 						}
 					}
 
@@ -170,31 +170,24 @@ module.exports = {
 				});
 			},
 			(newSong, next) => {
-				console.log(333);
 				const song = new db.models.queueSong(newSong);
 
 				song.save(err => {
 
 					if (err) {
 						console.error(err);
-						return next('Failed to add song to database.');
+						return next('Failed to add song to database');
 					}
 
 					//stations.getStation(station).playlist.push(newSong);
-
 					next(null, newSong);
 				});
 			}
 		],
 		(err, newSong) => {
-			console.log(444, err);
-			if (err) {
-				return cb({ status: 'failure', message: err });
-			}
-
-			//TODO Emit to Redis
-			notifications.emit("queue.newSong", newSong._id);
-			return cb({ status: 'success', message: 'Successfully added that song to the queue.' });
+			if (err) return cb({ status: 'error', message: err });
+			cache.pub('queue.newSong', newSong._id);
+			return cb({ status: 'success', message: 'Successfully added that song to the queue' });
 		});
 	}
 

+ 12 - 12
backend/logic/actions/stations.js

@@ -10,6 +10,7 @@ const cache = require('../cache');
 const notifications = require('../notifications');
 const utils = require('../utils');
 const stations = require('../stations');
+
 const defaultSong = {
 	_id: '60ItHLz5WEA',
 	title: 'Faded',
@@ -122,7 +123,7 @@ module.exports = {
 		if (!session) return cb({ status: 'failure', message: 'You must be logged in to skip a song!' });
 
 		stations.initializeAndReturnStation(stationId, (err, station) => {
-
+			
 			if (err && err !== true) {
 				return cb({ status: 'error', message: 'An error occurred while skipping the station' });
 			}
@@ -206,7 +207,7 @@ module.exports = {
 		async.waterfall([
 
 			(next) => {
-				return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data.' });
+				return (data) ? next() : cb({ 'status': 'failure', 'message': 'Invalid data' });
 			},
 
 			// check the cache for the station
@@ -214,27 +215,26 @@ module.exports = {
 
 			// if the cached version exist
 			(station, next) => {
-				if (station) return next({ 'status': 'failure', 'message': 'A station with that name already exists.' });
+				if (station) return next({ 'status': 'failure', 'message': 'A station with that name already exists' });
 				db.models.station.findOne({ _id: data.name }, next);
 			},
 
 			(station, next) => {
-				if (station) return next({ 'status': 'failure', 'message': 'A station with that name already exists.' });
+				if (station) return next({ 'status': 'failure', 'message': 'A station with that name already exists' });
+				const { _id, displayName, description, genres, playlist } = data;
 				db.models.station.create({
-					_id: data.name,
-					displayName: data.displayName,
-					description: data.description,
+					_id,
+					displayName,
+					description,
 					type: "official",
-					playlist: [defaultSong._id],
-					genres: ["edm"],
-					locked: true,
+					playlist,
+					genres,
 					currentSong: defaultSong
 				}, next);
 			}
 
 		], (err, station) => {
-			console.log(err, 123986);
-			if (err) return cb(err);
+			if (err) throw err;
 			stations.calculateSongForStation(station, () => {
 				cache.pub('station.create', data.name);
 				return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });

+ 1 - 4
backend/logic/actions/users.js

@@ -35,9 +35,7 @@ module.exports = {
 						let userSessionId = utils.guid();
 						cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
 							if (!err) {
-								console.log(sessionId, 222);
 								cache.hget('sessions', sessionId, (err, session) => {
-									console.log(err, session, 333);
 									session.userSessionId = userSessionId;
 									cache.hset('sessions', sessionId, session, (err) => {
 										next(null, { status: 'success', message: 'Login successful', user, SID: userSessionId });
@@ -84,8 +82,7 @@ module.exports = {
 			// check if the response from Google recaptcha is successful
 			// if it is, we check if a user with the requested username already exists
 			(/*response, body, */next) => {
-				/*let json = JSON.parse(body);
-				console.log(json);*/
+				/*let json = JSON.parse(body);*/
 				//if (json.success !== true) return next('Response from recaptcha was not successful');
 				db.models.user.findOne({ username }, next);
 			},

+ 1 - 1
backend/logic/db/index.js

@@ -12,7 +12,7 @@ let lib = {
 
 		lib.connection = mongoose.connect(url).connection;
 
-		lib.connection.on('error', err => console.log('Database error: ' + err.message));
+		lib.connection.on('error', err => console.error('Database error: ' + err.message));
 
 		lib.connection.once('open', _ => {
 

+ 2 - 2
backend/logic/db/schemas/station.js

@@ -18,6 +18,6 @@ module.exports = {
 	timePaused: { type: Number, default: 0, required: true },
 	playlist: { type: Array, required: true },
 	genres: [{ type: String }],
-	privacy: { type: String, enum: ["public", "unlisted", "private"], default: "private" },//Used for Community stations
-	locked: { type: Boolean, default: true }//Used for Official stations
+	privacy: { type: String, enum: ["public", "unlisted", "private"], default: "private" },
+	locked: { type: Boolean, default: false }
 };

+ 6 - 9
backend/logic/io.js

@@ -21,10 +21,7 @@ module.exports = {
 			let SID = utils.cookies.parseCookies(cookies).SID;
 
 			cache.hget('userSessions', SID, (err, userSession) => {
-				console.log(err, userSession);
-				if (err) {
-					SID = null;
-				}
+				if (err) SID = null;
 				let sessionId = utils.guid();
 				cache.hset('sessions', sessionId, cache.schemas.session(SID), (err) => {
 					socket.sessionId = sessionId;
@@ -35,7 +32,7 @@ module.exports = {
 
 		this.io.on('connection', socket => {
 			socket.join("SomeRoom");
-			console.log("io: User has connected");
+			console.info('User has connected');
 
 			// catch when the socket has been disconnected
 			socket.on('disconnect', () => {
@@ -47,11 +44,11 @@ module.exports = {
 					cache.hdel('sessions', socket.sessionId);
 				}
 
-				console.log('io: User has disconnected');
+				console.info('User has disconnected');
 			});
 
 			// catch errors on the socket (internal to socket.io)
-			socket.on('error', err => console.log(err));
+			socket.on('error', err => console.error(err));
 
 			// have the socket listen for each action
 			Object.keys(actions).forEach((namespace) => {
@@ -96,8 +93,8 @@ module.exports = {
 					socket.emit('ready', false);
 				} else if (session) {
 					if (!!session.userSessionId) {
-						cache.hget('userSessions', session.userSessionId, (err2, userSession) => {
-							if (err2 && err2 !== true) {
+						cache.hget('userSessions', session.userSessionId, (err, userSession) => {
+							if (err && err !== true) {
 								socket.emit('ready', false);
 							} else if (userSession) {
 								db.models.user.findOne({ _id: userSession.userId }, (err, user) => {

+ 5 - 6
backend/logic/stations.js

@@ -14,11 +14,10 @@ module.exports = {
 
 	init: function(cb) {
 		let _this = this;
-		console.log("Init stations");
 		db.models.station.find({}, (err, stations) => {
 			if (!err) {
 				stations.forEach((station) => {
-					console.log("Initing " + station._id);
+					console.info("Initializing Station: " + station._id);
 					_this.initializeAndReturnStation(station._id, (err, station) => {
 						//TODO Emit to homepage and admin station list
 					});
@@ -94,7 +93,6 @@ module.exports = {
 			/*let notification = notifications.subscribe(`stations.nextSong?id=${station._id}`, () => {*/
 			function skipSongTemp() {
 				// get the station from the cache
-				console.log('NOTIFICATION');
 				//TODO Recalculate songs if the last song of the station playlist is getting played
 				cache.hget('stations', station._id, (err, station) => {
 					if (station) {
@@ -104,7 +102,7 @@ module.exports = {
 							(next) => {
 								if (station.currentSongIndex < station.playlist.length - 1) {
 									station.currentSongIndex++;
-									db.models.song.findOne({_id: station.playlist[station.currentSongIndex]}, (err, song) => {
+									db.models.song.findOne({ _id: station.playlist[station.currentSongIndex] }, (err, song) => {
 										if (!err) {
 											station.currentSong = {
 												_id: song._id,
@@ -123,9 +121,10 @@ module.exports = {
 								} else {
 									station.currentSongIndex = 0;
 									_this.calculateSongForStation(station, (err, newPlaylist) => {
+										console.log('New playlist: ', newPlaylist)
 										if (!err) {
-											db.models.song.findOne({_id: newPlaylist[0]}, (err, song) => {
-												if (!err) {
+											db.models.song.findOne({ _id: newPlaylist[0] }, (err, song) => {
+												if (song) {
 													station.currentSong = {
 														_id: song._id,
 														title: song.title,

+ 0 - 1
frontend/App.vue

@@ -67,7 +67,6 @@
 				let { login: { email, password } } = this;
 
 				this.socket.emit('users.login', email, password, result => {
-					console.log(result);
 					if (result.status === 'success') {
 						let date = new Date();
 						date.setTime(new Date().getTime() + (2*365*24*60*60*1000));

+ 15 - 7
frontend/components/Admin/QueueSongs.vue

@@ -53,19 +53,27 @@
 		},
 		methods: {
 			update (song) {
-				this.socket.emit('queueSongs.update', song);
+				this.socket.emit('queueSongs.update', song, res => {
+					console.log(res);
+				});
 			},
 			remove (songId) {
-				this.socket.emit('queueSongs.remove', songId);
+				this.socket.emit('queueSongs.remove', songId, res => {
+					console.log(res);
+				});
 			}
 		},
 		ready: function() {
 			let _this = this;
-			_this.socket = _this.$parent.$parent.socket;
-			_this.socket.emit('queueSongs.index', (data) => {
-				console.log(data);
-				_this.songs = data;
-			});
+			let socketInterval = setInterval(() => {
+				if (!!_this.$parent.$parent.socket) {
+					_this.socket = _this.$parent.$parent.socket;
+					_this.socket.emit('queueSongs.index', data => {
+						_this.songs = data;
+					});
+					clearInterval(socketInterval);
+				}
+			}, 100);
 		}
 	}
 </script>

+ 50 - 21
frontend/components/Admin/Stations.vue

@@ -15,7 +15,7 @@
 					<tr v-for="(index, station) in stations" track-by="$index">
 						<td>
 							<p class="control">
-								<input class="input" type="text" :value="station.id" v-model="station.id">
+								<input class="input" type="text" :value="station.id" v-model="station._id">
 							</p>
 						</td>
 						<td>
@@ -50,14 +50,13 @@
 				</header>
 				<div class="card-content">
 					<div class="content">
-						<label class="label">Name</label>
 						<div class="control is-horizontal">
 							<div class="control is-grouped">
 								<p class="control is-expanded">
-									<input class="input" type="text" placeholder="Locale name" v-model="newStation.name">
+									<input class="input" type="text" placeholder="Unique Identifier" v-model="newStation._id">
 								</p>
 								<p class="control is-expanded">
-									<input class="input" type="text" placeholder="Display name" v-model="newStation.displayName">
+									<input class="input" type="text" placeholder="Display Name" v-model="newStation.displayName">
 								</p>
 							</div>
 						</div>
@@ -65,14 +64,16 @@
 						<p class="control is-expanded">
 							<input class="input" type="text" placeholder="Short description" v-model="newStation.description">
 						</p>
+						<label class="label">Default Song</label>
+						<p class="control is-expanded">
+							<input class="input" type="text" placeholder="YouTube ID" v-model="newStation.defaultSong">
+						</p>
 						<label class="label">Genres</label>
 						<p class="control has-addons">
-							<input class="input" type="text" placeholder="Genre" v-model="newStationGenre">
-							<a class="button is-info">Add genre</a>
+							<input class="input" id="new-genre" type="text" placeholder="Genre">
+							<a class="button is-info" @click="addGenre()">Add genre</a>
 						</p>
-						<span class="tag is-info">Bar<button class="delete is-info"></button></span>
-						<span class="tag is-info">Bar<button class="delete is-info"></button></span>
-						<span class="tag is-info">Bar<button class="delete is-info"></button></span>
+						<span class="tag is-info" v-for="genre in newStation.genres" track-by="$index">{{ genre }}<button class="delete is-info"></button></span>
 					</div>
 				</div>
 				<footer class="card-footer">
@@ -84,11 +85,15 @@
 </template>
 
 <script>
+	import { Toast } from 'vue-roaster';
+
 	export default {
 		data() {
 			return {
 				stations: [],
-				newStation: {}
+				newStation: {
+					genres: []
+				}
 			}
 		},
 		methods: {
@@ -113,22 +118,44 @@
 			// 		console.log(data);
 			// 	});
 			// },
-			createStation: function() {
+			createStation: function () {
 				let _this = this;
-				let { newStation: { name, displayName, description } } = this;
-				let data = { name, displayName, description, genres: ['edm'] };
-				_this.socket.emit('stations.create', data, result => {
+				let { newStation: { _id, displayName, description, genres } } = this;
+
+				let playlist = [];
+				playlist.push(this.newStation.defaultSong);
+
+				if (_id == undefined) return Toast.methods.addToast('Field (YouTube ID) cannot be empty', 2000);
+				if (displayName == undefined) return Toast.methods.addToast('Field (Display Name) cannot be empty', 2000);
+				if (description == undefined) return Toast.methods.addToast('Field (Description) cannot be empty', 2000);
+
+				_this.socket.emit('stations.create', {
+					_id,
+					type: "official",
+					displayName,
+					description,
+					playlist,
+					genres,
+				}, result => {
 					console.log(result);
 				});
+			},
+			addGenre: function () {
+				if ($("#new-genre").val() !== "") this.newStation.genres.push($("#new-genre").val());
+				else Toast.methods.addToast('Genre cannot be empty', 2000);
 			}
 		},
-		ready: function() {
-			let socket = this.socket = this.$parent.$parent.socket;
-			socket.emit("stations.index", (data) => {
-				console.log(data);
-				this.stations = data;
-			});
-			console.log('ready');
+		ready: function () {
+			let _this = this;
+			let socketInterval = setInterval(() => {
+				if (!!_this.$parent.$parent.socket) {
+					_this.socket = _this.$parent.$parent.socket;
+					_this.socket.emit("stations.index", data => {
+						_this.stations = data.stations;
+					});
+					clearInterval(socketInterval);
+				}
+			}, 100);
 		}
 	}
 </script>
@@ -137,4 +164,6 @@
 	.is-success {
 		width: 100%;
 	}
+
+	.tag:not(:last-child) { margin-right: 5px; }
 </style>

+ 5 - 12
frontend/components/Station/Station.vue

@@ -68,7 +68,7 @@
 							</td>
 							<td>{{result.title}}</td>
 							<td>
-								<a class="button is-success" @click="addSongToQueue(result)">
+								<a class="button is-success" @click="addSongToQueue(result.id)">
 									Add
 								</a>
 							</td>
@@ -105,7 +105,6 @@
 			},
 			youtubeReady: function() {
 				let local = this;
-				console.log(123457)
 				local.player = new YT.Player("player", {
 					height: 270,
 					width: 480,
@@ -113,7 +112,6 @@
 					playerVars: {controls: 1, iv_load_policy: 3, rel: 0, showinfo: 0},
 					events: {
 						'onReady': function(event) {
-							console.log(4540590459);
 							local.playerReady = true;
 							let volume = parseInt(localStorage.getItem("volume"));
 							volume = (typeof volume === "number") ? volume : 20;
@@ -124,11 +122,9 @@
 							local.playVideo();
 						},
 						'onStateChange': function(event) {
-							console.log(event);
 							if (event.data === 1 && local.videoLoading === true) {
 								local.videoLoading = false;
 								local.player.seekTo(local.getTimeElapsed() / 1000, true);
-								console.log(local.paused);
 								if (local.paused) {
 									local.player.pauseVideo();
 								}
@@ -185,8 +181,8 @@
 				let duration = (Date.now() - local.startedAt - local.timePaused) / 1000;
 				let songDuration = local.currentSong.duration;
 				if (songDuration <= duration) {
-					console.log("PAUSE!");
-					console.log(songDuration, duration);
+					// console.log("PAUSE!");
+					// console.log(songDuration, duration);
 					local.player.pauseVideo();
 				}
 
@@ -221,12 +217,11 @@
 				}
 			},
 			addSongToQueue: function(songId) {
-				console.log('add', songId);
 				let local = this;
 				local.socket.emit('queueSongs.add', songId, function(data) {
 					if (data) console.log(data);
 				});
-			}/*,
+			},
 			submitQuery: function() {
 				let local = this;
 				local.socket.emit('apis.searchYoutube', local.querySearch, function(results) {
@@ -241,7 +236,7 @@
 						});
 					}
 				});
-			}*/
+			}
 		},
 		ready: function() {
 			let _this = this;
@@ -252,7 +247,6 @@
 			_this.socket = _this.$parent.socket;
 
 			_this.socket.emit('stations.join', _this.stationId, data => {
-				console.log(data);
 				if (data.status === "success") {
 					_this.currentSong = data.currentSong;
 					_this.startedAt = data.startedAt;
@@ -266,7 +260,6 @@
 			});
 
 			_this.socket.on('event:songs.next', data => {
-				console.log("NEXT SONG");
 				_this.currentSong = data.currentSong;
 				_this.startedAt = data.startedAt;
 				_this.paused = data.paused;

+ 1 - 0
frontend/components/pages/Home.vue

@@ -64,6 +64,7 @@
 				if (!!_this.$parent.socket) {
 					_this.socket = _this.$parent.socket;
 					_this.socket.emit("stations.index", data => {
+						console.log(data)
 						if (data.status === "success")  data.stations.forEach(station => {
 							if (station.type == 'official') _this.stations.official.push(station);
 							else _this.stations.community.push(station);

+ 0 - 1
frontend/main.js

@@ -20,7 +20,6 @@ lofig.folder = '../config/default.json';
 lofig.get('socket.url', function(res) {
 	let socket = window.socket = io(window.location.protocol + '//' + res);
 	socket.on("ready", (status, role) => {
-		console.log(status, role)
 		auth.data(status, role);
 	});
 });