jellyfin-server/Emby.Dlna/DlnaManager.cs

576 lines
20 KiB
C#
Raw Normal View History

#nullable disable
#pragma warning disable CS1591
using System;
2019-01-13 19:16:19 +00:00
using System.Collections.Generic;
using System.Globalization;
2019-01-13 19:16:19 +00:00
using System.IO;
using System.Linq;
using System.Reflection;
2019-01-13 19:16:19 +00:00
using System.Text;
using System.Text.Json;
2019-01-13 19:16:19 +00:00
using System.Text.RegularExpressions;
2019-01-27 14:40:37 +00:00
using System.Threading.Tasks;
2019-01-13 19:16:19 +00:00
using Emby.Dlna.Profiles;
using Emby.Dlna.Server;
using MediaBrowser.Common.Configuration;
2016-10-29 22:22:20 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Json;
2016-10-29 22:22:20 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Dlna;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.IO;
2019-01-13 19:16:19 +00:00
using MediaBrowser.Model.Serialization;
using Microsoft.AspNetCore.Http;
2019-01-13 19:16:19 +00:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
2016-10-29 22:22:20 +00:00
2016-10-29 22:34:54 +00:00
namespace Emby.Dlna
2016-10-29 22:22:20 +00:00
{
public class DlnaManager : IDlnaManager
{
private readonly IApplicationPaths _appPaths;
private readonly IXmlSerializer _xmlSerializer;
private readonly IFileSystem _fileSystem;
2020-06-06 00:15:56 +00:00
private readonly ILogger<DlnaManager> _logger;
2016-10-29 22:22:20 +00:00
private readonly IServerApplicationHost _appHost;
private static readonly Assembly _assembly = typeof(DlnaManager).Assembly;
2021-03-09 04:57:38 +00:00
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
2016-10-29 22:22:20 +00:00
private readonly Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>> _profiles = new Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>>(StringComparer.Ordinal);
public DlnaManager(
IXmlSerializer xmlSerializer,
2016-10-29 22:22:20 +00:00
IFileSystem fileSystem,
IApplicationPaths appPaths,
ILoggerFactory loggerFactory,
IServerApplicationHost appHost)
2016-10-29 22:22:20 +00:00
{
_xmlSerializer = xmlSerializer;
_fileSystem = fileSystem;
_appPaths = appPaths;
2020-06-06 00:15:56 +00:00
_logger = loggerFactory.CreateLogger<DlnaManager>();
2016-10-29 22:22:20 +00:00
_appHost = appHost;
}
2020-08-07 17:26:28 +00:00
private string UserProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user");
private string SystemProfilesPath => Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system");
2019-01-27 14:40:37 +00:00
public async Task InitProfilesAsync()
2016-10-29 22:22:20 +00:00
{
try
{
2020-08-07 17:26:28 +00:00
await ExtractSystemProfilesAsync().ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
LoadProfiles();
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error extracting DLNA profiles.");
2016-10-29 22:22:20 +00:00
}
}
private void LoadProfiles()
{
var list = GetProfiles(UserProfilesPath, DeviceProfileType.User)
.OrderBy(i => i.Name)
.ToList();
list.AddRange(GetProfiles(SystemProfilesPath, DeviceProfileType.System)
.OrderBy(i => i.Name));
}
public IEnumerable<DeviceProfile> GetProfiles()
{
lock (_profiles)
{
var list = _profiles.Values.ToList();
return list
.OrderBy(i => i.Item1.Info.Type == DeviceProfileType.User ? 0 : 1)
.ThenBy(i => i.Item1.Info.Name)
.Select(i => i.Item2)
.ToList();
}
}
public DeviceProfile GetDefaultProfile()
{
return new DefaultProfile();
}
public DeviceProfile GetProfile(DeviceIdentification deviceInfo)
{
if (deviceInfo == null)
{
throw new ArgumentNullException(nameof(deviceInfo));
2016-10-29 22:22:20 +00:00
}
2021-04-20 17:08:19 +00:00
var profile = GetProfiles()
.FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification));
if (profile != null)
2016-10-29 22:22:20 +00:00
{
2021-04-20 17:08:19 +00:00
_logger.LogDebug("Found matching device profile: {ProfileName}", profile.Name);
2016-10-29 22:22:20 +00:00
}
2021-04-20 17:08:19 +00:00
else
2016-10-29 22:22:20 +00:00
{
2021-04-20 17:08:19 +00:00
LogUnmatchedProfile(deviceInfo);
2016-10-29 22:22:20 +00:00
}
2021-04-20 17:08:19 +00:00
return profile;
2016-10-29 22:22:20 +00:00
}
private void LogUnmatchedProfile(DeviceIdentification profile)
{
var builder = new StringBuilder();
builder.AppendLine("No matching device profile found. The default will need to be used.");
2021-04-10 15:09:45 +00:00
builder.Append("FriendlyName: ").AppendLine(profile.FriendlyName);
builder.Append("Manufacturer: ").AppendLine(profile.Manufacturer);
builder.Append("ManufacturerUrl: ").AppendLine(profile.ManufacturerUrl);
builder.Append("ModelDescription: ").AppendLine(profile.ModelDescription);
builder.Append("ModelName: ").AppendLine(profile.ModelName);
builder.Append("ModelNumber: ").AppendLine(profile.ModelNumber);
builder.Append("ModelUrl: ").AppendLine(profile.ModelUrl);
builder.Append("SerialNumber: ").AppendLine(profile.SerialNumber);
2016-10-29 22:22:20 +00:00
_logger.LogInformation(builder.ToString());
2016-10-29 22:22:20 +00:00
}
2021-04-19 13:07:14 +00:00
/// <summary>
/// Attempts to match a device with a profile.
/// Rules:
/// - If the profile field has no value, the field matches irregardless of its contents.
/// - the profile field can be an exact match, or a reg exp.
/// </summary>
/// <param name="deviceInfo">The <see cref="DeviceIdentification"/> of the device.</param>
/// <param name="profileInfo">The <see cref="DeviceIdentification"/> of the profile.</param>
/// <returns><b>True</b> if they match.</returns>
2021-04-20 17:04:16 +00:00
public bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo)
2016-10-29 22:22:20 +00:00
{
2021-04-19 13:24:58 +00:00
return IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)
2021-04-21 09:18:29 +00:00
&& IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)
&& IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)
&& IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)
&& IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)
&& IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)
&& IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)
&& IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber);
2016-10-29 22:22:20 +00:00
}
2021-04-20 17:04:16 +00:00
private bool IsRegexOrSubstringMatch(string input, string pattern)
2016-10-29 22:22:20 +00:00
{
2021-04-19 13:07:14 +00:00
if (string.IsNullOrEmpty(pattern))
{
// In profile identification: An empty pattern matches anything.
return true;
}
if (string.IsNullOrEmpty(input))
{
// The profile contains a value, and the device doesn't.
return false;
}
2021-04-20 17:14:23 +00:00
try
{
return input.Equals(pattern, StringComparison.OrdinalIgnoreCase)
2021-04-20 17:17:48 +00:00
|| Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
2021-04-20 17:14:23 +00:00
}
catch (ArgumentException ex)
{
_logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern);
return false;
}
2016-10-29 22:22:20 +00:00
}
public DeviceProfile GetProfile(IHeaderDictionary headers)
2016-10-29 22:22:20 +00:00
{
if (headers == null)
{
throw new ArgumentNullException(nameof(headers));
2016-10-29 22:22:20 +00:00
}
var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
if (profile != null)
{
_logger.LogDebug("Found matching device profile: {0}", profile.Name);
2016-10-29 22:22:20 +00:00
}
else
{
2020-08-07 17:26:28 +00:00
var headerString = string.Join(", ", headers.Select(i => string.Format(CultureInfo.InvariantCulture, "{0}={1}", i.Key, i.Value)));
_logger.LogDebug("No matching device profile found. {0}", headerString);
2016-10-29 22:22:20 +00:00
}
return profile;
}
private bool IsMatch(IHeaderDictionary headers, DeviceIdentification profileInfo)
2016-10-29 22:22:20 +00:00
{
return profileInfo.Headers.Any(i => IsMatch(headers, i));
}
private bool IsMatch(IHeaderDictionary headers, HttpHeaderInfo header)
2016-10-29 22:22:20 +00:00
{
2016-11-20 19:40:35 +00:00
// Handle invalid user setup
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(header.Name))
2016-11-20 19:40:35 +00:00
{
return false;
}
if (headers.TryGetValue(header.Name, out StringValues value))
2016-10-29 22:22:20 +00:00
{
switch (header.Match)
{
case HeaderMatchType.Equals:
return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
case HeaderMatchType.Substring:
var isMatch = value.ToString().IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
2020-06-14 09:11:11 +00:00
// _logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
2016-10-29 22:22:20 +00:00
return isMatch;
case HeaderMatchType.Regex:
return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase);
default:
throw new ArgumentException("Unrecognized HeaderMatchType");
}
}
return false;
}
private IEnumerable<DeviceProfile> GetProfiles(string path, DeviceProfileType type)
{
try
{
2017-03-29 06:26:48 +00:00
var xmlFies = _fileSystem.GetFilePaths(path)
.Where(i => string.Equals(Path.GetExtension(i), ".xml", StringComparison.OrdinalIgnoreCase))
2016-10-29 22:22:20 +00:00
.ToList();
2017-03-29 06:26:48 +00:00
return xmlFies
.Select(i => ParseProfileFile(i, type))
2016-10-29 22:22:20 +00:00
.Where(i => i != null)
.ToList();
}
2016-11-04 08:31:05 +00:00
catch (IOException)
2016-10-29 22:22:20 +00:00
{
return new List<DeviceProfile>();
}
}
private DeviceProfile ParseProfileFile(string path, DeviceProfileType type)
{
lock (_profiles)
{
if (_profiles.TryGetValue(path, out Tuple<InternalProfileInfo, DeviceProfile> profileTuple))
2016-10-29 22:22:20 +00:00
{
return profileTuple.Item2;
}
try
{
DeviceProfile profile;
2017-03-29 06:26:48 +00:00
var tempProfile = (DeviceProfile)_xmlSerializer.DeserializeFromFile(typeof(DeviceProfile), path);
2016-10-29 22:22:20 +00:00
2017-03-29 06:26:48 +00:00
profile = ReserializeProfile(tempProfile);
2016-10-29 22:22:20 +00:00
profile.Id = path.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
2016-10-29 22:22:20 +00:00
_profiles[path] = new Tuple<InternalProfileInfo, DeviceProfile>(GetInternalProfileInfo(_fileSystem.GetFileInfo(path), type), profile);
return profile;
}
catch (Exception ex)
{
2018-12-20 12:39:58 +00:00
_logger.LogError(ex, "Error parsing profile file: {Path}", path);
2016-10-29 22:22:20 +00:00
return null;
}
}
}
public DeviceProfile GetProfile(string id)
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(id))
2016-10-29 22:22:20 +00:00
{
throw new ArgumentNullException(nameof(id));
2016-10-29 22:22:20 +00:00
}
2021-03-12 22:20:13 +00:00
var info = GetProfileInfosInternal().FirstOrDefault(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase));
if (info == null)
{
return null;
}
2016-10-29 22:22:20 +00:00
return ParseProfileFile(info.Path, info.Info.Type);
}
private IEnumerable<InternalProfileInfo> GetProfileInfosInternal()
{
lock (_profiles)
{
var list = _profiles.Values.ToList();
return list
.Select(i => i.Item1)
.OrderBy(i => i.Info.Type == DeviceProfileType.User ? 0 : 1)
.ThenBy(i => i.Info.Name);
}
}
public IEnumerable<DeviceProfileInfo> GetProfileInfos()
{
return GetProfileInfosInternal().Select(i => i.Info);
}
private InternalProfileInfo GetInternalProfileInfo(FileSystemMetadata file, DeviceProfileType type)
{
return new InternalProfileInfo
{
Path = file.FullName,
Info = new DeviceProfileInfo
{
Id = file.FullName.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture),
2016-10-29 22:22:20 +00:00
Name = _fileSystem.GetFileNameWithoutExtension(file),
Type = type
}
};
}
2019-01-27 14:40:37 +00:00
private async Task ExtractSystemProfilesAsync()
2016-10-29 22:22:20 +00:00
{
2016-12-09 07:23:09 +00:00
var namespaceName = GetType().Namespace + ".Profiles.Xml.";
2016-10-29 22:22:20 +00:00
var systemProfilesPath = SystemProfilesPath;
foreach (var name in _assembly.GetManifestResourceNames())
2016-10-29 22:22:20 +00:00
{
if (!name.StartsWith(namespaceName, StringComparison.Ordinal))
{
continue;
}
2020-11-06 15:15:30 +00:00
var path = Path.Join(
systemProfilesPath,
Path.GetFileName(name.AsSpan()).Slice(namespaceName.Length));
2016-10-29 22:22:20 +00:00
using (var stream = _assembly.GetManifestResourceStream(name))
2016-10-29 22:22:20 +00:00
{
2016-11-04 08:31:05 +00:00
var fileInfo = _fileSystem.GetFileInfo(path);
2016-10-29 22:22:20 +00:00
if (!fileInfo.Exists || fileInfo.Length != stream.Length)
{
Directory.CreateDirectory(systemProfilesPath);
2016-10-29 22:22:20 +00:00
2021-03-07 13:43:28 +00:00
// use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
2016-10-29 22:22:20 +00:00
{
await stream.CopyToAsync(fileStream).ConfigureAwait(false);
2016-10-29 22:22:20 +00:00
}
}
}
}
// Not necessary, but just to make it easy to find
Directory.CreateDirectory(UserProfilesPath);
2016-10-29 22:22:20 +00:00
}
public void DeleteProfile(string id)
{
var info = GetProfileInfosInternal().First(i => string.Equals(id, i.Info.Id, StringComparison.OrdinalIgnoreCase));
if (info.Info.Type == DeviceProfileType.System)
{
throw new ArgumentException("System profiles cannot be deleted.");
}
_fileSystem.DeleteFile(info.Path);
lock (_profiles)
{
_profiles.Remove(info.Path);
}
}
public void CreateProfile(DeviceProfile profile)
{
profile = ReserializeProfile(profile);
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(profile.Name))
2016-10-29 22:22:20 +00:00
{
throw new ArgumentException("Profile is missing Name");
}
2016-12-09 07:23:09 +00:00
var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
2016-10-29 22:22:20 +00:00
var path = Path.Combine(UserProfilesPath, newFilename);
SaveProfile(profile, path, DeviceProfileType.User);
}
public void UpdateProfile(DeviceProfile profile)
{
profile = ReserializeProfile(profile);
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(profile.Id))
2016-10-29 22:22:20 +00:00
{
throw new ArgumentException("Profile is missing Id");
}
2020-06-15 21:43:52 +00:00
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(profile.Name))
2016-10-29 22:22:20 +00:00
{
throw new ArgumentException("Profile is missing Name");
}
var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase));
2016-12-09 07:23:09 +00:00
var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
2016-10-29 22:22:20 +00:00
var path = Path.Combine(UserProfilesPath, newFilename);
if (!string.Equals(path, current.Path, StringComparison.Ordinal) &&
current.Info.Type != DeviceProfileType.System)
{
_fileSystem.DeleteFile(current.Path);
}
SaveProfile(profile, path, DeviceProfileType.User);
}
private void SaveProfile(DeviceProfile profile, string path, DeviceProfileType type)
{
lock (_profiles)
{
_profiles[path] = new Tuple<InternalProfileInfo, DeviceProfile>(GetInternalProfileInfo(_fileSystem.GetFileInfo(path), type), profile);
}
2020-06-15 21:43:52 +00:00
2016-12-09 07:23:09 +00:00
SerializeToXml(profile, path);
2016-10-29 22:22:20 +00:00
}
2016-12-09 07:23:09 +00:00
internal void SerializeToXml(DeviceProfile profile, string path)
2016-10-29 22:22:20 +00:00
{
2016-12-09 07:23:09 +00:00
_xmlSerializer.SerializeToFile(profile, path);
2016-10-29 22:22:20 +00:00
}
/// <summary>
/// Recreates the object using serialization, to ensure it's not a subclass.
2020-11-18 13:23:45 +00:00
/// If it's a subclass it may not serialize properly to xml (different root element tag name).
2016-10-29 22:22:20 +00:00
/// </summary>
2020-08-20 19:04:57 +00:00
/// <param name="profile">The device profile.</param>
2020-11-18 13:23:45 +00:00
/// <returns>The re-serialized device profile.</returns>
2016-10-29 22:22:20 +00:00
private DeviceProfile ReserializeProfile(DeviceProfile profile)
{
if (profile.GetType() == typeof(DeviceProfile))
{
return profile;
}
var json = JsonSerializer.Serialize(profile, _jsonOptions);
2016-10-29 22:22:20 +00:00
return JsonSerializer.Deserialize<DeviceProfile>(json, _jsonOptions);
2016-10-29 22:22:20 +00:00
}
public string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress)
2016-10-29 22:22:20 +00:00
{
2020-09-05 20:25:47 +00:00
var profile = GetDefaultProfile();
2016-10-29 22:22:20 +00:00
var serverId = _appHost.SystemId;
return new DescriptionXmlBuilder(profile, serverUuId, serverAddress, _appHost.FriendlyName, serverId).GetXml();
}
public ImageStream GetIcon(string filename)
{
var format = filename.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
? ImageFormat.Png
: ImageFormat.Jpg;
2019-01-27 11:03:43 +00:00
var resource = GetType().Namespace + ".Images." + filename.ToLowerInvariant();
2016-11-03 22:53:02 +00:00
2016-10-29 22:22:20 +00:00
return new ImageStream
{
Format = format,
Stream = _assembly.GetManifestResourceStream(resource)
2016-10-29 22:22:20 +00:00
};
}
2020-08-20 19:04:57 +00:00
private class InternalProfileInfo
{
internal DeviceProfileInfo Info { get; set; }
internal string Path { get; set; }
}
2016-10-29 22:22:20 +00:00
}
2020-08-20 15:01:04 +00:00
2018-12-30 14:25:08 +00:00
/*
2018-12-30 12:18:38 +00:00
class DlnaProfileEntryPoint : IServerEntryPoint
2016-10-29 22:22:20 +00:00
{
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
2016-12-09 07:23:09 +00:00
private readonly IXmlSerializer _xmlSerializer;
2016-10-29 22:22:20 +00:00
2017-03-29 06:26:48 +00:00
public DlnaProfileEntryPoint(IApplicationPaths appPaths, IFileSystem fileSystem, IXmlSerializer xmlSerializer)
2016-10-29 22:22:20 +00:00
{
_appPaths = appPaths;
_fileSystem = fileSystem;
2016-12-09 07:23:09 +00:00
_xmlSerializer = xmlSerializer;
2016-10-29 22:22:20 +00:00
}
public void Run()
{
2018-09-12 17:26:21 +00:00
DumpProfiles();
2016-10-29 22:22:20 +00:00
}
private void DumpProfiles()
{
DeviceProfile[] list = new[]
2016-10-29 22:22:20 +00:00
{
new SamsungSmartTvProfile(),
new XboxOneProfile(),
new SonyPs3Profile(),
new SonyPs4Profile(),
new SonyBravia2010Profile(),
new SonyBravia2011Profile(),
new SonyBravia2012Profile(),
new SonyBravia2013Profile(),
new SonyBravia2014Profile(),
new SonyBlurayPlayer2013(),
new SonyBlurayPlayer2014(),
new SonyBlurayPlayer2015(),
new SonyBlurayPlayer2016(),
new SonyBlurayPlayerProfile(),
new PanasonicVieraProfile(),
new WdtvLiveProfile(),
new DenonAvrProfile(),
new LinksysDMA2100Profile(),
new LgTvProfile(),
new Foobar2000Profile(),
2017-01-17 02:58:47 +00:00
new SharpSmartTvProfile(),
2016-10-29 22:22:20 +00:00
new MediaMonkeyProfile(),
2020-06-14 09:11:11 +00:00
// new Windows81Profile(),
// new WindowsMediaCenterProfile(),
// new WindowsPhoneProfile(),
2016-10-29 22:22:20 +00:00
new DirectTvProfile(),
new DishHopperJoeyProfile(),
new DefaultProfile(),
2017-06-25 23:04:15 +00:00
new PopcornHourProfile(),
new MarantzProfile()
2016-10-29 22:22:20 +00:00
};
foreach (var item in list)
{
2016-12-09 07:23:09 +00:00
var path = Path.Combine(_appPaths.ProgramDataPath, _fileSystem.GetValidFilename(item.Name) + ".xml");
2016-10-29 22:22:20 +00:00
2016-12-09 07:23:09 +00:00
_xmlSerializer.SerializeToFile(item, path);
2016-10-29 22:22:20 +00:00
}
}
public void Dispose()
{
}
2018-12-30 14:25:08 +00:00
}*/
2018-12-30 12:18:38 +00:00
}