Skip to content

Commit

Permalink
make dlna project portable
Browse files Browse the repository at this point in the history
  • Loading branch information
LukePulverenti committed Nov 4, 2016
1 parent 9e32b9d commit cb087e1
Show file tree
Hide file tree
Showing 57 changed files with 1,310 additions and 1,028 deletions.
6 changes: 6 additions & 0 deletions Emby.Common.Implementations/BaseApplicationHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@
using MediaBrowser.Common.Extensions;
using Emby.Common.Implementations.Cryptography;
using Emby.Common.Implementations.Diagnostics;
using Emby.Common.Implementations.Net;
using Emby.Common.Implementations.Threading;
using MediaBrowser.Common;
using MediaBrowser.Common.IO;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Diagnostics;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Threading;
Expand Down Expand Up @@ -153,6 +155,7 @@ public abstract class BaseApplicationHost<TApplicationPathsType> : IApplicationH

protected IProcessFactory ProcessFactory { get; private set; }
protected ITimerFactory TimerFactory { get; private set; }
protected ISocketFactory SocketFactory { get; private set; }

/// <summary>
/// Gets the name.
Expand Down Expand Up @@ -549,6 +552,9 @@ protected virtual Task RegisterResources(IProgress<double> progress)
TimerFactory = new TimerFactory();
RegisterSingleInstance(TimerFactory);

SocketFactory = new SocketFactory(null);
RegisterSingleInstance(SocketFactory);

RegisterSingleInstance(CryptographyProvider);

return Task.FromResult(true);
Expand Down
74 changes: 74 additions & 0 deletions Emby.Common.Implementations/Net/DisposableManagedObjectBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Emby.Common.Implementations.Net
{
/// <summary>
/// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
/// </summary>
public abstract class DisposableManagedObjectBase : IDisposable
{

#region Public Methods

/// <summary>
/// Override this method and dispose any objects you own the lifetime of if disposing is true;
/// </summary>
/// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
protected abstract void Dispose(bool disposing);

/// <summary>
/// Throws and <see cref="System.ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
/// </summary>
/// <seealso cref="IsDisposed"/>
/// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
/// <seealso cref="Dispose()"/>
protected virtual void ThrowIfDisposed()
{
if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().FullName);
}

#endregion

#region Public Properties

/// <summary>
/// Sets or returns a boolean indicating whether or not this instance has been disposed.
/// </summary>
/// <seealso cref="Dispose()"/>
public bool IsDisposed
{
get;
private set;
}

#endregion

#region IDisposable Members

/// <summary>
/// Disposes this object instance and all internally managed resources.
/// </summary>
/// <remarks>
/// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
/// </remarks>
/// <seealso cref="IsDisposed"/>
public void Dispose()
{
try
{
IsDisposed = true;

Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}

#endregion
}
}
113 changes: 113 additions & 0 deletions Emby.Common.Implementations/Net/SocketFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;

namespace Emby.Common.Implementations.Net
{
public class SocketFactory : ISocketFactory
{
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
// Be careful to check any changes compile and work for all platform projects it is shared in.

// Not entirely happy with this. Would have liked to have done something more generic/reusable,
// but that wasn't really the point so kept to YAGNI principal for now, even if the
// interfaces are a bit ugly, specific and make assumptions.

/// <summary>
/// Used by RSSDP components to create implementations of the <see cref="IUdpSocket"/> interface, to perform platform agnostic socket communications.
/// </summary>
private IPAddress _LocalIP;

/// <summary>
/// Default constructor.
/// </summary>
/// <param name="localIP">A string containing the IP address of the local network adapter to bind sockets to. Null or empty string will use <see cref="IPAddress.Any"/>.</param>
public SocketFactory(string localIP)
{
if (String.IsNullOrEmpty(localIP))
_LocalIP = IPAddress.Any;
else
_LocalIP = IPAddress.Parse(localIP);
}

#region ISocketFactory Members

/// <summary>
/// Creates a new UDP socket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
/// </summary>
/// <param name="localPort">An integer specifying the local port to bind the socket to.</param>
/// <returns>An implementation of the <see cref="IUdpSocket"/> interface used by RSSDP components to perform socket operations.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The purpose of this method is to create and returns a disposable result, it is up to the caller to dispose it when they are done with it.")]
public IUdpSocket CreateUdpSocket(int localPort)
{
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");

var retVal = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
{
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), _LocalIP));
return new UdpSocket(retVal, localPort, _LocalIP.ToString());
}
catch
{
if (retVal != null)
retVal.Dispose();

throw;
}
}

/// <summary>
/// Creates a new UDP socket that is a member of the specified multicast IP address, and binds it to the specified local port.
/// </summary>
/// <param name="ipAddress">The multicast IP address to make the socket a member of.</param>
/// <param name="multicastTimeToLive">The multicast time to live value for the socket.</param>
/// <param name="localPort">The number of the local port to bind to.</param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ip"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The purpose of this method is to create and returns a disposable result, it is up to the caller to dispose it when they are done with it.")]
public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
{
if (ipAddress == null) throw new ArgumentNullException("ipAddress");
if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");

var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

try
{
#if NETSTANDARD1_3
// The ExclusiveAddressUse socket option is a Windows-specific option that, when set to "true," tells Windows not to allow another socket to use the same local address as this socket
// See https://github.com/dotnet/corefx/pull/11509 for more details
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
retVal.ExclusiveAddressUse = false;
}
#else
retVal.ExclusiveAddressUse = false;
#endif
retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), _LocalIP));
retVal.MulticastLoopback = true;

return new UdpSocket(retVal, localPort, _LocalIP.ToString());
}
catch
{
if (retVal != null)
retVal.Dispose();

throw;
}
}

#endregion
}
}
51 changes: 30 additions & 21 deletions RSSDP/UdpSocket.cs → Emby.Common.Implementations/Net/UdpSocket.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Rssdp.Infrastructure;
using MediaBrowser.Model.Net;

namespace Rssdp
namespace Emby.Common.Implementations.Net
{
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
// Be careful to check any changes compile and work for all platform projects it is shared in.
Expand Down Expand Up @@ -48,7 +46,7 @@ public UdpSocket(System.Net.Sockets.Socket socket, int localPort, string ipAddre

#region IUdpSocket Members

public System.Threading.Tasks.Task<ReceivedUdpData> ReceiveAsync()
public Task<ReceivedUdpData> ReceiveAsync()
{
ThrowIfDisposed();

Expand Down Expand Up @@ -76,22 +74,22 @@ public System.Threading.Tasks.Task<ReceivedUdpData> ReceiveAsync()
return tcs.Task;
}

public Task SendTo(byte[] messageData, UdpEndPoint endPoint)
public Task SendTo(byte[] messageData, IpEndPointInfo endPoint)
{
ThrowIfDisposed();

if (messageData == null) throw new ArgumentNullException("messageData");
if (endPoint == null) throw new ArgumentNullException("endPoint");

#if NETSTANDARD1_6
_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port));
_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IpAddress.ToString()), endPoint.Port));
return Task.FromResult(true);
#else
var taskSource = new TaskCompletionSource<bool>();

try
{
_Socket.BeginSendTo(messageData, 0, messageData.Length, SocketFlags.None, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port), result =>
_Socket.BeginSendTo(messageData, 0, messageData.Length, SocketFlags.None, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IpAddress.ToString()), endPoint.Port), result =>
{
try
{
Expand Down Expand Up @@ -166,11 +164,7 @@ private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveDa
{
Buffer = state.Buffer,
ReceivedBytes = bytesRead,
ReceivedFrom = new UdpEndPoint()
{
IPAddress = ipEndPoint.Address.ToString(),
Port = ipEndPoint.Port
}
ReceivedFrom = ToIpEndPointInfo(ipEndPoint)
}
);
}
Expand All @@ -191,6 +185,25 @@ private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveDa
}
}

private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
{
if (endpoint == null)
{
return null;
}

return new IpEndPointInfo
{
IpAddress = new IpAddressInfo
{
Address = endpoint.Address.ToString(),
IsIpv6 = endpoint.AddressFamily == AddressFamily.InterNetworkV6
},

Port = endpoint.Port
};
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions via task methods should be reported by task completion source, so this should be ok.")]
private void ProcessResponse(IAsyncResult asyncResult)
{
Expand All @@ -206,11 +219,7 @@ private void ProcessResponse(IAsyncResult asyncResult)
{
Buffer = state.Buffer,
ReceivedBytes = bytesRead,
ReceivedFrom = new UdpEndPoint()
{
IPAddress = ipEndPoint.Address.ToString(),
Port = ipEndPoint.Port
}
ReceivedFrom = ToIpEndPointInfo(ipEndPoint)
}
);
}
Expand Down Expand Up @@ -245,7 +254,7 @@ public AsyncReceiveState(System.Net.Sockets.Socket socket, EndPoint endPoint)
}

public EndPoint EndPoint;
public byte[] Buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize];
public byte[] Buffer = new byte[8192];

public System.Net.Sockets.Socket Socket { get; private set; }

Expand All @@ -256,4 +265,4 @@ public AsyncReceiveState(System.Net.Sockets.Socket socket, EndPoint endPoint)
#endregion

}
}
}
8 changes: 8 additions & 0 deletions Emby.Common.Implementations/Reflection/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,13 @@ public Stream GetManifestResourceStream(Type type, string resource)
#endif
return type.GetTypeInfo().Assembly.GetManifestResourceStream(resource);
}

public string[] GetManifestResourceNames(Type type)
{
#if NET46
return type.Assembly.GetManifestResourceNames();
#endif
return type.GetTypeInfo().Assembly.GetManifestResourceNames();
}
}
}
7 changes: 5 additions & 2 deletions Emby.Dlna/ConnectionManager/ConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Emby.Dlna.Service;
using MediaBrowser.Model.Logging;
using System.Collections.Generic;
using MediaBrowser.Model.Xml;

namespace Emby.Dlna.ConnectionManager
{
Expand All @@ -12,13 +13,15 @@ public class ConnectionManager : BaseService, IConnectionManager
private readonly IDlnaManager _dlna;
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;

public ConnectionManager(IDlnaManager dlna, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient)
public ConnectionManager(IDlnaManager dlna, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
: base(logger, httpClient)
{
_dlna = dlna;
_config = config;
_logger = logger;
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
}

public string GetServiceXml(IDictionary<string, string> headers)
Expand All @@ -31,7 +34,7 @@ public ControlResponse ProcessControlRequest(ControlRequest request)
var profile = _dlna.GetProfile(request.Headers) ??
_dlna.GetDefaultProfile();

return new ControlHandler(_logger, profile, _config).ProcessControlRequest(request);
return new ControlHandler(_config, _logger, XmlReaderSettingsFactory, profile).ProcessControlRequest(request);
}
}
}
Loading

0 comments on commit cb087e1

Please sign in to comment.