Explorar o código

Setup songs to be added to playlist. Fixed issues and cleaned up timeElapsed

theflametrooper %!s(int64=8) %!d(string=hai) anos
pai
achega
eb15cfe2a5

+ 1 - 2
backend/app.js

@@ -50,8 +50,7 @@ function setupExpress() {
 
 	global.db = {
 		user: require('./schemas/user')(mongoose),
-		station: require('./schemas/station')(mongoose),
-		song: require('./schemas/song')(mongoose)
+		station: require('./schemas/station')(mongoose)
 	};
 
 	const mongoStore = new MongoStore({'mongooseConnection': MongoDB});

+ 22 - 95
backend/logic/coreHandler.js

@@ -26,7 +26,7 @@ const edmStation = new stations.Station("edm", {
 			id: "dQw4w9WgXcQ",
 			title: "Never gonna give you up",
 			artists: ["Rick Astley"],
-			duration: 20,
+			duration: '00:01:18',
 			thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
 			likes: 0,
 			dislikes: 1
@@ -35,7 +35,7 @@ const edmStation = new stations.Station("edm", {
 			id: "GxBSyx85Kp8",
 			title: "Yeah!",
 			artists: ["Usher"],
-			duration: 20,
+			duration: '00:00:08',
 			thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
 			likes: 0,
 			dislikes: 1
@@ -47,36 +47,7 @@ const edmStation = new stations.Station("edm", {
 	description: "EDM Music"
 });
 
-const popStation = new stations.Station("pop", {
-	"genres": ["pop"],
-	playlist: [
-		{
-			id: "HXeYRs_zR6w",
-			title: "Nobody But Me",
-			artists: ["Michael Bublé"],
-			duration: 12,
-			thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
-			likes: 0,
-			dislikes: 1
-		},
-		{
-			id: "CR4YE7htLgI",
-			title: "Someday ",
-			artists: ["Michael Bublé", "Meghan Trainor"],
-			duration: 30,
-			thumbnail: "https://yt3.ggpht.com/-CGlBu6kDEi8/AAAAAAAAAAI/AAAAAAAAAAA/Pi679mvyyyU/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
-			likes: 0,
-			dislikes: 1
-		}
-	],
-	currentSongIndex: 0,
-	paused: false,
-	displayName: "Pop",
-	description: "Pop Music"
-});
-
 stations.addStation(edmStation);
-stations.addStation(popStation);
 
 module.exports = {
 
@@ -186,77 +157,33 @@ module.exports = {
 			'type=video',
 			'maxResults=15'
 		].join('&');
-		// function params(type, id) {
-		// 	if (type == "search") {
-		// 		return [
-		// 			'part=snippet',
-		// 			`q=${encodeURIComponent(query)}`,
-		// 			`key=${config.get('apis.youtube.key')}`,
-		// 			'type=video',
-		// 			'maxResults=15'
-		// 		].join('&');
-		// 	} else if (type == "video") {
-		// 		return [
-		// 			'part=snippet,contentDetails,statistics,status',
-		// 			`id=${encodeURIComponent(id)}`,
-		// 			`key=${config.get('apis.youtube.key')}`
-		// 		].join('&');
-		// 	}
-		// }
-
-		// let finalResults = [];
 
 		request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
 			cb(body);
-			// for (let i = 0; i < results.items.length; i++) {
-			// 	request(`https://www.googleapis.com/youtube/v3/videos?${
-			// 		params("video", results.items[i].id.videoId)
-			// 	}`, (err, res, body) => {
-			// 		finalResults.push(JSON.parse(body));
-			// 	});
-			// }
-			// setTimeout(() => {
-			// 	return cb(finalResults);
-			// }, 500);
 		});
 	},
 
-	'/songs/queue/add/:song': (song, user, cb) => {
+	'/stations/add/:song': (station, song, user, cb) => {
+		const params = [
+			'part=snippet,contentDetails,statistics,status',
+			`id=${encodeURIComponent(song.id)}`,
+			`key=${config.get('apis.youtube.key')}`
+		].join('&');
+
 		if (user.logged_in) {
-				// if (songs.length > 0) {
-				// 	let failed = 0;
-				// 	let success = 0;
-				// 	songs.forEach(function (song) {
-				// 		if (typeof song === "object" && song !== null) {
-				// 			let obj = {};
-				// 			obj.title = song.title;
-				// 			obj._id = song.id;
-				// 			obj.artists = [];
-				// 			obj.image = "test";
-				// 			obj.duration = 0;
-				// 			obj.genres = ["edm"];
-				// 			//TODO Get data from Wikipedia and Spotify
-				// 			obj.requestedBy = user._id;
-				// 			console.log(user._id);
-				// 			console.log(user);
-				// 			obj.requestedAt = Date.now();
-				// 			let queueSong = new global.db.queueSong(obj);
-				// 			queueSong.save(function(err) {
-				// 				console.log(err);
-				// 				if (err) failed++;
-				// 				else success++;
-				// 			});
-				// 		} else {
-				// 			failed++;
-				// 		}
-				// 	});
-				// 	cb({success, failed});
-				// } else {
-				// 	cb({err: "No songs supplied."});
-				// }
-				console.log(song);
-			} else {
-			cb({err: "Not logged in."});
+			request(`https://www.googleapis.com/youtube/v3/videos?${params}`, (err, res, body) => {
+				// TODO: Get data from Wikipedia and Spotify
+				body = JSON.parse(body);
+				let newSong = {
+					id: body.items[0].id,
+					title: body.items[0].snippet.title,
+					artists: [""],
+					duration: global.convertTime(body.items[0].contentDetails.duration),
+					thumbnail: body.items[0].snippet.thumbnails.high.url
+				};
+				stations.getStation(station).playlist.push(newSong);
+				cb(stations.getStation(station.playlist));
+			});
 		}
 	},
 

+ 5 - 2
backend/logic/global.js

@@ -1,12 +1,14 @@
 'use strict';
 
+const moment = require('moment');
+
 class Timer {
 	constructor(callback, delay, paused) {
 		this.callback = callback;
 		this.timerId = undefined;
 		this.start = undefined;
 		this.paused = paused;
-		this.remaining = delay * 1000;
+		this.remaining = moment.duration(delay, "hh:mm:ss").asSeconds() * 1000;
 		this.timeWhenPaused = 0;
 		this.timePaused = Date.now();
 
@@ -89,7 +91,8 @@ function convertTime(duration) {
     let minutes = Math.floor(duration % 3600 / 60);
     let seconds = Math.floor(duration % 3600 % 60);
 
-    return ((hours > 0 ? hours + ":" + (minutes) : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
+	return (hours < 10 ? ("0" + hours + ":") : (hours + ":")) + (minutes < 10 ? ("0" + minutes + ":") : (minutes + ":")) + (seconds < 10 ? ("0" + seconds) : seconds); // 00:00:23
+    // return moment.duration(final, "hh:mm:ss").asSeconds(); // 23
 }
 
 module.exports = {

+ 2 - 2
backend/logic/socketHandler.js

@@ -33,8 +33,8 @@ module.exports = (core, io) => {
 			});
 		});
 
-		socket.on('/songs/queue/add/:song', (song, cb) => {
-			core['/songs/queue/add/:song'](song, _user, result => {
+		socket.on('/stations/add/:song', (station, song, cb) => {
+			core['/stations/add/:song'](station, song, _user, result => {
 				cb(result);
 			});
 		});

+ 4 - 11
backend/logic/stations.js

@@ -45,15 +45,16 @@ module.exports = {
 			if (this.playlist.length > 0) {
 				if (this.timer !== undefined) this.timer.pause();
 
-				if (this.currentSongIndex + 1 < this.playlist.length) {
+				if (this.currentSongIndex + 1 <= this.playlist.length - 1) {
 					this.currentSongIndex++;
-				}
-				else {
+				} else {
 					this.currentSongIndex = 0;
 				}
 
 				this.currentSong = this.playlist[this.currentSongIndex];
 
+				// console.log(this.currentSong.duration);
+
 				let self = this;
 				this.timer = new global.Timer(() => {
 					self.nextSong();
@@ -82,14 +83,6 @@ module.exports = {
 			}
 		}
 
-		// isPaused() {
-		// 	return this.paused;
-		// }
-
-		// getCurrentSong() {
-		// 	return this.currentSong;
-		// }
-
 		updateDisplayName(newDisplayName) {
 			// TODO: Update db
 			this.displayName = newDisplayName;

+ 1 - 0
backend/package.json

@@ -14,6 +14,7 @@
     "cookie-parser": "^1.4.3",
     "express": "^4.14.0",
     "express-session": "^1.14.0",
+    "moment": "^2.15.2",
     "mongoose": "^4.6.0",
     "passport": "^0.3.2",
     "passport-discord": "^0.1.1",

+ 0 - 14
backend/schemas/song.js

@@ -1,14 +0,0 @@
-module.exports = mongoose => {
-
-	const Schema = mongoose.Schema;
-
-	const songSchema = new Schema({
-		id: { type: String, length: 11, index: true, unique: true, required: true },
-		title: { type: String, required: true },
-		artists: [{ type: String, min: 1 }],
-		duration: { type: Number, required: true },
-		thumbnail: { type: String, required: true }
-	});
-
-	return songSchema;
-};

+ 10 - 8
frontend/components/pages/Station.vue

@@ -91,7 +91,7 @@
 				player: undefined,
 				timePaused: 0,
 				paused: false,
-				timeElapsed: "0:00",
+				timeElapsed: "00:00:00",
 				interval: 0,
 				querySearch: "",
 				queryResults: [],
@@ -146,9 +146,6 @@
 					local.videoLoading = true;
 					local.player.loadVideoById(local.currentSong.id);
 
-					const d = moment.duration(parseInt(local.currentSong.duration), 'seconds');
-					local.currentSong.songDuration = d.minutes() + ":" + ("0" + d.seconds()).slice(-2);
-
 					local.currentSong.artists = local.currentSong.artists.join(", ");
 
 					if (local.interval !== 0) {
@@ -170,18 +167,23 @@
 			calculateTimeElapsed: function() {
 				let local = this;
 				let currentTime = Date.now();
+
 				if (local.currentTime !== undefined && local.paused) {
 					local.timePaused += (Date.now() - local.currentTime);
 					local.currentTime = undefined;
 				}
+
 				let duration = (Date.now() - local.currentSong.startedAt - local.timePaused) / 1000;
-				let songDuration = local.currentSong.duration;
+				let songDuration = moment.duration(local.currentSong.duration, "hh:mm:ss").asSeconds();
+
 				if (songDuration <= duration) {
 					local.player.pauseVideo();
 				}
+
 				let d = moment.duration(duration, 'seconds');
+
 				if ((!local.paused || local.timeElapsed === "0:00") && duration <= songDuration) {
-					local.timeElapsed = d.minutes() + ":" + ("0" + d.seconds()).slice(-2);
+					local.timeElapsed = (d.hours() < 10 ? ("0" + d.hours() + ":") : (d.hours() + ":")) + (d.minutes() < 10 ? ("0" + d.minutes() + ":") : (d.minutes() + ":")) + (d.seconds() < 10 ? ("0" + d.seconds()) : d.seconds());
 				}
 			},
 			changeVolume: function() {
@@ -212,8 +214,8 @@
 			},
 			addSongToQueue: function(song) {
 				let local = this;
-				local.socket.emit("/songs/queue/add/:song", song, function(data) {
-					console.log(data);
+				local.socket.emit("/stations/add/:song", local.$route.params.id, song, function(data) {
+					if (data) console.log(data);
 				});
 			},
 			submitQuery: function() {