//
// Copyright (c) PlaceholderCompany. All rights reserved.
//
namespace Download_Faturas
{
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
///
/// Main program class.
///
public class Program
{
#if DEBUG
///
/// Path to the log file for invoices.
///
public const string LogFaturas = @"X:\Back\Carteira x.x\4Docs\import.txt";
#else
public const string LogFaturas = "import.txt";
#endif
private static readonly HttpClient HttpClient = new ();
///
/// Main entry point of the program.
///
public static void Main()
{
for (int i = 1; i < 3; i++)
{
for (int j = 1; j < 7; j++)
{
DirectoryInfo pasta = new (@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\1 - INDIVIDUAIS");
DirectoryInfo pasta_agrupadas = new (@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\2 - AGRUPADAS");
if (LerPasta(pasta, agrupada: false))
{
LerPasta(pasta_agrupadas, agrupada: true);
}
}
}
}
///
/// Reads the specified folder and processes the invoices.
///
/// The directory to read invoices from.
/// Indicates whether the invoices are grouped.
/// True if the folder was read successfully; otherwise, false.
public static bool LerPasta(DirectoryInfo pasta, bool agrupada)
{
if (pasta.Exists)
{
string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
// token = await req_token();
FileInfo[] faturas = pasta.GetFiles("*.pdf");
StreamWriter sw = new (LogFaturas, true);
foreach (FileInfo fatura in faturas)
{
if (!IsFileLocked(fatura))
{
HttpResponseMessage response = SendFatura(token, fatura.FullName, agrupada);
if (response.IsSuccessStatusCode)
{
var iD = JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("requestId");
fatura.MoveTo(fatura.Directory?.Parent?.FullName + $@"\3 - PROCESSANDO\ID {iD} - " + fatura.Name.Replace(",", string.Empty));
sw.Write(iD);
sw.Write(",");
sw.Write(",");
sw.WriteLine(fatura.FullName);
}
}
}
sw.Close();
return true;
}
else
{
return false;
}
}
///
/// Requests an authentication token.
///
/// The authentication token as a string.
public static string? ReqToken()
{
var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/oauth2/token");
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("smart:vnqtvmesikjzyipc"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("grant_type=client_credentials");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = HttpClient.Send(request);
return JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("access_token").GetString();
}
///
/// Sends an invoice to the API for processing.
///
/// The authentication token.
/// The path to the invoice file.
/// Indicates whether the invoices are grouped.
/// The HTTP response from the API.
public static HttpResponseMessage SendFatura(string token, string fatura, bool agrupada)
{
var handler = new HttpClientHandler
{
// Proxy = new WebProxy("http://127.0.0.1:8888"),
// UseProxy = true,
// ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
};
using (var httpClient = new HttpClient(handler))
{
var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/parse");
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
var multipartContent = new MultipartFormDataContent
{
{ new ByteArrayContent(File.ReadAllBytes(fatura)), @"""file""", @$"""{Path.GetFileName(fatura)}""" },
};
multipartContent.ElementAt(0).Headers.Add("Content-Type", "application/pdf");
var payload = new
{
callbackUrl = "https://4docs.webhook.smartenergia.com.br/api",
pipelineName = "energy",
multiple = agrupada,
clientData = new
{
fatura_PATH = fatura.Replace(",", string.Empty).Replace("1 - INDIVIDUAIS", "3 - PROCESSANDO"),
},
};
var json = JsonSerializer.Serialize(payload);
multipartContent.Add(new StringContent(json, Encoding.UTF8, "application/json"), "json");
request.Content = multipartContent;
return httpClient.Send(request);
}
}
///
/// Checks if a file is locked.
///
/// The file to check.
/// True if the file is locked; otherwise, false.
public static bool IsFileLocked(FileInfo file)
{
try
{
using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
// the file is unavailable because it is:
// still being written to
// or being processed by another thread
// or does not exist (has already been processed)
return true;
}
// file is not locked
return false;
}
}
}