Some small changes in Device.cs and DidlBuilder.cs

Device.cs:
* Improve dispose function
* Style fixes
* Remove unused field

DidlBuilder.cs:
* Remove unused field
* Replace giant if chain with a switch statement
This commit is contained in:
Bond_009 2019-02-05 17:37:38 +01:00
parent 0ef2b46106
commit 84d56976ba
4 changed files with 170 additions and 188 deletions

View File

@ -63,7 +63,7 @@ namespace Emby.Dlna.ContentDirectory
_profile = profile; _profile = profile;
_config = config; _config = config;
_didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, libraryManager, mediaEncoder); _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, mediaEncoder);
} }
protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams) protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, IDictionary<string, string> methodParams)

View File

@ -43,22 +43,30 @@ namespace Emby.Dlna.Didl
private readonly ILocalizationManager _localization; private readonly ILocalizationManager _localization;
private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaSourceManager _mediaSourceManager;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
private readonly IMediaEncoder _mediaEncoder; private readonly IMediaEncoder _mediaEncoder;
public DidlBuilder(DeviceProfile profile, User user, IImageProcessor imageProcessor, string serverAddress, string accessToken, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, ILogger logger, ILibraryManager libraryManager, IMediaEncoder mediaEncoder) public DidlBuilder(
DeviceProfile profile,
User user,
IImageProcessor imageProcessor,
string serverAddress,
string accessToken,
IUserDataManager userDataManager,
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
ILogger logger,
IMediaEncoder mediaEncoder)
{ {
_profile = profile; _profile = profile;
_user = user;
_imageProcessor = imageProcessor; _imageProcessor = imageProcessor;
_serverAddress = serverAddress; _serverAddress = serverAddress;
_accessToken = accessToken;
_userDataManager = userDataManager; _userDataManager = userDataManager;
_localization = localization; _localization = localization;
_mediaSourceManager = mediaSourceManager; _mediaSourceManager = mediaSourceManager;
_logger = logger; _logger = logger;
_libraryManager = libraryManager;
_mediaEncoder = mediaEncoder; _mediaEncoder = mediaEncoder;
_accessToken = accessToken;
_user = user;
} }
public static string NormalizeDlnaMediaUrl(string url) public static string NormalizeDlnaMediaUrl(string url)
@ -117,7 +125,8 @@ namespace Emby.Dlna.Didl
} }
} }
public void WriteItemElement(DlnaOptions options, public void WriteItemElement(
DlnaOptions options,
XmlWriter writer, XmlWriter writer,
BaseItem item, BaseItem item,
User user, User user,
@ -232,12 +241,15 @@ namespace Emby.Dlna.Didl
AddVideoResource(writer, video, deviceId, filter, contentFeature, streamInfo); AddVideoResource(writer, video, deviceId, filter, contentFeature, streamInfo);
} }
var subtitleProfiles = streamInfo.GetSubtitleProfiles(_mediaEncoder, false, _serverAddress, _accessToken) var subtitleProfiles = streamInfo.GetSubtitleProfiles(_mediaEncoder, false, _serverAddress, _accessToken);
.Where(subtitle => subtitle.DeliveryMethod == SubtitleDeliveryMethod.External)
.ToList();
foreach (var subtitle in subtitleProfiles) foreach (var subtitle in subtitleProfiles)
{ {
if (subtitle.DeliveryMethod != SubtitleDeliveryMethod.External)
{
continue;
}
var subtitleAdded = AddSubtitleElement(writer, subtitle); var subtitleAdded = AddSubtitleElement(writer, subtitle);
if (subtitleAdded && _profile.EnableSingleSubtitleLimit) if (subtitleAdded && _profile.EnableSingleSubtitleLimit)
@ -250,7 +262,8 @@ namespace Emby.Dlna.Didl
private bool AddSubtitleElement(XmlWriter writer, SubtitleStreamInfo info) private bool AddSubtitleElement(XmlWriter writer, SubtitleStreamInfo info)
{ {
var subtitleProfile = _profile.SubtitleProfiles var subtitleProfile = _profile.SubtitleProfiles
.FirstOrDefault(i => string.Equals(info.Format, i.Format, StringComparison.OrdinalIgnoreCase) && i.Method == SubtitleDeliveryMethod.External); .FirstOrDefault(i => string.Equals(info.Format, i.Format, StringComparison.OrdinalIgnoreCase)
&& i.Method == SubtitleDeliveryMethod.External);
if (subtitleProfile == null) if (subtitleProfile == null)
{ {
@ -387,91 +400,39 @@ namespace Emby.Dlna.Didl
private string GetDisplayName(BaseItem item, StubType? itemStubType, BaseItem context) private string GetDisplayName(BaseItem item, StubType? itemStubType, BaseItem context)
{ {
if (itemStubType.HasValue && itemStubType.Value == StubType.Latest) if (itemStubType.HasValue)
{ {
return _localization.GetLocalizedString("Latest"); switch (itemStubType.Value)
} {
if (itemStubType.HasValue && itemStubType.Value == StubType.Playlists) case StubType.Latest: return _localization.GetLocalizedString("Latest");
{ case StubType.Playlists: return _localization.GetLocalizedString("Playlists");
return _localization.GetLocalizedString("Playlists"); case StubType.AlbumArtists: return _localization.GetLocalizedString("HeaderAlbumArtists");
} case StubType.Albums: return _localization.GetLocalizedString("Albums");
if (itemStubType.HasValue && itemStubType.Value == StubType.AlbumArtists) case StubType.Artists: return _localization.GetLocalizedString("Artists");
{ case StubType.Songs: return _localization.GetLocalizedString("Songs");
return _localization.GetLocalizedString("HeaderAlbumArtists"); case StubType.Genres: return _localization.GetLocalizedString("Genres");
} case StubType.FavoriteAlbums: return _localization.GetLocalizedString("HeaderFavoriteAlbums");
if (itemStubType.HasValue && itemStubType.Value == StubType.Albums) case StubType.FavoriteArtists: return _localization.GetLocalizedString("HeaderFavoriteArtists");
{ case StubType.FavoriteSongs: return _localization.GetLocalizedString("HeaderFavoriteSongs");
return _localization.GetLocalizedString("Albums"); case StubType.ContinueWatching: return _localization.GetLocalizedString("HeaderContinueWatching");
} case StubType.Movies: return _localization.GetLocalizedString("Movies");
if (itemStubType.HasValue && itemStubType.Value == StubType.Artists) case StubType.Collections: return _localization.GetLocalizedString("Collections");
{ case StubType.Favorites: return _localization.GetLocalizedString("Favorites");
return _localization.GetLocalizedString("Artists"); case StubType.NextUp: return _localization.GetLocalizedString("HeaderNextUp");
} case StubType.FavoriteSeries: return _localization.GetLocalizedString("HeaderFavoriteShows");
if (itemStubType.HasValue && itemStubType.Value == StubType.Songs) case StubType.FavoriteEpisodes: return _localization.GetLocalizedString("HeaderFavoriteEpisodes");
{ case StubType.Series: return _localization.GetLocalizedString("Shows");
return _localization.GetLocalizedString("Songs"); default: break;
} }
if (itemStubType.HasValue && itemStubType.Value == StubType.Genres)
{
return _localization.GetLocalizedString("Genres");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteAlbums)
{
return _localization.GetLocalizedString("HeaderFavoriteAlbums");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteArtists)
{
return _localization.GetLocalizedString("HeaderFavoriteArtists");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteSongs)
{
return _localization.GetLocalizedString("HeaderFavoriteSongs");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.ContinueWatching)
{
return _localization.GetLocalizedString("HeaderContinueWatching");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.Movies)
{
return _localization.GetLocalizedString("Movies");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.Collections)
{
return _localization.GetLocalizedString("Collections");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.Favorites)
{
return _localization.GetLocalizedString("Favorites");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.NextUp)
{
return _localization.GetLocalizedString("HeaderNextUp");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteSeries)
{
return _localization.GetLocalizedString("HeaderFavoriteShows");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteEpisodes)
{
return _localization.GetLocalizedString("HeaderFavoriteEpisodes");
}
if (itemStubType.HasValue && itemStubType.Value == StubType.Series)
{
return _localization.GetLocalizedString("Shows");
} }
var episode = item as Episode; if (item is Episode episode && context is Season season)
var season = context as Season;
if (episode != null && season != null)
{ {
// This is a special embedded within a season // This is a special embedded within a season
if (item.ParentIndexNumber.HasValue && item.ParentIndexNumber.Value == 0) if (item.ParentIndexNumber.HasValue && item.ParentIndexNumber.Value == 0
&& season.IndexNumber.HasValue && season.IndexNumber.Value != 0)
{ {
if (season.IndexNumber.HasValue && season.IndexNumber.Value != 0) return string.Format(_localization.GetLocalizedString("ValueSpecialEpisodeName"), item.Name);
{
return string.Format(_localization.GetLocalizedString("ValueSpecialEpisodeName"), item.Name);
}
} }
if (item.IndexNumber.HasValue) if (item.IndexNumber.HasValue)
@ -585,10 +546,8 @@ namespace Emby.Dlna.Didl
public static bool IsIdRoot(string id) public static bool IsIdRoot(string id)
{ {
if (string.IsNullOrWhiteSpace(id) || if (string.IsNullOrWhiteSpace(id)
|| string.Equals(id, "0", StringComparison.OrdinalIgnoreCase)
string.Equals(id, "0", StringComparison.OrdinalIgnoreCase)
// Samsung sometimes uses 1 as root // Samsung sometimes uses 1 as root
|| string.Equals(id, "1", StringComparison.OrdinalIgnoreCase)) || string.Equals(id, "1", StringComparison.OrdinalIgnoreCase))
{ {
@ -1112,7 +1071,7 @@ namespace Emby.Dlna.Didl
}; };
} }
class ImageDownloadInfo private class ImageDownloadInfo
{ {
internal Guid ItemId; internal Guid ItemId;
internal string ImageTag; internal string ImageTag;
@ -1128,7 +1087,7 @@ namespace Emby.Dlna.Didl
internal ItemImageInfo ItemImageInfo; internal ItemImageInfo ItemImageInfo;
} }
class ImageUrlInfo private class ImageUrlInfo
{ {
internal string Url; internal string Url;

View File

@ -39,12 +39,7 @@ namespace Emby.Dlna.PlayTo
public TimeSpan? Duration { get; set; } public TimeSpan? Duration { get; set; }
private TimeSpan _position = TimeSpan.FromSeconds(0); public TimeSpan Position { get; set; } = TimeSpan.FromSeconds(0);
public TimeSpan Position
{
get => _position;
set => _position = value;
}
public TRANSPORTSTATE TransportState { get; private set; } public TRANSPORTSTATE TransportState { get; private set; }
@ -60,7 +55,6 @@ namespace Emby.Dlna.PlayTo
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IServerConfigurationManager _config; private readonly IServerConfigurationManager _config;
public DateTime DateLastActivity { get; private set; }
public Action OnDeviceUnavailable { get; set; } public Action OnDeviceUnavailable { get; set; }
public Device(DeviceInfo deviceProperties, IHttpClient httpClient, ILogger logger, IServerConfigurationManager config) public Device(DeviceInfo deviceProperties, IHttpClient httpClient, ILogger logger, IServerConfigurationManager config)
@ -115,7 +109,9 @@ namespace Emby.Dlna.PlayTo
lock (_timerLock) lock (_timerLock)
{ {
if (_disposed) if (_disposed)
{
return; return;
}
_volumeRefreshActive = true; _volumeRefreshActive = true;
@ -132,7 +128,9 @@ namespace Emby.Dlna.PlayTo
lock (_timerLock) lock (_timerLock)
{ {
if (_disposed) if (_disposed)
{
return; return;
}
_volumeRefreshActive = false; _volumeRefreshActive = false;
@ -140,11 +138,6 @@ namespace Emby.Dlna.PlayTo
} }
} }
public void OnPlaybackStartedExternally()
{
RestartTimer(true);
}
#region Commanding #region Commanding
public Task VolumeDown(CancellationToken cancellationToken) public Task VolumeDown(CancellationToken cancellationToken)
@ -165,7 +158,7 @@ namespace Emby.Dlna.PlayTo
{ {
if (IsMuted) if (IsMuted)
{ {
return Unmute(cancellationToken); return UnMute(cancellationToken);
} }
return Mute(cancellationToken); return Mute(cancellationToken);
@ -181,7 +174,7 @@ namespace Emby.Dlna.PlayTo
} }
} }
public async Task Unmute(CancellationToken cancellationToken) public async Task UnMute(CancellationToken cancellationToken)
{ {
var success = await SetMute(false, cancellationToken).ConfigureAwait(true); var success = await SetMute(false, cancellationToken).ConfigureAwait(true);
@ -329,7 +322,9 @@ namespace Emby.Dlna.PlayTo
private string CreateDidlMeta(string value) private string CreateDidlMeta(string value)
{ {
if (string.IsNullOrEmpty(value)) if (string.IsNullOrEmpty(value))
{
return string.Empty; return string.Empty;
}
return DescriptionXmlBuilder.Escape(value); return DescriptionXmlBuilder.Escape(value);
} }
@ -338,10 +333,11 @@ namespace Emby.Dlna.PlayTo
{ {
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Play"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Play");
if (command == null) if (command == null)
{
return Task.CompletedTask; return Task.CompletedTask;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
if (service == null) if (service == null)
{ {
throw new InvalidOperationException("Unable to find service"); throw new InvalidOperationException("Unable to find service");
@ -365,7 +361,9 @@ namespace Emby.Dlna.PlayTo
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Stop"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Stop");
if (command == null) if (command == null)
{
return; return;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
@ -381,7 +379,9 @@ namespace Emby.Dlna.PlayTo
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Pause"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Pause");
if (command == null) if (command == null)
{
return; return;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
@ -401,7 +401,9 @@ namespace Emby.Dlna.PlayTo
private async void TimerCallback(object sender) private async void TimerCallback(object sender)
{ {
if (_disposed) if (_disposed)
{
return; return;
}
try try
{ {
@ -421,8 +423,6 @@ namespace Emby.Dlna.PlayTo
return; return;
} }
DateLastActivity = DateTime.UtcNow;
if (transportState.HasValue) if (transportState.HasValue)
{ {
// If we're not playing anything no need to get additional data // If we're not playing anything no need to get additional data
@ -501,7 +501,9 @@ namespace Emby.Dlna.PlayTo
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;
}
var service = GetServiceRenderingControl(); var service = GetServiceRenderingControl();
@ -514,13 +516,17 @@ namespace Emby.Dlna.PlayTo
.ConfigureAwait(false); .ConfigureAwait(false);
if (result == null || result.Document == null) if (result == null || result.Document == null)
{
return; return;
}
var volume = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i != null); var volume = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i != null);
var volumeValue = volume == null ? null : volume.Value; var volumeValue = volume?.Value;
if (string.IsNullOrWhiteSpace(volumeValue)) if (string.IsNullOrWhiteSpace(volumeValue))
{
return; return;
}
Volume = int.Parse(volumeValue, UsCulture); Volume = int.Parse(volumeValue, UsCulture);
@ -541,7 +547,9 @@ namespace Emby.Dlna.PlayTo
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;
}
var service = GetServiceRenderingControl(); var service = GetServiceRenderingControl();
@ -556,39 +564,44 @@ namespace Emby.Dlna.PlayTo
if (result == null || result.Document == null) if (result == null || result.Document == null)
return; return;
var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse").Select(i => i.Element("CurrentMute")).FirstOrDefault(i => i != null); var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse")
var value = valueNode == null ? null : valueNode.Value; .Select(i => i.Element("CurrentMute"))
.FirstOrDefault(i => i != null);
IsMuted = string.Equals(value, "1", StringComparison.OrdinalIgnoreCase); IsMuted = string.Equals(valueNode?.Value, "1", StringComparison.OrdinalIgnoreCase);
} }
private async Task<TRANSPORTSTATE?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken) private async Task<TRANSPORTSTATE?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken)
{ {
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetTransportInfo"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetTransportInfo");
if (command == null) if (command == null)
{
return null; return null;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
if (service == null) if (service == null)
{
return null; return null;
}
var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false) var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false)
.ConfigureAwait(false); .ConfigureAwait(false);
if (result == null || result.Document == null) if (result == null || result.Document == null)
{
return null; return null;
}
var transportState = var transportState =
result.Document.Descendants(uPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i != null); result.Document.Descendants(uPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i != null);
var transportStateValue = transportState == null ? null : transportState.Value; var transportStateValue = transportState == null ? null : transportState.Value;
if (transportStateValue != null) if (transportStateValue != null
&& Enum.TryParse(transportStateValue, true, out TRANSPORTSTATE state))
{ {
if (Enum.TryParse(transportStateValue, true, out TRANSPORTSTATE state)) return state;
{
return state;
}
} }
return null; return null;
@ -598,10 +611,11 @@ namespace Emby.Dlna.PlayTo
{ {
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMediaInfo"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMediaInfo");
if (command == null) if (command == null)
{
return null; return null;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
if (service == null) if (service == null)
{ {
throw new InvalidOperationException("Unable to find service"); throw new InvalidOperationException("Unable to find service");
@ -613,7 +627,9 @@ namespace Emby.Dlna.PlayTo
.ConfigureAwait(false); .ConfigureAwait(false);
if (result == null || result.Document == null) if (result == null || result.Document == null)
{
return null; return null;
}
var track = result.Document.Descendants("CurrentURIMetaData").FirstOrDefault(); var track = result.Document.Descendants("CurrentURIMetaData").FirstOrDefault();
@ -653,11 +669,13 @@ namespace Emby.Dlna.PlayTo
return null; return null;
} }
private async Task<Tuple<bool, uBaseObject>> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken) private async Task<(bool, uBaseObject)> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken)
{ {
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetPositionInfo"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetPositionInfo");
if (command == null) if (command == null)
return new Tuple<bool, uBaseObject>(false, null); {
return (false, null);
}
var service = GetAvTransportService(); var service = GetAvTransportService();
@ -672,7 +690,9 @@ namespace Emby.Dlna.PlayTo
.ConfigureAwait(false); .ConfigureAwait(false);
if (result == null || result.Document == null) if (result == null || result.Document == null)
return new Tuple<bool, uBaseObject>(false, null); {
return (false, null);
}
var trackUriElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackURI")).FirstOrDefault(i => i != null); 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 trackUri = trackUriElem == null ? null : trackUriElem.Value;
@ -680,8 +700,8 @@ namespace Emby.Dlna.PlayTo
var durationElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i != null); var durationElem = result.Document.Descendants(uPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i != null);
var duration = durationElem == null ? null : durationElem.Value; var duration = durationElem == null ? null : durationElem.Value;
if (!string.IsNullOrWhiteSpace(duration) && if (!string.IsNullOrWhiteSpace(duration)
!string.Equals(duration, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase)) && !string.Equals(duration, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{ {
Duration = TimeSpan.Parse(duration, UsCulture); Duration = TimeSpan.Parse(duration, UsCulture);
} }
@ -703,14 +723,14 @@ namespace Emby.Dlna.PlayTo
if (track == null) if (track == null)
{ {
//If track is null, some vendors do this, use GetMediaInfo instead //If track is null, some vendors do this, use GetMediaInfo instead
return new Tuple<bool, uBaseObject>(true, null); return (true, null);
} }
var trackString = (string)track; var trackString = (string)track;
if (string.IsNullOrWhiteSpace(trackString) || string.Equals(trackString, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrWhiteSpace(trackString) || string.Equals(trackString, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
{ {
return new Tuple<bool, uBaseObject>(true, null); return (true, null);
} }
XElement uPnpResponse; XElement uPnpResponse;
@ -731,7 +751,7 @@ namespace Emby.Dlna.PlayTo
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Unable to parse xml {0}", trackString); _logger.LogError(ex, "Unable to parse xml {0}", trackString);
return new Tuple<bool, uBaseObject>(true, null); return (true, null);
} }
} }
@ -739,7 +759,7 @@ namespace Emby.Dlna.PlayTo
var uTrack = CreateUBaseObject(e, trackUri); var uTrack = CreateUBaseObject(e, trackUri);
return new Tuple<bool, uBaseObject>(true, uTrack); return (true, uTrack);
} }
private static uBaseObject CreateUBaseObject(XElement container, string trackUri) private static uBaseObject CreateUBaseObject(XElement container, string trackUri)
@ -797,11 +817,9 @@ namespace Emby.Dlna.PlayTo
private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken) private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken)
{ {
var avCommands = AvCommands; if (AvCommands != null)
if (avCommands != null)
{ {
return avCommands; return AvCommands;
} }
if (_disposed) if (_disposed)
@ -821,18 +839,15 @@ namespace Emby.Dlna.PlayTo
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
avCommands = TransportCommands.Create(document); AvCommands = TransportCommands.Create(document);
AvCommands = avCommands; return AvCommands;
return avCommands;
} }
private async Task<TransportCommands> GetRenderingProtocolAsync(CancellationToken cancellationToken) private async Task<TransportCommands> GetRenderingProtocolAsync(CancellationToken cancellationToken)
{ {
var rendererCommands = RendererCommands; if (RendererCommands != null)
if (rendererCommands != null)
{ {
return rendererCommands; return RendererCommands;
} }
if (_disposed) if (_disposed)
@ -841,7 +856,6 @@ namespace Emby.Dlna.PlayTo
} }
var avService = GetServiceRenderingControl(); var avService = GetServiceRenderingControl();
if (avService == null) if (avService == null)
{ {
throw new ArgumentException("Device AvService is null"); throw new ArgumentException("Device AvService is null");
@ -853,9 +867,8 @@ namespace Emby.Dlna.PlayTo
_logger.LogDebug("Dlna Device.GetRenderingProtocolAsync"); _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync");
var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
rendererCommands = TransportCommands.Create(document); RendererCommands = TransportCommands.Create(document);
RendererCommands = rendererCommands; return RendererCommands;
return rendererCommands;
} }
private string NormalizeUrl(string baseUrl, string url) private string NormalizeUrl(string baseUrl, string url)
@ -867,24 +880,21 @@ namespace Emby.Dlna.PlayTo
} }
if (!url.Contains("/")) if (!url.Contains("/"))
{
url = "/dmr/" + url; url = "/dmr/" + url;
}
if (!url.StartsWith("/")) if (!url.StartsWith("/"))
{
url = "/" + url; url = "/" + url;
}
return baseUrl + url; return baseUrl + url;
} }
private TransportCommands AvCommands private TransportCommands AvCommands { get; set; }
{
get;
set;
}
private TransportCommands RendererCommands private TransportCommands RendererCommands { get; set; }
{
get;
set;
}
public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, CancellationToken cancellationToken) public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, CancellationToken cancellationToken)
{ {
@ -892,8 +902,6 @@ namespace Emby.Dlna.PlayTo
var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false); var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false);
var deviceProperties = new DeviceInfo();
var friendlyNames = new List<string>(); var friendlyNames = new List<string>();
var name = document.Descendants(uPnpNamespaces.ud.GetName("friendlyName")).FirstOrDefault(); var name = document.Descendants(uPnpNamespaces.ud.GetName("friendlyName")).FirstOrDefault();
@ -908,7 +916,11 @@ namespace Emby.Dlna.PlayTo
friendlyNames.Add(room.Value); friendlyNames.Add(room.Value);
} }
deviceProperties.Name = string.Join(" ", friendlyNames); var deviceProperties = new DeviceInfo()
{
Name = string.Join(" ", friendlyNames),
BaseUrl = string.Format("http://{0}:{1}", url.Host, url.Port)
};
var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault(); var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault();
if (model != null) if (model != null)
@ -964,8 +976,6 @@ namespace Emby.Dlna.PlayTo
deviceProperties.ModelDescription = modelDescription.Value; deviceProperties.ModelDescription = modelDescription.Value;
} }
deviceProperties.BaseUrl = string.Format("http://{0}:{1}", url.Host, url.Port);
var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault(); var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault();
if (icon != null) if (icon != null)
{ {
@ -980,7 +990,6 @@ namespace Emby.Dlna.PlayTo
} }
var servicesList = services.Descendants(uPnpNamespaces.ud.GetName("service")); var servicesList = services.Descendants(uPnpNamespaces.ud.GetName("service"));
if (servicesList == null) if (servicesList == null)
{ {
continue; continue;
@ -997,9 +1006,7 @@ namespace Emby.Dlna.PlayTo
} }
} }
var device = new Device(deviceProperties, httpClient, logger, config); return new Device(deviceProperties, httpClient, logger, config);
return device;
} }
#endregion #endregion
@ -1127,23 +1134,29 @@ namespace Emby.Dlna.PlayTo
#region IDisposable #region IDisposable
bool _disposed; bool _disposed;
public void Dispose() public void Dispose()
{ {
if (!_disposed) Dispose(true);
{ GC.SuppressFinalize(this);
_disposed = true;
DisposeTimer();
}
} }
private void DisposeTimer() protected virtual void Dispose(bool disposing)
{ {
if (_timer != null) if (_disposed)
{ {
_timer.Dispose(); return;
_timer = null;
} }
if (disposing)
{
_timer?.Dispose();
}
_timer = null;
Properties = null;
_disposed = true;
} }
#endregion #endregion

View File

@ -42,30 +42,43 @@ namespace Emby.Dlna.PlayTo
private readonly IDeviceDiscovery _deviceDiscovery; private readonly IDeviceDiscovery _deviceDiscovery;
private readonly string _serverAddress; private readonly string _serverAddress;
private readonly string _accessToken; private readonly string _accessToken;
private readonly DateTime _creationTime;
public bool IsSessionActive => !_disposed && _device != null; public bool IsSessionActive => !_disposed && _device != null;
public bool SupportsMediaControl => IsSessionActive; public bool SupportsMediaControl => IsSessionActive;
public PlayToController(SessionInfo session, ISessionManager sessionManager, ILibraryManager libraryManager, ILogger logger, IDlnaManager dlnaManager, IUserManager userManager, IImageProcessor imageProcessor, string serverAddress, string accessToken, IDeviceDiscovery deviceDiscovery, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IConfigurationManager config, IMediaEncoder mediaEncoder) public PlayToController(
SessionInfo session,
ISessionManager sessionManager,
ILibraryManager libraryManager,
ILogger logger,
IDlnaManager dlnaManager,
IUserManager userManager,
IImageProcessor imageProcessor,
string serverAddress,
string accessToken,
IDeviceDiscovery deviceDiscovery,
IUserDataManager userDataManager,
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
IConfigurationManager config,
IMediaEncoder mediaEncoder)
{ {
_session = session; _session = session;
_sessionManager = sessionManager; _sessionManager = sessionManager;
_libraryManager = libraryManager; _libraryManager = libraryManager;
_logger = logger;
_dlnaManager = dlnaManager; _dlnaManager = dlnaManager;
_userManager = userManager; _userManager = userManager;
_imageProcessor = imageProcessor; _imageProcessor = imageProcessor;
_serverAddress = serverAddress; _serverAddress = serverAddress;
_accessToken = accessToken;
_deviceDiscovery = deviceDiscovery; _deviceDiscovery = deviceDiscovery;
_userDataManager = userDataManager; _userDataManager = userDataManager;
_localization = localization; _localization = localization;
_mediaSourceManager = mediaSourceManager; _mediaSourceManager = mediaSourceManager;
_config = config; _config = config;
_mediaEncoder = mediaEncoder; _mediaEncoder = mediaEncoder;
_accessToken = accessToken;
_logger = logger;
_creationTime = DateTime.UtcNow;
} }
public void Init(Device device) public void Init(Device device)
@ -374,9 +387,7 @@ namespace Emby.Dlna.PlayTo
return _device.IsPaused ? _device.SetPlay(CancellationToken.None) : _device.SetPause(CancellationToken.None); return _device.IsPaused ? _device.SetPlay(CancellationToken.None) : _device.SetPause(CancellationToken.None);
case PlaystateCommand.Seek: case PlaystateCommand.Seek:
{ return Seek(command.SeekPositionTicks ?? 0);
return Seek(command.SeekPositionTicks ?? 0);
}
case PlaystateCommand.NextTrack: case PlaystateCommand.NextTrack:
return SetPlaylistIndex(_currentPlaylistIndex + 1); return SetPlaylistIndex(_currentPlaylistIndex + 1);
@ -442,8 +453,7 @@ namespace Emby.Dlna.PlayTo
var profile = _dlnaManager.GetProfile(deviceInfo.ToDeviceIdentification()) ?? var profile = _dlnaManager.GetProfile(deviceInfo.ToDeviceIdentification()) ??
_dlnaManager.GetDefaultProfile(); _dlnaManager.GetDefaultProfile();
var hasMediaSources = item as IHasMediaSources; var mediaSources = item is IHasMediaSources
var mediaSources = hasMediaSources != null
? (_mediaSourceManager.GetStaticMediaSources(item, true, user)) ? (_mediaSourceManager.GetStaticMediaSources(item, true, user))
: new List<MediaSourceInfo>(); : new List<MediaSourceInfo>();
@ -452,7 +462,7 @@ namespace Emby.Dlna.PlayTo
playlistItem.StreamUrl = DidlBuilder.NormalizeDlnaMediaUrl(playlistItem.StreamInfo.ToUrl(_serverAddress, _accessToken)); playlistItem.StreamUrl = DidlBuilder.NormalizeDlnaMediaUrl(playlistItem.StreamInfo.ToUrl(_serverAddress, _accessToken));
var itemXml = new DidlBuilder(profile, user, _imageProcessor, _serverAddress, _accessToken, _userDataManager, _localization, _mediaSourceManager, _logger, _libraryManager, _mediaEncoder) var itemXml = new DidlBuilder(profile, user, _imageProcessor, _serverAddress, _accessToken, _userDataManager, _localization, _mediaSourceManager, _logger, _mediaEncoder)
.GetItemDidl(_config.GetDlnaConfiguration(), item, user, null, _session.DeviceId, new Filter(), playlistItem.StreamInfo); .GetItemDidl(_config.GetDlnaConfiguration(), item, user, null, _session.DeviceId, new Filter(), playlistItem.StreamInfo);
playlistItem.Didl = itemXml; playlistItem.Didl = itemXml;
@ -631,7 +641,7 @@ namespace Emby.Dlna.PlayTo
case GeneralCommandType.Mute: case GeneralCommandType.Mute:
return _device.Mute(cancellationToken); return _device.Mute(cancellationToken);
case GeneralCommandType.Unmute: case GeneralCommandType.Unmute:
return _device.Unmute(cancellationToken); return _device.UnMute(cancellationToken);
case GeneralCommandType.ToggleMute: case GeneralCommandType.ToggleMute:
return _device.ToggleMute(cancellationToken); return _device.ToggleMute(cancellationToken);
case GeneralCommandType.SetAudioStreamIndex: case GeneralCommandType.SetAudioStreamIndex: