start fixing apiRoll
This commit is contained in:
		
							parent
							
								
									d2a7c25879
								
							
						
					
					
						commit
						1069b99091
					
				
							
								
								
									
										22
									
								
								src/api.ts
								
								
								
								
							
							
						
						
									
										22
									
								
								src/api.ts
								
								
								
								
							| 
						 | 
				
			
			@ -16,7 +16,7 @@ import stdResp from './endpoints/stdResponses.ts';
 | 
			
		|||
 | 
			
		||||
// start() returns nothing
 | 
			
		||||
// start initializes and runs the entire API for the bot
 | 
			
		||||
const start = async (): Promise<void> => {
 | 
			
		||||
const start = () => {
 | 
			
		||||
  log(LT.INFO, `HTTP api running at: http://localhost:${config.api.port}/`);
 | 
			
		||||
 | 
			
		||||
  // rateLimitTime holds all users with the last time they started a rate limit timer
 | 
			
		||||
| 
						 | 
				
			
			@ -102,13 +102,13 @@ const start = async (): Promise<void> => {
 | 
			
		|||
              switch (path.toLowerCase()) {
 | 
			
		||||
                case '/key':
 | 
			
		||||
                case '/key/':
 | 
			
		||||
                  return await endpoints.get.apiKeyAdmin(query, apiUserid);
 | 
			
		||||
                  return endpoints.get.apiKeyAdmin(query, apiUserid);
 | 
			
		||||
                case '/channel':
 | 
			
		||||
                case '/channel/':
 | 
			
		||||
                  return await endpoints.get.apiChannel(query, apiUserid);
 | 
			
		||||
                  return endpoints.get.apiChannel(query, apiUserid);
 | 
			
		||||
                case '/roll':
 | 
			
		||||
                case '/roll/':
 | 
			
		||||
                  return await endpoints.get.apiRoll(query, apiUserid, request);
 | 
			
		||||
                  return endpoints.get.apiRoll(query, apiUserid);
 | 
			
		||||
                default:
 | 
			
		||||
                  // Alert API user that they messed up
 | 
			
		||||
                  return stdResp.NotFound('Auth Get');
 | 
			
		||||
| 
						 | 
				
			
			@ -118,7 +118,7 @@ const start = async (): Promise<void> => {
 | 
			
		|||
              switch (path.toLowerCase()) {
 | 
			
		||||
                case '/channel/add':
 | 
			
		||||
                case '/channel/add/':
 | 
			
		||||
                  return await endpoints.post.apiChannelAdd(query, apiUserid);
 | 
			
		||||
                  return endpoints.post.apiChannelAdd(query, apiUserid);
 | 
			
		||||
                default:
 | 
			
		||||
                  // Alert API user that they messed up
 | 
			
		||||
                  return stdResp.NotFound('Auth Post');
 | 
			
		||||
| 
						 | 
				
			
			@ -134,17 +134,17 @@ const start = async (): Promise<void> => {
 | 
			
		|||
                case '/key/activate/':
 | 
			
		||||
                case '/key/deactivate':
 | 
			
		||||
                case '/key/deactivate/':
 | 
			
		||||
                  return await endpoints.put.apiKeyManage(query, apiUserid, path);
 | 
			
		||||
                  return endpoints.put.apiKeyManage(query, apiUserid, path);
 | 
			
		||||
                case '/channel/ban':
 | 
			
		||||
                case '/channel/ban/':
 | 
			
		||||
                case '/channel/unban':
 | 
			
		||||
                case '/channel/unban/':
 | 
			
		||||
                  return await endpoints.put.apiChannelManageBan(query, apiUserid, path);
 | 
			
		||||
                  return endpoints.put.apiChannelManageBan(query, apiUserid, path);
 | 
			
		||||
                case '/channel/activate':
 | 
			
		||||
                case '/channel/activate/':
 | 
			
		||||
                case '/channel/deactivate':
 | 
			
		||||
                case '/channel/deactivate/':
 | 
			
		||||
                  return await endpoints.put.apiChannelManageActive(query, apiUserid, path);
 | 
			
		||||
                  return endpoints.put.apiChannelManageActive(query, apiUserid, path);
 | 
			
		||||
                default:
 | 
			
		||||
                  // Alert API user that they messed up
 | 
			
		||||
                  return stdResp.NotFound('Auth Put');
 | 
			
		||||
| 
						 | 
				
			
			@ -154,7 +154,7 @@ const start = async (): Promise<void> => {
 | 
			
		|||
              switch (path.toLowerCase()) {
 | 
			
		||||
                case '/key/delete':
 | 
			
		||||
                case '/key/delete/':
 | 
			
		||||
                  return await endpoints.delete.apiKeyDelete(query, apiUserid, apiUserEmail, apiUserDelCode);
 | 
			
		||||
                  return endpoints.delete.apiKeyDelete(query, apiUserid, apiUserEmail, apiUserDelCode);
 | 
			
		||||
                default:
 | 
			
		||||
                  // Alert API user that they messed up
 | 
			
		||||
                  return stdResp.NotFound('Auth Del');
 | 
			
		||||
| 
						 | 
				
			
			@ -164,14 +164,14 @@ const start = async (): Promise<void> => {
 | 
			
		|||
              // Alert API user that they messed up
 | 
			
		||||
              return stdResp.MethodNotAllowed('Auth');
 | 
			
		||||
          }
 | 
			
		||||
        } else if (!authenticated) {
 | 
			
		||||
        } else {
 | 
			
		||||
          // Handle the unathenticated request
 | 
			
		||||
          switch (request.method) {
 | 
			
		||||
            case 'GET':
 | 
			
		||||
              switch (path.toLowerCase()) {
 | 
			
		||||
                case '/key':
 | 
			
		||||
                case '/key/':
 | 
			
		||||
                  return await endpoints.get.apiKey(query);
 | 
			
		||||
                  return endpoints.get.apiKey(query);
 | 
			
		||||
                case '/heatmap.png':
 | 
			
		||||
                  return endpoints.get.heatmapPng();
 | 
			
		||||
                default:
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -12,7 +12,6 @@ import {
 | 
			
		|||
import { rollingEmbed, warnColor } from '../commandUtils.ts';
 | 
			
		||||
import rollFuncs from './roll/_index.ts';
 | 
			
		||||
import { queueRoll } from '../solver/rollQueue.ts';
 | 
			
		||||
import { QueuedRoll } from '../mod.d.ts';
 | 
			
		||||
import utils from '../utils.ts';
 | 
			
		||||
 | 
			
		||||
export const roll = async (message: DiscordenoMessage, args: string[], command: string) => {
 | 
			
		||||
| 
						 | 
				
			
			@ -53,15 +52,13 @@ export const roll = async (message: DiscordenoMessage, args: string[], command:
 | 
			
		|||
    // Rejoin all of the args and send it into the solver, if solver returns a falsy item, an error object will be substituded in
 | 
			
		||||
    const rollCmd = message.content.substring(2);
 | 
			
		||||
 | 
			
		||||
    queueRoll(
 | 
			
		||||
      <QueuedRoll> {
 | 
			
		||||
    queueRoll({
 | 
			
		||||
      apiRoll: false,
 | 
			
		||||
      dd: { m, message },
 | 
			
		||||
      rollCmd,
 | 
			
		||||
      modifiers,
 | 
			
		||||
      originalCommand,
 | 
			
		||||
      },
 | 
			
		||||
    );
 | 
			
		||||
    });
 | 
			
		||||
  } catch (e) {
 | 
			
		||||
    log(LT.ERROR, `Undandled Error: ${JSON.stringify(e)}`);
 | 
			
		||||
  }
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -8,14 +8,14 @@ import {
 | 
			
		|||
  log,
 | 
			
		||||
  LT,
 | 
			
		||||
} from '../../../deps.ts';
 | 
			
		||||
import { QueuedRoll, RollModifiers } from '../../mod.d.ts';
 | 
			
		||||
import { RollModifiers } from '../../mod.d.ts';
 | 
			
		||||
import utils from '../../utils.ts';
 | 
			
		||||
import { queueRoll } from '../../solver/rollQueue.ts';
 | 
			
		||||
import stdResp from '../stdResponses.ts';
 | 
			
		||||
 | 
			
		||||
const apiWarning = `The following roll was conducted using my built in API.  If someone in this channel did not request this roll, please report API abuse here: <${config.api.supportURL}>`;
 | 
			
		||||
 | 
			
		||||
export const apiRoll = async (query: Map<string, string>, apiUserid: bigint, request: Request): Promise<Response> => {
 | 
			
		||||
export const apiRoll = async (query: Map<string, string>, apiUserid: bigint): Promise<Response> => {
 | 
			
		||||
  // Make sure query contains all the needed parts
 | 
			
		||||
  if (
 | 
			
		||||
    query.has('rollstr') &&
 | 
			
		||||
| 
						 | 
				
			
			@ -61,7 +61,7 @@ export const apiRoll = async (query: Map<string, string>, apiUserid: bigint, req
 | 
			
		|||
      try {
 | 
			
		||||
        // Make sure rollCmd is not undefined
 | 
			
		||||
        let rollCmd = query.get('rollstr') || '';
 | 
			
		||||
        const originalCommand = query.get('rollstr');
 | 
			
		||||
        const originalCommand = query.get('rollstr') || '';
 | 
			
		||||
 | 
			
		||||
        if (rollCmd.length === 0) {
 | 
			
		||||
          // Always log API rolls for abuse detection
 | 
			
		||||
| 
						 | 
				
			
			@ -101,15 +101,13 @@ export const apiRoll = async (query: Map<string, string>, apiUserid: bigint, req
 | 
			
		|||
        };
 | 
			
		||||
 | 
			
		||||
        // Parse the roll and get the return text
 | 
			
		||||
        await queueRoll(
 | 
			
		||||
          <QueuedRoll> {
 | 
			
		||||
        await queueRoll({
 | 
			
		||||
          apiRoll: true,
 | 
			
		||||
            api: { request, channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') },
 | 
			
		||||
          api: { channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') },
 | 
			
		||||
          rollCmd,
 | 
			
		||||
          modifiers,
 | 
			
		||||
          originalCommand,
 | 
			
		||||
          },
 | 
			
		||||
        );
 | 
			
		||||
        });
 | 
			
		||||
      } catch (err) {
 | 
			
		||||
        // Handle any errors we missed
 | 
			
		||||
        log(LT.ERROR, `Unhandled Error: ${JSON.stringify(err)}`);
 | 
			
		||||
| 
						 | 
				
			
			@ -118,7 +116,7 @@ export const apiRoll = async (query: Map<string, string>, apiUserid: bigint, req
 | 
			
		|||
    } else {
 | 
			
		||||
      // Alert API user that they messed up
 | 
			
		||||
      return stdResp.Forbidden(
 | 
			
		||||
        `Verify you are a member of the guild you are sending this roll to.  If you are, the ${config.name} may not have that registered, please send a message in the guild so ${config.name} can register this.  This registration is temporary, so if you see this error again, just poke your server again.`,
 | 
			
		||||
        `Verify you are a member of the guild you are sending this roll to.  If you are, the ${config.name} may not have that registered, please send a message in the guild so ${config.name} can register this.  This registration is temporary, so if you see this error again, just poke your server again.`
 | 
			
		||||
      );
 | 
			
		||||
    }
 | 
			
		||||
  } else {
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -26,21 +26,25 @@ export type RollModifiers = {
 | 
			
		|||
};
 | 
			
		||||
 | 
			
		||||
// QueuedRoll is the structure to track rolls we could not immediately handle
 | 
			
		||||
export type QueuedRoll = {
 | 
			
		||||
  apiRoll: boolean;
 | 
			
		||||
interface QueuedRoll {
 | 
			
		||||
  rollCmd: string;
 | 
			
		||||
  modifiers: RollModifiers;
 | 
			
		||||
  originalCommand: string;
 | 
			
		||||
}
 | 
			
		||||
export interface ApiQueuedRoll extends QueuedRoll {
 | 
			
		||||
  apiRoll: true;
 | 
			
		||||
  api: {
 | 
			
		||||
    request: Request;
 | 
			
		||||
    channelId: bigint;
 | 
			
		||||
    userId: bigint;
 | 
			
		||||
  };
 | 
			
		||||
}
 | 
			
		||||
export interface DDQueuedRoll extends QueuedRoll {
 | 
			
		||||
  apiRoll: false;
 | 
			
		||||
  dd: {
 | 
			
		||||
    m: DiscordenoMessage;
 | 
			
		||||
    message: DiscordenoMessage;
 | 
			
		||||
  };
 | 
			
		||||
  originalCommand: string;
 | 
			
		||||
  rollCmd: string;
 | 
			
		||||
  modifiers: RollModifiers;
 | 
			
		||||
};
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export type PastCommandCount = {
 | 
			
		||||
  command: string;
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -13,16 +13,16 @@ import {
 | 
			
		|||
  sendMessage,
 | 
			
		||||
} from '../../deps.ts';
 | 
			
		||||
import { SolvedRoll } from '../solver/solver.d.ts';
 | 
			
		||||
import { QueuedRoll, RollModifiers } from '../mod.d.ts';
 | 
			
		||||
import { ApiQueuedRoll, DDQueuedRoll, RollModifiers } from '../mod.d.ts';
 | 
			
		||||
import { generateCountDetailsEmbed, generateDMFailed, generateRollEmbed, infoColor2, rollingEmbed } from '../commandUtils.ts';
 | 
			
		||||
import stdResp from '../endpoints/stdResponses.ts';
 | 
			
		||||
import utils from '../utils.ts';
 | 
			
		||||
 | 
			
		||||
let currentWorkers = 0;
 | 
			
		||||
const rollQueue: Array<QueuedRoll> = [];
 | 
			
		||||
const rollQueue: Array<ApiQueuedRoll | DDQueuedRoll> = [];
 | 
			
		||||
 | 
			
		||||
// Handle setting up and calling the rollWorker
 | 
			
		||||
const handleRollWorker = async (rq: QueuedRoll) => {
 | 
			
		||||
const handleRollWorker = async (rq: ApiQueuedRoll | DDQueuedRoll) => {
 | 
			
		||||
  currentWorkers++;
 | 
			
		||||
 | 
			
		||||
  // gmModifiers used to create gmEmbed (basically just turn off the gmRoll)
 | 
			
		||||
| 
						 | 
				
			
			@ -48,7 +48,7 @@ const handleRollWorker = async (rq: QueuedRoll) => {
 | 
			
		|||
                  errorCode: 'TooComplex',
 | 
			
		||||
                  errorMsg: 'Error: Roll took too long to process, try breaking roll down into simpler parts',
 | 
			
		||||
                },
 | 
			
		||||
                <RollModifiers> {},
 | 
			
		||||
                <RollModifiers>{}
 | 
			
		||||
              )
 | 
			
		||||
            ).embed,
 | 
			
		||||
          ],
 | 
			
		||||
| 
						 | 
				
			
			@ -175,9 +175,9 @@ const handleRollWorker = async (rq: QueuedRoll) => {
 | 
			
		|||
                    }
 | 
			
		||||
                  : {
 | 
			
		||||
                      details: pubEmbedDetails,
 | 
			
		||||
                  },
 | 
			
		||||
              ),
 | 
			
		||||
            ),
 | 
			
		||||
                    }
 | 
			
		||||
              )
 | 
			
		||||
            )
 | 
			
		||||
          );
 | 
			
		||||
        }
 | 
			
		||||
      }
 | 
			
		||||
| 
						 | 
				
			
			@ -191,7 +191,7 @@ const handleRollWorker = async (rq: QueuedRoll) => {
 | 
			
		|||
};
 | 
			
		||||
 | 
			
		||||
// Runs the roll or queues it depending on how many workers are currently running
 | 
			
		||||
export const queueRoll = async (rq: QueuedRoll) => {
 | 
			
		||||
export const queueRoll = async (rq: ApiQueuedRoll | DDQueuedRoll) => {
 | 
			
		||||
  if (rq.apiRoll) {
 | 
			
		||||
    handleRollWorker(rq);
 | 
			
		||||
  } else if (!rollQueue.length && currentWorkers < config.limits.maxWorkers) {
 | 
			
		||||
| 
						 | 
				
			
			@ -218,7 +218,7 @@ The results for this roll will replace this message when it is done.`,
 | 
			
		|||
setInterval(async () => {
 | 
			
		||||
  log(
 | 
			
		||||
    LT.LOG,
 | 
			
		||||
    `Checking rollQueue for items, rollQueue length: ${rollQueue.length}, currentWorkers: ${currentWorkers}, config.limits.maxWorkers: ${config.limits.maxWorkers}`,
 | 
			
		||||
    `Checking rollQueue for items, rollQueue length: ${rollQueue.length}, currentWorkers: ${currentWorkers}, config.limits.maxWorkers: ${config.limits.maxWorkers}`
 | 
			
		||||
  );
 | 
			
		||||
  if (rollQueue.length && currentWorkers < config.limits.maxWorkers) {
 | 
			
		||||
    const temp = rollQueue.shift();
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
		Reference in New Issue