105 lines
3.2 KiB
C#
105 lines
3.2 KiB
C#
using System.Net.Http.Json;
|
||
using Microsoft.Extensions.Options;
|
||
|
||
namespace DeviceAgent.Services;
|
||
|
||
public class ReportService
|
||
{
|
||
private readonly HttpClient _httpClient;
|
||
private readonly AgentConfig _config;
|
||
private readonly ILogger<ReportService> _logger;
|
||
|
||
public ReportService(HttpClient httpClient, IOptions<AgentConfig> config, ILogger<ReportService> logger)
|
||
{
|
||
_httpClient = httpClient;
|
||
_config = config.Value;
|
||
_logger = logger;
|
||
|
||
_httpClient.BaseAddress = new Uri(_config.ServerUrl);
|
||
_httpClient.Timeout = TimeSpan.FromSeconds(30);
|
||
|
||
if (!string.IsNullOrEmpty(_config.AgentKey))
|
||
{
|
||
_httpClient.DefaultRequestHeaders.Add("X-Agent-Key", _config.AgentKey);
|
||
}
|
||
}
|
||
|
||
public async Task<bool> ReportDeviceInfoAsync(DeviceInfo deviceInfo)
|
||
{
|
||
try
|
||
{
|
||
_logger.LogInformation("正在上报设备信息: {Uuid} - {Ip}", deviceInfo.Uuid, deviceInfo.IpAddress);
|
||
|
||
var response = await _httpClient.PostAsJsonAsync("/api/agent/report", deviceInfo);
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
_logger.LogInformation("设备信息上报成功");
|
||
return true;
|
||
}
|
||
|
||
var content = await response.Content.ReadAsStringAsync();
|
||
_logger.LogWarning("设备信息上报失败: {StatusCode} - {Content}", response.StatusCode, content);
|
||
return false;
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
_logger.LogError(ex, "HTTP请求失败,服务器可能不可达");
|
||
return false;
|
||
}
|
||
catch (TaskCanceledException ex)
|
||
{
|
||
_logger.LogError(ex, "请求超时");
|
||
return false;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "上报设备信息时发生异常");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
public async Task<bool> SendHeartbeatAsync(string uuid)
|
||
{
|
||
try
|
||
{
|
||
var response = await _httpClient.PostAsJsonAsync("/api/agent/heartbeat", new { uuid });
|
||
return response.IsSuccessStatusCode;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(ex, "心跳发送失败");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 上传屏幕截图
|
||
/// </summary>
|
||
public async Task<bool> UploadScreenshotAsync(string uuid, byte[] screenshot)
|
||
{
|
||
try
|
||
{
|
||
using var content = new MultipartFormDataContent();
|
||
content.Add(new StringContent(uuid), "uuid");
|
||
content.Add(new ByteArrayContent(screenshot), "screenshot", "screen.jpg");
|
||
|
||
var response = await _httpClient.PostAsync("/api/agent/screenshot", content);
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
_logger.LogDebug("屏幕截图上传成功");
|
||
return true;
|
||
}
|
||
|
||
_logger.LogWarning("屏幕截图上传失败: {StatusCode}", response.StatusCode);
|
||
return false;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(ex, "屏幕截图上传失败");
|
||
return false;
|
||
}
|
||
}
|
||
}
|