agrobot_base/AgroBase/AgroBase/Services/APIService.cs

174 lines
6.2 KiB
C#

using AgroBase.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace AgroBase.Services
{
public class APIService
{
private static AsyncTaskTimerModel tmrMonitoramento;
private static string Endpoint
{
get
{
return !Variaveis.Producao ? "http://localhost:1337/agrobase/" : "https://zendioninc.com.br/api/agrobase/";
}
}
private static string UrlDownloadArquivos
{
get
{
return "https://zendioninc.com.br/agrobase/downloads";
}
}
private static bool _hasInternet
{
get
{
try
{
using (var client = new WebClient())
{
using (client.OpenRead("http://google.com"))
{
return true;
}
}
}
catch
{
return false;
}
}
}
public static bool HasInternet { get; set; }
public static bool HasInternetNow() => _hasInternet;
public static void IniciarRotinas()
{
Task.Run(async () => await tmrMonitoramento_Tick());
tmrMonitoramento?.Dispose();
tmrMonitoramento = new AsyncTaskTimerModel("tmrMonitoramento", tmrMonitoramento_Tick, 10000);
tmrMonitoramento.Start();
}
private static async Task tmrMonitoramento_Tick()
{
HasInternet = HasInternetNow();
}
// Método para GET
public static async Task<(bool, string)> GetAsync(string url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Endpoint);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return (true, await response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine($"Erro: {response.StatusCode} - {response.ReasonPhrase}");
return (false, null);
}
}
}
// Método para POST com campos dinâmicos e arquivos opcionais
public static async Task<(bool, string)> PostAsync(string url, Dictionary<string, string> fields, Dictionary<string, byte[]> files = null)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Endpoint);
using (var content = new MultipartFormDataContent())
{
// Adiciona os campos dinâmicos
foreach (var field in fields)
{
content.Add(new StringContent(field.Value), field.Key);
}
// Adiciona os arquivos, se existirem
if (files != null)
{
foreach (var file in files)
{
var fileContent = new ByteArrayContent(file.Value);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = file.Key,
FileName = file.Key
};
content.Add(fileContent);
}
}
// Envia a requisição
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return (true, await response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine($"Erro: {response.StatusCode} - {response.ReasonPhrase}");
return (false, null);
}
}
}
}
// Método para baixar arquivos
public static async Task<bool> DownloadFileAsync(string fileName, string savePath, Action<double> reportProgress = null)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Endpoint);
string url = $"{UrlDownloadArquivos}/{fileName}";
HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
var totalBytes = response.Content.Headers.ContentLength ?? -1L;
var downloadedBytes = 0L;
using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var contentStream = await response.Content.ReadAsStreamAsync())
{
var buffer = new byte[81920]; // 80 KB buffer
int bytesRead;
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
downloadedBytes += bytesRead;
// Reporta o progresso
if (reportProgress != null && totalBytes > 0)
{
double progress = (double)downloadedBytes / totalBytes * 100;
reportProgress?.Invoke(progress);
}
}
}
return true;
}
else
{
throw new Exception($"Erro ao baixar o arquivo: {response.StatusCode} - {response.ReasonPhrase}");
}
}
}
}
}