using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PCMonitor {
///
/// API Client untuk komunikasi dengan Server
///
public class ApiClient : IDisposable {
private readonly string baseUrl;
private readonly string agentId;
private readonly HttpClient httpClient;
private readonly ILog logger = new FileLogger();
public ApiClient(string serverUrl, string agentID) {
baseUrl = serverUrl.TrimEnd('/');
agentId = agentID;
httpClient = new HttpClient {
Timeout = TimeSpan.FromSeconds(30)
};
}
///
/// Send data to API (POST/PUT)
///
public async Task SendAsync(string endpoint, string method, object data) {
try {
string url = $"{baseUrl}/api/{endpoint}";
string jsonContent = JsonConvert.SerializeObject(data);
using (var request = new HttpRequestMessage {
Method = new HttpMethod(method),
RequestUri = new Uri(url),
Content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json")
}) {
// Add agent ID header
request.Headers.Add("X-Agent-ID", agentId);
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode) {
logger.Info($"Successfully sent {endpoint}");
return true;
} else {
logger.Warning($"Failed to send {endpoint}: {response.StatusCode}");
return false;
}
}
} catch (Exception ex) {
logger.Error($"Error sending {endpoint}: {ex.Message}");
return false;
}
}
///
/// Get data from API (GET)
///
public async Task GetAsync(string endpoint) {
try {
string url = $"{baseUrl}/api/{endpoint}";
using (var request = new HttpRequestMessage {
Method = HttpMethod.Get,
RequestUri = new Uri(url)
}) {
request.Headers.Add("X-Agent-ID", agentId);
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode) {
string content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject(content);
logger.Info($"Successfully retrieved {endpoint}");
return result;
} else {
logger.Warning($"Failed to retrieve {endpoint}: {response.StatusCode}");
return null;
}
}
} catch (Exception ex) {
logger.Error($"Error retrieving {endpoint}: {ex.Message}");
return null;
}
}
///
/// Send activity data to API
///
public async Task SendActivityAsync(object activity) {
return await SendAsync("activity", "POST", activity);
}
///
/// Upload file ke API
///
public async Task UploadFileAsync(string endpoint, string filePath) {
try {
if (!File.Exists(filePath)) {
logger.Warning($"File not found: {filePath}");
return false;
}
string url = $"{baseUrl}/api/{endpoint}";
using (var content = new MultipartFormDataContent()) {
using (var fileStream = File.OpenRead(filePath)) {
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(fileContent, "file", Path.GetFileName(filePath));
content.Add(new StringContent(agentId), "agent_id");
var response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode) {
logger.Info($"Successfully uploaded {endpoint}");
return true;
} else {
logger.Warning($"Failed to upload {endpoint}: {response.StatusCode}");
return false;
}
}
}
} catch (Exception ex) {
logger.Error($"Error uploading {endpoint}: {ex.Message}");
return false;
}
}
public void Dispose() {
httpClient?.Dispose();
}
}
}