Explorar o código

reduce traffic from play to feature

Luke Pulverenti %!s(int64=8) %!d(string=hai) anos
pai
achega
b9f758e14d

+ 25 - 0
Emby.Dlna/PlayTo/Device.cs

@@ -440,6 +440,11 @@ namespace Emby.Dlna.PlayTo
             {
             {
                 var transportState = await GetTransportInfo().ConfigureAwait(false);
                 var transportState = await GetTransportInfo().ConfigureAwait(false);
 
 
+                if (_disposed)
+                {
+                    return;
+                }
+
                 DateLastActivity = DateTime.UtcNow;
                 DateLastActivity = DateTime.UtcNow;
 
 
                 if (transportState.HasValue)
                 if (transportState.HasValue)
@@ -530,6 +535,11 @@ namespace Emby.Dlna.PlayTo
 
 
         private async Task GetVolume()
         private async Task GetVolume()
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             var command = RendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
             var command = RendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
             if (command == null)
             if (command == null)
                 return;
                 return;
@@ -563,6 +573,11 @@ namespace Emby.Dlna.PlayTo
 
 
         private async Task GetMute()
         private async Task GetMute()
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             var command = RendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
             var command = RendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
             if (command == null)
             if (command == null)
                 return;
                 return;
@@ -793,6 +808,11 @@ namespace Emby.Dlna.PlayTo
 
 
         private async Task GetAVProtocolAsync()
         private async Task GetAVProtocolAsync()
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             var avService = GetAvTransportService();
             var avService = GetAvTransportService();
             if (avService == null)
             if (avService == null)
                 return;
                 return;
@@ -807,6 +827,11 @@ namespace Emby.Dlna.PlayTo
 
 
         private async Task GetRenderingProtocolAsync()
         private async Task GetRenderingProtocolAsync()
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             var avService = GetServiceRenderingControl();
             var avService = GetServiceRenderingControl();
 
 
             if (avService == null)
             if (avService == null)

+ 20 - 0
Emby.Dlna/PlayTo/PlayToController.cs

@@ -149,6 +149,11 @@ namespace Emby.Dlna.PlayTo
 
 
         async void _device_MediaChanged(object sender, MediaChangedEventArgs e)
         async void _device_MediaChanged(object sender, MediaChangedEventArgs e)
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             try
             try
             {
             {
                 var streamInfo = await StreamParams.ParseFromUrl(e.OldMediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);
                 var streamInfo = await StreamParams.ParseFromUrl(e.OldMediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);
@@ -176,6 +181,11 @@ namespace Emby.Dlna.PlayTo
 
 
         async void _device_PlaybackStopped(object sender, PlaybackStoppedEventArgs e)
         async void _device_PlaybackStopped(object sender, PlaybackStoppedEventArgs e)
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             try
             try
             {
             {
                 var streamInfo = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager)
                 var streamInfo = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager)
@@ -239,6 +249,11 @@ namespace Emby.Dlna.PlayTo
 
 
         async void _device_PlaybackStart(object sender, PlaybackStartEventArgs e)
         async void _device_PlaybackStart(object sender, PlaybackStartEventArgs e)
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             try
             try
             {
             {
                 var info = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);
                 var info = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);
@@ -258,6 +273,11 @@ namespace Emby.Dlna.PlayTo
 
 
         async void _device_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
         async void _device_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             try
             try
             {
             {
                 var info = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);
                 var info = await StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager).ConfigureAwait(false);

+ 22 - 0
Emby.Dlna/PlayTo/PlayToManager.cs

@@ -43,6 +43,7 @@ namespace Emby.Dlna.PlayTo
 
 
         private readonly List<string> _nonRendererUrls = new List<string>();
         private readonly List<string> _nonRendererUrls = new List<string>();
         private DateTime _lastRendererClear;
         private DateTime _lastRendererClear;
+        private bool _disposed;
 
 
         public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, IServerConfigurationManager config, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ITimerFactory timerFactory)
         public PlayToManager(ILogger logger, ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IDlnaManager dlnaManager, IServerApplicationHost appHost, IImageProcessor imageProcessor, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, IServerConfigurationManager config, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, ITimerFactory timerFactory)
         {
         {
@@ -70,6 +71,11 @@ namespace Emby.Dlna.PlayTo
 
 
         async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
         async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
         {
         {
+            if (_disposed)
+            {
+                return;
+            }
+
             var info = e.Argument;
             var info = e.Argument;
 
 
             string usn;
             string usn;
@@ -121,6 +127,11 @@ namespace Emby.Dlna.PlayTo
                     }
                     }
                 }
                 }
 
 
+                if (_disposed)
+                {
+                    return;
+                }
+
                 _logger.Debug("Logging session activity from location {0}", location);
                 _logger.Debug("Logging session activity from location {0}", location);
                 var sessionInfo = await _sessionManager.LogSessionActivity(device.Properties.ClientType, _appHost.ApplicationVersion.ToString(), device.Properties.UUID, device.Properties.Name, uri.OriginalString, null)
                 var sessionInfo = await _sessionManager.LogSessionActivity(device.Properties.ClientType, _appHost.ApplicationVersion.ToString(), device.Properties.UUID, device.Properties.Name, uri.OriginalString, null)
                     .ConfigureAwait(false);
                     .ConfigureAwait(false);
@@ -129,6 +140,11 @@ namespace Emby.Dlna.PlayTo
 
 
                 if (controller == null)
                 if (controller == null)
                 {
                 {
+                    if (_disposed)
+                    {
+                        return;
+                    }
+
                     string serverAddress;
                     string serverAddress;
                     if (info.LocalIpAddress == null)
                     if (info.LocalIpAddress == null)
                     {
                     {
@@ -187,6 +203,11 @@ namespace Emby.Dlna.PlayTo
             catch (Exception ex)
             catch (Exception ex)
             {
             {
                 _logger.ErrorException("Error creating PlayTo device.", ex);
                 _logger.ErrorException("Error creating PlayTo device.", ex);
+
+                lock (_nonRendererUrls)
+                {
+                    _nonRendererUrls.Add(location);
+                }
             }
             }
         }
         }
 
 
@@ -202,6 +223,7 @@ namespace Emby.Dlna.PlayTo
 
 
         public void Dispose()
         public void Dispose()
         {
         {
+            _disposed = true;
             _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
             _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
         }
         }
     }
     }

+ 2 - 1
Emby.Dlna/Ssdp/DeviceDiscovery.cs

@@ -104,7 +104,8 @@ namespace Emby.Dlna.Ssdp
                 Argument = new UpnpDeviceInfo
                 Argument = new UpnpDeviceInfo
                 {
                 {
                     Location = e.DiscoveredDevice.DescriptionLocation,
                     Location = e.DiscoveredDevice.DescriptionLocation,
-                    Headers = headers
+                    Headers = headers,
+                    LocalIpAddress = e.LocalIpAddress
                 }
                 }
             };
             };
 
 

+ 13 - 4
Emby.Server.Core/EntryPoints/ExternalPortForwarding.cs

@@ -11,6 +11,7 @@ using MediaBrowser.Model.Events;
 using MediaBrowser.Model.Logging;
 using MediaBrowser.Model.Logging;
 using MediaBrowser.Model.Threading;
 using MediaBrowser.Model.Threading;
 using Mono.Nat;
 using Mono.Nat;
+using System.Threading.Tasks;
 
 
 namespace Emby.Server.Core.EntryPoints
 namespace Emby.Server.Core.EntryPoints
 {
 {
@@ -223,7 +224,7 @@ namespace Emby.Server.Core.EntryPoints
 
 
         private List<string> _createdRules = new List<string>();
         private List<string> _createdRules = new List<string>();
         private List<string> _usnsHandled = new List<string>();
         private List<string> _usnsHandled = new List<string>();
-        private void CreateRules(INatDevice device)
+        private async void CreateRules(INatDevice device)
         {
         {
             if (_disposed)
             if (_disposed)
             {
             {
@@ -239,12 +240,16 @@ namespace Emby.Server.Core.EntryPoints
             {
             {
                 _createdRules.Add(address);
                 _createdRules.Add(address);
 
 
-                CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
-                CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
+                var success = await CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort).ConfigureAwait(false);
+
+                if (success)
+                {
+                    await CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort).ConfigureAwait(false);
+                }
             }
             }
         }
         }
 
 
-        private async void CreatePortMap(INatDevice device, int privatePort, int publicPort)
+        private async Task<bool> CreatePortMap(INatDevice device, int privatePort, int publicPort)
         {
         {
             _logger.Debug("Creating port map on port {0}", privatePort);
             _logger.Debug("Creating port map on port {0}", privatePort);
 
 
@@ -255,10 +260,14 @@ namespace Emby.Server.Core.EntryPoints
                     Description = _appHost.Name
                     Description = _appHost.Name
 
 
                 }).ConfigureAwait(false);
                 }).ConfigureAwait(false);
+
+                return true;
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
                 _logger.Error("Error creating port map: " + ex.Message);
                 _logger.Error("Error creating port map: " + ex.Message);
+
+                return false;
             }
             }
         }
         }
 
 

+ 4 - 2
RSSDP/DeviceAvailableEventArgs.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
+using MediaBrowser.Model.Net;
 
 
 namespace Rssdp
 namespace Rssdp
 {
 {
@@ -11,10 +12,11 @@ namespace Rssdp
 	/// </summary>
 	/// </summary>
 	public sealed class DeviceAvailableEventArgs : EventArgs
 	public sealed class DeviceAvailableEventArgs : EventArgs
 	{
 	{
+        public IpAddressInfo LocalIpAddress { get; set; }
 
 
-		#region Fields
+        #region Fields
 
 
-		private readonly DiscoveredSsdpDevice _DiscoveredDevice;
+        private readonly DiscoveredSsdpDevice _DiscoveredDevice;
 		private readonly bool _IsNewlyDiscovered;
 		private readonly bool _IsNewlyDiscovered;
 
 
 		#endregion
 		#endregion

+ 4 - 2
RSSDP/ResponseReceivedEventArgs.cs

@@ -15,9 +15,11 @@ namespace Rssdp.Infrastructure
 	public sealed class ResponseReceivedEventArgs : EventArgs
 	public sealed class ResponseReceivedEventArgs : EventArgs
 	{
 	{
 
 
-		#region Fields
+        public IpAddressInfo LocalIpAddress { get; set; }
 
 
-		private readonly HttpResponseMessage _Message;
+        #region Fields
+
+        private readonly HttpResponseMessage _Message;
 		private readonly IpEndPointInfo _ReceivedFrom;
 		private readonly IpEndPointInfo _ReceivedFrom;
 
 
 		#endregion
 		#endregion

+ 6 - 3
RSSDP/SsdpCommunicationsServer.cs

@@ -454,7 +454,7 @@ namespace Rssdp.Infrastructure
                 }
                 }
 
 
                 if (responseMessage != null)
                 if (responseMessage != null)
-                    OnResponseReceived(responseMessage, endPoint);
+                    OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
             }
             }
             else
             else
             {
             {
@@ -490,11 +490,14 @@ namespace Rssdp.Infrastructure
                 handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
                 handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
         }
         }
 
 
-        private void OnResponseReceived(HttpResponseMessage data, IpEndPointInfo endPoint)
+        private void OnResponseReceived(HttpResponseMessage data, IpEndPointInfo endPoint, IpAddressInfo localIpAddress)
         {
         {
             var handlers = this.ResponseReceived;
             var handlers = this.ResponseReceived;
             if (handlers != null)
             if (handlers != null)
-                handlers(this, new ResponseReceivedEventArgs(data, endPoint));
+                handlers(this, new ResponseReceivedEventArgs(data, endPoint)
+                {
+                    LocalIpAddress = localIpAddress
+                });
         }
         }
 
 
         #endregion
         #endregion

+ 19 - 17
RSSDP/SsdpDeviceLocatorBase.cs

@@ -7,6 +7,7 @@ using System.Net.Http;
 using System.Text;
 using System.Text;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
+using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Threading;
 using MediaBrowser.Model.Threading;
 using RSSDP;
 using RSSDP;
 
 
@@ -163,7 +164,7 @@ namespace Rssdp.Infrastructure
             {
             {
                 foreach (var device in GetUnexpiredDevices().Where(NotificationTypeMatchesFilter))
                 foreach (var device in GetUnexpiredDevices().Where(NotificationTypeMatchesFilter))
                 {
                 {
-                    DeviceFound(device, false);
+                    DeviceFound(device, false, null);
                 }
                 }
             }
             }
 
 
@@ -237,16 +238,17 @@ namespace Rssdp.Infrastructure
         /// <summary>
         /// <summary>
         /// Raises the <see cref="DeviceAvailable"/> event.
         /// Raises the <see cref="DeviceAvailable"/> event.
         /// </summary>
         /// </summary>
-        /// <param name="device">A <see cref="DiscoveredSsdpDevice"/> representing the device that is now available.</param>
-        /// <param name="isNewDevice">True if the device was not currently in the cahce before this event was raised.</param>
         /// <seealso cref="DeviceAvailable"/>
         /// <seealso cref="DeviceAvailable"/>
-        protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice)
+        protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
         {
         {
             if (this.IsDisposed) return;
             if (this.IsDisposed) return;
 
 
             var handlers = this.DeviceAvailable;
             var handlers = this.DeviceAvailable;
             if (handlers != null)
             if (handlers != null)
-                handlers(this, new DeviceAvailableEventArgs(device, isNewDevice));
+                handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
+                {
+                    LocalIpAddress = localIpAddress
+                });
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -335,7 +337,7 @@ namespace Rssdp.Infrastructure
 
 
         #region Discovery/Device Add
         #region Discovery/Device Add
 
 
-        private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device)
+        private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IpAddressInfo localIpAddress)
         {
         {
             bool isNewDevice = false;
             bool isNewDevice = false;
             lock (_Devices)
             lock (_Devices)
@@ -353,10 +355,10 @@ namespace Rssdp.Infrastructure
                 }
                 }
             }
             }
 
 
-            DeviceFound(device, isNewDevice);
+            DeviceFound(device, isNewDevice, localIpAddress);
         }
         }
 
 
-        private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice)
+        private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
         {
         {
             // Don't raise the event if we've already done it for a cached
             // Don't raise the event if we've already done it for a cached
             // version of this device, and the cached version isn't
             // version of this device, and the cached version isn't
@@ -391,7 +393,7 @@ namespace Rssdp.Infrastructure
             }
             }
 
 
             if (raiseEvent)
             if (raiseEvent)
-                OnDeviceAvailable(device, isNewDevice);
+                OnDeviceAvailable(device, isNewDevice, localIpAddress);
         }
         }
 
 
         private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
         private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
@@ -428,7 +430,7 @@ namespace Rssdp.Infrastructure
             return _CommunicationsServer.SendMulticastMessage(message);
             return _CommunicationsServer.SendMulticastMessage(message);
         }
         }
 
 
-        private void ProcessSearchResponseMessage(HttpResponseMessage message)
+        private void ProcessSearchResponseMessage(HttpResponseMessage message, IpAddressInfo localIpAddress)
         {
         {
             if (!message.IsSuccessStatusCode) return;
             if (!message.IsSuccessStatusCode) return;
 
 
@@ -445,22 +447,22 @@ namespace Rssdp.Infrastructure
                     ResponseHeaders = message.Headers
                     ResponseHeaders = message.Headers
                 };
                 };
 
 
-                AddOrUpdateDiscoveredDevice(device);
+                AddOrUpdateDiscoveredDevice(device, localIpAddress);
             }
             }
         }
         }
 
 
-        private void ProcessNotificationMessage(HttpRequestMessage message)
+        private void ProcessNotificationMessage(HttpRequestMessage message, IpAddressInfo localIpAddress)
         {
         {
             if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) return;
             if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) return;
 
 
             var notificationType = GetFirstHeaderStringValue("NTS", message);
             var notificationType = GetFirstHeaderStringValue("NTS", message);
             if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
             if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
-                ProcessAliveNotification(message);
+                ProcessAliveNotification(message, localIpAddress);
             else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
             else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
                 ProcessByeByeNotification(message);
                 ProcessByeByeNotification(message);
         }
         }
 
 
-        private void ProcessAliveNotification(HttpRequestMessage message)
+        private void ProcessAliveNotification(HttpRequestMessage message, IpAddressInfo localIpAddress)
         {
         {
             var location = GetFirstHeaderUriValue("Location", message);
             var location = GetFirstHeaderUriValue("Location", message);
             if (location != null)
             if (location != null)
@@ -475,7 +477,7 @@ namespace Rssdp.Infrastructure
                     ResponseHeaders = message.Headers
                     ResponseHeaders = message.Headers
                 };
                 };
 
 
-                AddOrUpdateDiscoveredDevice(device);
+                AddOrUpdateDiscoveredDevice(device, localIpAddress);
 
 
                 ResetExpireCachedDevicesTimer();
                 ResetExpireCachedDevicesTimer();
             }
             }
@@ -702,12 +704,12 @@ namespace Rssdp.Infrastructure
 
 
         private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
         private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
         {
         {
-            ProcessSearchResponseMessage(e.Message);
+            ProcessSearchResponseMessage(e.Message, e.LocalIpAddress);
         }
         }
 
 
         private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
         private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
         {
         {
-            ProcessNotificationMessage(e.Message);
+            ProcessNotificationMessage(e.Message, e.LocalIpAddress);
         }
         }
 
 
         #endregion
         #endregion