SB-6.3-BETA 2

Added Moderation
Added Node Modules
This commit is contained in:
ItzEmerald committed 2021-03-27 16:22:19 +00:00
1 parent 60daab82d2
commit 09aad61cfe
385 files changed
+78314 -20

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
'use strict';
const https = require('https');
const FormData = require('@discordjs/form-data');
const AbortController = require('abort-controller');
const fetch = require('node-fetch');
const { browser, UserAgent } = require('../util/Constants');
if (https.Agent) var agent = new https.Agent({ keepAlive: true });
class APIRequest {
constructor(rest, method, path, options) {
this.rest = rest;
this.client = rest.client;
this.method = method;
this.route = options.route;
this.options = options;
this.retries = 0;
let queryString = '';
if (options.query) {
const query = Object.entries(options.query)
.filter(([, value]) => ![null, 'null', 'undefined'].includes(value) && typeof value !== 'undefined')
.flatMap(([key, value]) => (Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]));
queryString = new URLSearchParams(query).toString();
}
this.path = `${path}${queryString && `?${queryString}`}`;
}
make() {
const API =
this.options.versioned === false
? this.client.options.http.api
: `${this.client.options.http.api}/v${this.client.options.http.version}`;
const url = API + this.path;
let headers = {};
if (this.options.auth !== false) headers.Authorization = this.rest.getAuth();
if (this.options.reason) headers['X-Audit-Log-Reason'] = encodeURIComponent(this.options.reason);
if (!browser) headers['User-Agent'] = UserAgent;
if (this.options.headers) headers = Object.assign(headers, this.options.headers);
let body;
if (this.options.files && this.options.files.length) {
body = new FormData();
for (const file of this.options.files) if (file && file.file) body.append(file.name, file.file, file.name);
if (typeof this.options.data !== 'undefined') body.append('payload_json', JSON.stringify(this.options.data));
if (!browser) headers = Object.assign(headers, body.getHeaders());
// eslint-disable-next-line eqeqeq
} else if (this.options.data != null) {
body = JSON.stringify(this.options.data);
headers['Content-Type'] = 'application/json';
}
const controller = new AbortController();
const timeout = this.client.setTimeout(() => controller.abort(), this.client.options.restRequestTimeout);
return fetch(url, {
method: this.method,
headers,
agent,
body,
signal: controller.signal,
}).finally(() => this.client.clearTimeout(timeout));
}
}
module.exports = APIRequest;
+53
View File
@@ -0,0 +1,53 @@
'use strict';
const noop = () => {}; // eslint-disable-line no-empty-function
const methods = ['get', 'post', 'delete', 'patch', 'put'];
const reflectors = [
'toString',
'valueOf',
'inspect',
'constructor',
Symbol.toPrimitive,
Symbol.for('nodejs.util.inspect.custom'),
];
function buildRoute(manager) {
const route = [''];
const handler = {
get(target, name) {
if (reflectors.includes(name)) return () => route.join('/');
if (methods.includes(name)) {
const routeBucket = [];
for (let i = 0; i < route.length; i++) {
// Reactions routes and sub-routes all share the same bucket
if (route[i - 1] === 'reactions') break;
// Literal IDs should only be taken account if they are the Major ID (the Channel/Guild ID)
if (/\d{16,19}/g.test(route[i]) && !/channels|guilds/.test(route[i - 1])) routeBucket.push(':id');
// All other parts of the route should be considered as part of the bucket identifier
else routeBucket.push(route[i]);
}
return options =>
manager.request(
name,
route.join('/'),
Object.assign(
{
versioned: manager.versioned,
route: routeBucket.join('/'),
},
options,
),
);
}
route.push(name);
return new Proxy(noop, handler);
},
apply(target, _, args) {
route.push(...args.filter(x => x != null)); // eslint-disable-line eqeqeq
return new Proxy(noop, handler);
},
};
return new Proxy(noop, handler);
}
module.exports = buildRoute;
+95
View File
@@ -0,0 +1,95 @@
/**
* MIT License
*
* Copyright (c) 2020 kyranet, discord.js
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict';
// TODO(kyranet, vladfrangu): replace this with discord.js v13's core AsyncQueue.
/**
* An async queue that preserves the stack and prevents lock-ups.
* @private
*/
class AsyncQueue {
constructor() {
/**
* The promises array.
* @type {Array<{promise: Promise<void>, resolve: Function}>}
* @private
*/
this.promises = [];
}
/**
* The remaining amount of queued promises
* @type {number}
*/
get remaining() {
return this.promises.length;
}
/**
* Waits for last promise and queues a new one.
* @returns {Promise<void>}
* @example
* const queue = new AsyncQueue();
* async function request(url, options) {
* await queue.wait();
* try {
* const result = await fetch(url, options);
* // Do some operations with 'result'
* } finally {
* // Remove first entry from the queue and resolve for the next entry
* queue.shift();
* }
* }
*
* request(someUrl1, someOptions1); // Will call fetch() immediately
* request(someUrl2, someOptions2); // Will call fetch() after the first finished
* request(someUrl3, someOptions3); // Will call fetch() after the second finished
*/
wait() {
const next = this.promises.length ? this.promises[this.promises.length - 1].promise : Promise.resolve();
let resolve;
const promise = new Promise(res => {
resolve = res;
});
this.promises.push({
resolve,
promise,
});
return next;
}
/**
* Frees the queue's lock for the next item to process.
*/
shift() {
const deferred = this.promises.shift();
if (typeof deferred !== 'undefined') deferred.resolve();
}
}
module.exports = AsyncQueue;
+68
View File
@@ -0,0 +1,68 @@
'use strict';
/**
* Represents an error from the Discord API.
* @extends Error
*/
class DiscordAPIError extends Error {
constructor(path, error, method, status) {
super();
const flattened = this.constructor.flattenErrors(error.errors || error).join('\n');
this.name = 'DiscordAPIError';
this.message = error.message && flattened ? `${error.message}\n${flattened}` : error.message || flattened;
/**
* The HTTP method used for the request
* @type {string}
*/
this.method = method;
/**
* The path of the request relative to the HTTP endpoint
* @type {string}
*/
this.path = path;
/**
* HTTP error code returned by Discord
* @type {number}
*/
this.code = error.code;
/**
* The HTTP status code
* @type {number}
*/
this.httpStatus = status;
}
/**
* Flattens an errors object returned from the API into an array.
* @param {Object} obj Discord errors object
* @param {string} [key] Used internally to determine key names of nested fields
* @returns {string[]}
* @private
*/
static flattenErrors(obj, key = '') {
let messages = [];
for (const [k, v] of Object.entries(obj)) {
if (k === 'message') continue;
const newKey = key ? (isNaN(k) ? `${key}.${k}` : `${key}[${k}]`) : k;
if (v._errors) {
messages.push(`${newKey}: ${v._errors.map(e => e.message).join(' ')}`);
} else if (v.code || v.message) {
messages.push(`${v.code ? `${v.code}: ` : ''}${v.message}`.trim());
} else if (typeof v === 'string') {
messages.push(v);
} else {
messages = messages.concat(this.flattenErrors(v, newKey));
}
}
return messages;
}
}
module.exports = DiscordAPIError;
+37
View File
@@ -0,0 +1,37 @@
'use strict';
/**
* Represents a HTTP error from a request.
* @extends Error
*/
class HTTPError extends Error {
constructor(message, name, code, method, path) {
super(message);
/**
* The name of the error
* @type {string}
*/
this.name = name;
/**
* HTTP error code returned from the request
* @type {number}
*/
this.code = code || 500;
/**
* The HTTP method used for the request
* @type {string}
*/
this.method = method;
/**
* The path of the request relative to the HTTP endpoint
* @type {string}
*/
this.path = path;
}
}
module.exports = HTTPError;
+59
View File
@@ -0,0 +1,59 @@
'use strict';
const APIRequest = require('./APIRequest');
const routeBuilder = require('./APIRouter');
const RequestHandler = require('./RequestHandler');
const { Error } = require('../errors');
const Collection = require('../util/Collection');
const { Endpoints } = require('../util/Constants');
class RESTManager {
constructor(client, tokenPrefix = 'Bot') {
this.client = client;
this.handlers = new Collection();
this.tokenPrefix = tokenPrefix;
this.versioned = true;
this.globalTimeout = null;
if (client.options.restSweepInterval > 0) {
client.setInterval(() => {
this.handlers.sweep(handler => handler._inactive);
}, client.options.restSweepInterval * 1000);
}
}
get api() {
return routeBuilder(this);
}
getAuth() {
const token = this.client.token || this.client.accessToken;
if (token) return `${this.tokenPrefix} ${token}`;
throw new Error('TOKEN_MISSING');
}
get cdn() {
return Endpoints.CDN(this.client.options.http.cdn);
}
request(method, url, options = {}) {
const apiRequest = new APIRequest(this, method, url, options);
let handler = this.handlers.get(apiRequest.route);
if (!handler) {
handler = new RequestHandler(this);
this.handlers.set(apiRequest.route, handler);
}
return handler.push(apiRequest);
}
get endpoint() {
return this.client.options.http.api;
}
set endpoint(endpoint) {
this.client.options.http.api = endpoint;
}
}
module.exports = RESTManager;
+173
View File
@@ -0,0 +1,173 @@
'use strict';
const AsyncQueue = require('./AsyncQueue');
const DiscordAPIError = require('./DiscordAPIError');
const HTTPError = require('./HTTPError');
const {
Events: { RATE_LIMIT },
browser,
} = require('../util/Constants');
const Util = require('../util/Util');
function parseResponse(res) {
if (res.headers.get('content-type').startsWith('application/json')) return res.json();
if (browser) return res.blob();
return res.buffer();
}
function getAPIOffset(serverDate) {
return new Date(serverDate).getTime() - Date.now();
}
function calculateReset(reset, serverDate) {
return new Date(Number(reset) * 1000).getTime() - getAPIOffset(serverDate);
}
class RequestHandler {
constructor(manager) {
this.manager = manager;
this.queue = new AsyncQueue();
this.reset = -1;
this.remaining = -1;
this.limit = -1;
this.retryAfter = -1;
}
async push(request) {
await this.queue.wait();
try {
return await this.execute(request);
} finally {
this.queue.shift();
}
}
get limited() {
return Boolean(this.manager.globalTimeout) || (this.remaining <= 0 && Date.now() < this.reset);
}
get _inactive() {
return this.queue.remaining === 0 && !this.limited;
}
async execute(request) {
// After calculations and requests have been done, pre-emptively stop further requests
if (this.limited) {
const timeout = this.reset + this.manager.client.options.restTimeOffset - Date.now();
if (this.manager.client.listenerCount(RATE_LIMIT)) {
/**
* Emitted when the client hits a rate limit while making a request
* @event Client#rateLimit
* @param {Object} rateLimitInfo Object containing the rate limit info
* @param {number} rateLimitInfo.timeout Timeout in ms
* @param {number} rateLimitInfo.limit Number of requests that can be made to this endpoint
* @param {string} rateLimitInfo.method HTTP method used for request that triggered this event
* @param {string} rateLimitInfo.path Path used for request that triggered this event
* @param {string} rateLimitInfo.route Route used for request that triggered this event
*/
this.manager.client.emit(RATE_LIMIT, {
timeout,
limit: this.limit,
method: request.method,
path: request.path,
route: request.route,
});
}
if (this.manager.globalTimeout) {
await this.manager.globalTimeout;
} else {
// Wait for the timeout to expire in order to avoid an actual 429
await Util.delayFor(timeout);
}
}
// Perform the request
let res;
try {
res = await request.make();
} catch (error) {
// Retry the specified number of times for request abortions
if (request.retries === this.manager.client.options.retryLimit) {
throw new HTTPError(error.message, error.constructor.name, error.status, request.method, request.path);
}
request.retries++;
return this.execute(request);
}
if (res && res.headers) {
const serverDate = res.headers.get('date');
const limit = res.headers.get('x-ratelimit-limit');
const remaining = res.headers.get('x-ratelimit-remaining');
const reset = res.headers.get('x-ratelimit-reset');
const retryAfter = res.headers.get('retry-after');
this.limit = limit ? Number(limit) : Infinity;
this.remaining = remaining ? Number(remaining) : 1;
this.reset = reset ? calculateReset(reset, serverDate) : Date.now();
this.retryAfter = retryAfter ? Number(retryAfter) : -1;
// https://github.com/discordapp/discord-api-docs/issues/182
if (request.route.includes('reactions')) {
this.reset = new Date(serverDate).getTime() - getAPIOffset(serverDate) + 250;
}
// Handle global ratelimit
if (res.headers.get('x-ratelimit-global')) {
// Set the manager's global timeout as the promise for other requests to "wait"
this.manager.globalTimeout = Util.delayFor(this.retryAfter);
// Wait for the global timeout to resolve before continuing
await this.manager.globalTimeout;
// Clean up global timeout
this.manager.globalTimeout = null;
}
}
// Handle 2xx and 3xx responses
if (res.ok) {
// Nothing wrong with the request, proceed with the next one
return parseResponse(res);
}
// Handle 4xx responses
if (res.status >= 400 && res.status < 500) {
// Handle ratelimited requests
if (res.status === 429) {
// A ratelimit was hit - this should never happen
this.manager.client.emit('debug', `429 hit on route ${request.route}`);
await Util.delayFor(this.retryAfter);
return this.execute(request);
}
// Handle possible malformed requests
let data;
try {
data = await parseResponse(res);
} catch (err) {
throw new HTTPError(err.message, err.constructor.name, err.status, request.method, request.path);
}
throw new DiscordAPIError(request.path, data, request.method, res.status);
}
// Handle 5xx responses
if (res.status >= 500 && res.status < 600) {
// Retry the specified number of times for possible serverside issues
if (request.retries === this.manager.client.options.retryLimit) {
throw new HTTPError(res.statusText, res.constructor.name, res.status, request.method, request.path);
}
request.retries++;
return this.execute(request);
}
// Fallback in the rare case a status code outside the range 200..=599 is returned
return null;
}
}
module.exports = RequestHandler;