Skip to content

Commit

Permalink
1. commands left to be fixed dynamically. 2. assuming that cleanup ti…
Browse files Browse the repository at this point in the history
…me is returned as response header
  • Loading branch information
Aasif Khan authored and Aasif Khan committed Oct 11, 2024
1 parent 1feedd2 commit 268adb2
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 35 deletions.
6 changes: 3 additions & 3 deletions apps/playground-web/components/CLI/CLI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
import { useCli } from './hooks/useCli';

interface CliProps {
decreaseCommandsLeft: () => void;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}

export default function Cli({ decreaseCommandsLeft }: CliProps) {
export default function Cli({ onCommandExecuted }: CliProps) {
const {
handleInputChange,
handleKeyDown,
terminalRef,
inputRef,
output,
command,
} = useCli(decreaseCommandsLeft);
} = useCli(onCommandExecuted);
return (
<div
ref={terminalRef}
Expand Down
5 changes: 2 additions & 3 deletions apps/playground-web/components/CLI/hooks/useCli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from 'react';
import { handleCommand } from '@/shared/utils/cliUtils';
import blocklistedCommands from '@/shared/utils/blocklist'; // Assuming you added blocklist here

export const useCli = (decreaseCommandsLeft: () => void) => {
export const useCli = (onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void) => {
// states
const [command, setCommand] = useState('');
const [output, setOutput] = useState<string[]>([]);
Expand All @@ -27,11 +27,10 @@ export const useCli = (decreaseCommandsLeft: () => void) => {
`(error) ERR unknown command '${commandName}'`,
]);
} else {
handleCommand({ command, setOutput }); // Execute if not blocklisted
handleCommand({ command, setOutput, onCommandExecuted }); // Execute if not blocklisted
}

setCommand(''); // Clear input
decreaseCommandsLeft(); // Call to update remaining commands
};

useEffect(() => {
Expand Down
18 changes: 10 additions & 8 deletions apps/playground-web/components/Playground/TerminalUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ import { useState } from 'react';
import Tooltip from '../Overlays/Tooltip';
export function TerminalUI() {
const [commandsLeft, setCommandsLeft] = useState(1000);
const decreaseCommandsLeft = () => {
setCommandsLeft((prev) => (prev > 0 ? prev - 1 : 0));
const [cleanupTimeLeft, setCleanupTimeLeft] = useState(15*60);
const handleCommandExecuted = (commands: number, cleanup: number) => {
setCommandsLeft(commands);
setCleanupTimeLeft(cleanup);
};

return (
<>
<div className="bg-gray-900 rounded-lg">
Expand All @@ -20,22 +23,21 @@ export function TerminalUI() {
</div>
</div>
<div className="h-64 md:h-[30rem] bg-gray-100 rounded-lg overflow-hidden shadow-md">
<Shell decreaseCommandsLeft={decreaseCommandsLeft} />
<Shell onCommandExecuted={handleCommandExecuted} />
</div>
</div>
<TerminalCounter commandsLeft={commandsLeft} />
<TerminalCounter commandsLeft={commandsLeft} cleanupTimeLeft={cleanupTimeLeft} />
</>
);
}

function TerminalCounter({ commandsLeft }: { commandsLeft: number }) {
const { timeLeft } = useTimer(15 * 60);
function TerminalCounter({ commandsLeft, cleanupTimeLeft }: { commandsLeft: number; cleanupTimeLeft: number }) {
return (
<div className="flex flex-col">
<div className="flex flex-row justify-between text-gray-900 mt-4">
<div className="flex flex-row items-center space-x-2">
<div className="flex items-center justify-between border border-gray-400 text-sm bg-transparent p-3 rounded-lg">
<span>Cleanup in: {formatTime(timeLeft)} mins</span>
<span>Cleanup in: {formatTime(cleanupTimeLeft)} mins</span>
</div>
<Tooltip message="The time remaining until cleanup is initiated." />
</div>
Expand All @@ -56,4 +58,4 @@ function TerminalCounter({ commandsLeft }: { commandsLeft: number }) {
</div>
</div>
);
}
}
6 changes: 3 additions & 3 deletions apps/playground-web/components/Shell/Shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
import { useShell } from './hooks/useShell';

interface ShellProps {
decreaseCommandsLeft: () => void;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}

export default function Shell({ decreaseCommandsLeft }: ShellProps) {
export default function Shell({ onCommandExecuted }: ShellProps) {
const {
handleInputChange,
handleKeyDown,
terminalRef,
inputRef,
output,
command,
} = useShell(decreaseCommandsLeft);
} = useShell(onCommandExecuted);
return (
<div
ref={terminalRef}
Expand Down
5 changes: 2 additions & 3 deletions apps/playground-web/components/Shell/hooks/useShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from 'react';
import { handleCommand } from '@/shared/utils/shellUtils';
import blocklistedCommands from '@/shared/utils/blocklist';

export const useShell = (decreaseCommandsLeft: () => void) => {
export const useShell = (onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void) => {
// states
const [command, setCommand] = useState('');
const [output, setOutput] = useState<string[]>([]);
Expand All @@ -32,11 +32,10 @@ export const useShell = (decreaseCommandsLeft: () => void) => {
`(error) ERR unknown command '${commandName}'`,
]);
} else {
handleCommand({ command, setOutput }); // Execute if not blocklisted
handleCommand({ command, setOutput, onCommandExecuted }); // Execute if not blocklisted
}

setCommand(''); // Clear input
decreaseCommandsLeft(); // Call to update remaining commands
};

useEffect(() => {
Expand Down
8 changes: 4 additions & 4 deletions apps/playground-web/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export const executeShellCommandOnServer = async (
const response = await WebService.post(cmdExecURL, cmdOptions);

// Check if the response contains data or if it's an error response
if (response?.data) {
return response.data;
} else if (response?.error) {
return response.error;
if (response?.body?.data) {
return response;
} else if (response?.body.error) {
return response;
} else {
throw new Error('Unexpected response structure');
}
Expand Down
10 changes: 8 additions & 2 deletions apps/playground-web/services/webServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,15 @@ export const WebService = {
}
}

const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
headers['x-ratelimit-remaining'] = 101;

// Parse the result as JSON
const result = await response.json();
return result;
const body = await response.json();
return { headers: headers, body: body };
} catch (error) {
if (error instanceof Error) {
console.error(`Error with ${method} request: ${error.message}`);
Expand Down
19 changes: 14 additions & 5 deletions apps/playground-web/shared/utils/cliUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import { executeShellCommandOnServer } from '@/lib/api';
import { CommandHandler } from '@/types';

export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
export const handleCommand = async ({ command, setOutput, onCommandExecuted }: CommandHandler) => {
const newOutput = `dice > ${command}`;
let result: string;
let result: any;

Check warning on line 8 in apps/playground-web/shared/utils/cliUtils.ts

View workflow job for this annotation

GitHub Actions / Build and Test

Unexpected any. Specify a different type

const [cmd, ...args] = command.split(' ');
if (!cmd) {
Expand All @@ -26,7 +26,10 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
const [key] = args;
const cmdOptions = { key: key };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
const commandsLeft = result.headers['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand All @@ -40,7 +43,10 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
try {
const cmdOptions = { key: key, value: value };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
const commandsLeft = result.headers['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand All @@ -59,7 +65,10 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
try {
const cmdOptions = { keys: [keys] };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
const commandsLeft = result.headers['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand Down
2 changes: 1 addition & 1 deletion apps/playground-web/shared/utils/commonUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
};
};
9 changes: 6 additions & 3 deletions apps/playground-web/shared/utils/shellUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import { executeShellCommandOnServer } from '@/lib/api';
import { CommandHandler } from '@/types';

export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
export const handleCommand = async ({ command, setOutput, onCommandExecuted }: CommandHandler) => {
const newOutput = `dice > ${command}`;
let result: string;
let result: any;

Check warning on line 8 in apps/playground-web/shared/utils/shellUtils.ts

View workflow job for this annotation

GitHub Actions / Build and Test

Unexpected any. Specify a different type

const [cmd, ...args] = command.split(' ');

Expand All @@ -14,7 +14,10 @@ export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
}
try {
result = await executeShellCommandOnServer(cmd, args);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
const commandsLeft = result.headers['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand Down
1 change: 1 addition & 0 deletions apps/playground-web/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import * as React from 'react';
export interface CommandHandler {
command: string;
setOutput: React.Dispatch<React.SetStateAction<string[]>>;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}

0 comments on commit 268adb2

Please sign in to comment.