소스 검색

chore: replaced 'request' (which is deprecated) with 'axios' package

Signed-off-by: Jonathan <theflametrooper@gmail.com>
Jonathan 4 년 전
부모
커밋
d281ebd44f
7개의 변경된 파일214개의 추가작업 그리고 695개의 파일을 삭제
  1. 6 10
      backend/logic/actions/apis.js
  2. 10 14
      backend/logic/actions/users.js
  3. 30 34
      backend/logic/app.js
  4. 2 2
      backend/logic/io.js
  5. 105 119
      backend/logic/youtube.js
  6. 60 515
      backend/package-lock.json
  7. 1 1
      backend/package.json

+ 6 - 10
backend/logic/actions/apis.js

@@ -1,6 +1,6 @@
 import config from "config";
 import async from "async";
-import request from "request";
+import axios from "axios";
 
 import { isAdminRequired } from "./hooks";
 
@@ -73,10 +73,8 @@ export default {
 		async.waterfall(
 			[
 				next => {
-					const params = [`q=${encodeURIComponent(query)}`, `per_page=20`, `page=${page}`].join("&");
-
 					const options = {
-						url: `https://api.discogs.com/database/search?${params}`,
+						params: { q: query, per_page: 20, page },
 						headers: {
 							"User-Agent": "Request",
 							Authorization: `Discogs key=${config.get("apis.discogs.client")}, secret=${config.get(
@@ -85,12 +83,10 @@ export default {
 						}
 					};
 
-					request(options, (err, res, body) => {
-						if (err) next(err);
-						body = JSON.parse(body);
-						next(null, body);
-						if (body.error) next(body.error);
-					});
+					axios
+						.get("https://api.discogs.com/database/search", options)
+						.then(res => next(null, res.data))
+						.catch(err => next(err));
 				}
 			],
 			async (err, body) => {

+ 10 - 14
backend/logic/actions/users.js

@@ -2,7 +2,7 @@ import config from "config";
 
 import async from "async";
 
-import request from "request";
+import axios from "axios";
 import bcrypt from "bcrypt";
 import sha256 from "sha256";
 import { isAdminRequired, isLoginRequired } from "./hooks";
@@ -330,27 +330,23 @@ export default {
 				// verify the request with google recaptcha
 				next => {
 					if (config.get("apis.recaptcha.enabled") === true)
-						request(
-							{
-								url: "https://www.google.com/recaptcha/api/siteverify",
-								method: "POST",
-								form: {
+						axios
+							.post("https://www.google.com/recaptcha/api/siteverify", {
+								data: {
 									secret: config.get("apis").recaptcha.secret,
 									response: recaptcha
 								}
-							},
-							next
-						);
+							})
+							.then(res => next(null, res.data))
+							.catch(err => next(err));
 					else next(null, null, null);
 				},
 
 				// 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) => {
-					if (config.get("apis.recaptcha.enabled") === true) {
-						const json = JSON.parse(body);
-						if (json.success !== true) return next("Response from recaptcha was not successful.");
-					}
+				(body, next) => {
+					if (config.get("apis.recaptcha.enabled") === true)
+						if (body.success !== true) return next("Response from recaptcha was not successful.");
 
 					return userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
 				},

+ 30 - 34
backend/logic/app.js

@@ -1,8 +1,6 @@
 import config from "config";
-
+import axios from "axios";
 import async from "async";
-import request from "request";
-
 import cors from "cors";
 import cookieParser from "cookie-parser";
 import bodyParser from "body-parser";
@@ -154,22 +152,21 @@ class _AppModule extends CoreClass {
 
 							accessToken = _accessToken;
 
-							return request.get(
-								{
-									url: `https://api.github.com/user`,
-									headers: {
-										"User-Agent": "request",
-										Authorization: `token ${accessToken}`
-									}
-								},
-								next
-							);
-						},
+							const options = {
+								headers: {
+									"User-Agent": "request",
+									Authorization: `token ${accessToken}`
+								}
+							};
 
-						(httpResponse, _body, next) => {
-							body = _body = JSON.parse(_body);
+							return axios
+								.get("https://api.github.com/user", options)
+								.then(res => next(null, res))
+								.catch(err => next(err));
+						},
 
-							if (httpResponse.statusCode !== 200) return next(body.message);
+						(res, next) => {
+							if (res.status !== 200) return next(res.data.message);
 
 							if (state) {
 								return async.waterfall(
@@ -198,7 +195,7 @@ class _AppModule extends CoreClass {
 												{
 													$set: {
 														"services.github": {
-															id: body.id,
+															id: res.data.id,
 															accessToken
 														}
 													}
@@ -206,7 +203,7 @@ class _AppModule extends CoreClass {
 												{ runValidators: true },
 												err => {
 													if (err) return next(err);
-													return next(null, user, body);
+													return next(null, user, res.data);
 												}
 											);
 										},
@@ -223,14 +220,16 @@ class _AppModule extends CoreClass {
 								);
 							}
 
-							if (!body.id) return next("Something went wrong, no id.");
+							if (!res.data.id) return next("Something went wrong, no id.");
 
-							return userModel.findOne({ "services.github.id": body.id }, (err, user) => {
-								next(err, user, body);
+							return userModel.findOne({ "services.github.id": res.data.id }, (err, user) => {
+								next(err, user, res.data);
 							});
 						},
 
-						(user, body, next) => {
+						(user, _body, next) => {
+							body = _body;
+
 							if (user) {
 								user.services.github.access_token = accessToken;
 								return user.save(() => next(true, user._id));
@@ -244,24 +243,21 @@ class _AppModule extends CoreClass {
 						(user, next) => {
 							if (user) return next(`An account with that username already exists.`);
 
-							return request.get(
-								{
-									url: `https://api.github.com/user/emails`,
+							return axios
+								.get("https://api.github.com/user/emails", {
 									headers: {
 										"User-Agent": "request",
 										Authorization: `token ${accessToken}`
 									}
-								},
-								next
-							);
+								})
+								.then(res => next(null, res.data))
+								.catch(err => next(err));
 						},
 
-						(httpResponse, body2, next) => {
-							body2 = JSON.parse(body2);
-
-							if (!Array.isArray(body2)) return next(body2.message);
+						(body, next) => {
+							if (!Array.isArray(body)) return next(body.message);
 
-							body2.forEach(email => {
+							body.forEach(email => {
 								if (email.primary) address = email.email.toLowerCase();
 							});
 

+ 2 - 2
backend/logic/io.js

@@ -47,9 +47,9 @@ class _IOModule extends CoreClass {
 
 		// TODO: Check every 30s/, for all sockets, if they are still allowed to be in the rooms they are in, and on socket at all (permission changing/banning)
 		const server = await AppModule.runJob("SERVER");
-		this._io = socketio(server);
 
-		this._io.origins(config.get("cors.origin"));
+		this._io = socketio(server);
+		// this._io.origins(config.get("cors.origin"));
 
 		return new Promise(resolve => {
 			this.setStage(3);

+ 105 - 119
backend/logic/youtube.js

@@ -1,7 +1,7 @@
 import async from "async";
 import config from "config";
 
-import request from "request";
+import axios from "axios";
 
 import CoreClass from "../core";
 
@@ -40,31 +40,31 @@ class _YouTubeModule extends CoreClass {
 	 * @returns {Promise} - returns promise (reject, resolve)
 	 */
 	SEARCH(payload) {
-		const params = [
-			"part=snippet",
-			`q=${encodeURIComponent(payload.query)}`,
-			`key=${config.get("apis.youtube.key")}`,
-			"type=video",
-			"maxResults=10",
-			payload.pageToken ? `pageToken=${payload.pageToken}` : null
-		].join("&");
+		const params = {
+			part: "snippet",
+			q: payload.query,
+			key: config.get("apis.youtube.key"),
+			type: "video",
+			maxResults: 10
+		};
 
-		return new Promise((resolve, reject) => {
-			request(`https://www.googleapis.com/youtube/v3/search?${params}`, (err, res, body) => {
-				if (err) {
-					YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
-					return reject(new Error("An error has occured. Please try again later."));
-				}
+		if (payload.pageToken) params.pageToken = payload.pageToken;
 
-				body = JSON.parse(body);
+		return new Promise((resolve, reject) => {
+			axios
+				.get("https://www.googleapis.com/youtube/v3/search", { params })
+				.then(res => {
+					if (res.data.err) {
+						YouTubeModule.log("ERROR", "SEARCH", `${res.data.error.message}`);
+						return reject(new Error("An error has occured. Please try again later."));
+					}
 
-				if (body.err) {
-					YouTubeModule.log("ERROR", "SEARCH", `${body.error.message}`);
+					return resolve(res.data);
+				})
+				.catch(err => {
+					YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
 					return reject(new Error("An error has occured. Please try again later."));
-				}
-
-				return resolve(body);
-			});
+				});
 		});
 	}
 
@@ -76,39 +76,33 @@ class _YouTubeModule extends CoreClass {
 	 * @returns {Promise} - returns promise (reject, resolve)
 	 */
 	GET_SONG(payload) {
-		// songId, cb
 		return new Promise((resolve, reject) => {
-			const youtubeParams = [
-				"part=snippet,contentDetails,statistics,status",
-				`id=${encodeURIComponent(payload.songId)}`,
-				`key=${config.get("apis.youtube.key")}`
-			].join("&");
-
-			request(
-				{
-					url: `https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`,
-					timeout: 30000,
-					agent: false,
-					pool: { maxSockets: 100 }
-				},
-				(err, res, body) => {
-					if (err) {
-						YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
-						return reject(new Error("An error has occured. Please try again later."));
-					}
-
-					body = JSON.parse(body);
-
-					if (body.error) {
-						YouTubeModule.log("ERROR", "GET_SONG", `${body.error.message}`);
+			const params = {
+				part: "snippet,contentDetails,statistics,status",
+				id: payload.songId,
+				key: config.get("apis.youtube.key")
+			};
+
+			if (payload.pageToken) params.pageToken = payload.pageToken;
+
+			axios
+				.get("https://www.googleapis.com/youtube/v3/videos", {
+					params,
+					timeout: 30000
+					// agent: false,
+					// pool: { maxSockets: 100 }
+				})
+				.then(res => {
+					if (res.data.error) {
+						YouTubeModule.log("ERROR", "GET_SONG", `${res.data.error.message}`);
 						return reject(new Error("An error has occured. Please try again later."));
 					}
 
-					if (body.items[0] === undefined)
+					if (res.data.items[0] === undefined)
 						return reject(new Error("The specified video does not exist or cannot be publicly accessed."));
 
 					// TODO Clean up duration converter
-					let dur = body.items[0].contentDetails.duration;
+					let dur = res.data.items[0].contentDetails.duration;
 
 					dur = dur.replace("PT", "");
 
@@ -134,16 +128,18 @@ class _YouTubeModule extends CoreClass {
 					});
 
 					const song = {
-						songId: body.items[0].id,
-						title: body.items[0].snippet.title,
-						thumbnail: body.items[0].snippet.thumbnails.default.url,
+						songId: res.data.items[0].id,
+						title: res.data.items[0].snippet.title,
+						thumbnail: res.data.items[0].snippet.thumbnails.default.url,
 						duration
 					};
 
 					return resolve({ song });
-				}
-			);
-			// songId: payload.songId
+				})
+				.catch(err => {
+					YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
+					return reject(new Error("An error has occured. Please try again later."));
+				});
 		});
 	}
 
@@ -251,44 +247,39 @@ class _YouTubeModule extends CoreClass {
 	 * @returns {Promise} - returns promise (reject, resolve)
 	 */
 	GET_PLAYLIST_PAGE(payload) {
-		// payload includes: playlistId, nextPageToken
 		return new Promise((resolve, reject) => {
-			const nextPageToken = payload.nextPageToken ? `pageToken=${payload.nextPageToken}` : "";
-			const videosPerPage = 50;
-			const youtubeParams = [
-				"part=contentDetails",
-				`playlistId=${encodeURIComponent(payload.playlistId)}`,
-				`maxResults=${videosPerPage}`,
-				`key=${config.get("apis.youtube.key")}`,
-				nextPageToken
-			].join("&");
-
-			request(
-				{
-					url: `https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`,
-					timeout: 30000,
-					agent: false,
-					pool: { maxSockets: 100 }
-				},
-				async (err, res, body) => {
-					if (err) {
-						YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
+			const params = {
+				part: "contentDetails",
+				playlistId: payload.playlistId,
+				key: config.get("apis.youtube.key"),
+				maxResults: 50
+			};
+
+			if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
+
+			axios
+				.get("https://www.googleapis.com/youtube/v3/playlistItems", {
+					params,
+					timeout: 30000
+					// agent: false,
+					// pool: { maxSockets: 100 }
+				})
+				.then(res => {
+					if (res.data.err) {
+						YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${res.data.error.message}`);
 						return reject(new Error("An error has occured. Please try again later."));
 					}
 
-					body = JSON.parse(body);
-
-					if (body.error) {
-						YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${body.error.message}`);
-						return reject(new Error("An error has occured. Please try again later."));
-					}
+					const songs = res.data.items;
 
-					const songs = body.items;
+					if (res.data.nextPageToken) return resolve({ nextPageToken: res.data.nextPageToken, songs });
 
-					if (body.nextPageToken) return resolve({ nextPageToken: body.nextPageToken, songs });
 					return resolve({ songs });
-				}
-			);
+				})
+				.catch(err => {
+					YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
+					return reject(new Error("An error has occured. Please try again later."));
+				});
 		});
 	}
 
@@ -303,42 +294,38 @@ class _YouTubeModule extends CoreClass {
 	FILTER_MUSIC_VIDEOS(payload) {
 		return new Promise((resolve, reject) => {
 			const page = payload.page ? payload.page : 0;
-			const videosPerPage = 50; // 50 is the max I believe
+
+			const videosPerPage = 50;
+
 			const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
 
 			if (localVideoIds.length === 0) {
 				return resolve({ videoIds: [] });
 			}
 
-			const youtubeParams = [
-				"part=topicDetails",
-				`id=${encodeURIComponent(localVideoIds.join(","))}`,
-				`maxResults=${videosPerPage}`,
-				`key=${config.get("apis.youtube.key")}`
-			].join("&");
-
-			return request(
-				{
-					url: `https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`,
-					timeout: 30000,
-					agent: false,
-					pool: { maxSockets: 100 }
-				},
-				(err, res, body) => {
-					if (err) {
-						YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
-						return reject(new Error("Failed to find playlist from YouTube"));
-					}
-
-					body = JSON.parse(body);
-
-					if (body.error) {
-						YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${body.error.message}`);
+			const params = {
+				part: "topicDetails",
+				id: localVideoIds.join(","),
+				key: config.get("apis.youtube.key"),
+				maxResults: videosPerPage
+			};
+
+			return axios
+				.get("https://www.googleapis.com/youtube/v3/videos", {
+					params,
+					timeout: 30000
+					// agent: false,
+					// pool: { maxSockets: 100 }
+				})
+				.then(res => {
+					if (res.data.err) {
+						YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${res.data.error.message}`);
 						return reject(new Error("An error has occured. Please try again later."));
 					}
 
 					const songIds = [];
-					body.items.forEach(item => {
+
+					res.data.items.forEach(item => {
 						const songId = item.id;
 						if (!item.topicDetails) return;
 						if (item.topicDetails.relevantTopicIds.indexOf("/m/04rlf") !== -1) {
@@ -351,14 +338,13 @@ class _YouTubeModule extends CoreClass {
 						{ videoIds: payload.videoIds, page: page + 1 },
 						this
 					)
-						.then(result => {
-							resolve({ songIds: songIds.concat(result.songIds) });
-						})
-						.catch(err => {
-							reject(err);
-						});
-				}
-			);
+						.then(result => resolve({ songIds: songIds.concat(result.songIds) }))
+						.catch(err => reject(err));
+				})
+				.catch(err => {
+					YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
+					return reject(new Error("Failed to find playlist from YouTube"));
+				});
 		});
 	}
 }

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 60 - 515
backend/package-lock.json


+ 1 - 1
backend/package.json

@@ -16,6 +16,7 @@
   },
   "dependencies": {
     "async": "3.1.0",
+    "axios": "^0.21.1",
     "bcrypt": "^5.0.0",
     "bluebird": "^3.5.5",
     "body-parser": "^1.19.0",
@@ -28,7 +29,6 @@
     "nodemailer": "^6.4.18",
     "oauth": "^0.9.15",
     "redis": "^2.8.0",
-    "request": "^2.88.0",
     "sha256": "^0.2.0",
     "socket.io": "2.4.1",
     "underscore": "^1.10.2"

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.