Files
parcer/src/components/robot/RobotEdit.tsx

455 lines
16 KiB
TypeScript
Raw Normal View History

2024-11-17 00:31:36 +05:30
import React, { useState, useEffect } from 'react';
2024-12-21 15:42:35 +05:30
import { useTranslation } from 'react-i18next';
2025-01-09 19:49:20 +05:30
import { GenericModal } from "../ui/GenericModal";
2025-01-21 22:27:48 +05:30
import { TextField, Typography, Box, Button, IconButton, InputAdornment } from "@mui/material";
import { Visibility, VisibilityOff } from '@mui/icons-material';
2025-01-09 20:09:46 +05:30
import { modalStyle } from "../recorder/AddWhereCondModal";
2024-11-17 00:31:36 +05:30
import { useGlobalInfoStore } from '../../context/globalInfo';
2024-11-17 02:27:11 +05:30
import { getStoredRecording, updateRecording } from '../../api/storage';
2024-11-17 00:31:36 +05:30
import { WhereWhatPair } from 'maxun-core';
interface RobotMeta {
name: string;
id: string;
createdAt: string;
pairs: number;
updatedAt: string;
params: any[];
}
interface RobotWorkflow {
workflow: WhereWhatPair[];
}
interface ScheduleConfig {
runEvery: number;
runEveryUnit: 'MINUTES' | 'HOURS' | 'DAYS' | 'WEEKS' | 'MONTHS';
startFrom: 'SUNDAY' | 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY';
atTimeStart?: string;
atTimeEnd?: string;
timezone: string;
lastRunAt?: Date;
nextRunAt?: Date;
cronExpression?: string;
}
export interface RobotSettings {
id: string;
userId?: number;
recording_meta: RobotMeta;
recording: RobotWorkflow;
google_sheet_email?: string | null;
google_sheet_name?: string | null;
google_sheet_id?: string | null;
google_access_token?: string | null;
google_refresh_token?: string | null;
schedule?: ScheduleConfig | null;
}
interface RobotSettingsProps {
isOpen: boolean;
handleStart: (settings: RobotSettings) => void;
handleClose: () => void;
initialSettings?: RobotSettings | null;
}
2025-01-23 01:16:42 +05:30
interface CredentialInfo {
value: string;
type: string;
}
interface Credentials {
[key: string]: CredentialInfo;
}
interface CredentialVisibility {
[key: string]: boolean;
}
interface GroupedCredentials {
passwords: string[];
emails: string[];
usernames: string[];
others: string[];
}
2024-11-17 00:31:36 +05:30
export const RobotEditModal = ({ isOpen, handleStart, handleClose, initialSettings }: RobotSettingsProps) => {
2024-12-21 15:42:35 +05:30
const { t } = useTranslation();
2024-11-17 00:31:36 +05:30
const [robot, setRobot] = useState<RobotSettings | null>(null);
2025-01-21 22:27:48 +05:30
const [credentials, setCredentials] = useState<Credentials>({});
2024-11-17 00:31:36 +05:30
const { recordingId, notify } = useGlobalInfoStore();
2025-01-25 15:50:27 +05:30
const [credentialGroups, setCredentialGroups] = useState<GroupedCredentials>({
passwords: [],
2025-01-23 01:16:42 +05:30
emails: [],
usernames: [],
2025-01-25 15:50:27 +05:30
others: []
2025-01-23 01:16:42 +05:30
});
2025-01-21 22:27:48 +05:30
const [showPasswords, setShowPasswords] = useState<CredentialVisibility>({});
2025-01-23 01:16:42 +05:30
const isEmailPattern = (value: string): boolean => {
return value.includes('@');
};
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
const isUsernameSelector = (selector: string): boolean => {
2025-01-25 15:50:27 +05:30
return selector.toLowerCase().includes('username') ||
selector.toLowerCase().includes('user') ||
selector.toLowerCase().includes('email');
2025-01-21 22:27:48 +05:30
};
2024-11-17 00:31:36 +05:30
2025-01-23 01:16:42 +05:30
const determineCredentialType = (selector: string, info: CredentialInfo): 'password' | 'email' | 'username' | 'other' => {
if (info.type === 'password' || selector.toLowerCase().includes('password')) {
2025-01-23 01:16:42 +05:30
return 'password';
}
if (isEmailPattern(info.value) || selector.toLowerCase().includes('email')) {
return 'email';
}
if (isUsernameSelector(selector)) {
return 'username';
}
return 'other';
};
2025-01-25 15:50:27 +05:30
2024-11-17 00:31:36 +05:30
useEffect(() => {
if (isOpen) {
getRobot();
}
}, [isOpen]);
2025-01-21 22:27:48 +05:30
useEffect(() => {
if (robot?.recording?.workflow) {
2025-01-23 01:16:42 +05:30
const extractedCredentials = extractInitialCredentials(robot.recording.workflow);
setCredentials(extractedCredentials);
setCredentialGroups(groupCredentialsByType(extractedCredentials));
2025-01-21 22:27:48 +05:30
}
}, [robot]);
2025-01-23 01:16:42 +05:30
const extractInitialCredentials = (workflow: any[]): Credentials => {
const credentials: Credentials = {};
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Helper function to check if a character is printable
const isPrintableCharacter = (char: string): boolean => {
return char.length === 1 && !!char.match(/^[\x20-\x7E]$/);
};
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Process each step in the workflow
workflow.forEach(step => {
if (!step.what) return;
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Keep track of the current input field being processed
let currentSelector = '';
let currentValue = '';
let currentType = '';
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Process actions in sequence to maintain correct text state
step.what.forEach((action: any) => {
if (
2025-01-25 15:50:27 +05:30
(action.action === 'type' || action.action === 'press') &&
action.args?.length >= 2 &&
typeof action.args[1] === 'string'
) {
2025-01-23 01:53:04 +05:30
const selector: string = action.args[0];
2025-01-23 01:16:42 +05:30
const character: string = action.args[1];
const inputType: string = action.args[2] || '';
2025-01-25 15:50:27 +05:30
2025-01-25 16:09:33 +05:30
// Detect `input[type="password"]`
if (!currentType && inputType.toLowerCase() === 'password') {
currentType = 'password';
}
2025-01-23 01:53:04 +05:30
// If we're dealing with a new selector, store the previous one
if (currentSelector && selector !== currentSelector) {
if (!credentials[currentSelector]) {
credentials[currentSelector] = {
value: currentValue,
type: currentType
};
} else {
credentials[currentSelector].value = currentValue;
}
}
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Update current tracking variables
if (selector !== currentSelector) {
currentSelector = selector;
currentValue = credentials[selector]?.value || '';
currentType = inputType || credentials[selector]?.type || '';
}
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Handle different types of key actions
if (character === 'Backspace') {
// Remove the last character when backspace is pressed
currentValue = currentValue.slice(0, -1);
} else if (isPrintableCharacter(character)) {
// Add the character to the current value
currentValue += character;
}
2025-01-23 01:53:04 +05:30
// Note: We ignore other special keys like 'Shift', 'Enter', etc.
}
});
2025-01-25 15:50:27 +05:30
2025-01-23 01:53:04 +05:30
// Store the final state of the last processed selector
if (currentSelector) {
credentials[currentSelector] = {
value: currentValue,
type: currentType
};
}
});
2025-01-25 15:50:27 +05:30
return credentials;
};
2025-01-23 01:16:42 +05:30
const groupCredentialsByType = (credentials: Credentials): GroupedCredentials => {
return Object.entries(credentials).reduce((acc: GroupedCredentials, [selector, info]) => {
const credentialType = determineCredentialType(selector, info);
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
switch (credentialType) {
case 'password':
acc.passwords.push(selector);
break;
case 'email':
acc.emails.push(selector);
break;
case 'username':
acc.usernames.push(selector);
break;
default:
acc.others.push(selector);
}
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
return acc;
}, { passwords: [], emails: [], usernames: [], others: [] });
};
2024-11-17 00:31:36 +05:30
const getRobot = async () => {
if (recordingId) {
const robot = await getStoredRecording(recordingId);
setRobot(robot);
} else {
2024-12-21 15:42:35 +05:30
notify('error', t('robot_edit.notifications.update_failed'));
2024-11-17 00:31:36 +05:30
}
2025-01-23 01:16:42 +05:30
};
const handleClickShowPassword = (selector: string) => {
setShowPasswords(prev => ({
...prev,
[selector]: !prev[selector]
}));
};
2024-11-17 00:31:36 +05:30
2024-11-17 02:27:11 +05:30
const handleRobotNameChange = (newName: string) => {
setRobot((prev) =>
prev ? { ...prev, recording_meta: { ...prev.recording_meta, name: newName } } : prev
);
};
2025-01-21 22:27:48 +05:30
const handleCredentialChange = (selector: string, value: string) => {
setCredentials(prev => ({
2025-01-23 01:16:42 +05:30
...prev,
[selector]: {
...prev[selector],
value
}
2025-01-21 22:27:48 +05:30
}));
};
2024-11-17 02:27:11 +05:30
const handleLimitChange = (newLimit: number) => {
setRobot((prev) => {
if (!prev) return prev;
2024-11-18 06:12:35 +05:30
2024-11-17 02:27:11 +05:30
const updatedWorkflow = [...prev.recording.workflow];
if (
updatedWorkflow.length > 0 &&
updatedWorkflow[0]?.what &&
updatedWorkflow[0].what.length > 0 &&
updatedWorkflow[0].what[0].args &&
updatedWorkflow[0].what[0].args.length > 0 &&
updatedWorkflow[0].what[0].args[0]
) {
updatedWorkflow[0].what[0].args[0].limit = newLimit;
}
2024-11-18 06:12:35 +05:30
2024-11-17 02:27:11 +05:30
return { ...prev, recording: { ...prev.recording, workflow: updatedWorkflow } };
});
};
2024-12-21 15:42:35 +05:30
2025-01-23 01:16:42 +05:30
const renderAllCredentialFields = () => {
return (
<>
{renderCredentialFields(
2025-01-25 15:50:27 +05:30
credentialGroups.usernames,
2025-01-25 15:42:33 +05:30
t('Username'),
2025-01-25 15:44:05 +05:30
'text'
2025-01-23 01:16:42 +05:30
)}
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
{renderCredentialFields(
2025-01-25 15:50:27 +05:30
credentialGroups.emails,
2025-01-25 15:43:05 +05:30
t('Email'),
2025-01-25 15:44:05 +05:30
'text'
2025-01-23 01:16:42 +05:30
)}
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
{renderCredentialFields(
2025-01-25 15:50:27 +05:30
credentialGroups.passwords,
2025-01-25 15:43:18 +05:30
t('Password'),
2025-01-25 15:44:05 +05:30
'password'
2025-01-23 01:16:42 +05:30
)}
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
{renderCredentialFields(
2025-01-25 15:50:27 +05:30
credentialGroups.others,
2025-01-25 15:43:30 +05:30
t('Other'),
2025-01-25 15:44:05 +05:30
'text'
2025-01-23 01:16:42 +05:30
)}
</>
);
};
const renderCredentialFields = (selectors: string[], headerText: string, defaultType: 'text' | 'password' = 'text') => {
if (selectors.length === 0) return null;
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
return (
<>
2025-01-25 15:57:23 +05:30
{/* <Typography variant="h6" style={{ marginBottom: '20px' }}>
2025-01-23 01:16:42 +05:30
{headerText}
2025-01-25 15:57:23 +05:30
</Typography> */}
{selectors.map((selector, index) => {
2025-01-23 20:23:53 +05:30
const isVisible = showPasswords[selector];
2025-01-25 15:50:27 +05:30
2025-01-23 20:23:53 +05:30
return (
<TextField
key={selector}
type={isVisible ? 'text' : 'password'}
2025-01-25 16:17:48 +05:30
label={headerText === 'Other' ? `${`Input`} ${index + 1}` : headerText}
2025-01-23 20:23:53 +05:30
value={credentials[selector]?.value || ''}
onChange={(e) => handleCredentialChange(selector, e.target.value)}
style={{ marginBottom: '20px' }}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
2025-01-25 15:50:12 +05:30
aria-label="Show input"
2025-01-23 20:23:53 +05:30
onClick={() => handleClickShowPassword(selector)}
edge="end"
disabled={!credentials[selector]?.value}
>
{isVisible ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
),
}}
/>
);
})}
2025-01-23 01:16:42 +05:30
</>
);
};
2024-11-17 02:27:11 +05:30
const handleSave = async () => {
if (!robot) return;
2024-11-18 06:12:35 +05:30
2024-11-17 02:27:11 +05:30
try {
2025-01-23 01:16:42 +05:30
const credentialsForPayload = Object.entries(credentials).reduce((acc, [selector, info]) => {
const enforceType = info.type === 'password' ? 'password' : 'text';
acc[selector] = {
value: info.value,
type: enforceType
};
return acc;
}, {} as Record<string, CredentialInfo>);
2024-11-18 06:12:35 +05:30
const payload = {
name: robot.recording_meta.name,
limit: robot.recording.workflow[0]?.what[0]?.args?.[0]?.limit,
2025-01-23 01:16:42 +05:30
credentials: credentialsForPayload,
2024-11-18 06:12:35 +05:30
};
const success = await updateRecording(robot.recording_meta.id, payload);
if (success) {
2024-12-21 15:42:35 +05:30
notify('success', t('robot_edit.notifications.update_success'));
2025-01-23 01:16:42 +05:30
handleStart(robot);
2025-01-09 19:17:48 +05:30
handleClose();
2024-11-18 06:12:35 +05:30
2024-11-22 23:40:05 +05:30
setTimeout(() => {
window.location.reload();
}, 1000);
2024-11-18 06:12:35 +05:30
} else {
2024-12-21 15:42:35 +05:30
notify('error', t('robot_edit.notifications.update_failed'));
2024-11-18 06:12:35 +05:30
}
2024-11-17 02:27:11 +05:30
} catch (error) {
2024-12-21 15:42:35 +05:30
notify('error', t('robot_edit.notifications.update_error'));
2024-11-18 06:12:35 +05:30
console.error('Error updating robot:', error);
2024-11-17 02:27:11 +05:30
}
};
2024-11-17 00:31:36 +05:30
return (
<GenericModal
isOpen={isOpen}
onClose={handleClose}
modalStyle={modalStyle}
>
<>
2024-12-21 15:42:35 +05:30
<Typography variant="h5" style={{ marginBottom: '20px' }}>
{t('robot_edit.title')}
</Typography>
2024-11-17 00:31:36 +05:30
<Box style={{ display: 'flex', flexDirection: 'column' }}>
2025-01-23 01:16:42 +05:30
{robot && (
<>
<TextField
label={t('robot_edit.change_name')}
key="Robot Name"
type='text'
value={robot.recording_meta.name}
onChange={(e) => handleRobotNameChange(e.target.value)}
style={{ marginBottom: '20px' }}
/>
2025-01-25 15:50:27 +05:30
2025-01-23 01:16:42 +05:30
{robot.recording.workflow?.[0]?.what?.[0]?.args?.[0]?.limit !== undefined && (
2024-11-17 00:31:36 +05:30
<TextField
2025-01-23 01:16:42 +05:30
label={t('robot_edit.robot_limit')}
type="number"
value={robot.recording.workflow[0].what[0].args[0].limit || ''}
onChange={(e) => {
const value = parseInt(e.target.value, 10);
if (value >= 1) {
handleLimitChange(value);
}
}}
inputProps={{ min: 1 }}
2024-11-17 00:31:36 +05:30
style={{ marginBottom: '20px' }}
/>
2025-01-23 01:16:42 +05:30
)}
2025-01-25 17:31:23 +05:30
{(Object.keys(credentials).length > 0) && (
2025-01-23 01:16:42 +05:30
<>
2025-01-25 16:21:56 +05:30
<Typography variant="body1" style={{ marginBottom: '20px' }}>
{t('Input Texts')}
</Typography>
2025-01-23 01:16:42 +05:30
{renderAllCredentialFields()}
</>
)}
<Box mt={2} display="flex" justifyContent="flex-end">
<Button variant="contained" color="primary" onClick={handleSave}>
{t('robot_edit.save')}
</Button>
<Button
onClick={handleClose}
color="primary"
variant="outlined"
style={{ marginLeft: '10px' }}
sx={{
color: '#ff00c3 !important',
borderColor: '#ff00c3 !important',
backgroundColor: 'whitesmoke !important',
}}>
{t('robot_edit.cancel')}
</Button>
</Box>
</>
)}
2024-11-17 00:31:36 +05:30
</Box>
</>
</GenericModal>
);
2025-01-23 01:16:42 +05:30
};