Files
bodyshop-uploader/BodyshopUploader/Utils/HTTPServer.cs
2020-06-02 16:41:56 -07:00

93 lines
3.4 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;
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.Debug("/qb/ - POST");
//Input will be an array of XMLs.
string[] requestXMLstrings = ParseBodyToArray(req);
hlog("Received QuickBooks Receivable request.");
// string requestXMLstring = ParseBodyToString(req);
foreach (var requestXMLstring in requestXMLstrings)
{
XDocument requestXMLdoc = ParseStringToXml(requestXMLstring);
XDocument response = XDocument.Parse(QuickBooksInterop.ProcessQBXmlRequest(requestXMLstring));
Models.QbXmlResponse ResponseStatus = QuickBooksInterop.ParseResponseXml(response);
logger.Info(response.ToString());
logger.Info(ResponseStatus.ToString());
hlog(ResponseStatus.ToString());
}
hlog("Completed QuickBooks request.");
res.WithCORS().Close();
}
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);
}
}
}