2023-11-02 16:30:57 +01:00

135 lines
3.8 KiB
C#

using DigitalData.Modules.Database;
using DigitalData.Modules.Logging;
using EnvelopeGenerator.Common;
using Microsoft.Extensions.Primitives;
using System.Reflection.Metadata;
using System.Text;
namespace EnvelopeGenerator.Web.Services
{
public class ApiService
{
private readonly DatabaseService database;
private readonly LogConfig logConfig;
private readonly Logger logger;
public ApiService(LoggingService Logging, DatabaseService database, IConfiguration Config)
{
this.database = database;
this.logConfig = Logging.LogConfig;
this.logger = Logging.LogConfig.GetLogger();
logger.Debug("Initializing ApiService");
}
public EnvelopeResponse EnsureValidEnvelopeKey(string envelopeKey)
{
logger.Debug("Parsing EnvelopeKey..");
if (string.IsNullOrEmpty(envelopeKey))
throw new ArgumentNullException("EnvelopeKey");
Tuple<string, string> result = Helpers.DecodeEnvelopeReceiverId(envelopeKey);
logger.Debug("EnvelopeUUID: [{0}]", result.Item1);
logger.Debug("ReceiverSignature: [{0}]", result.Item2);
if (string.IsNullOrEmpty(result.Item1))
throw new ArgumentNullException("EnvelopeUUID");
if (string.IsNullOrEmpty(result.Item2))
throw new ArgumentNullException("ReceiverSignature");
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
return r;
}
public async Task<string?> EnsureValidAnnotationData(HttpRequest request)
{
logger.Debug("Parsing AnnotationData..");
try
{
using MemoryStream ms = new();
await request.BodyReader.CopyToAsync(ms);
var bytes = ms.ToArray();
return Encoding.UTF8.GetString(bytes);
}
catch (Exception e)
{
logger.Error(e);
return null;
}
}
public int EnsureValidDocumentIndex(HttpRequest request)
{
if (request.Query.TryGetValue("index", out StringValues documentIndexString))
{
try
{
return int.Parse(documentIndexString.First());
}
catch (Exception e)
{
throw new ArgumentNullException("DocumentIndex", e);
}
}
else
{
throw new ArgumentNullException("DocumentIndex");
}
}
public EnvelopeDocument GetDocument(HttpRequest request, string envelopeKey)
{
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
int documentId = EnsureValidDocumentIndex(request);
var document = r.Envelope.Documents.
Where(d => d.Id == documentId).
FirstOrDefault();
if (document == null)
throw new ArgumentException("DocumentId");
return document;
}
public async Task<bool> UpdateDocument(Stream fileStream, string filePath)
{
try
{
using FileStream fs = new(filePath, FileMode.Open);
await fileStream.CopyToAsync(fs);
fs.Flush();
return true;
}
catch (Exception ex)
{
logger.Error(ex);
return false;
}
}
public State GetState(LogConfig LogConfig, MSSQLServer Database)
{
return new State
{
LogConfig = LogConfig,
Database = Database,
};
}
}
}