Browse Source

Removed Spotify and Discord integrations

Owen Diffey 4 years ago
parent
commit
58a16de49e

+ 0 - 4
README.md

@@ -52,11 +52,7 @@ We currently only utilize 1 backend, 1 MongoDB server and 1 Redis server running
     | `apis.recaptcha.secret`       | Can be obtained by setting up a [ReCaptcha Site (v3)](https://www.google.com/recaptcha/admin). |
     | `apis.recaptcha.enabled`       | Keep at false to keep disabled. |
     | `apis.github` | Can be obtained by setting up a [GitHub OAuth Application](https://github.com/settings/developers). You need to fill in some values to create the OAuth application. The homepage is the homepage of frontend. The authorization callback url is the backend url with `/auth/github/authorize/callback` added at the end. For example `http://localhost:8080/auth/github/authorize/callback`. |
-    | `apis.discord.token` | Token for the Discord bot. |
-    | `apis.discord.loggingServer`  | Server ID of the Discord logging server. |
-    | `apis.discord.loggingChannel` | ID of the channel to be used in the Discord logging server. |
     | `apis.mailgun` | Can be obtained by setting up a [Mailgun account](http://www.mailgun.com/), or you can disable it. |
-    | `apis.spotify` | Can be obtained by setting up a [Spotify client id](https://developer.spotify.com/dashboard/applications), or you can disable it. |
     | `apis.discogs` | Can be obtained by setting up a [Discogs application](https://www.discogs.com/settings/developers), or you can disable it. |
     | `redis.url` | Should be left alone for Docker, and changed to `redis://localhost:6379/0` for non-Docker. |
     | `redis.password` | Should be the Redis password you either put in your `startRedis.cmd` file for Windows, or `.env` for docker. |

+ 0 - 10
backend/config/template.json

@@ -21,21 +21,11 @@
 			"secret": "",
 			"redirect_uri": ""
 		},
-		"discord": {
-			"token": "",
-			"loggingChannel": "",
-			"loggingServer": ""
-		},
 		"mailgun": {
 			"key": "",
 			"domain": "",
 			"enabled": false
 		},
-		"spotify": {
-			"client": "",
-			"secret": "",
-			"enabled": false
-		},
 		"discogs": {
 			"client": "",
 			"secret": "",

+ 0 - 15
backend/index.js

@@ -152,12 +152,10 @@ if (config.debug && config.debug.traceUnhandledPromises === true) {
 
 // 	allModulesInitialized() {
 // 		this.logger.success("MODULE_MANAGER", "All modules have started!");
-// 		this.modules["discord"].sendAdminAlertMessage("The backend server started successfully.", "#00AA00", "Startup", false, []);
 // 	}
 
 // 	aModuleFailed(failedModule) {
 // 		this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
-// 		this.modules["discord"].sendAdminAlertMessage(`The backend server failed to start due to a failing module: ${failedModule.name}.`, "#AA0000", "Startup", false, []);
 
 // 		this._lockdown();
 // 	}
@@ -205,7 +203,6 @@ if (config.debug && config.debug.traceUnhandledPromises === true) {
 // moduleManager.addModule("mail");
 // moduleManager.addModule("api");
 // moduleManager.addModule("app");
-// moduleManager.addModule("discord");
 // moduleManager.addModule("io");
 // moduleManager.addModule("logger");
 // moduleManager.addModule("notifications");
@@ -213,7 +210,6 @@ if (config.debug && config.debug.traceUnhandledPromises === true) {
 // moduleManager.addModule("playlists");
 // moduleManager.addModule("punishments");
 // moduleManager.addModule("songs");
-// moduleManager.addModule("spotify");
 // moduleManager.addModule("stations");
 // moduleManager.addModule("tasks");
 // moduleManager.addModule("utils");
@@ -355,15 +351,6 @@ class ModuleManager {
 	 */
 	onAllModulesInitialized() {
 		this.log("INFO", "All modules initialized!");
-		if (this.modules.discord) {
-			this.modules.discord.runJob("SEND_ADMIN_ALERT_MESSAGE", {
-				message: "The backend server started successfully.",
-				color: "#00AA00",
-				type: "Startup",
-				critical: false,
-				extraFields: []
-			});
-		} else this.log("INFO", "No Discord module, so not sending an admin alert message.");
 	}
 
 	/**
@@ -400,13 +387,11 @@ moduleManager.addModule("mail");
 moduleManager.addModule("activities");
 moduleManager.addModule("api");
 moduleManager.addModule("app");
-moduleManager.addModule("discord");
 moduleManager.addModule("io");
 moduleManager.addModule("notifications");
 moduleManager.addModule("playlists");
 moduleManager.addModule("punishments");
 moduleManager.addModule("songs");
-moduleManager.addModule("spotify");
 moduleManager.addModule("stations");
 moduleManager.addModule("tasks");
 moduleManager.addModule("utils");

+ 0 - 31
backend/logic/actions/apis.js

@@ -56,37 +56,6 @@ export default {
 		);
 	},
 
-	/**
-	 * Gets Spotify data
-	 *
-	 * @param session
-	 * @param title - the title of the song
-	 * @param artist - an artist for that song
-	 * @param cb
-	 */
-	getSpotifySongs: isAdminRequired((session, title, artist, cb) => {
-		async.waterfall(
-			[
-				next => {
-					utils
-						.runJob("GET_SONGS_FROM_SPOTIFY", { title, artist })
-						.then(songs => {
-							next(null, songs);
-						})
-						.catch(next);
-				}
-			],
-			songs => {
-				console.log(
-					"SUCCESS",
-					"APIS_GET_SPOTIFY_SONGS",
-					`User "${session.userId}" got Spotify songs for title "${title}" successfully.`
-				);
-				cb({ status: "success", songs });
-			}
-		);
-	}),
-
 	/**
 	 * Gets Discogs data
 	 *

+ 0 - 6
backend/logic/actions/queueSongs.js

@@ -261,12 +261,6 @@ const lib = {
 						})
 						.catch(next);
 				},
-				/* (newSong, next) => {
-				utils.getSongFromSpotify(newSong, (err, song) => {
-					if (!song) next(null, newSong);
-					else next(err, song);
-				});
-			}, */
 				(newSong, next) => {
 					const song = new QueueSongModel(newSong);
 					song.save({ validateBeforeSave: false }, (err, song) => {

+ 0 - 120
backend/logic/discord.js

@@ -1,120 +0,0 @@
-import config from "config";
-import Discord from "discord.js";
-
-import CoreClass from "../core";
-
-let DiscordModule;
-
-class _DiscordModule extends CoreClass {
-	// eslint-disable-next-line require-jsdoc
-	constructor() {
-		super("discord");
-
-		DiscordModule = this;
-	}
-
-	/**
-	 * Initialises the discord module
-	 *
-	 * @returns {Promise} - returns promise (reject, resolve)
-	 */
-	initialize() {
-		return new Promise((resolve, reject) => {
-			this.log("INFO", "Discord initialize");
-
-			this.client = new Discord.Client();
-			this.adminAlertChannelId = config.get("apis.discord").loggingChannel;
-
-			this.client.on("ready", () => {
-				this.log("INFO", `Logged in as ${this.client.user.tag}!`);
-
-				if (this.getStatus() === "INITIALIZING") {
-					resolve();
-				} else if (this.getStatus() === "RECONNECTING") {
-					this.log("INFO", `Discord client reconnected.`);
-					this.setStatus("READY");
-				}
-			});
-
-			this.client.on("disconnect", () => {
-				this.log("INFO", `Discord client disconnected.`);
-
-				if (this.getStatus() === "INITIALIZING") reject();
-				else {
-					this.setStatus("DISCONNECTED");
-				}
-			});
-
-			this.client.on("reconnecting", () => {
-				this.log("INFO", `Discord client reconnecting.`);
-				this.setStatus("RECONNECTING");
-			});
-
-			this.client.on("error", err => {
-				this.log("INFO", `Discord client encountered an error: ${err.message}.`);
-			});
-
-			this.client.login(config.get("apis.discord").token);
-		});
-	}
-
-	/**
-	 * Adds a new activity to the database
-	 *
-	 * @param {object} payload - object that contains the payload
-	 * @param {string} payload.color - The colour of the alert title
-	 * @param {string} payload.message - The message to send as the alert
-	 * @param {string} payload.type - The type of alert e.g. Startup
-	 * @param {boolean} payload.critical - If the message is service critical
-	 * @param {Array} payload.extraFields - Any extra fields to show in the discord message
-	 * @returns {Promise} - returns promise (reject, resolve)
-	 */
-	SEND_ADMIN_ALERT_MESSAGE(payload) {
-		return new Promise((resolve, reject) => {
-			const channel = DiscordModule.client.channels.find(
-				channel => channel.id === DiscordModule.adminAlertChannelId
-			);
-
-			if (channel !== null) {
-				const richEmbed = new Discord.RichEmbed();
-				richEmbed.setAuthor(
-					"Musare Logger",
-					`${config.get("domain")}/favicon-194x194.png`,
-					config.get("domain")
-				);
-				richEmbed.setColor(payload.color);
-				richEmbed.setDescription(payload.message);
-				// richEmbed.setFooter("Footer", "https://musare.com/favicon-194x194.png");
-				// richEmbed.setImage("https://musare.com/favicon-194x194.png");
-				// richEmbed.setThumbnail("https://musare.com/favicon-194x194.png");
-				richEmbed.setTimestamp(new Date());
-				richEmbed.setTitle("MUSARE ALERT");
-				richEmbed.setURL(config.get("domain"));
-				richEmbed.addField("Type:", payload.type, true);
-				richEmbed.addField("Critical:", payload.critical ? "True" : "False", true);
-				payload.extraFields.forEach(extraField => {
-					richEmbed.addField(extraField.name, extraField.value, extraField.inline);
-				});
-
-				channel
-					.send(payload.message, { embed: richEmbed })
-					.then(message =>
-						resolve({
-							status: "success",
-							message: `Successfully sent admin alert message: ${message}`
-						})
-					)
-					.catch(() => reject(new Error("Couldn't send admin alert message")));
-			} else {
-				reject(new Error("Channel was not found"));
-			}
-			// if (true) {
-			//     resolve({});
-			// } else {
-			//     reject(new Error("Nothing changed."));
-			// }
-		});
-	}
-}
-
-export default new _DiscordModule();

+ 0 - 125
backend/logic/spotify.js

@@ -1,125 +0,0 @@
-import config from "config";
-import async from "async";
-import oauth from "oauth";
-
-import CoreClass from "../core";
-
-const { OAuth2 } = oauth;
-
-let apiResults = {
-	access_token: "",
-	token_type: "",
-	expires_in: 0,
-	expires_at: 0,
-	scope: ""
-};
-
-let SpotifyModule;
-let CacheModule;
-let UtilsModule;
-
-class _SpotifyModule extends CoreClass {
-	// eslint-disable-next-line require-jsdoc
-	constructor() {
-		super("spotify");
-
-		SpotifyModule = this;
-	}
-
-	/**
-	 * Initialises the spotify module
-	 *
-	 * @returns {Promise} - returns promise (reject, resolve)
-	 */
-	initialize() {
-		return new Promise((resolve, reject) => {
-			CacheModule = this.moduleManager.modules.cache;
-			UtilsModule = this.moduleManager.modules.utils;
-
-			const client = config.get("apis.spotify.client");
-			const secret = config.get("apis.spotify.secret");
-
-			this.SpotifyOauth = new OAuth2(client, secret, "https://accounts.spotify.com/", null, "api/token", null);
-
-			async.waterfall(
-				[
-					next => {
-						this.setStage(2);
-						CacheModule.runJob("HGET", { table: "api", key: "spotify" })
-							.then(data => {
-								next(null, data);
-							})
-							.catch(next);
-					},
-
-					(data, next) => {
-						this.setStage(3);
-						if (data) apiResults = data;
-						next();
-					}
-				],
-				async err => {
-					if (err) {
-						err = await UtilsModule.runJob("GET_ERROR", {
-							error: err
-						});
-						reject(new Error(err));
-					} else {
-						resolve();
-					}
-				}
-			);
-		});
-	}
-
-	/**
-	 * Returns the request token for the Spotify api if one exists, otherwise creates a new one
-	 *
-	 * @returns {Promise} - returns a promise (resolve, reject)
-	 */
-	GET_TOKEN() {
-		return new Promise(resolve => {
-			if (Date.now() > apiResults.expires_at) {
-				SpotifyModule.runJob("REQUEST_TOKEN", null, this).then(() => {
-					resolve(apiResults.access_token);
-				});
-			} else resolve(apiResults.access_token);
-		});
-	}
-
-	/**
-	 * Creates a request token for the Spotify api
-	 *
-	 * @returns {Promise} - returns a promise (resolve, reject)
-	 */
-	REQUEST_TOKEN() {
-		return new Promise(resolve => {
-			async.waterfall(
-				[
-					next => {
-						SpotifyModule.log("INFO", "SPOTIFY_REQUEST_TOKEN", "Requesting new Spotify token.");
-						SpotifyModule.SpotifyOauth.getOAuthAccessToken("", { grant_type: "client_credentials" }, next);
-					},
-					(accessToken, refreshToken, results, next) => {
-						apiResults = results;
-						apiResults.expires_at = Date.now() + results.expires_in * 1000;
-
-						CacheModule.runJob(
-							"HSET",
-							{
-								table: "api",
-								key: "spotify",
-								value: apiResults,
-								stringifyJson: true
-							},
-							this
-						).finally(() => next());
-					}
-				],
-				() => resolve()
-			);
-		});
-	}
-}
-
-export default new _SpotifyModule();

+ 0 - 119
backend/logic/utils.js

@@ -7,7 +7,6 @@ import CoreClass from "../core";
 
 let UtilsModule;
 let IOModule;
-let SpotifyModule;
 let CacheModule;
 
 class _UtilsModule extends CoreClass {
@@ -30,7 +29,6 @@ class _UtilsModule extends CoreClass {
 	initialize() {
 		return new Promise(resolve => {
 			IOModule = this.moduleManager.modules.io;
-			SpotifyModule = this.moduleManager.modules.spotify;
 			CacheModule = this.moduleManager.modules.cache;
 
 			resolve();
@@ -819,123 +817,6 @@ class _UtilsModule extends CoreClass {
 		});
 	}
 
-	/**
-	 * Gets the details of a song from the Spotify API
-	 *
-	 * @param {object} payload - object that contains the payload
-	 * @param {object} payload.song - the song object (song.title etc.)
-	 * @returns {Promise} - returns promise (reject, resolve)
-	 */
-	async GET_SONG_FROM_SPOTIFY(payload) {
-		// song
-		const token = await SpotifyModule.runJob("GET_TOKEN", {}, this);
-
-		return new Promise((resolve, reject) => {
-			if (!config.get("apis.spotify.enabled")) return reject(new Error("Spotify is not enabled."));
-
-			const song = { ...payload.song };
-
-			const spotifyParams = [`q=${encodeURIComponent(payload.song.title)}`, `type=track`].join("&");
-
-			const options = {
-				url: `https://api.spotify.com/v1/search?${spotifyParams}`,
-				headers: {
-					Authorization: `Bearer ${token}`
-				}
-			};
-
-			return request(options, (err, res, body) => {
-				if (err) console.error(err);
-				body = JSON.parse(body);
-				if (body.error) console.error(body.error);
-				Object.keys(body).forEach(bodyKey => {
-					const { items } = body[bodyKey];
-
-					Object.keys(items).every(itemsKey => {
-						const item = items[itemsKey];
-
-						let hasArtist = false;
-						for (let k = 0; k < item.artists.length; k += 1) {
-							const artist = item.artists[k];
-							if (song.title.indexOf(artist.name) !== -1) hasArtist = true;
-						}
-						if (hasArtist && song.title.indexOf(item.name) !== -1) {
-							song.duration = item.duration_ms / 1000;
-							song.artists = item.artists.map(artist => artist.name);
-							song.title = item.name;
-							song.explicit = item.explicit;
-							song.thumbnail = item.album.images[1].url;
-							return false;
-						}
-						return true;
-					});
-				});
-
-				resolve({ song });
-			});
-		});
-	}
-
-	/**
-	 * Returns the details of multiple songs from the Spotify API
-	 *
-	 * @param {object} payload - object that contains the payload
-	 * @param {object} payload.title - the query/title of a song to search the API with
-	 * @returns {Promise} - returns promise (reject, resolve)
-	 */
-	async GET_SONGS_FROM_SPOTIFY(payload) {
-		// title, artist
-		const token = await SpotifyModule.runJob("GET_TOKEN", {}, this);
-
-		return new Promise((resolve, reject) => {
-			if (!config.get("apis.spotify.enabled")) return reject(new Error("Spotify is not enabled."));
-
-			const spotifyParams = [`q=${encodeURIComponent(payload.title)}`, `type=track`].join("&");
-
-			const options = {
-				url: `https://api.spotify.com/v1/search?${spotifyParams}`,
-				headers: {
-					Authorization: `Bearer ${token}`
-				}
-			};
-
-			return request(options, (err, res, body) => {
-				if (err) return console.error(err);
-				body = JSON.parse(body);
-				if (body.error) return console.error(body.error);
-
-				const songs = [];
-
-				Object.keys(body).forEach(bodyKey => {
-					const { items } = body[bodyKey];
-
-					Object.keys(items).forEach(itemsKey => {
-						const item = items[itemsKey];
-						let hasArtist = false;
-						for (let k = 0; k < item.artists.length; k += 1) {
-							const localArtist = item.artists[k];
-							if (payload.artist.toLowerCase() === localArtist.name.toLowerCase()) hasArtist = true;
-						}
-						if (
-							hasArtist &&
-							(payload.title.indexOf(item.name) !== -1 || item.name.indexOf(payload.title) !== -1)
-						) {
-							const song = {};
-							song.duration = item.duration_ms / 1000;
-							song.artists = item.artists.map(artist => artist.name);
-							song.title = item.name;
-							song.explicit = item.explicit;
-							song.thumbnail = item.album.images[1].url;
-							songs.push(song);
-						}
-					});
-				});
-
-				return resolve({ songs });
-			});
-		});
-	}
-
 	/**
 	 * Shuffles an array of songs
 	 *

+ 1 - 2
backend/package.json

@@ -22,7 +22,6 @@
     "config": "^3.3.1",
     "cookie-parser": "^1.4.5",
     "cors": "^2.8.5",
-    "discord.js": "^11.6.4",
     "express": "^4.17.1",
     "mailgun-js": "^0.22.0",
     "moment": "^2.24.0",
@@ -44,4 +43,4 @@
     "prettier": "^2.2.1",
     "trace-unhandled": "^1.2.1"
   }
-}
+}