cs-codex-dist-tests/Tools/BiblioTech/DeploymentsFilesMonitor.cs

90 lines
2.7 KiB
C#
Raw Normal View History

2023-10-20 07:49:23 +00:00
using CodexPlugin;
2023-10-24 13:43:07 +00:00
using Discord;
2023-10-20 07:49:23 +00:00
using Newtonsoft.Json;
namespace BiblioTech
{
public class DeploymentsFilesMonitor
{
2023-11-02 11:30:48 +00:00
private readonly List<CodexDeployment> deployments = new List<CodexDeployment>();
2023-10-20 07:49:23 +00:00
public void Initialize()
2023-10-20 07:49:23 +00:00
{
2023-11-02 11:30:48 +00:00
LoadDeployments();
}
2023-10-20 07:49:23 +00:00
2023-11-02 11:30:48 +00:00
public CodexDeployment[] GetDeployments()
{
return deployments.ToArray();
2023-10-20 07:49:23 +00:00
}
2023-10-24 13:43:07 +00:00
public async Task<bool> DownloadDeployment(IAttachment file)
{
using var http = new HttpClient();
var response = await http.GetAsync(file.Url);
var str = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(str)) return false;
try
{
var deploy = JsonConvert.DeserializeObject<CodexDeployment>(str);
if (deploy != null)
{
var targetFile = Path.Combine(Program.Config.EndpointsPath, Guid.NewGuid().ToString().ToLowerInvariant() + ".json");
File.WriteAllText(targetFile, str);
2023-11-02 11:30:48 +00:00
deployments.Add(deploy);
2023-10-24 13:43:07 +00:00
return true;
}
}
catch { }
return false;
}
public bool DeleteDeployment(string deploymentName)
{
var path = Program.Config.EndpointsPath;
if (!Directory.Exists(path)) return false;
var files = Directory.GetFiles(path);
2023-11-02 11:30:48 +00:00
foreach (var file in files)
2023-10-24 13:43:07 +00:00
{
var deploy = ProcessFile(file);
if (deploy != null && deploy.Metadata.Name == deploymentName)
{
File.Delete(file);
2023-11-02 11:30:48 +00:00
deployments.Remove(deploy);
2023-10-24 13:43:07 +00:00
return true;
}
}
return false;
}
2023-11-02 11:30:48 +00:00
private void LoadDeployments()
2023-10-20 07:49:23 +00:00
{
var path = Program.Config.EndpointsPath;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
File.WriteAllText(Path.Combine(path, "readme.txt"), "Place codex-deployment.json here.");
return;
}
var files = Directory.GetFiles(path);
2023-11-02 11:30:48 +00:00
deployments.AddRange(files.Select(ProcessFile).Where(d => d != null).Cast<CodexDeployment>());
2023-10-20 07:49:23 +00:00
}
private CodexDeployment? ProcessFile(string filename)
{
try
{
var lines = string.Join(" ", File.ReadAllLines(filename));
return JsonConvert.DeserializeObject<CodexDeployment>(lines);
}
catch
{
return null;
}
}
}
}