Skip to content

Commit

Permalink
updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Nursid committed Aug 7, 2024
1 parent 835bdc0 commit 35b528c
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 102 deletions.
31 changes: 28 additions & 3 deletions actions/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,41 @@ const list = async () => {
}

const userData = getUserData();
const token = userData.token;

if (!userData || !userData.jwtToken) {
console.log(chalk.red('Failed to retrieve user data or authentication token.'));
return;
}

const token = userData.jwtToken;

try {
// Fetch the list of agents
const response = await axios.get('https://codeboltai.web.app/api/agents/list', {
headers: {
'Authorization': `Bearer ${token}`
}
});


const agents = response.data;
// Fetch the username
const usernameResponse = await axios.get(
'https://codeboltai.web.app/api/auth/check-username',
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);

if (!usernameResponse.data || !usernameResponse.data.usersData || usernameResponse.data.usersData.length === 0) {
console.log(chalk.red('Failed to retrieve username or no user data available.'));
return;
}

const username = usernameResponse.data.usersData[0].username;

// Filter agents created by the current user
const agents = response?.data?.filter(agent => agent.createdByUser === username) || [];

if (agents.length === 0) {
console.log(chalk.yellow('No agents found.'));
Expand All @@ -38,4 +62,5 @@ const list = async () => {
}
};


module.exports = { list };
2 changes: 1 addition & 1 deletion actions/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const signIn = () => {
const response = await axios.get(
`https://us-central1-codeboltai.cloudfunctions.net/checkOneTimeToken?oneTimeToken=${uuid}`
);
console.log(response.data)

if (response.status === 200) {
clearInterval(intervalId);
console.log(chalk.green('Login successful!'));
Expand Down
190 changes: 95 additions & 95 deletions actions/uploadfolder.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ const AdmZip = require('adm-zip');
const yaml = require('js-yaml');
const StreamZip = require('node-stream-zip');
const path = require('path');
const { checkUserAuth } = require('./userData');
const { validateYAML, checkYamlDetails } = require('./yamlService');

const { checkUserAuth, getUserData } = require('./userData');
const { validateYAML, checkYamlDetails } = require('../services/yamlService');

// Function to check for node_modules and extract .yaml file
async function processZipFile(zipFilePath) {
Expand Down Expand Up @@ -61,98 +60,99 @@ async function processZipFile(zipFilePath) {


const uploadFolder = async (targetPath) => {
// Check if the user is logged in
if (!checkUserAuth()) {
console.log('Error: Please login using codebolt-cli login');
return;
}

console.log(chalk.blue('Processing the Code....'));
const folderPath = targetPath || '.';

// Resolve folder path and create zip file path
const folder = path.resolve(folderPath);
const zipFilePath = `${folder}.zip`;

const YamlValidation = await checkYamlDetails(folderPath);

if (!YamlValidation) {
return;
}

// Create a file stream to write the zip file
const output = createWriteStream(zipFilePath);
const archive = archiver('zip', {
zlib: { level: 9 }
});

// Pipe archive data to the file
archive.pipe(output);

// Read .gitignore file and add its contents to the archiver's ignore list
const gitignorePath = path.join(folder, '.gitignore');
const ignoreFiles = ['node_modules/**/*', '**/*.zip']; // Ignore node_modules and zip files
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
ignoreFiles.push(...gitignoreContent.split('\n').filter(line => line && !line.startsWith('#')));
}

// Add files to the archive while respecting .gitignore
archive.glob('**/*', {
cwd: folder,
ignore: ignoreFiles
});

// Finalize the archive (i.e., finalize the zip file)
archive.finalize();

// Listen for the close event to handle the upload
output.on('close', async () => {
try {
if (YamlValidation.title) {
// Prepare the form data for file upload
const formData = new FormData();
formData.append('file', createReadStream(zipFilePath));

// Make the HTTP POST request to upload the file
const uploadResponse = await axios.post('https://codeboltai.web.app/api/upload/single', formData, {
headers: formData.getHeaders()
});

if (uploadResponse.status === 200) {
// Prepare data for agent creation
const agentData = {
...YamlValidation,
zipFilePath: uploadResponse.data.url
};

// Make the HTTP POST request to add the agent
const agentResponse = await axios.post(
'https://codeboltai.web.app/api/agents/add',
agentData
);

// Handle the response for agent creation
if (agentResponse.status === 201) {
console.log(agentResponse.data.message);
} else {
console.log(`Unexpected status code: ${agentResponse.data.message}`);
}
} else {
console.log(`File upload failed with status code: ${uploadResponse.status}`);
}
} else {
console.log('YAML validation failed.');
}
} catch (error) {
console.error('Error handling zip file:', error);
}
});

archive.on('error', (err) => {
console.error('Archive error:', err);
});
};
let authToken;

// Check if the user is logged in
if (!checkUserAuth()) {
console.log(chalk.red('User not authenticated. Please login first.'));
return;
}

try {
const data = getUserData();
authToken = data.jwtToken;

console.log(chalk.blue('Processing the Code....'));

const folderPath = targetPath || '.';
const folder = path.resolve(folderPath);
const zipFilePath = `${folder}.zip`;

const YamlValidation = await checkYamlDetails(folderPath);
if (!YamlValidation) {
console.log('YAML validation failed.');
return;
}

// Create a file stream to write the zip file
const output = createWriteStream(zipFilePath);
const archive = archiver('zip', { zlib: { level: 9 } });

// Pipe archive data to the file
archive.pipe(output);

// Read .gitignore file and add its contents to the archiver's ignore list
const gitignorePath = path.join(folder, '.gitignore');
const ignoreFiles = ['node_modules/**/*', '**/*.zip']; // Ignore node_modules and zip files
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
ignoreFiles.push(...gitignoreContent.split('\n').filter(line => line && !line.startsWith('#')));
}

// Add files to the archive while respecting .gitignore
archive.glob('**/*', {
cwd: folder,
ignore: ignoreFiles
});

// Finalize the archive
await new Promise((resolve, reject) => {
output.on('close', resolve);
archive.on('error', reject);
archive.finalize();
});

// Handle the upload
const formData = new FormData();
formData.append('file', createReadStream(zipFilePath));

const uploadResponse = await axios.post('https://codeboltai.web.app/api/upload/single', formData, {
headers: formData.getHeaders()
});

if (uploadResponse.status === 200) {
const getUsernameResponse = await axios.get(
'https://codeboltai.web.app/api/auth/check-username',
{ headers: { 'Authorization': `Bearer ${authToken}` } }
);

const username = getUsernameResponse.data.usersData[0].username;

const agentData = {
...YamlValidation,
zipFilePath: uploadResponse.data.url,
createdByUser: username
};

const agentResponse = await axios.post(
'https://codeboltai.web.app/api/agents/add',
agentData
);

if (agentResponse.status === 201) {
console.log(agentResponse.data.message);
} else {
console.log(`Unexpected status code: ${agentResponse.data.message}`);
}
} else {
console.log(`File upload failed with status code: ${uploadResponse.status}`);
}

} catch (error) {
console.error('Error:', error.message || error);
}
};



module.exports = {
Expand Down
5 changes: 2 additions & 3 deletions actions/userData.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,8 @@ const saveUserData = (userData) => {

const checkUserAuth = () => {
const userData = getUserData();

//TODO: Along with the file available check if the token is expired or not.
if (!userData) {
if (Object.keys(userData).length === 0) {
console.log('Please login first');
return false;
}
Expand All @@ -61,7 +60,7 @@ const deleteUserData = () => {
fs.unlinkSync(usersFile);
console.log('User data deleted successfully');
} catch (error) {
console.error('Error deleting user data:', error);
// console.error('Error deleting user data:', error);
}
}

Expand Down

0 comments on commit 35b528c

Please sign in to comment.