mirror of
https://github.com/TechplexEngineer/plexview.git
synced 2026-07-31 04:07:24 +00:00
Initial commit
I wish I could figure out how to have PlexVie be out of the LibOMV tree but its just not working die to a DLL not found exception about libopenjpeg. (Yes the dll is in the bin folder) This will do for now
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
/*
|
||||
* Copyright (c) 2006-2014, openmetaverse.org
|
||||
* All rights reserved.
|
||||
*
|
||||
* - Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* - Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* - Neither the name of the openmetaverse.org nor the names
|
||||
* of its contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace OpenMetaverse.Http
|
||||
{
|
||||
public class TrustAllCertificatePolicy : ICertificatePolicy
|
||||
{
|
||||
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool TrustAllCertificateHandler(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static class CapsBase
|
||||
{
|
||||
public delegate void OpenWriteEventHandler(HttpWebRequest request);
|
||||
public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive);
|
||||
public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error);
|
||||
|
||||
static CapsBase()
|
||||
{
|
||||
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
|
||||
// Even though this will compile on Mono 2.4, it throws a runtime exception
|
||||
//ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler;
|
||||
}
|
||||
|
||||
private class RequestState
|
||||
{
|
||||
public HttpWebRequest Request;
|
||||
public byte[] UploadData;
|
||||
public int MillisecondsTimeout;
|
||||
public OpenWriteEventHandler OpenWriteCallback;
|
||||
public DownloadProgressEventHandler DownloadProgressCallback;
|
||||
public RequestCompletedEventHandler CompletedCallback;
|
||||
|
||||
public RequestState(HttpWebRequest request, byte[] uploadData, int millisecondsTimeout, OpenWriteEventHandler openWriteCallback,
|
||||
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
|
||||
{
|
||||
Request = request;
|
||||
UploadData = uploadData;
|
||||
MillisecondsTimeout = millisecondsTimeout;
|
||||
OpenWriteCallback = openWriteCallback;
|
||||
DownloadProgressCallback = downloadProgressCallback;
|
||||
CompletedCallback = completedCallback;
|
||||
}
|
||||
}
|
||||
|
||||
public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data,
|
||||
int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback,
|
||||
RequestCompletedEventHandler completedCallback)
|
||||
{
|
||||
// Create the request
|
||||
HttpWebRequest request = SetupRequest(address, clientCert);
|
||||
request.ContentLength = data.Length;
|
||||
if (!String.IsNullOrEmpty(contentType))
|
||||
request.ContentType = contentType;
|
||||
request.Method = "POST";
|
||||
|
||||
// Create an object to hold all of the state for this request
|
||||
RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback,
|
||||
downloadProgressCallback, completedCallback);
|
||||
|
||||
// Start the request for a stream to upload to
|
||||
IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);
|
||||
// Register a timeout for the request
|
||||
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public static HttpWebRequest DownloadStringAsync(Uri address, X509Certificate2 clientCert, int millisecondsTimeout,
|
||||
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
|
||||
{
|
||||
// Create the request
|
||||
HttpWebRequest request = SetupRequest(address, clientCert);
|
||||
request.Method = "GET";
|
||||
DownloadDataAsync(request, millisecondsTimeout, downloadProgressCallback, completedCallback);
|
||||
return request;
|
||||
}
|
||||
|
||||
public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
|
||||
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
|
||||
{
|
||||
// Create an object to hold all of the state for this request
|
||||
RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
|
||||
completedCallback);
|
||||
|
||||
// Start the request for the remote server response
|
||||
IAsyncResult result = request.BeginGetResponse(GetResponse, state);
|
||||
// Register a timeout for the request
|
||||
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
|
||||
}
|
||||
|
||||
static HttpWebRequest SetupRequest(Uri address, X509Certificate2 clientCert)
|
||||
{
|
||||
if (address == null)
|
||||
throw new ArgumentNullException("address");
|
||||
|
||||
// Create the request
|
||||
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address);
|
||||
|
||||
// Add the client certificate to the request if one was given
|
||||
if (clientCert != null)
|
||||
request.ClientCertificates.Add(clientCert);
|
||||
|
||||
// Leave idle connections to this endpoint open for up to 60 seconds
|
||||
request.ServicePoint.MaxIdleTime = 1000 * 60;
|
||||
// Disable stupid Expect-100: Continue header
|
||||
request.ServicePoint.Expect100Continue = false;
|
||||
// Crank up the max number of connections per endpoint
|
||||
// We set this manually here instead of in ServicePointManager to avoid intereference with callers.
|
||||
if (request.ServicePoint.ConnectionLimit < Settings.MAX_HTTP_CONNECTIONS)
|
||||
{
|
||||
Logger.Log(
|
||||
string.Format(
|
||||
"In CapsBase.SetupRequest() setting conn limit for {0}:{1} to {2}",
|
||||
address.Host, address.Port, Settings.MAX_HTTP_CONNECTIONS), Helpers.LogLevel.Debug);
|
||||
request.ServicePoint.ConnectionLimit = Settings.MAX_HTTP_CONNECTIONS;
|
||||
}
|
||||
// Caps requests are never sent as trickles of data, so Nagle's
|
||||
// coalescing algorithm won't help us
|
||||
request.ServicePoint.UseNagleAlgorithm = false;
|
||||
// If not on mono, set accept-encoding header that allows response compression
|
||||
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||
return request;
|
||||
}
|
||||
|
||||
static void OpenWrite(IAsyncResult ar)
|
||||
{
|
||||
RequestState state = (RequestState)ar.AsyncState;
|
||||
|
||||
try
|
||||
{
|
||||
// Get the stream to write our upload to
|
||||
using (Stream uploadStream = state.Request.EndGetRequestStream(ar))
|
||||
{
|
||||
// Fire the callback for successfully opening the stream
|
||||
if (state.OpenWriteCallback != null)
|
||||
state.OpenWriteCallback(state.Request);
|
||||
|
||||
// Write our data to the upload stream
|
||||
uploadStream.Write(state.UploadData, 0, state.UploadData.Length);
|
||||
}
|
||||
|
||||
// Start the request for the remote server response
|
||||
IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state);
|
||||
// Register a timeout for the request
|
||||
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state,
|
||||
state.MillisecondsTimeout, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message);
|
||||
if (state.CompletedCallback != null)
|
||||
state.CompletedCallback(state.Request, null, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
static void GetResponse(IAsyncResult ar)
|
||||
{
|
||||
RequestState state = (RequestState)ar.AsyncState;
|
||||
HttpWebResponse response = null;
|
||||
byte[] responseData = null;
|
||||
Exception error = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (response = (HttpWebResponse)state.Request.EndGetResponse(ar))
|
||||
{
|
||||
// Get the stream for downloading the response
|
||||
using (Stream responseStream = response.GetResponseStream())
|
||||
{
|
||||
#region Read the response
|
||||
|
||||
// If Content-Length is set we create a buffer of the exact size, otherwise
|
||||
// a MemoryStream is used to receive the response
|
||||
bool nolength = (response.ContentLength <= 0) || (Type.GetType("Mono.Runtime") != null);
|
||||
int size = (nolength) ? 8192 : (int)response.ContentLength;
|
||||
MemoryStream ms = (nolength) ? new MemoryStream() : null;
|
||||
byte[] buffer = new byte[size];
|
||||
|
||||
int bytesRead = 0;
|
||||
int offset = 0;
|
||||
int totalBytesRead = 0;
|
||||
int totalSize = nolength ? 0 : size;
|
||||
|
||||
while ((bytesRead = responseStream.Read(buffer, offset, size)) != 0)
|
||||
{
|
||||
totalBytesRead += bytesRead;
|
||||
|
||||
if (nolength)
|
||||
{
|
||||
totalSize += (size - bytesRead);
|
||||
ms.Write(buffer, 0, bytesRead);
|
||||
}
|
||||
else
|
||||
{
|
||||
offset += bytesRead;
|
||||
size -= bytesRead;
|
||||
}
|
||||
|
||||
// Fire the download progress callback for each chunk of received data
|
||||
if (state.DownloadProgressCallback != null)
|
||||
state.DownloadProgressCallback(state.Request, response, totalBytesRead, totalSize);
|
||||
}
|
||||
|
||||
if (nolength)
|
||||
{
|
||||
responseData = ms.ToArray();
|
||||
ms.Close();
|
||||
ms.Dispose();
|
||||
}
|
||||
else
|
||||
{
|
||||
responseData = buffer;
|
||||
}
|
||||
|
||||
#endregion Read the response
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Logger.DebugLog("CapsBase.GetResponse(): " + ex.Message);
|
||||
error = ex;
|
||||
}
|
||||
|
||||
if (state.CompletedCallback != null)
|
||||
state.CompletedCallback(state.Request, response, responseData, error);
|
||||
}
|
||||
|
||||
static void TimeoutCallback(object state, bool timedOut)
|
||||
{
|
||||
if (timedOut)
|
||||
{
|
||||
RequestState requestState = state as RequestState;
|
||||
//Logger.Log.Debug("CapsBase.TimeoutCallback(): Request to " + requestState.Request.RequestUri +
|
||||
// " timed out after " + requestState.MillisecondsTimeout + " milliseconds");
|
||||
if (requestState != null && requestState.Request != null)
|
||||
requestState.Request.Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright (c) 2006-2014, openmetaverse.org
|
||||
* All rights reserved.
|
||||
*
|
||||
* - Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* - Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* - Neither the name of the openmetaverse.org nor the names
|
||||
* of its contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading;
|
||||
using OpenMetaverse.StructuredData;
|
||||
|
||||
namespace OpenMetaverse.Http
|
||||
{
|
||||
public class CapsClient
|
||||
{
|
||||
public delegate void DownloadProgressCallback(CapsClient client, int bytesReceived, int totalBytesToReceive);
|
||||
public delegate void CompleteCallback(CapsClient client, OSD result, Exception error);
|
||||
|
||||
public event DownloadProgressCallback OnDownloadProgress;
|
||||
public event CompleteCallback OnComplete;
|
||||
|
||||
public object UserData;
|
||||
|
||||
protected Uri _Address;
|
||||
protected byte[] _PostData;
|
||||
protected X509Certificate2 _ClientCert;
|
||||
protected string _ContentType;
|
||||
protected HttpWebRequest _Request;
|
||||
protected OSD _Response;
|
||||
protected AutoResetEvent _ResponseEvent = new AutoResetEvent(false);
|
||||
|
||||
public CapsClient(Uri capability)
|
||||
: this(capability, null)
|
||||
{
|
||||
}
|
||||
|
||||
public CapsClient(Uri capability, X509Certificate2 clientCert)
|
||||
{
|
||||
_Address = capability;
|
||||
_ClientCert = clientCert;
|
||||
}
|
||||
|
||||
public void BeginGetResponse(int millisecondsTimeout)
|
||||
{
|
||||
BeginGetResponse(null, null, millisecondsTimeout);
|
||||
}
|
||||
|
||||
public void BeginGetResponse(OSD data, OSDFormat format, int millisecondsTimeout)
|
||||
{
|
||||
byte[] postData;
|
||||
string contentType;
|
||||
|
||||
switch (format)
|
||||
{
|
||||
case OSDFormat.Xml:
|
||||
postData = OSDParser.SerializeLLSDXmlBytes(data);
|
||||
contentType = "application/llsd+xml";
|
||||
break;
|
||||
case OSDFormat.Binary:
|
||||
postData = OSDParser.SerializeLLSDBinary(data);
|
||||
contentType = "application/llsd+binary";
|
||||
break;
|
||||
case OSDFormat.Json:
|
||||
default:
|
||||
postData = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data));
|
||||
contentType = "application/llsd+json";
|
||||
break;
|
||||
}
|
||||
|
||||
BeginGetResponse(postData, contentType, millisecondsTimeout);
|
||||
}
|
||||
|
||||
public void BeginGetResponse(byte[] postData, string contentType, int millisecondsTimeout)
|
||||
{
|
||||
_PostData = postData;
|
||||
_ContentType = contentType;
|
||||
|
||||
if (_Request != null)
|
||||
{
|
||||
_Request.Abort();
|
||||
_Request = null;
|
||||
}
|
||||
|
||||
if (postData == null)
|
||||
{
|
||||
// GET
|
||||
//Logger.Log.Debug("[CapsClient] GET " + _Address);
|
||||
_Request = CapsBase.DownloadStringAsync(_Address, _ClientCert, millisecondsTimeout, DownloadProgressHandler,
|
||||
RequestCompletedHandler);
|
||||
}
|
||||
else
|
||||
{
|
||||
// POST
|
||||
//Logger.Log.Debug("[CapsClient] POST (" + postData.Length + " bytes) " + _Address);
|
||||
_Request = CapsBase.UploadDataAsync(_Address, _ClientCert, contentType, postData, millisecondsTimeout, null,
|
||||
DownloadProgressHandler, RequestCompletedHandler);
|
||||
}
|
||||
}
|
||||
|
||||
public OSD GetResponse(int millisecondsTimeout)
|
||||
{
|
||||
BeginGetResponse(millisecondsTimeout);
|
||||
_ResponseEvent.WaitOne(millisecondsTimeout, false);
|
||||
return _Response;
|
||||
}
|
||||
|
||||
public OSD GetResponse(OSD data, OSDFormat format, int millisecondsTimeout)
|
||||
{
|
||||
BeginGetResponse(data, format, millisecondsTimeout);
|
||||
_ResponseEvent.WaitOne(millisecondsTimeout, false);
|
||||
return _Response;
|
||||
}
|
||||
|
||||
public OSD GetResponse(byte[] postData, string contentType, int millisecondsTimeout)
|
||||
{
|
||||
BeginGetResponse(postData, contentType, millisecondsTimeout);
|
||||
_ResponseEvent.WaitOne(millisecondsTimeout, false);
|
||||
return _Response;
|
||||
}
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
if (_Request != null)
|
||||
_Request.Abort();
|
||||
}
|
||||
|
||||
void DownloadProgressHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive)
|
||||
{
|
||||
_Request = request;
|
||||
|
||||
if (OnDownloadProgress != null)
|
||||
{
|
||||
try { OnDownloadProgress(this, bytesReceived, totalBytesToReceive); }
|
||||
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
|
||||
}
|
||||
}
|
||||
|
||||
void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
|
||||
{
|
||||
_Request = request;
|
||||
|
||||
OSD result = null;
|
||||
|
||||
if (responseData != null)
|
||||
{
|
||||
try { result = OSDParser.Deserialize(responseData); }
|
||||
catch (Exception ex) { error = ex; }
|
||||
}
|
||||
|
||||
FireCompleteCallback(result, error);
|
||||
}
|
||||
|
||||
private void FireCompleteCallback(OSD result, Exception error)
|
||||
{
|
||||
CompleteCallback callback = OnComplete;
|
||||
if (callback != null)
|
||||
{
|
||||
try { callback(this, result, error); }
|
||||
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
|
||||
}
|
||||
|
||||
_Response = result;
|
||||
_ResponseEvent.Set();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Copyright (c) 2006-2014, openmetaverse.org
|
||||
* All rights reserved.
|
||||
*
|
||||
* - Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* - Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
* - Neither the name of the openmetaverse.org nor the names
|
||||
* of its contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using OpenMetaverse.StructuredData;
|
||||
|
||||
namespace OpenMetaverse.Http
|
||||
{
|
||||
public class EventQueueClient
|
||||
{
|
||||
/// <summary>=</summary>
|
||||
public const int REQUEST_TIMEOUT = 1000 * 120;
|
||||
|
||||
public delegate void ConnectedCallback();
|
||||
public delegate void EventCallback(string eventName, OSDMap body);
|
||||
|
||||
public ConnectedCallback OnConnected;
|
||||
public EventCallback OnEvent;
|
||||
|
||||
public bool Running { get { return _Running; } }
|
||||
|
||||
protected Uri _Address;
|
||||
protected bool _Dead;
|
||||
protected bool _Running;
|
||||
protected HttpWebRequest _Request;
|
||||
|
||||
/// <summary>Number of times we've received an unknown CAPS exception in series.</summary>
|
||||
private int _errorCount;
|
||||
/// <summary>For exponential backoff on error.</summary>
|
||||
private static Random _random = new Random();
|
||||
|
||||
public EventQueueClient(Uri eventQueueLocation)
|
||||
{
|
||||
_Address = eventQueueLocation;
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_Dead = false;
|
||||
|
||||
// Create an EventQueueGet request
|
||||
OSDMap request = new OSDMap();
|
||||
request["ack"] = new OSD();
|
||||
request["done"] = OSD.FromBoolean(false);
|
||||
|
||||
byte[] postData = OSDParser.SerializeLLSDXmlBytes(request);
|
||||
|
||||
_Request = CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT, OpenWriteHandler, null, RequestCompletedHandler);
|
||||
}
|
||||
|
||||
public void Stop(bool immediate)
|
||||
{
|
||||
_Dead = true;
|
||||
|
||||
if (immediate)
|
||||
_Running = false;
|
||||
|
||||
if (_Request != null)
|
||||
_Request.Abort();
|
||||
}
|
||||
|
||||
void OpenWriteHandler(HttpWebRequest request)
|
||||
{
|
||||
_Running = true;
|
||||
_Request = request;
|
||||
|
||||
Logger.DebugLog("Capabilities event queue connected");
|
||||
|
||||
// The event queue is starting up for the first time
|
||||
if (OnConnected != null)
|
||||
{
|
||||
try { OnConnected(); }
|
||||
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
|
||||
}
|
||||
}
|
||||
|
||||
void RequestCompletedHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error)
|
||||
{
|
||||
// We don't care about this request now that it has completed
|
||||
_Request = null;
|
||||
|
||||
OSDArray events = null;
|
||||
int ack = 0;
|
||||
|
||||
if (responseData != null)
|
||||
{
|
||||
_errorCount = 0;
|
||||
// Got a response
|
||||
OSDMap result = OSDParser.DeserializeLLSDXml(responseData) as OSDMap;
|
||||
|
||||
if (result != null)
|
||||
{
|
||||
events = result["events"] as OSDArray;
|
||||
ack = result["id"].AsInteger();
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Log("Got an unparseable response from the event queue: \"" +
|
||||
System.Text.Encoding.UTF8.GetString(responseData) + "\"", Helpers.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
else if (error != null)
|
||||
{
|
||||
#region Error handling
|
||||
|
||||
HttpStatusCode code = HttpStatusCode.OK;
|
||||
|
||||
if (error is WebException)
|
||||
{
|
||||
WebException webException = (WebException)error;
|
||||
|
||||
if (webException.Response != null)
|
||||
code = ((HttpWebResponse)webException.Response).StatusCode;
|
||||
else if (webException.Status == WebExceptionStatus.RequestCanceled)
|
||||
goto HandlingDone;
|
||||
}
|
||||
|
||||
if (error is WebException && ((WebException)error).Response != null)
|
||||
code = ((HttpWebResponse)((WebException)error).Response).StatusCode;
|
||||
|
||||
if (code == HttpStatusCode.NotFound || code == HttpStatusCode.Gone)
|
||||
{
|
||||
Logger.Log(String.Format("Closing event queue at {0} due to missing caps URI", _Address), Helpers.LogLevel.Info);
|
||||
|
||||
_Running = false;
|
||||
_Dead = true;
|
||||
}
|
||||
else if (code == HttpStatusCode.BadGateway)
|
||||
{
|
||||
// This is not good (server) protocol design, but it's normal.
|
||||
// The EventQueue server is a proxy that connects to a Squid
|
||||
// cache which will time out periodically. The EventQueue server
|
||||
// interprets this as a generic error and returns a 502 to us
|
||||
// that we ignore
|
||||
}
|
||||
else
|
||||
{
|
||||
++_errorCount;
|
||||
|
||||
// Try to log a meaningful error message
|
||||
if (code != HttpStatusCode.OK)
|
||||
{
|
||||
Logger.Log(String.Format("Unrecognized caps connection problem from {0}: {1}",
|
||||
_Address, code), Helpers.LogLevel.Warning);
|
||||
}
|
||||
else if (error.InnerException != null)
|
||||
{
|
||||
Logger.Log(String.Format("Unrecognized internal caps exception from {0}: {1}",
|
||||
_Address, error.InnerException.Message), Helpers.LogLevel.Warning);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
|
||||
_Address, error.Message), Helpers.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Error handling
|
||||
}
|
||||
else
|
||||
{
|
||||
++_errorCount;
|
||||
|
||||
Logger.Log("No response from the event queue but no reported error either", Helpers.LogLevel.Warning);
|
||||
}
|
||||
|
||||
HandlingDone:
|
||||
|
||||
#region Resume the connection
|
||||
|
||||
if (_Running)
|
||||
{
|
||||
OSDMap osdRequest = new OSDMap();
|
||||
if (ack != 0) osdRequest["ack"] = OSD.FromInteger(ack);
|
||||
else osdRequest["ack"] = new OSD();
|
||||
osdRequest["done"] = OSD.FromBoolean(_Dead);
|
||||
|
||||
byte[] postData = OSDParser.SerializeLLSDXmlBytes(osdRequest);
|
||||
|
||||
if (_errorCount > 0) // Exponentially back off, so we don't hammer the CPU
|
||||
Thread.Sleep(_random.Next(500 + (int)Math.Pow(2, _errorCount)));
|
||||
|
||||
// Resume the connection. The event handler for the connection opening
|
||||
// just sets class _Request variable to the current HttpWebRequest
|
||||
CapsBase.UploadDataAsync(_Address, null, "application/xml", postData, REQUEST_TIMEOUT,
|
||||
delegate(HttpWebRequest newRequest) { _Request = newRequest; }, null, RequestCompletedHandler);
|
||||
|
||||
// If the event queue is dead at this point, turn it off since
|
||||
// that was the last thing we want to do
|
||||
if (_Dead)
|
||||
{
|
||||
_Running = false;
|
||||
Logger.DebugLog("Sent event queue shutdown message");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Resume the connection
|
||||
|
||||
#region Handle incoming events
|
||||
|
||||
if (OnEvent != null && events != null && events.Count > 0)
|
||||
{
|
||||
// Fire callbacks for each event received
|
||||
foreach (OSDMap evt in events)
|
||||
{
|
||||
string msg = evt["message"].AsString();
|
||||
OSDMap body = (OSDMap)evt["body"];
|
||||
|
||||
try { OnEvent(msg, body); }
|
||||
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Handle incoming events
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user