Files
bodyshop-uploader/BodyshopUploader/Utils/HTTPServer.cs

136 lines
5.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleHttp;
using System.Xml.Linq;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BodyshopPartner.Models;
namespace BodyshopPartner.Utils
{
public static class HTTPServer
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public delegate void HttpLogger(string s);
private static HttpLogger hlog;
public static void InitHttpServer(HttpLogger HttpLogger)
{
Route.Add("/qb/", (req, res, props) =>
{
res.WithCORS();
//res.AddHeader("Access-Control-Allow-Origin", "http://localhost:3000 https://localhost:3000 http://localhost:5000 https://localhost:5000 https://*.imex.online,imex.online");
res.Close();
}, "OPTIONS");
Route.Add("/qb/",
(req, res, props) => { HandleQbPost(req, res); }
, "POST");
logger.Trace("Starting HTTP server...");
hlog = HttpLogger;
hlog("Starting HTTP server...");
//TODO As a part of the installer, add netsh http add urlacl url=http://+:1337/ user="Everyone
HttpServer.ListenAsync(1337, System.Threading.CancellationToken.None, Route.OnHttpRequestAsync).Wait();
}
private static void HandleQbPost(System.Net.HttpListenerRequest req, System.Net.HttpListenerResponse res)
{
logger.Trace("/qb/ - POST");
hlog("Received QuickBooks Receivable request.");
//Input will be an array of objects containing XMLs.
List<QbRequestItem> AllRequests = ParseRequest(req);
List<QbResponseItem> HttpResponse = new List<QbResponseItem>();
hlog("Connecting to QuickBooks. This may take a moment...");
QuickBooksInterop.ConnectToQuickBooks();
foreach (QbRequestItem request in AllRequests)
{
try
{
hlog("Processing QuickBooks request. ImEX Online Record ID:" + request.Id);
XDocument response = XDocument.Parse(QuickBooksInterop.ProcessQBXmlRequestUnManaged(request.QbXML));
QbXmlResponse ResponseStatus = QuickBooksInterop.ParseResponseXml(response);
logger.Trace(response.ToString());
logger.Debug(ResponseStatus.ToString());
hlog(ResponseStatus.ToString());
QbResponseItem r = new QbResponseItem()
{
Id = request.Id,
Success = ResponseStatus.StatusCode == "0" || request.OkStatusCodes.Contains(ResponseStatus.StatusCode),
ErrorMessage = ResponseStatus.StatusMessage
};
HttpResponse.Add(r);
}
catch (Exception Ex)
{
//Shouldn't really get here unless something is malformed.
logger.Error(Ex, "Error encountered when processing QbXML Request.\n {0}", request.QbXML);
QbResponseItem r = new QbResponseItem()
{
Id = request.Id,
Success = false,
ErrorMessage = Ex.Message
};
HttpResponse.Add(r);
}
}
QuickBooksInterop.DisconnectFromQuickBooks();
hlog("Completed QuickBooks requests.");
res.WithCORS().AsText(JsonConvert.SerializeObject(HttpResponse));
}
public static List<QbRequestItem> ParseRequest(System.Net.HttpListenerRequest req)
{
System.IO.Stream body = req.InputStream;
System.Text.Encoding encoding = req.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string s = reader.ReadToEnd();
body.Close();
reader.Close();
return JsonConvert.DeserializeObject<List<QbRequestItem>>(s);
}
public static string[] ParseBodyToArray(System.Net.HttpListenerRequest req)
{
System.IO.Stream body = req.InputStream;
System.Text.Encoding encoding = req.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string s = reader.ReadToEnd();
body.Close();
reader.Close();
return JArray.Parse(s).Select(jv => jv.ToString()).ToArray();
}
public static string ParseBodyToString(System.Net.HttpListenerRequest req)
{
System.IO.Stream body = req.InputStream;
System.Text.Encoding encoding = req.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string s = reader.ReadToEnd();
body.Close();
return s;
}
public static XDocument ParseStringToXml(string input)
{
return XDocument.Parse(input);
}
}
}