Browse Source

feat: added Spotify module to generate tokens, to fix the existing Spotify requests

Kristian Vos 5 years ago
parent
commit
3ed9af28ae
3 changed files with 77 additions and 6 deletions
  1. 6 1
      backend/config/template.json
  2. 45 0
      backend/logic/spotify.js
  3. 26 5
      backend/logic/utils.js

+ 6 - 1
backend/config/template.json

@@ -26,7 +26,12 @@
 		"mailgun": {
 			"key": "",
 			"domain": "",
-		  	"enabled": true
+		  	"enabled": false
+		},
+		"spotify": {
+			"client": "",
+			"secret": "",
+			"enabled": false
 		}
 	},
 	"cors": {

+ 45 - 0
backend/logic/spotify.js

@@ -0,0 +1,45 @@
+const config = require('config');
+
+const client = config.get("apis.spotify.client");
+const secret = config.get("apis.spotify.secret");
+
+const OAuth2 = require('oauth').OAuth2;
+const SpotifyOauth = new OAuth2(
+	client,
+	secret, 
+	'https://accounts.spotify.com/', 
+	null,
+	'api/token',
+	null);
+
+let apiResults = {
+	access_token: "",
+	token_type: "",
+	expires_in: 0,
+	expires_at: 0,
+	scope: "",
+};
+
+let lib = {
+	getToken: () => {
+		return new Promise((resolve, reject) => {
+			if (Date.now() > apiResults.expires_at) {
+				lib.requestToken(() => {
+					resolve(apiResults.access_token);
+				});
+			} else resolve(apiResults.access_token);
+		});
+	},
+	requestToken: (cb) => {
+		SpotifyOauth.getOAuthAccessToken(
+			'',
+			{ 'grant_type': 'client_credentials' },
+			(e, access_token, refresh_token, results) => {
+				apiResults = results;
+				apiResults.expires_at = Date.now() + (results.expires_in * 1000);
+				cb();
+		});
+	}
+};
+
+module.exports = lib;

+ 26 - 5
backend/logic/utils.js

@@ -3,6 +3,7 @@
 const moment  = require('moment'),
 	  io      = require('./io'),
 	  db      = require('./db'),
+	  spotify = require('./spotify'),
 	  config  = require('config'),
 	  async	  = require('async'),
 	  request = require('request'),
@@ -353,17 +354,25 @@ module.exports = {
 		}
 		getPage(null, []);
 	},
-	getSongFromSpotify: (song, cb) => {
+	getSongFromSpotify: async (song, cb) => {
+		if (!config.get("apis.spotify.enabled")) return cb(null);
 		const spotifyParams = [
 			`q=${encodeURIComponent(song.title)}`,
 			`type=track`
 		].join('&');
 
-		request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
+		const token = await spotify.getToken();
+		const options = {
+			url: `https://api.spotify.com/v1/search?${spotifyParams}`,
+			headers: {
+				Authorization: `Bearer ${token}`
+			}
+		};
 
+		request(options, (err, res, body) => {
 			if (err) console.error(err);
-
 			body = JSON.parse(body);
+			if (body.error) console.error(body.error);
 
 			durationArtistLoop:
 			for (let i in body) {
@@ -391,15 +400,27 @@ module.exports = {
 			cb(song);
 		});
 	},
-	getSongsFromSpotify: (title, artist, cb) => {
+	getSongsFromSpotify: async (title, artist, cb) => {
+		if (!config.get("apis.spotify.enabled")) return cb([]);
+
 		const spotifyParams = [
 			`q=${encodeURIComponent(title)}`,
 			`type=track`
 		].join('&');
+		
+		const token = await spotify.getToken();
+		const options = {
+			url: `https://api.spotify.com/v1/search?${spotifyParams}`,
+			headers: {
+				Authorization: `Bearer ${token}`
+			}
+		};
 
-		request(`https://api.spotify.com/v1/search?${spotifyParams}`, (err, res, body) => {
+		request(options, (err, res, body) => {
 			if (err) return console.error(err);
 			body = JSON.parse(body);
+			if (body.error) return console.error(body.error);
+
 			let songs = [];
 
 			for (let i in body) {