From 35b528cf50bfa054d9e74aaaf118f4879c9a6c15 Mon Sep 17 00:00:00 2001 From: Nursid Ansari <114871863+Nursid@users.noreply.github.com> Date: Wed, 7 Aug 2024 13:47:40 +0530 Subject: [PATCH] updated --- actions/list.js | 31 ++++++- actions/login.js | 2 +- actions/uploadfolder.js | 190 ++++++++++++++++++++-------------------- actions/userData.js | 5 +- 4 files changed, 126 insertions(+), 102 deletions(-) diff --git a/actions/list.js b/actions/list.js index 8466b2c..9e88896 100644 --- a/actions/list.js +++ b/actions/list.js @@ -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.')); @@ -38,4 +62,5 @@ const list = async () => { } }; + module.exports = { list }; diff --git a/actions/login.js b/actions/login.js index f91557c..31dc578 100644 --- a/actions/login.js +++ b/actions/login.js @@ -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!')); diff --git a/actions/uploadfolder.js b/actions/uploadfolder.js index d8d8043..77bc59f 100644 --- a/actions/uploadfolder.js +++ b/actions/uploadfolder.js @@ -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) { @@ -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 = { diff --git a/actions/userData.js b/actions/userData.js index d4d6dd1..315141b 100644 --- a/actions/userData.js +++ b/actions/userData.js @@ -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; } @@ -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); } }