aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net
diff options
context:
space:
mode:
authorLukePulverenti Luke Pulverenti luke pulverenti <LukePulverenti Luke Pulverenti luke.pulverenti@gmail.com>2012-07-21 14:39:47 -0400
committerLukePulverenti Luke Pulverenti luke pulverenti <LukePulverenti Luke Pulverenti luke.pulverenti@gmail.com>2012-07-21 14:39:47 -0400
commit0a48b5e31aa712acd988626a88c52c47467945b2 (patch)
treed2f9cc9bc6aacca3c1cd847bcdfaa209566b7231 /MediaBrowser.Common/Net
parent3f557077550b79e2c209a4041a9318886b79ed14 (diff)
Added a BaseKernel for the UI and Server to share, and made some other minor re-organizations.
Diffstat (limited to 'MediaBrowser.Common/Net')
-rw-r--r--MediaBrowser.Common/Net/CollectionExtensions.cs14
-rw-r--r--MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs58
-rw-r--r--MediaBrowser.Common/Net/Handlers/BaseHandler.cs111
-rw-r--r--MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs11
-rw-r--r--MediaBrowser.Common/Net/HttpServer.cs42
-rw-r--r--MediaBrowser.Common/Net/Request.cs18
-rw-r--r--MediaBrowser.Common/Net/RequestContext.cs118
-rw-r--r--MediaBrowser.Common/Net/StreamExtensions.cs19
8 files changed, 391 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Net/CollectionExtensions.cs b/MediaBrowser.Common/Net/CollectionExtensions.cs
new file mode 100644
index 0000000000..98d24dfc04
--- /dev/null
+++ b/MediaBrowser.Common/Net/CollectionExtensions.cs
@@ -0,0 +1,14 @@
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Linq;
+
+namespace MediaBrowser.Common.Net
+{
+ public static class CollectionExtensions
+ {
+ public static IDictionary<string, IEnumerable<string>> ToDictionary(this NameValueCollection source)
+ {
+ return source.AllKeys.ToDictionary<string, string, IEnumerable<string>>(key => key, source.GetValues);
+ }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs
new file mode 100644
index 0000000000..d8347db30e
--- /dev/null
+++ b/MediaBrowser.Common/Net/Handlers/BaseEmbeddedResourceHandler.cs
@@ -0,0 +1,58 @@
+using System;
+using System.IO;
+
+namespace MediaBrowser.Common.Net.Handlers
+{
+ public abstract class BaseEmbeddedResourceHandler : BaseHandler
+ {
+ public BaseEmbeddedResourceHandler(string resourcePath)
+ : base()
+ {
+ ResourcePath = resourcePath;
+ }
+
+ protected string ResourcePath { get; set; }
+
+ public override string ContentType
+ {
+ get
+ {
+ string extension = Path.GetExtension(ResourcePath);
+
+ if (extension.EndsWith("jpeg", StringComparison.OrdinalIgnoreCase) || extension.EndsWith("jpg", StringComparison.OrdinalIgnoreCase))
+ {
+ return "image/jpeg";
+ }
+ else if (extension.EndsWith("png", StringComparison.OrdinalIgnoreCase))
+ {
+ return "image/png";
+ }
+ else if (extension.EndsWith("ico", StringComparison.OrdinalIgnoreCase))
+ {
+ return "image/ico";
+ }
+ else if (extension.EndsWith("js", StringComparison.OrdinalIgnoreCase))
+ {
+ return "application/x-javascript";
+ }
+ else if (extension.EndsWith("css", StringComparison.OrdinalIgnoreCase))
+ {
+ return "text/css";
+ }
+ else if (extension.EndsWith("html", StringComparison.OrdinalIgnoreCase))
+ {
+ return "text/html; charset=utf-8";
+ }
+
+ return "text/plain; charset=utf-8";
+ }
+ }
+
+ protected override void WriteResponseToOutputStream(Stream stream)
+ {
+ GetEmbeddedResourceStream().CopyTo(stream);
+ }
+
+ protected abstract Stream GetEmbeddedResourceStream();
+ }
+}
diff --git a/MediaBrowser.Common/Net/Handlers/BaseHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs
new file mode 100644
index 0000000000..6f6779ad3a
--- /dev/null
+++ b/MediaBrowser.Common/Net/Handlers/BaseHandler.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.IO;
+using System.IO.Compression;
+
+namespace MediaBrowser.Common.Net.Handlers
+{
+ public abstract class BaseHandler
+ {
+ /// <summary>
+ /// Response headers
+ /// </summary>
+ public IDictionary<string, string> Headers = new Dictionary<string, string>();
+
+ /// <summary>
+ /// The action to write the response to the output stream
+ /// </summary>
+ public Action<Stream> WriteStream { get; set; }
+
+ /// <summary>
+ /// The original RequestContext
+ /// </summary>
+ public RequestContext RequestContext { get; set; }
+
+ /// <summary>
+ /// The original QueryString
+ /// </summary>
+ protected NameValueCollection QueryString
+ {
+ get
+ {
+ return RequestContext.Request.QueryString;
+ }
+ }
+
+ /// <summary>
+ /// Gets the MIME type to include in the response headers
+ /// </summary>
+ public abstract string ContentType { get; }
+
+ /// <summary>
+ /// Gets the status code to include in the response headers
+ /// </summary>
+ public virtual int StatusCode
+ {
+ get
+ {
+ return 200;
+ }
+ }
+
+ /// <summary>
+ /// Gets the cache duration to include in the response headers
+ /// </summary>
+ public virtual TimeSpan CacheDuration
+ {
+ get
+ {
+ return TimeSpan.FromTicks(0);
+ }
+ }
+
+ /// <summary>
+ /// Gets the last date modified of the content being returned, if this can be determined.
+ /// This will be used to invalidate the cache, so it's not needed if CacheDuration is 0.
+ /// </summary>
+ public virtual DateTime? LastDateModified
+ {
+ get
+ {
+ return null;
+ }
+ }
+
+ public virtual bool GzipResponse
+ {
+ get
+ {
+ return true;
+ }
+ }
+
+ public BaseHandler()
+ {
+ WriteStream = s =>
+ {
+ WriteReponse(s);
+ s.Close();
+ };
+ }
+
+ private void WriteReponse(Stream stream)
+ {
+ if (GzipResponse)
+ {
+ using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Compress, false))
+ {
+ WriteResponseToOutputStream(gzipStream);
+ }
+ }
+ else
+ {
+ WriteResponseToOutputStream(stream);
+ }
+ }
+
+ protected abstract void WriteResponseToOutputStream(Stream stream);
+
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs b/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs
new file mode 100644
index 0000000000..30113198b9
--- /dev/null
+++ b/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs
@@ -0,0 +1,11 @@
+
+namespace MediaBrowser.Common.Net.Handlers
+{
+ public abstract class BaseJsonHandler : BaseHandler
+ {
+ public override string ContentType
+ {
+ get { return "application/json"; }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Net/HttpServer.cs b/MediaBrowser.Common/Net/HttpServer.cs
new file mode 100644
index 0000000000..fad8d13eb9
--- /dev/null
+++ b/MediaBrowser.Common/Net/HttpServer.cs
@@ -0,0 +1,42 @@
+using System;
+using System.Net;
+using System.Reactive.Linq;
+
+namespace MediaBrowser.Common.Net
+{
+ public class HttpServer : IObservable<RequestContext>, IDisposable
+ {
+ private readonly HttpListener listener;
+ private readonly IObservable<RequestContext> stream;
+
+ public HttpServer(string url)
+ {
+ listener = new HttpListener();
+ listener.Prefixes.Add(url);
+ listener.Start();
+ stream = ObservableHttpContext();
+ }
+
+ private IObservable<RequestContext> ObservableHttpContext()
+ {
+ return Observable.Create<RequestContext>(obs =>
+ Observable.FromAsyncPattern<HttpListenerContext>(listener.BeginGetContext,
+ listener.EndGetContext)()
+ .Select(c => new RequestContext(c))
+ .Subscribe(obs))
+ .Repeat()
+ .Retry()
+ .Publish()
+ .RefCount();
+ }
+ public void Dispose()
+ {
+ listener.Stop();
+ }
+
+ public IDisposable Subscribe(IObserver<RequestContext> observer)
+ {
+ return stream.Subscribe(observer);
+ }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Common/Net/Request.cs b/MediaBrowser.Common/Net/Request.cs
new file mode 100644
index 0000000000..795c9c36ba
--- /dev/null
+++ b/MediaBrowser.Common/Net/Request.cs
@@ -0,0 +1,18 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+
+namespace MediaBrowser.Common.Net
+{
+ public class Request
+ {
+ public string HttpMethod { get; set; }
+ public IDictionary<string, IEnumerable<string>> Headers { get; set; }
+ public Stream InputStream { get; set; }
+ public string RawUrl { get; set; }
+ public int ContentLength
+ {
+ get { return int.Parse(Headers["Content-Length"].First()); }
+ }
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Common/Net/RequestContext.cs b/MediaBrowser.Common/Net/RequestContext.cs
new file mode 100644
index 0000000000..5c7a6b99f0
--- /dev/null
+++ b/MediaBrowser.Common/Net/RequestContext.cs
@@ -0,0 +1,118 @@
+using System;
+using System.Linq;
+using System.Net;
+using MediaBrowser.Common.Net.Handlers;
+
+namespace MediaBrowser.Common.Net
+{
+ public class RequestContext
+ {
+ public HttpListenerRequest Request { get; private set; }
+ public HttpListenerResponse Response { get; private set; }
+
+ public string LocalPath
+ {
+ get
+ {
+ return Request.Url.LocalPath;
+ }
+ }
+
+ public RequestContext(HttpListenerContext context)
+ {
+ Response = context.Response;
+ Request = context.Request;
+ }
+
+ public void Respond(BaseHandler handler)
+ {
+ Response.AddHeader("Access-Control-Allow-Origin", "*");
+
+ Response.KeepAlive = true;
+
+ foreach (var header in handler.Headers)
+ {
+ Response.AddHeader(header.Key, header.Value);
+ }
+
+ int statusCode = handler.StatusCode;
+ Response.ContentType = handler.ContentType;
+
+ TimeSpan cacheDuration = handler.CacheDuration;
+
+ if (Request.Headers.AllKeys.Contains("If-Modified-Since"))
+ {
+ DateTime ifModifiedSince;
+
+ if (DateTime.TryParse(Request.Headers["If-Modified-Since"].Replace(" GMT", string.Empty), out ifModifiedSince))
+ {
+ // If the cache hasn't expired yet just return a 304
+ if (IsCacheValid(ifModifiedSince, cacheDuration, handler.LastDateModified))
+ {
+ statusCode = 304;
+ }
+ }
+ }
+
+ Response.SendChunked = true;
+ Response.StatusCode = statusCode;
+
+ if (statusCode != 304)
+ {
+ if (handler.GzipResponse)
+ {
+ Response.AddHeader("Content-Encoding", "gzip");
+ }
+
+ if (cacheDuration.Ticks > 0)
+ {
+ CacheResponse(Response, cacheDuration, handler.LastDateModified);
+ }
+ handler.WriteStream(Response.OutputStream);
+ }
+ else
+ {
+ Response.OutputStream.Flush();
+ Response.OutputStream.Close();
+ }
+ }
+
+ private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
+ {
+ DateTime lastModified = dateModified ?? DateTime.Now;
+
+ response.Headers[HttpResponseHeader.CacheControl] = "Public";
+ response.Headers[HttpResponseHeader.Expires] = DateTime.Now.Add(duration).ToString("r");
+ response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
+ }
+
+ private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
+ {
+ if (dateModified.HasValue)
+ {
+ DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
+ ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
+
+ return lastModified <= ifModifiedSince;
+ }
+
+ DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
+
+ if (DateTime.Now < cacheExpirationDate)
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
+ /// </summary>
+ private DateTime NormalizeDateForComparison(DateTime date)
+ {
+ return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
+ }
+
+ }
+} \ No newline at end of file
diff --git a/MediaBrowser.Common/Net/StreamExtensions.cs b/MediaBrowser.Common/Net/StreamExtensions.cs
new file mode 100644
index 0000000000..c10e458ada
--- /dev/null
+++ b/MediaBrowser.Common/Net/StreamExtensions.cs
@@ -0,0 +1,19 @@
+using System;
+using System.IO;
+using System.Reactive.Linq;
+
+namespace MediaBrowser.Common.Net
+{
+ public static class StreamExtensions
+ {
+ public static IObservable<byte[]> ReadBytes(this Stream stream, int count)
+ {
+ var buffer = new byte[count];
+ return Observable.FromAsyncPattern((cb, state) => stream.BeginRead(buffer, 0, count, cb, state), ar =>
+ {
+ stream.EndRead(ar);
+ return buffer;
+ })();
+ }
+ }
+} \ No newline at end of file