Skip to content

Commit 35b528c

Browse files
committed
updated
1 parent 835bdc0 commit 35b528c

File tree

4 files changed

+126
-102
lines changed

4 files changed

+126
-102
lines changed

actions/list.js

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,41 @@ const list = async () => {
1010
}
1111

1212
const userData = getUserData();
13-
const token = userData.token;
13+
14+
if (!userData || !userData.jwtToken) {
15+
console.log(chalk.red('Failed to retrieve user data or authentication token.'));
16+
return;
17+
}
18+
19+
const token = userData.jwtToken;
1420

1521
try {
22+
// Fetch the list of agents
1623
const response = await axios.get('https://codeboltai.web.app/api/agents/list', {
1724
headers: {
1825
'Authorization': `Bearer ${token}`
1926
}
2027
});
2128

22-
23-
const agents = response.data;
29+
// Fetch the username
30+
const usernameResponse = await axios.get(
31+
'https://codeboltai.web.app/api/auth/check-username',
32+
{
33+
headers: {
34+
'Authorization': `Bearer ${token}`
35+
}
36+
}
37+
);
38+
39+
if (!usernameResponse.data || !usernameResponse.data.usersData || usernameResponse.data.usersData.length === 0) {
40+
console.log(chalk.red('Failed to retrieve username or no user data available.'));
41+
return;
42+
}
43+
44+
const username = usernameResponse.data.usersData[0].username;
45+
46+
// Filter agents created by the current user
47+
const agents = response?.data?.filter(agent => agent.createdByUser === username) || [];
2448

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

65+
4166
module.exports = { list };

actions/login.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const signIn = () => {
2727
const response = await axios.get(
2828
`https://us-central1-codeboltai.cloudfunctions.net/checkOneTimeToken?oneTimeToken=${uuid}`
2929
);
30-
console.log(response.data)
30+
3131
if (response.status === 200) {
3232
clearInterval(intervalId);
3333
console.log(chalk.green('Login successful!'));

actions/uploadfolder.js

Lines changed: 95 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ const AdmZip = require('adm-zip');
88
const yaml = require('js-yaml');
99
const StreamZip = require('node-stream-zip');
1010
const path = require('path');
11-
const { checkUserAuth } = require('./userData');
12-
const { validateYAML, checkYamlDetails } = require('./yamlService');
13-
11+
const { checkUserAuth, getUserData } = require('./userData');
12+
const { validateYAML, checkYamlDetails } = require('../services/yamlService');
1413

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

6261

6362
const uploadFolder = async (targetPath) => {
64-
// Check if the user is logged in
65-
if (!checkUserAuth()) {
66-
console.log('Error: Please login using codebolt-cli login');
67-
return;
68-
}
69-
70-
console.log(chalk.blue('Processing the Code....'));
71-
const folderPath = targetPath || '.';
72-
73-
// Resolve folder path and create zip file path
74-
const folder = path.resolve(folderPath);
75-
const zipFilePath = `${folder}.zip`;
76-
77-
const YamlValidation = await checkYamlDetails(folderPath);
78-
79-
if (!YamlValidation) {
80-
return;
81-
}
82-
83-
// Create a file stream to write the zip file
84-
const output = createWriteStream(zipFilePath);
85-
const archive = archiver('zip', {
86-
zlib: { level: 9 }
87-
});
88-
89-
// Pipe archive data to the file
90-
archive.pipe(output);
91-
92-
// Read .gitignore file and add its contents to the archiver's ignore list
93-
const gitignorePath = path.join(folder, '.gitignore');
94-
const ignoreFiles = ['node_modules/**/*', '**/*.zip']; // Ignore node_modules and zip files
95-
if (fs.existsSync(gitignorePath)) {
96-
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
97-
ignoreFiles.push(...gitignoreContent.split('\n').filter(line => line && !line.startsWith('#')));
98-
}
99-
100-
// Add files to the archive while respecting .gitignore
101-
archive.glob('**/*', {
102-
cwd: folder,
103-
ignore: ignoreFiles
104-
});
105-
106-
// Finalize the archive (i.e., finalize the zip file)
107-
archive.finalize();
108-
109-
// Listen for the close event to handle the upload
110-
output.on('close', async () => {
111-
try {
112-
if (YamlValidation.title) {
113-
// Prepare the form data for file upload
114-
const formData = new FormData();
115-
formData.append('file', createReadStream(zipFilePath));
116-
117-
// Make the HTTP POST request to upload the file
118-
const uploadResponse = await axios.post('https://codeboltai.web.app/api/upload/single', formData, {
119-
headers: formData.getHeaders()
120-
});
121-
122-
if (uploadResponse.status === 200) {
123-
// Prepare data for agent creation
124-
const agentData = {
125-
...YamlValidation,
126-
zipFilePath: uploadResponse.data.url
127-
};
128-
129-
// Make the HTTP POST request to add the agent
130-
const agentResponse = await axios.post(
131-
'https://codeboltai.web.app/api/agents/add',
132-
agentData
133-
);
134-
135-
// Handle the response for agent creation
136-
if (agentResponse.status === 201) {
137-
console.log(agentResponse.data.message);
138-
} else {
139-
console.log(`Unexpected status code: ${agentResponse.data.message}`);
140-
}
141-
} else {
142-
console.log(`File upload failed with status code: ${uploadResponse.status}`);
143-
}
144-
} else {
145-
console.log('YAML validation failed.');
146-
}
147-
} catch (error) {
148-
console.error('Error handling zip file:', error);
149-
}
150-
});
151-
152-
archive.on('error', (err) => {
153-
console.error('Archive error:', err);
154-
});
155-
};
63+
let authToken;
64+
65+
// Check if the user is logged in
66+
if (!checkUserAuth()) {
67+
console.log(chalk.red('User not authenticated. Please login first.'));
68+
return;
69+
}
70+
71+
try {
72+
const data = getUserData();
73+
authToken = data.jwtToken;
74+
75+
console.log(chalk.blue('Processing the Code....'));
76+
77+
const folderPath = targetPath || '.';
78+
const folder = path.resolve(folderPath);
79+
const zipFilePath = `${folder}.zip`;
80+
81+
const YamlValidation = await checkYamlDetails(folderPath);
82+
if (!YamlValidation) {
83+
console.log('YAML validation failed.');
84+
return;
85+
}
86+
87+
// Create a file stream to write the zip file
88+
const output = createWriteStream(zipFilePath);
89+
const archive = archiver('zip', { zlib: { level: 9 } });
90+
91+
// Pipe archive data to the file
92+
archive.pipe(output);
93+
94+
// Read .gitignore file and add its contents to the archiver's ignore list
95+
const gitignorePath = path.join(folder, '.gitignore');
96+
const ignoreFiles = ['node_modules/**/*', '**/*.zip']; // Ignore node_modules and zip files
97+
if (fs.existsSync(gitignorePath)) {
98+
const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
99+
ignoreFiles.push(...gitignoreContent.split('\n').filter(line => line && !line.startsWith('#')));
100+
}
101+
102+
// Add files to the archive while respecting .gitignore
103+
archive.glob('**/*', {
104+
cwd: folder,
105+
ignore: ignoreFiles
106+
});
107+
108+
// Finalize the archive
109+
await new Promise((resolve, reject) => {
110+
output.on('close', resolve);
111+
archive.on('error', reject);
112+
archive.finalize();
113+
});
114+
115+
// Handle the upload
116+
const formData = new FormData();
117+
formData.append('file', createReadStream(zipFilePath));
118+
119+
const uploadResponse = await axios.post('https://codeboltai.web.app/api/upload/single', formData, {
120+
headers: formData.getHeaders()
121+
});
122+
123+
if (uploadResponse.status === 200) {
124+
const getUsernameResponse = await axios.get(
125+
'https://codeboltai.web.app/api/auth/check-username',
126+
{ headers: { 'Authorization': `Bearer ${authToken}` } }
127+
);
128+
129+
const username = getUsernameResponse.data.usersData[0].username;
130+
131+
const agentData = {
132+
...YamlValidation,
133+
zipFilePath: uploadResponse.data.url,
134+
createdByUser: username
135+
};
136+
137+
const agentResponse = await axios.post(
138+
'https://codeboltai.web.app/api/agents/add',
139+
agentData
140+
);
141+
142+
if (agentResponse.status === 201) {
143+
console.log(agentResponse.data.message);
144+
} else {
145+
console.log(`Unexpected status code: ${agentResponse.data.message}`);
146+
}
147+
} else {
148+
console.log(`File upload failed with status code: ${uploadResponse.status}`);
149+
}
150+
151+
} catch (error) {
152+
console.error('Error:', error.message || error);
153+
}
154+
};
155+
156156

157157

158158
module.exports = {

actions/userData.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,8 @@ const saveUserData = (userData) => {
4747

4848
const checkUserAuth = () => {
4949
const userData = getUserData();
50-
5150
//TODO: Along with the file available check if the token is expired or not.
52-
if (!userData) {
51+
if (Object.keys(userData).length === 0) {
5352
console.log('Please login first');
5453
return false;
5554
}
@@ -61,7 +60,7 @@ const deleteUserData = () => {
6160
fs.unlinkSync(usersFile);
6261
console.log('User data deleted successfully');
6362
} catch (error) {
64-
console.error('Error deleting user data:', error);
63+
// console.error('Error deleting user data:', error);
6564
}
6665
}
6766

0 commit comments

Comments
 (0)