-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
184 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
using MicrobotApi.Database; | ||
using MicrobotApi.Services; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.EntityFrameworkCore; | ||
using Microsoft.Extensions.Caching.Memory; | ||
|
||
namespace MicrobotApi.Controllers; | ||
|
||
[ApiController] | ||
[Route("api/[controller]")] | ||
public class ScriptController(MicrobotContext microbotContext, IMemoryCache memoryCache, XataService xataService) | ||
: Controller | ||
{ | ||
private readonly XataService _xataService = xataService; | ||
|
||
[HttpGet("{key}/{hwid}")] | ||
public async Task<IActionResult> List(string key, string hwid) | ||
{ | ||
var exists = await microbotContext.Keys.AnyAsync(x => x.Key == key && (x.HWID == "" || x.HWID == hwid)); | ||
|
||
if (!exists) return Unauthorized(); | ||
|
||
var scripts = await microbotContext.Scripts | ||
Check failure on line 23 in MicrobotApi/Controllers/ScriptController.cs GitHub Actions / build
Check failure on line 23 in MicrobotApi/Controllers/ScriptController.cs GitHub Actions / build
|
||
.Where(x => x.ScriptKeys.Any(s => s.Key == key && (s.HWID == "" || s.HWID == hwid))) | ||
.ToListAsync(); | ||
|
||
var cacheEntryOptions = new MemoryCacheEntryOptions() | ||
.SetSlidingExpiration(TimeSpan.FromSeconds(30)); | ||
|
||
memoryCache.Set(key, DateTime.Now, cacheEntryOptions); | ||
|
||
return Ok(scripts.Select(x => x.Id)); | ||
} | ||
|
||
|
||
[HttpPost("runtime")] | ||
public async Task<IActionResult> UpdateRunTime([FromBody] ScriptStats scriptStats) | ||
{ | ||
var a = await xataService.GetRecordsAsync("script_runtime"); | ||
|
||
foreach (var scriptStat in scriptStats.scriptRunTimes) | ||
{ | ||
// Check if the script name exists in the records | ||
var script = a.Records | ||
.FirstOrDefault(record => string.Equals(record.Name, scriptStat.Key, StringComparison.CurrentCultureIgnoreCase)); | ||
|
||
if (script == null) | ||
{ | ||
// If no matching script is found, add a new record | ||
await xataService.AddRecordAsync("script_runtime", new { name = scriptStat.Key, runtime_minutes = scriptStat.Value }); | ||
} | ||
else | ||
{ | ||
// If a matching script is found, update its runtime_minutes | ||
script.RuntimeMinutes += scriptStat.Value; | ||
await xataService.PatchRecordAsync("script_runtime", script.Id, new { name = script.Name, runtime_minutes = script.RuntimeMinutes }); | ||
} | ||
} | ||
|
||
|
||
return Ok(); | ||
} | ||
|
||
|
||
} | ||
|
||
public class ScriptStats { | ||
public Dictionary<String, int> scriptRunTimes { get; set; } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
using System.Net.Http.Headers; | ||
using System.Text; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace MicrobotApi.Services; | ||
|
||
public class XataService | ||
{ | ||
private readonly HttpClient _client; | ||
private readonly string _baseUrl; | ||
|
||
public XataService(IConfiguration configuration) | ||
{ | ||
_client = new HttpClient(); | ||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration.GetSection("Xata:Key").Value); | ||
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | ||
_baseUrl = "https://Sami-Chkhachkhi-s-workspace-tio4if.eu-west-1.xata.sh/db/microbot:main"; | ||
//_baseUrl = "https://api.xata.io/workspaces"; | ||
} | ||
|
||
public async Task<XataResponse> GetRecordsAsync(string tableName) | ||
{ | ||
// Define the JSON payload | ||
var payload = new | ||
{ | ||
columns = new[] { "xata_id", "name", "runtime_minutes" }, | ||
page = new { size = 200 } | ||
}; | ||
|
||
// Convert the payload to JSON | ||
var jsonContent = new StringContent(System.Text.Json.JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"); | ||
|
||
// Make the POST request | ||
var response = await _client.PostAsync($"{_baseUrl}/tables/{tableName}/query", jsonContent); | ||
|
||
response.EnsureSuccessStatusCode(); | ||
|
||
// Read the response content as a string | ||
var jsonResponse = await response.Content.ReadAsStringAsync(); | ||
|
||
// Deserialize the JSON response into the XataResponse model | ||
var xataResponse = JsonSerializer.Deserialize<XataResponse>(jsonResponse, new JsonSerializerOptions | ||
{ | ||
PropertyNameCaseInsensitive = true | ||
}); | ||
|
||
return xataResponse; | ||
} | ||
|
||
public async Task<string> AddRecordAsync(string tableName, object record) | ||
{ | ||
var jsonContent = new StringContent(JsonSerializer.Serialize(record), Encoding.UTF8, "application/json"); | ||
var response = await _client.PostAsync($"{_baseUrl}/tables/{tableName}/data", jsonContent); | ||
response.EnsureSuccessStatusCode(); | ||
return await response.Content.ReadAsStringAsync(); | ||
} | ||
|
||
public async Task<string> PatchRecordAsync(string tableName, string recordId, object payload, string query = "?columns=id") | ||
{ | ||
var url = $"{_baseUrl}/tables/{tableName}/data/{recordId}{query}"; | ||
|
||
// Serialize the payload to JSON | ||
var jsonContent = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"); | ||
|
||
// Create an HttpRequestMessage for PATCH | ||
var request = new HttpRequestMessage(new HttpMethod("PATCH"), url) | ||
{ | ||
Content = jsonContent | ||
}; | ||
|
||
// Send the PATCH request | ||
var response = await _client.SendAsync(request); | ||
|
||
// Ensure the request was successful | ||
response.EnsureSuccessStatusCode(); | ||
|
||
// Return the response content | ||
return await response.Content.ReadAsStringAsync(); | ||
} | ||
} | ||
|
||
public class Meta | ||
{ | ||
public Page Page { get; set; } | ||
} | ||
|
||
public class Page | ||
{ | ||
public string Cursor { get; set; } | ||
public bool More { get; set; } | ||
public int Size { get; set; } | ||
} | ||
|
||
public class Record | ||
{ | ||
public string Id { get; set; } | ||
public string Name { get; set; } | ||
[JsonPropertyName("runtime_minutes")] | ||
public int RuntimeMinutes { get; set; } | ||
public XataMeta Xata { get; set; } | ||
} | ||
|
||
public class XataMeta | ||
{ | ||
public DateTime CreatedAt { get; set; } | ||
public DateTime UpdatedAt { get; set; } | ||
public int Version { get; set; } | ||
} | ||
|
||
public class XataResponse | ||
{ | ||
public Meta Meta { get; set; } | ||
public List<Record> Records { get; set; } | ||
} |