-
Notifications
You must be signed in to change notification settings - Fork 0
/
PythonCsharp.cs
485 lines (449 loc) · 21.9 KB
/
PythonCsharp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using Beezlabs.RPAHive.Lib;
using Beezlabs.RPAHive.Lib.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.Json;
namespace Beezlabs.RPA.Bots
{
public class soxpy : RPABotTemplate
{
BotExecutionModel botExecutionModel = null;
BotInputs BotInputs = new BotInputs();
VMLoginDetails VMLoginDetails = new VMLoginDetails();
OauthCredentials OauthCredentials = new OauthCredentials();
string pyErrorMsg = "";
string workingDirectory = "";
string pythonException = "";
protected override void BotLogic(BotExecutionModel botExecutionModel)
{
try
{
this.botExecutionModel = botExecutionModel;
workingDirectory = GetWorkingDirectory();
GetInputs();
GetVMLoginredentials();
GetOauthCredentials();
GetBotLibraryPath();
string encodeIdentity = EncodeIdentity();
CreateInputJson();
ConnectToRdp(GetAccessToken());
Python(encodeIdentity); // Calling python script
SendOutputToState();
CloseRdp(GetAccessToken());
Success("Bot Executed Successfully");
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, $"Bot failed {exception.Message}");
Failure($"Bot failed : {exception.Message}");
}
}
private void GetInputs()
{
try
{
BotInputs.HexId = GetStringInputs("hexId");
BotInputs.BotClassName = GetStringInputs("botClassName");
BotInputs.ServerName = GetStringInputs("serverName");
BotInputs.ServerAddress = GetStringInputs("serverAddress");
BotInputs.CloseRDPApiUrl = GetStringInputs("closeRDPApiUrl");
BotInputs.ConnectRDPApiUrl = GetStringInputs("connectRDPApiUrl");
BotInputs.AccessTokenBaseurl = GetStringInputs("accessTokenBaseurl");
}
catch (Exception ex)
{
throw new Exception("Input Error: " + ex.Message);
}
}
private String GetStringInputs(String key)
{
try
{
VariableModel varInput = null;
varInput = null;
LogMessage(this.GetType().Name, "Trying to Input with Key: " + key);
this.botExecutionModel.proposedBotInputs.TryGetValue(key, out varInput);
if (varInput == null || varInput.value == null)
{
throw new Exception("Input not found with key: " + key);
}
return varInput.value.ToString();
}
catch (Exception ex)
{
throw new Exception($"Input Error with kery {key} : " + ex.Message);
}
}
private void GetVMLoginredentials()
{
try
{
BotInputs.LoginIdentityKey = GetStringInputs("LoginIdentityKey");
LogMessage(this.GetType().FullName, $"VM login Credential key received - {BotInputs.LoginIdentityKey}");
BotIdentityModel vmLgoinCred = this.botExecutionModel.identityList.Find(cred => cred.name.Equals(BotInputs.LoginIdentityKey));
if (vmLgoinCred == null || vmLgoinCred.credential == null || vmLgoinCred.credential.basicAuth == null)
{
throw new Exception("VM login credentials invalid");
}
this.VMLoginDetails = new VMLoginDetails
{
Username = vmLgoinCred.credential.basicAuth.username,
Password = vmLgoinCred.credential.basicAuth.password
};
LogMessage(this.GetType().FullName, "VM login Username and password is passed");
}
catch (Exception ex)
{
throw new Exception("VM login credentials not passed " + ex.Message);
}
}
private void GetOauthCredentials()
{
try
{
BotInputs.RDPIdentityKey = GetStringInputs("RDPIdentityKey");
BotIdentityModel rdpCred = this.botExecutionModel.identityList.Find(cred => cred.name.Equals(BotInputs.RDPIdentityKey));
OauthCredentials = new OauthCredentials
{
GrantType = rdpCred.credential.oAuth2.grantType,
ClientId = rdpCred.credential.oAuth2.clientId,
ClientSecret = rdpCred.credential.oAuth2.clientSecret,
Scope = rdpCred.credential.oAuth2.scope,
State = rdpCred.credential.oAuth2.state
};
LogMessage(this.GetType().FullName, "OAuth client id and password is passed");
}
catch (Exception ex)
{
LogMessage(this.GetType().FullName, "OAuth credentials not passed " + ex.Message);
throw new Exception("OAuth credentials not passed " + ex.Message);
}
}
//private void GetOauthCredentials()
//{
// try
// {
// BotInputs.RDPIdentityKey = GetStringInputs("RDPIdentityKey");
// this.OauthCredentials = new OauthCredentials
// {
// GrantType = this.botExecutionModel.identityList[0].credential.oAuth2.grantType,
// ClientId = this.botExecutionModel.identityList[0].credential.oAuth2.clientId,
// ClientSecret = this.botExecutionModel.identityList[0].credential.oAuth2.clientSecret,
// Scope = this.botExecutionModel.identityList[0].credential.oAuth2.scope,
// State = this.botExecutionModel.identityList[0].credential.oAuth2.state
// };
// LogMessage(this.GetType().FullName, "OAuth client id and password is passed");
// }
// catch (Exception ex)
// {
// LogMessage(this.GetType().FullName, "OAuth credentials not passed " + ex.Message);
// throw new Exception("OAuth credentials not passed " + ex.Message);
// }
//}
private void GetBotLibraryPath()
{
string assemplyLocation = "";
MethodBase method = new StackTrace().GetFrame(0).GetMethod();
// Get the type of the current executing method
Type type = method.DeclaringType;
// Get the name of the current executing class
string className = type.Name;
// Get all loaded assemblies
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
if (assembly.ExportedTypes.ToList().Count > 0 && assembly.ExportedTypes.ToList()[0].Name == className)
{
assemplyLocation = assembly.Location;
break;
}
}
string directoryPath = Path.GetDirectoryName(assemplyLocation);
LogMessage(this.GetType().Name, $"Bot library directory path {directoryPath}");
BotInputs.BotFilepath = directoryPath;
}
private string EncodeIdentity()
{
try
{
if (botExecutionModel.identityList.Count > 0)
{
string identityJson = System.Text.Json.JsonSerializer.Serialize(this.botExecutionModel.identityList);
string encodedIdentity = Convert.ToBase64String(Encoding.ASCII.GetBytes(identityJson));
return encodedIdentity;
}
else
return " ";
}
catch
{
throw;
}
}
private void Python(string identity)
{
try
{
MethodBase method = new StackTrace().GetFrame(0).GetMethod();
Type type = method.DeclaringType;
string className = type.Name;
string pythonInterpreter = Path.Combine(BotInputs.BotFilepath, ".venv", "Scripts", "python.exe");
// Path to setup.py
string mainPath = Path.Combine(BotInputs.BotFilepath, "main.py");
LogMessage(this.GetType().Name, $"Setup file path : {mainPath}");
string hivebotId = botExecutionModel.hiveBotId.ToString();
string executionId = botExecutionModel.executionId.ToString();
if (File.Exists(mainPath))
{
// Command to execute
string command = $"{@pythonInterpreter} \"{mainPath}\" --bot_name {className} --hiveBotId \"{hivebotId}\" --executionId \"{executionId}\" --working_dir \"{workingDirectory}\" --identity \"{identity}\"";
// Start the process
Process process = new Process();
process.StartInfo.FileName = "cmd.exe"; // Command prompt
process.StartInfo.Arguments = $"/c {command}"; // Pass the command
process.StartInfo.UseShellExecute = true;
// Start the process
process.Start();
// Wait for the process to exit
process.WaitForExit();
}
else
{
LogMessage(this.GetType().Name, $"main.py file not found in the path {mainPath}");
throw new Exception($"main.py file not found {mainPath}");
}
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, $"Error while executing python file {exception.Message}");
throw;
}
}
private void CreateInputJson()
{
try
{
JObject root = new JObject();
JObject botInputs = new JObject();
foreach (var proposedBotInput in this.botExecutionModel.proposedBotInputs)
{
string key = proposedBotInput.Key;
VariableModel variable = proposedBotInput.Value;
JToken valueToken;
if (variable.value is IEnumerable<object> enumerable && !(variable.value is string))
{
string str = enumerable.ToString();
valueToken = JArray.Parse(str);
}
else
{
valueToken = variable.value is null ? "" : JToken.FromObject(variable.value);
}
JObject variableObject = new JObject
{
{ "value", valueToken },
{ "type", variable.type.ToString() },
{ "objectTypeName", variable.objectTypeName },
{ "flowVariable", variable.flowVariable }
};
botInputs.Add(key, variableObject);
}
root.Add("hiveBotId", JToken.FromObject(this.botExecutionModel.hiveBotId));
root.Add("executionId", JToken.FromObject(this.botExecutionModel.executionId));
this.botExecutionModel.identityList.Clear();
root.Add("identityList", JToken.FromObject(this.botExecutionModel.identityList));
root.Add("connectionParams", "");
root.Add("proposedBotInputs", botInputs);
string jsonString = root.ToString(Formatting.Indented);
LogMessage(this.GetType().Name, $"input.json file's json string created successfully : {jsonString}.");
string inputDirectory = Path.Combine(workingDirectory, "input");
if (!Directory.Exists(inputDirectory))
{
Directory.CreateDirectory(inputDirectory);
LogMessage(this.GetType().Name, $"input directory created");
}
string filePath = Path.Combine(inputDirectory, "input.json");
File.WriteAllText(filePath, jsonString);
LogMessage(this.GetType().Name, $"input.json file created successfully in the filepath of {workingDirectory}.");
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, $"Error while preparing input json file");
throw;
}
}
private void SendOutputToState()
{
try
{
LogMessage(this.GetType().Name, $"started to Deserialize the output json file");
string jsonFilePath = Path.Combine(workingDirectory, "output/output.json"); // assuming the file is named output.json in the current directory
LogMessage(this.GetType().Name, $"output file path {jsonFilePath}");
if (File.Exists(jsonFilePath))
{
string jsonContent = File.ReadAllText(jsonFilePath);
BotReplyModel botReplyModel = JsonConvert.DeserializeObject<BotReplyModel>(jsonContent);
if (botReplyModel.runStatus == RunStatus.SUCCESSFUL)
{
foreach (var variableModel in botReplyModel.variableMap)
{
LogMessage(this.GetType().Name, $"key : {variableModel.Key} and value : {variableModel.Value.value}");
AddVariable(variableModel.Key, variableModel.Value.type == VariableTypes.OBJECT ? variableModel.Value.value as JToken : variableModel.Value.value);
}
}
else
{
throw new Exception($"Exception from python script : {botReplyModel.botMessage}");
}
}
else
{
LogMessage(this.GetType().Name, $"Output file not found");
throw new Exception($"Output file not found and the error from python file is : {pythonException}");
}
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, $"Error while send outputs to state {exception.Message}");
throw exception;
}
}
private void AddVariables(string key, object value)
{
AddVariable(key, value);
}
private string GetAccessToken()
{
try
{
string requestBody = "grant_type=" + Uri.EscapeDataString(OauthCredentials.GrantType.ToString()) +
"&scope=" + Uri.EscapeDataString(OauthCredentials.Scope);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BotInputs.AccessTokenBaseurl);
string credentials = OauthCredentials.ClientId + ":" + OauthCredentials.ClientSecret;
string credentialsBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentialsBase64);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpClient client = new HttpClient();
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var responseString = response.Content.ReadAsStringAsync().Result;
var responseMap = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseString);
LogMessage(this.GetType().Name, "Access token fetched successfully");
return responseMap["access_token"].ToString();
}
else
{
LogMessage(this.GetType().Name, "Failed to get access token - " + response.Content.ReadAsStringAsync().Result);
throw new Exception("Failed to get access token");
}
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, "An error occurred while fetching access token - " + exception.Message);
throw new Exception("An error occurred while fetching access token. Exception: " + exception.Message);
}
}
private void ConnectToRdp(string accessToken)
{
try
{
LogMessage(this.GetType().Name, "Connecting to RDP");
HttpClientHandler httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
};
using (HttpClient client = new HttpClient(httpClientHandler))
{
string requestBody = "{\"Username\":\"" + VMLoginDetails.Username + "\",\"Password\":\"" + VMLoginDetails.Password + "\",\"ServerAddress\":\"" + BotInputs.ServerAddress + "\",\"BotClassName\":\"" + BotInputs.BotClassName + "\",\"ServerName\":\"" + BotInputs.ServerName + "\",\"HexId\":\"" + BotInputs.HexId + "\"}";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BotInputs.ConnectRDPApiUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
LogMessage(this.GetType().Name, "RDP connection successful");
}
else
{
LogMessage(this.GetType().Name, "Failed to connect to RDP " + response.Content.ReadAsStringAsync().Result);
throw new Exception("Failed to connect to RDP");
}
}
}
catch (Exception exception)
{
LogMessage(this.GetType().Name, "while connecting to RDP " + exception.Message);
throw new Exception("while connecting to RDP " + exception.Message + " " + string.Join(", ", exception.StackTrace));
}
}
private void CloseRdp(string accessToken)
{
try
{
LogMessage(this.GetType().Name, "Connecting to RDP");
HttpClientHandler httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
};
using (HttpClient client = new HttpClient(httpClientHandler))
{
string requestBody = "{\"RDPServerAddress\":\"" + BotInputs.ServerAddress + "\"}";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BotInputs.CloseRDPApiUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
LogMessage(this.GetType().Name, "RDP connection successful");
}
else
{
LogMessage(this.GetType().Name, "Failed to connect to RDP - " + response.Content.ReadAsStringAsync().Result.ToString());
throw new Exception("Failed to connect to RDP - " + response.Content.ReadAsStringAsync().Result.ToString());
}
}
}
catch (Exception exception)
{
throw new Exception("while connecting to RDP " + exception.Message + " " + string.Join(", ", exception.StackTrace));
}
}
}
internal class BotInputs
{
public string HexId { get; set; }
public string ServerName { get; set; }
public string BotClassName { get; set; }
public string ServerAddress { get; set; }
public string CloseRDPApiUrl { get; set; }
public string ConnectRDPApiUrl { get; set; }
public string AccessTokenBaseurl { get; set; }
public string RDPIdentityKey { get; set; }
public string LoginIdentityKey { get; set; }
public string BotFilepath { get; set; }
}
class VMLoginDetails
{
public string Username { get; set; }
public string Password { get; set; }
}
class OauthCredentials
{
public OAuth2Model.GrantType GrantType { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Scope { get; set; }
public string State { get; set; }
}
}