jellyfin-server/Emby.Dlna/PlayTo/Device.cs

1209 lines
39 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
#pragma warning disable SA1600
using System;
2016-10-29 22:22:20 +00:00
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2019-02-13 19:23:13 +00:00
using System.Xml;
2016-10-29 22:22:20 +00:00
using System.Xml.Linq;
2019-01-13 19:16:19 +00:00
using Emby.Dlna.Common;
2016-10-29 22:34:54 +00:00
using Emby.Dlna.Server;
2019-01-13 19:16:19 +00:00
using Emby.Dlna.Ssdp;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using Microsoft.Extensions.Logging;
2016-10-29 22:22:20 +00:00
2016-10-29 22:34:54 +00:00
namespace Emby.Dlna.PlayTo
2016-10-29 22:22:20 +00:00
{
public class Device : IDisposable
{
#region Fields & Properties
2019-02-05 08:49:46 +00:00
private Timer _timer;
2016-10-29 22:22:20 +00:00
public DeviceInfo Properties { get; set; }
private int _muteVol;
public bool IsMuted { get; set; }
private int _volume;
public int Volume
{
get
{
RefreshVolumeIfNeeded();
return _volume;
}
set => _volume = value;
2016-10-29 22:22:20 +00:00
}
public TimeSpan? Duration { get; set; }
public TimeSpan Position { get; set; } = TimeSpan.FromSeconds(0);
2016-10-29 22:22:20 +00:00
public TRANSPORTSTATE TransportState { get; private set; }
public bool IsPlaying => TransportState == TRANSPORTSTATE.PLAYING;
2016-10-29 22:22:20 +00:00
public bool IsPaused => TransportState == TRANSPORTSTATE.PAUSED || TransportState == TRANSPORTSTATE.PAUSED_PLAYBACK;
2016-10-29 22:22:20 +00:00
public bool IsStopped => TransportState == TRANSPORTSTATE.STOPPED;
2016-10-29 22:22:20 +00:00
#endregion
private readonly IHttpClient _httpClient;
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
public Action OnDeviceUnavailable { get; set; }
2019-02-05 08:49:46 +00:00
public Device(DeviceInfo deviceProperties, IHttpClient httpClient, ILogger logger, IServerConfigurationManager config)
2016-10-29 22:22:20 +00:00
{
Properties = deviceProperties;
_httpClient = httpClient;
_logger = logger;
_config = config;
}
public void Start()
{
_logger.LogDebug("Dlna Device.Start");
2019-02-05 08:49:46 +00:00
_timer = new Timer(TimerCallback, null, 1000, Timeout.Infinite);
2016-10-29 22:22:20 +00:00
}
private DateTime _lastVolumeRefresh;
2018-09-12 17:26:21 +00:00
private bool _volumeRefreshActive;
2016-10-29 22:22:20 +00:00
private void RefreshVolumeIfNeeded()
{
2018-09-12 17:26:21 +00:00
if (!_volumeRefreshActive)
2016-10-29 22:22:20 +00:00
{
return;
}
if (DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
{
_lastVolumeRefresh = DateTime.UtcNow;
2018-09-12 17:26:21 +00:00
RefreshVolume(CancellationToken.None);
2016-10-29 22:22:20 +00:00
}
}
2018-09-12 17:26:21 +00:00
private async void RefreshVolume(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
if (_disposed)
return;
try
{
2018-09-12 17:26:21 +00:00
await GetVolume(cancellationToken).ConfigureAwait(false);
await GetMute(cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
catch (Exception ex)
{
2018-12-20 12:39:58 +00:00
_logger.LogError(ex, "Error updating device volume info for {DeviceName}", Properties.Name);
2016-10-29 22:22:20 +00:00
}
}
private readonly object _timerLock = new object();
2018-09-12 17:26:21 +00:00
private void RestartTimer(bool immediate = false)
2016-10-29 22:22:20 +00:00
{
2017-08-10 20:06:36 +00:00
lock (_timerLock)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
if (_disposed)
{
2018-09-12 17:26:21 +00:00
return;
}
2018-09-12 17:26:21 +00:00
_volumeRefreshActive = true;
2017-08-10 20:06:36 +00:00
2018-09-12 17:26:21 +00:00
var time = immediate ? 100 : 10000;
_timer.Change(time, Timeout.Infinite);
2016-10-29 22:22:20 +00:00
}
}
/// <summary>
/// Restarts the timer in inactive mode.
/// </summary>
private void RestartTimerInactive()
{
2017-08-10 20:06:36 +00:00
lock (_timerLock)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
if (_disposed)
{
2018-09-12 17:26:21 +00:00
return;
}
2016-10-29 22:22:20 +00:00
2018-09-12 17:26:21 +00:00
_volumeRefreshActive = false;
2017-08-10 20:06:36 +00:00
2018-09-12 17:26:21 +00:00
_timer.Change(Timeout.Infinite, Timeout.Infinite);
2016-10-29 22:22:20 +00:00
}
}
#region Commanding
2018-09-12 17:26:21 +00:00
public Task VolumeDown(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
var sendVolume = Math.Max(Volume - 5, 0);
2018-09-12 17:26:21 +00:00
return SetVolume(sendVolume, cancellationToken);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public Task VolumeUp(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
var sendVolume = Math.Min(Volume + 5, 100);
2018-09-12 17:26:21 +00:00
return SetVolume(sendVolume, cancellationToken);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public Task ToggleMute(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
if (IsMuted)
{
2019-02-05 17:16:10 +00:00
return Unmute(cancellationToken);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
return Mute(cancellationToken);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public async Task Mute(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var success = await SetMute(true, cancellationToken).ConfigureAwait(true);
2016-10-29 22:22:20 +00:00
if (!success)
{
2018-09-12 17:26:21 +00:00
await SetVolume(0, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
}
2019-02-05 17:16:10 +00:00
public async Task Unmute(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var success = await SetMute(false, cancellationToken).ConfigureAwait(true);
2016-10-29 22:22:20 +00:00
if (!success)
{
var sendVolume = _muteVol <= 0 ? 20 : _muteVol;
2018-09-12 17:26:21 +00:00
await SetVolume(sendVolume, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
}
2016-12-15 07:12:52 +00:00
private DeviceService GetServiceRenderingControl()
{
var services = Properties.Services;
return services.FirstOrDefault(s => string.Equals(s.ServiceType, "urn:schemas-upnp-org:service:RenderingControl:1", StringComparison.OrdinalIgnoreCase)) ??
services.FirstOrDefault(s => (s.ServiceType ?? string.Empty).StartsWith("urn:schemas-upnp-org:service:RenderingControl", StringComparison.OrdinalIgnoreCase));
}
private DeviceService GetAvTransportService()
{
var services = Properties.Services;
return services.FirstOrDefault(s => string.Equals(s.ServiceType, "urn:schemas-upnp-org:service:AVTransport:1", StringComparison.OrdinalIgnoreCase)) ??
services.FirstOrDefault(s => (s.ServiceType ?? string.Empty).StartsWith("urn:schemas-upnp-org:service:AVTransport", StringComparison.OrdinalIgnoreCase));
}
2018-09-12 17:26:21 +00:00
private async Task<bool> SetMute(bool mute, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetMute");
2016-10-29 22:22:20 +00:00
if (command == null)
return false;
2016-12-15 07:12:52 +00:00
var service = GetServiceRenderingControl();
2016-10-29 22:22:20 +00:00
if (service == null)
{
return false;
}
_logger.LogDebug("Setting mute");
2016-10-29 22:22:20 +00:00
var value = mute ? 1 : 0;
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value))
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
IsMuted = mute;
return true;
}
/// <summary>
/// Sets volume on a scale of 0-100
/// </summary>
2018-09-12 17:26:21 +00:00
public async Task SetVolume(int value, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume");
2016-10-29 22:22:20 +00:00
if (command == null)
return;
2016-12-15 07:12:52 +00:00
var service = GetServiceRenderingControl();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
// Set it early and assume it will succeed
// Remote control will perform better
Volume = value;
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value))
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
}
2018-09-12 17:26:21 +00:00
public async Task Seek(TimeSpan value, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Seek");
2016-10-29 22:22:20 +00:00
if (command == null)
return;
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, string.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME"))
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
RestartTimer(true);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public async Task SetAvTransport(string url, string header, string metaData, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
url = url.Replace("&", "&amp;");
_logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header);
2016-10-29 22:22:20 +00:00
2018-09-12 17:26:21 +00:00
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
2016-10-29 22:22:20 +00:00
if (command == null)
return;
var dictionary = new Dictionary<string, string>
{
{"CurrentURI", url},
{"CurrentURIMetaData", CreateDidlMeta(metaData)}
};
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
2018-09-12 17:26:21 +00:00
var post = avCommands.BuildPost(command, service.ServiceType, url, dictionary);
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
await Task.Delay(50).ConfigureAwait(false);
try
{
2018-09-12 17:26:21 +00:00
await SetPlay(avCommands, CancellationToken.None).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
catch
{
// Some devices will throw an error if you tell it to play when it's already playing
// Others won't
}
2018-09-12 17:26:21 +00:00
RestartTimer(true);
2016-10-29 22:22:20 +00:00
}
private string CreateDidlMeta(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
2016-10-29 22:22:20 +00:00
return DescriptionXmlBuilder.Escape(value);
}
2018-09-12 17:26:21 +00:00
private Task SetPlay(TransportCommands avCommands, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Play");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2018-09-12 17:26:21 +00:00
return Task.CompletedTask;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
return new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1));
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public async Task SetPlay(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
await SetPlay(avCommands, cancellationToken).ConfigureAwait(false);
RestartTimer(true);
}
public async Task SetStop(CancellationToken cancellationToken)
{
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Stop");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1))
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
RestartTimer(true);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
public async Task SetPause(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Pause");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1))
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
TransportState = TRANSPORTSTATE.PAUSED;
2018-09-12 17:26:21 +00:00
RestartTimer(true);
2016-10-29 22:22:20 +00:00
}
#endregion
#region Get data
private int _connectFailureCount;
private async void TimerCallback(object sender)
{
if (_disposed)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
try
{
2018-09-12 17:26:21 +00:00
var cancellationToken = CancellationToken.None;
var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
if (avCommands == null)
{
return;
}
var transportState = await GetTransportInfo(avCommands, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
2017-01-24 19:54:18 +00:00
if (_disposed)
{
return;
}
2016-10-29 22:22:20 +00:00
if (transportState.HasValue)
{
// If we're not playing anything no need to get additional data
if (transportState.Value == TRANSPORTSTATE.STOPPED)
{
UpdateMediaInfo(null, transportState.Value);
}
else
{
2018-09-12 17:26:21 +00:00
var tuple = await GetPositionInfo(avCommands, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
var currentObject = tuple.Item2;
if (tuple.Item1 && currentObject == null)
{
2018-09-12 17:26:21 +00:00
currentObject = await GetMediaInfo(avCommands, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
if (currentObject != null)
{
UpdateMediaInfo(currentObject, transportState.Value);
}
}
_connectFailureCount = 0;
if (_disposed)
return;
// If we're not playing anything make sure we don't get data more often than neccessry to keep the Session alive
if (transportState.Value == TRANSPORTSTATE.STOPPED)
{
2018-09-12 17:26:21 +00:00
RestartTimerInactive();
2016-10-29 22:22:20 +00:00
}
else
{
RestartTimer();
}
}
2017-08-10 20:06:36 +00:00
else
{
RestartTimerInactive();
}
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
catch (Exception ex)
2016-10-29 22:22:20 +00:00
{
if (_disposed)
return;
2018-12-20 12:39:58 +00:00
_logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name);
2016-10-29 22:22:20 +00:00
_connectFailureCount++;
if (_connectFailureCount >= 3)
{
2018-09-12 17:26:21 +00:00
var action = OnDeviceUnavailable;
if (action != null)
2016-10-29 22:22:20 +00:00
{
_logger.LogDebug("Disposing device due to loss of connection");
2018-09-12 17:26:21 +00:00
action();
2016-10-29 22:22:20 +00:00
return;
}
}
2018-09-12 17:26:21 +00:00
RestartTimerInactive();
2016-10-29 22:22:20 +00:00
}
}
2018-09-12 17:26:21 +00:00
private async Task GetVolume(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2017-01-24 19:54:18 +00:00
if (_disposed)
{
return;
}
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetServiceRenderingControl();
2016-10-29 22:22:20 +00:00
if (service == null)
{
return;
}
var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
if (result == null || result.Document == null)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
var volume = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i != null);
var volumeValue = volume?.Value;
2016-10-29 22:22:20 +00:00
if (string.IsNullOrWhiteSpace(volumeValue))
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
Volume = int.Parse(volumeValue, UsCulture);
if (Volume > 0)
{
_muteVol = Volume;
}
}
2018-09-12 17:26:21 +00:00
private async Task GetMute(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2017-01-24 19:54:18 +00:00
if (_disposed)
{
return;
}
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetServiceRenderingControl();
2016-10-29 22:22:20 +00:00
if (service == null)
{
return;
}
var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
if (result == null || result.Document == null)
return;
var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse")
.Select(i => i.Element("CurrentMute"))
.FirstOrDefault(i => i != null);
2016-10-29 22:22:20 +00:00
IsMuted = string.Equals(valueNode?.Value, "1", StringComparison.OrdinalIgnoreCase);
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
private async Task<TRANSPORTSTATE?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetTransportInfo");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return null;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
2016-10-29 22:22:20 +00:00
return null;
}
2016-10-29 22:22:20 +00:00
var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
if (result == null || result.Document == null)
{
2016-10-29 22:22:20 +00:00
return null;
}
2016-10-29 22:22:20 +00:00
var transportState =
result.Document.Descendants(uPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i != null);
var transportStateValue = transportState == null ? null : transportState.Value;
if (transportStateValue != null
&& Enum.TryParse(transportStateValue, true, out TRANSPORTSTATE state))
2016-10-29 22:22:20 +00:00
{
return state;
2016-10-29 22:22:20 +00:00
}
return null;
}
2018-09-12 17:26:21 +00:00
private async Task<uBaseObject> GetMediaInfo(TransportCommands avCommands, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMediaInfo");
2016-10-29 22:22:20 +00:00
if (command == null)
{
2016-10-29 22:22:20 +00:00
return null;
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
if (result == null || result.Document == null)
{
2016-10-29 22:22:20 +00:00
return null;
}
2016-10-29 22:22:20 +00:00
var track = result.Document.Descendants("CurrentURIMetaData").FirstOrDefault();
if (track == null)
{
return null;
}
var e = track.Element(uPnpNamespaces.items) ?? track;
2017-09-27 14:51:36 +00:00
var elementString = (string)e;
if (!string.IsNullOrWhiteSpace(elementString))
{
return UpnpContainer.Create(e);
}
track = result.Document.Descendants("CurrentURI").FirstOrDefault();
if (track == null)
{
return null;
}
e = track.Element(uPnpNamespaces.items) ?? track;
elementString = (string)e;
if (!string.IsNullOrWhiteSpace(elementString))
{
return new uBaseObject
{
Url = elementString
};
}
return null;
2016-10-29 22:22:20 +00:00
}
private async Task<(bool, uBaseObject)> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetPositionInfo");
2016-10-29 22:22:20 +00:00
if (command == null)
{
return (false, null);
}
2016-10-29 22:22:20 +00:00
2016-12-15 07:12:52 +00:00
var service = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (service == null)
{
throw new InvalidOperationException("Unable to find service");
}
2018-09-12 17:26:21 +00:00
var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false)
2016-10-29 22:22:20 +00:00
.ConfigureAwait(false);
if (result == null || result.Document == null)
{
return (false, null);
}
2016-10-29 22:22:20 +00:00
var trackUriElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackURI")).FirstOrDefault(i => i != null);
var trackUri = trackUriElem == null ? null : trackUriElem.Value;
var durationElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i != null);
var duration = durationElem == null ? null : durationElem.Value;
if (!string.IsNullOrWhiteSpace(duration)
&& !string.Equals(duration, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
2016-10-29 22:22:20 +00:00
{
Duration = TimeSpan.Parse(duration, UsCulture);
}
else
{
Duration = null;
}
var positionElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("RelTime")).FirstOrDefault(i => i != null);
var position = positionElem == null ? null : positionElem.Value;
if (!string.IsNullOrWhiteSpace(position) && !string.Equals(position, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{
Position = TimeSpan.Parse(position, UsCulture);
}
var track = result.Document.Descendants("TrackMetaData").FirstOrDefault();
if (track == null)
{
2019-01-07 23:27:46 +00:00
//If track is null, some vendors do this, use GetMediaInfo instead
return (true, null);
2016-10-29 22:22:20 +00:00
}
var trackString = (string)track;
if (string.IsNullOrWhiteSpace(trackString) || string.Equals(trackString, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{
return (true, null);
2016-10-29 22:22:20 +00:00
}
2019-02-13 19:23:13 +00:00
XElement uPnpResponse = null;
2016-12-15 07:12:52 +00:00
2016-10-29 22:22:20 +00:00
try
{
2019-02-13 19:23:13 +00:00
uPnpResponse = ParseResponse(trackString);
2016-10-29 22:22:20 +00:00
}
2019-02-13 19:23:13 +00:00
catch (Exception ex)
2016-10-29 22:22:20 +00:00
{
2019-02-13 19:23:13 +00:00
_logger.LogError(ex, "Uncaught exception while parsing xml");
}
if (uPnpResponse == null)
{
_logger.LogError("Failed to parse xml: \n {Xml}", trackString);
return (true, null);
2016-10-29 22:22:20 +00:00
}
var e = uPnpResponse.Element(uPnpNamespaces.items);
var uTrack = CreateUBaseObject(e, trackUri);
return (true, uTrack);
2016-10-29 22:22:20 +00:00
}
2019-02-13 19:23:13 +00:00
private XElement ParseResponse(string xml)
{
// Handle different variations sent back by devices
try
{
return XElement.Parse(xml);
}
catch (XmlException)
{
}
// first try to add a root node with a dlna namesapce
try
{
return XElement.Parse("<data xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">" + xml + "</data>")
.Descendants()
.First();
}
catch (XmlException)
{
}
// some devices send back invalid xml
try
{
return XElement.Parse(xml.Replace("&", "&amp;"));
}
catch (XmlException)
{
}
return null;
}
2016-10-29 22:22:20 +00:00
private static uBaseObject CreateUBaseObject(XElement container, string trackUri)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
2016-10-29 22:22:20 +00:00
}
var url = container.GetValue(uPnpNamespaces.Res);
if (string.IsNullOrWhiteSpace(url))
{
url = trackUri;
}
return new uBaseObject
{
Id = container.GetAttributeValue(uPnpNamespaces.Id),
ParentId = container.GetAttributeValue(uPnpNamespaces.ParentId),
Title = container.GetValue(uPnpNamespaces.title),
IconUrl = container.GetValue(uPnpNamespaces.Artwork),
SecondText = "",
Url = url,
ProtocolInfo = GetProtocolInfo(container),
MetaData = container.ToString()
};
}
private static string[] GetProtocolInfo(XElement container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
2016-10-29 22:22:20 +00:00
}
var resElement = container.Element(uPnpNamespaces.Res);
if (resElement != null)
{
var info = resElement.Attribute(uPnpNamespaces.ProtocolInfo);
if (info != null && !string.IsNullOrWhiteSpace(info.Value))
{
return info.Value.Split(':');
}
}
return new string[4];
}
#endregion
#region From XML
2018-09-12 17:26:21 +00:00
private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
if (AvCommands != null)
2018-09-12 17:26:21 +00:00
{
return AvCommands;
2018-09-12 17:26:21 +00:00
}
2017-01-24 19:54:18 +00:00
if (_disposed)
{
2018-09-12 17:26:21 +00:00
throw new ObjectDisposedException(GetType().Name);
2017-01-24 19:54:18 +00:00
}
2016-12-15 07:12:52 +00:00
var avService = GetAvTransportService();
2016-10-29 22:22:20 +00:00
if (avService == null)
2018-09-12 17:26:21 +00:00
{
return null;
}
2016-10-29 22:22:20 +00:00
string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
var httpClient = new SsdpHttpClient(_httpClient);
2018-09-12 17:26:21 +00:00
2017-11-23 15:46:16 +00:00
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
AvCommands = TransportCommands.Create(document);
return AvCommands;
2016-10-29 22:22:20 +00:00
}
2018-09-12 17:26:21 +00:00
private async Task<TransportCommands> GetRenderingProtocolAsync(CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
if (RendererCommands != null)
2018-09-12 17:26:21 +00:00
{
return RendererCommands;
2018-09-12 17:26:21 +00:00
}
2017-01-24 19:54:18 +00:00
if (_disposed)
{
2018-09-12 17:26:21 +00:00
throw new ObjectDisposedException(GetType().Name);
2017-01-24 19:54:18 +00:00
}
2016-12-15 07:12:52 +00:00
var avService = GetServiceRenderingControl();
2016-10-29 22:22:20 +00:00
if (avService == null)
2018-09-12 17:26:21 +00:00
{
throw new ArgumentException("Device AvService is null");
}
2016-10-29 22:22:20 +00:00
string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
var httpClient = new SsdpHttpClient(_httpClient);
_logger.LogDebug("Dlna Device.GetRenderingProtocolAsync");
2017-11-23 15:46:16 +00:00
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
RendererCommands = TransportCommands.Create(document);
return RendererCommands;
2016-10-29 22:22:20 +00:00
}
private string NormalizeUrl(string baseUrl, string url)
{
// If it's already a complete url, don't stick anything onto the front of it
if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
return url;
}
if (!url.Contains("/"))
{
2016-10-29 22:22:20 +00:00
url = "/dmr/" + url;
}
2016-10-29 22:22:20 +00:00
if (!url.StartsWith("/"))
{
2016-10-29 22:22:20 +00:00
url = "/" + url;
}
2016-10-29 22:22:20 +00:00
return baseUrl + url;
}
private TransportCommands AvCommands { get; set; }
2016-10-29 22:22:20 +00:00
private TransportCommands RendererCommands { get; set; }
2016-10-29 22:22:20 +00:00
2019-02-05 08:49:46 +00:00
public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, CancellationToken cancellationToken)
2016-10-29 22:22:20 +00:00
{
var ssdpHttpClient = new SsdpHttpClient(httpClient);
2016-10-29 22:22:20 +00:00
2017-11-23 15:46:16 +00:00
var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
var friendlyNames = new List<string>();
var name = document.Descendants(uPnpNamespaces.ud.GetName("friendlyName")).FirstOrDefault();
if (name != null && !string.IsNullOrWhiteSpace(name.Value))
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
friendlyNames.Add(name.Value);
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var room = document.Descendants(uPnpNamespaces.ud.GetName("roomName")).FirstOrDefault();
if (room != null && !string.IsNullOrWhiteSpace(room.Value))
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
friendlyNames.Add(room.Value);
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var deviceProperties = new DeviceInfo()
{
Name = string.Join(" ", friendlyNames),
BaseUrl = string.Format("http://{0}:{1}", url.Host, url.Port)
};
2016-10-29 22:22:20 +00:00
var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault();
if (model != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.ModelName = model.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var modelNumber = document.Descendants(uPnpNamespaces.ud.GetName("modelNumber")).FirstOrDefault();
if (modelNumber != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.ModelNumber = modelNumber.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var uuid = document.Descendants(uPnpNamespaces.ud.GetName("UDN")).FirstOrDefault();
if (uuid != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.UUID = uuid.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var manufacturer = document.Descendants(uPnpNamespaces.ud.GetName("manufacturer")).FirstOrDefault();
if (manufacturer != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.Manufacturer = manufacturer.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var manufacturerUrl = document.Descendants(uPnpNamespaces.ud.GetName("manufacturerURL")).FirstOrDefault();
if (manufacturerUrl != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.ManufacturerUrl = manufacturerUrl.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var presentationUrl = document.Descendants(uPnpNamespaces.ud.GetName("presentationURL")).FirstOrDefault();
if (presentationUrl != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.PresentationUrl = presentationUrl.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var modelUrl = document.Descendants(uPnpNamespaces.ud.GetName("modelURL")).FirstOrDefault();
if (modelUrl != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.ModelUrl = modelUrl.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var serialNumber = document.Descendants(uPnpNamespaces.ud.GetName("serialNumber")).FirstOrDefault();
if (serialNumber != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.SerialNumber = serialNumber.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var modelDescription = document.Descendants(uPnpNamespaces.ud.GetName("modelDescription")).FirstOrDefault();
if (modelDescription != null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
deviceProperties.ModelDescription = modelDescription.Value;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault();
if (icon != null)
{
deviceProperties.Icon = CreateIcon(icon);
}
foreach (var services in document.Descendants(uPnpNamespaces.ud.GetName("serviceList")))
{
if (services == null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
continue;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
var servicesList = services.Descendants(uPnpNamespaces.ud.GetName("service"));
if (servicesList == null)
2019-01-27 11:03:43 +00:00
{
2016-10-29 22:22:20 +00:00
continue;
2019-01-27 11:03:43 +00:00
}
2016-10-29 22:22:20 +00:00
foreach (var element in servicesList)
{
var service = Create(element);
if (service != null)
{
deviceProperties.Services.Add(service);
}
}
}
return new Device(deviceProperties, httpClient, logger, config);
2016-10-29 22:22:20 +00:00
}
#endregion
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
private static DeviceIcon CreateIcon(XElement element)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
2016-10-29 22:22:20 +00:00
}
var mimeType = element.GetDescendantValue(uPnpNamespaces.ud.GetName("mimetype"));
var width = element.GetDescendantValue(uPnpNamespaces.ud.GetName("width"));
var height = element.GetDescendantValue(uPnpNamespaces.ud.GetName("height"));
var depth = element.GetDescendantValue(uPnpNamespaces.ud.GetName("depth"));
var url = element.GetDescendantValue(uPnpNamespaces.ud.GetName("url"));
2018-09-12 17:26:21 +00:00
var widthValue = int.Parse(width, NumberStyles.Integer, UsCulture);
var heightValue = int.Parse(height, NumberStyles.Integer, UsCulture);
2016-10-29 22:22:20 +00:00
return new DeviceIcon
{
Depth = depth,
Height = heightValue,
MimeType = mimeType,
Url = url,
Width = widthValue
};
}
private static DeviceService Create(XElement element)
{
var type = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceType"));
var id = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceId"));
var scpdUrl = element.GetDescendantValue(uPnpNamespaces.ud.GetName("SCPDURL"));
var controlURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("controlURL"));
var eventSubURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("eventSubURL"));
return new DeviceService
{
ControlUrl = controlURL,
EventSubUrl = eventSubURL,
ScpdUrl = scpdUrl,
ServiceId = id,
ServiceType = type
};
}
public event EventHandler<PlaybackStartEventArgs> PlaybackStart;
public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped;
public event EventHandler<MediaChangedEventArgs> MediaChanged;
public uBaseObject CurrentMediaInfo { get; private set; }
private void UpdateMediaInfo(uBaseObject mediaInfo, TRANSPORTSTATE state)
{
TransportState = state;
var previousMediaInfo = CurrentMediaInfo;
CurrentMediaInfo = mediaInfo;
if (previousMediaInfo == null && mediaInfo != null)
{
if (state != TRANSPORTSTATE.STOPPED)
{
OnPlaybackStart(mediaInfo);
}
}
else if (mediaInfo != null && previousMediaInfo != null && !mediaInfo.Equals(previousMediaInfo))
{
OnMediaChanged(previousMediaInfo, mediaInfo);
}
else if (mediaInfo == null && previousMediaInfo != null)
{
OnPlaybackStop(previousMediaInfo);
}
else if (mediaInfo != null && mediaInfo.Equals(previousMediaInfo))
{
OnPlaybackProgress(mediaInfo);
}
}
private void OnPlaybackStart(uBaseObject mediaInfo)
{
2019-02-24 14:47:59 +00:00
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
{
return;
}
2019-01-27 11:03:43 +00:00
PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
2016-10-29 22:22:20 +00:00
{
2019-01-27 11:03:43 +00:00
MediaInfo = mediaInfo
});
2016-10-29 22:22:20 +00:00
}
private void OnPlaybackProgress(uBaseObject mediaInfo)
{
2019-02-24 14:47:59 +00:00
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
2018-09-12 17:26:21 +00:00
{
return;
}
2019-01-27 11:03:43 +00:00
PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
2016-10-29 22:22:20 +00:00
{
2019-01-27 11:03:43 +00:00
MediaInfo = mediaInfo
});
2016-10-29 22:22:20 +00:00
}
private void OnPlaybackStop(uBaseObject mediaInfo)
{
2019-01-27 11:03:43 +00:00
PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
2016-10-29 22:22:20 +00:00
{
2019-01-27 11:03:43 +00:00
MediaInfo = mediaInfo
});
2016-10-29 22:22:20 +00:00
}
private void OnMediaChanged(uBaseObject old, uBaseObject newMedia)
{
2019-01-27 11:03:43 +00:00
MediaChanged?.Invoke(this, new MediaChangedEventArgs
2016-10-29 22:22:20 +00:00
{
2019-01-27 11:03:43 +00:00
OldMediaInfo = old,
NewMediaInfo = newMedia
});
2016-10-29 22:22:20 +00:00
}
#region IDisposable
bool _disposed;
2016-10-29 22:22:20 +00:00
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
2016-10-29 22:22:20 +00:00
}
protected virtual void Dispose(bool disposing)
2016-10-29 22:22:20 +00:00
{
if (_disposed)
2016-10-29 22:22:20 +00:00
{
return;
2016-10-29 22:22:20 +00:00
}
if (disposing)
{
_timer?.Dispose();
}
_timer = null;
Properties = null;
_disposed = true;
2016-10-29 22:22:20 +00:00
}
#endregion
public override string ToString()
{
return string.Format("{0} - {1}", Properties.Name, Properties.BaseUrl);
2016-10-29 22:22:20 +00:00
}
}
}