DlnaManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Plugins;
  7. using MediaBrowser.Dlna.Profiles;
  8. using MediaBrowser.Dlna.Server;
  9. using MediaBrowser.Model.Dlna;
  10. using MediaBrowser.Model.Drawing;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Text.RegularExpressions;
  19. using CommonIO;
  20. namespace MediaBrowser.Dlna
  21. {
  22. public class DlnaManager : IDlnaManager
  23. {
  24. private readonly IApplicationPaths _appPaths;
  25. private readonly IXmlSerializer _xmlSerializer;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly ILogger _logger;
  28. private readonly IJsonSerializer _jsonSerializer;
  29. private readonly IServerApplicationHost _appHost;
  30. public DlnaManager(IXmlSerializer xmlSerializer,
  31. IFileSystem fileSystem,
  32. IApplicationPaths appPaths,
  33. ILogger logger,
  34. IJsonSerializer jsonSerializer, IServerApplicationHost appHost)
  35. {
  36. _xmlSerializer = xmlSerializer;
  37. _fileSystem = fileSystem;
  38. _appPaths = appPaths;
  39. _logger = logger;
  40. _jsonSerializer = jsonSerializer;
  41. _appHost = appHost;
  42. }
  43. public IEnumerable<DeviceProfile> GetProfiles()
  44. {
  45. ExtractProfilesIfNeeded();
  46. var list = GetProfiles(UserProfilesPath, DeviceProfileType.User)
  47. .OrderBy(i => i.Name)
  48. .ToList();
  49. list.AddRange(GetProfiles(SystemProfilesPath, DeviceProfileType.System)
  50. .OrderBy(i => i.Name));
  51. return list;
  52. }
  53. private bool _extracted;
  54. private readonly object _syncLock = new object();
  55. private void ExtractProfilesIfNeeded()
  56. {
  57. if (!_extracted)
  58. {
  59. lock (_syncLock)
  60. {
  61. if (!_extracted)
  62. {
  63. try
  64. {
  65. ExtractSystemProfiles();
  66. }
  67. catch (Exception ex)
  68. {
  69. _logger.ErrorException("Error extracting DLNA profiles.", ex);
  70. }
  71. _extracted = true;
  72. }
  73. }
  74. }
  75. }
  76. public DeviceProfile GetDefaultProfile()
  77. {
  78. ExtractProfilesIfNeeded();
  79. return new DefaultProfile();
  80. }
  81. public DeviceProfile GetProfile(DeviceIdentification deviceInfo)
  82. {
  83. if (deviceInfo == null)
  84. {
  85. throw new ArgumentNullException("deviceInfo");
  86. }
  87. var profile = GetProfiles()
  88. .FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification));
  89. if (profile != null)
  90. {
  91. _logger.Debug("Found matching device profile: {0}", profile.Name);
  92. }
  93. else
  94. {
  95. _logger.Debug("No matching device profile found. The default will need to be used.");
  96. LogUnmatchedProfile(deviceInfo);
  97. }
  98. return profile;
  99. }
  100. private void LogUnmatchedProfile(DeviceIdentification profile)
  101. {
  102. var builder = new StringBuilder();
  103. builder.AppendLine(string.Format("DeviceDescription:{0}", profile.DeviceDescription ?? string.Empty));
  104. builder.AppendLine(string.Format("FriendlyName:{0}", profile.FriendlyName ?? string.Empty));
  105. builder.AppendLine(string.Format("Manufacturer:{0}", profile.Manufacturer ?? string.Empty));
  106. builder.AppendLine(string.Format("ManufacturerUrl:{0}", profile.ManufacturerUrl ?? string.Empty));
  107. builder.AppendLine(string.Format("ModelDescription:{0}", profile.ModelDescription ?? string.Empty));
  108. builder.AppendLine(string.Format("ModelName:{0}", profile.ModelName ?? string.Empty));
  109. builder.AppendLine(string.Format("ModelNumber:{0}", profile.ModelNumber ?? string.Empty));
  110. builder.AppendLine(string.Format("ModelUrl:{0}", profile.ModelUrl ?? string.Empty));
  111. builder.AppendLine(string.Format("SerialNumber:{0}", profile.SerialNumber ?? string.Empty));
  112. _logger.LogMultiline("No matching device profile found. The default will need to be used.", LogSeverity.Info, builder);
  113. }
  114. private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo)
  115. {
  116. if (!string.IsNullOrWhiteSpace(profileInfo.DeviceDescription))
  117. {
  118. if (deviceInfo.DeviceDescription == null || !IsRegexMatch(deviceInfo.DeviceDescription, profileInfo.DeviceDescription))
  119. return false;
  120. }
  121. if (!string.IsNullOrWhiteSpace(profileInfo.FriendlyName))
  122. {
  123. if (deviceInfo.FriendlyName == null || !IsRegexMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName))
  124. return false;
  125. }
  126. if (!string.IsNullOrWhiteSpace(profileInfo.Manufacturer))
  127. {
  128. if (deviceInfo.Manufacturer == null || !IsRegexMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer))
  129. return false;
  130. }
  131. if (!string.IsNullOrWhiteSpace(profileInfo.ManufacturerUrl))
  132. {
  133. if (deviceInfo.ManufacturerUrl == null || !IsRegexMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl))
  134. return false;
  135. }
  136. if (!string.IsNullOrWhiteSpace(profileInfo.ModelDescription))
  137. {
  138. if (deviceInfo.ModelDescription == null || !IsRegexMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription))
  139. return false;
  140. }
  141. if (!string.IsNullOrWhiteSpace(profileInfo.ModelName))
  142. {
  143. if (deviceInfo.ModelName == null || !IsRegexMatch(deviceInfo.ModelName, profileInfo.ModelName))
  144. return false;
  145. }
  146. if (!string.IsNullOrWhiteSpace(profileInfo.ModelNumber))
  147. {
  148. if (deviceInfo.ModelNumber == null || !IsRegexMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber))
  149. return false;
  150. }
  151. if (!string.IsNullOrWhiteSpace(profileInfo.ModelUrl))
  152. {
  153. if (deviceInfo.ModelUrl == null || !IsRegexMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl))
  154. return false;
  155. }
  156. if (!string.IsNullOrWhiteSpace(profileInfo.SerialNumber))
  157. {
  158. if (deviceInfo.SerialNumber == null || !IsRegexMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber))
  159. return false;
  160. }
  161. return true;
  162. }
  163. private bool IsRegexMatch(string input, string pattern)
  164. {
  165. try
  166. {
  167. return Regex.IsMatch(input, pattern);
  168. }
  169. catch (ArgumentException ex)
  170. {
  171. _logger.ErrorException("Error evaluating regex pattern {0}", ex, pattern);
  172. return false;
  173. }
  174. }
  175. public DeviceProfile GetProfile(IDictionary<string, string> headers)
  176. {
  177. if (headers == null)
  178. {
  179. throw new ArgumentNullException("headers");
  180. }
  181. //_logger.Debug("GetProfile. Headers: " + _jsonSerializer.SerializeToString(headers));
  182. // Convert to case insensitive
  183. headers = new Dictionary<string, string>(headers, StringComparer.OrdinalIgnoreCase);
  184. var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
  185. if (profile != null)
  186. {
  187. _logger.Debug("Found matching device profile: {0}", profile.Name);
  188. }
  189. else
  190. {
  191. string userAgent = null;
  192. headers.TryGetValue("User-Agent", out userAgent);
  193. var msg = "No matching device profile via headers found. The default will be used. ";
  194. if (!string.IsNullOrEmpty(userAgent))
  195. {
  196. msg += "User-agent: " + userAgent + ". ";
  197. }
  198. _logger.Debug(msg);
  199. }
  200. return profile;
  201. }
  202. private bool IsMatch(IDictionary<string, string> headers, DeviceIdentification profileInfo)
  203. {
  204. return profileInfo.Headers.Any(i => IsMatch(headers, i));
  205. }
  206. private bool IsMatch(IDictionary<string, string> headers, HttpHeaderInfo header)
  207. {
  208. string value;
  209. if (headers.TryGetValue(header.Name, out value))
  210. {
  211. switch (header.Match)
  212. {
  213. case HeaderMatchType.Equals:
  214. return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
  215. case HeaderMatchType.Substring:
  216. var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
  217. //_logger.Debug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
  218. return isMatch;
  219. case HeaderMatchType.Regex:
  220. // Reports of IgnoreCase not working on linux so try it a couple different ways.
  221. return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase) || Regex.IsMatch(value.ToUpper(), header.Value.ToUpper(), RegexOptions.IgnoreCase);
  222. default:
  223. throw new ArgumentException("Unrecognized HeaderMatchType");
  224. }
  225. }
  226. return false;
  227. }
  228. private string UserProfilesPath
  229. {
  230. get
  231. {
  232. return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user");
  233. }
  234. }
  235. private string SystemProfilesPath
  236. {
  237. get
  238. {
  239. return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system");
  240. }
  241. }
  242. private IEnumerable<DeviceProfile> GetProfiles(string path, DeviceProfileType type)
  243. {
  244. try
  245. {
  246. return _fileSystem.GetFiles(path)
  247. .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
  248. .Select(i => ParseProfileXmlFile(i.FullName, type))
  249. .Where(i => i != null)
  250. .ToList();
  251. }
  252. catch (DirectoryNotFoundException)
  253. {
  254. return new List<DeviceProfile>();
  255. }
  256. }
  257. private DeviceProfile ParseProfileXmlFile(string path, DeviceProfileType type)
  258. {
  259. try
  260. {
  261. var profile = (DeviceProfile)_xmlSerializer.DeserializeFromFile(typeof(DeviceProfile), path);
  262. profile.Id = path.ToLower().GetMD5().ToString("N");
  263. profile.ProfileType = type;
  264. return profile;
  265. }
  266. catch (Exception ex)
  267. {
  268. _logger.ErrorException("Error parsing profile xml: {0}", ex, path);
  269. return null;
  270. }
  271. }
  272. public DeviceProfile GetProfile(string id)
  273. {
  274. if (string.IsNullOrWhiteSpace(id))
  275. {
  276. throw new ArgumentNullException("id");
  277. }
  278. var info = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase));
  279. return ParseProfileXmlFile(info.Path, info.Info.Type);
  280. }
  281. private IEnumerable<InternalProfileInfo> GetProfileInfosInternal()
  282. {
  283. ExtractProfilesIfNeeded();
  284. return GetProfileInfos(UserProfilesPath, DeviceProfileType.User)
  285. .Concat(GetProfileInfos(SystemProfilesPath, DeviceProfileType.System))
  286. .OrderBy(i => i.Info.Type == DeviceProfileType.User ? 0 : 1)
  287. .ThenBy(i => i.Info.Name);
  288. }
  289. public IEnumerable<DeviceProfileInfo> GetProfileInfos()
  290. {
  291. return GetProfileInfosInternal().Select(i => i.Info);
  292. }
  293. private IEnumerable<InternalProfileInfo> GetProfileInfos(string path, DeviceProfileType type)
  294. {
  295. try
  296. {
  297. return _fileSystem.GetFiles(path)
  298. .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
  299. .Select(i => new InternalProfileInfo
  300. {
  301. Path = i.FullName,
  302. Info = new DeviceProfileInfo
  303. {
  304. Id = i.FullName.ToLower().GetMD5().ToString("N"),
  305. Name = _fileSystem.GetFileNameWithoutExtension(i),
  306. Type = type
  307. }
  308. })
  309. .ToList();
  310. }
  311. catch (DirectoryNotFoundException)
  312. {
  313. return new List<InternalProfileInfo>();
  314. }
  315. }
  316. private void ExtractSystemProfiles()
  317. {
  318. var assembly = GetType().Assembly;
  319. var namespaceName = GetType().Namespace + ".Profiles.Xml.";
  320. var systemProfilesPath = SystemProfilesPath;
  321. foreach (var name in assembly.GetManifestResourceNames()
  322. .Where(i => i.StartsWith(namespaceName))
  323. .ToList())
  324. {
  325. var filename = Path.GetFileName(name).Substring(namespaceName.Length);
  326. var path = Path.Combine(systemProfilesPath, filename);
  327. using (var stream = assembly.GetManifestResourceStream(name))
  328. {
  329. var fileInfo = new FileInfo(path);
  330. if (!fileInfo.Exists || fileInfo.Length != stream.Length)
  331. {
  332. _fileSystem.CreateDirectory(systemProfilesPath);
  333. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  334. {
  335. stream.CopyTo(fileStream);
  336. }
  337. }
  338. }
  339. }
  340. // Not necessary, but just to make it easy to find
  341. _fileSystem.CreateDirectory(UserProfilesPath);
  342. }
  343. public void DeleteProfile(string id)
  344. {
  345. var info = GetProfileInfosInternal().First(i => string.Equals(id, i.Info.Id, StringComparison.OrdinalIgnoreCase));
  346. if (info.Info.Type == DeviceProfileType.System)
  347. {
  348. throw new ArgumentException("System profiles cannot be deleted.");
  349. }
  350. _fileSystem.DeleteFile(info.Path);
  351. }
  352. public void CreateProfile(DeviceProfile profile)
  353. {
  354. profile = ReserializeProfile(profile);
  355. if (string.IsNullOrWhiteSpace(profile.Name))
  356. {
  357. throw new ArgumentException("Profile is missing Name");
  358. }
  359. var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
  360. var path = Path.Combine(UserProfilesPath, newFilename);
  361. _xmlSerializer.SerializeToFile(profile, path);
  362. }
  363. public void UpdateProfile(DeviceProfile profile)
  364. {
  365. profile = ReserializeProfile(profile);
  366. if (string.IsNullOrWhiteSpace(profile.Id))
  367. {
  368. throw new ArgumentException("Profile is missing Id");
  369. }
  370. if (string.IsNullOrWhiteSpace(profile.Name))
  371. {
  372. throw new ArgumentException("Profile is missing Name");
  373. }
  374. var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase));
  375. var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
  376. var path = Path.Combine(UserProfilesPath, newFilename);
  377. if (!string.Equals(path, current.Path, StringComparison.Ordinal) &&
  378. current.Info.Type != DeviceProfileType.System)
  379. {
  380. _fileSystem.DeleteFile(current.Path);
  381. }
  382. _xmlSerializer.SerializeToFile(profile, path);
  383. }
  384. /// <summary>
  385. /// Recreates the object using serialization, to ensure it's not a subclass.
  386. /// If it's a subclass it may not serlialize properly to xml (different root element tag name)
  387. /// </summary>
  388. /// <param name="profile"></param>
  389. /// <returns></returns>
  390. private DeviceProfile ReserializeProfile(DeviceProfile profile)
  391. {
  392. if (profile.GetType() == typeof(DeviceProfile))
  393. {
  394. return profile;
  395. }
  396. var json = _jsonSerializer.SerializeToString(profile);
  397. return _jsonSerializer.DeserializeFromString<DeviceProfile>(json);
  398. }
  399. class InternalProfileInfo
  400. {
  401. internal DeviceProfileInfo Info { get; set; }
  402. internal string Path { get; set; }
  403. }
  404. public string GetServerDescriptionXml(IDictionary<string, string> headers, string serverUuId, string serverAddress)
  405. {
  406. var profile = GetProfile(headers) ??
  407. GetDefaultProfile();
  408. var serverId = _appHost.SystemId;
  409. return new DescriptionXmlBuilder(profile, serverUuId, serverAddress, _appHost.FriendlyName, serverId).GetXml();
  410. }
  411. public ImageStream GetIcon(string filename)
  412. {
  413. var format = filename.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
  414. ? ImageFormat.Png
  415. : ImageFormat.Jpg;
  416. return new ImageStream
  417. {
  418. Format = format,
  419. Stream = GetType().Assembly.GetManifestResourceStream("MediaBrowser.Dlna.Images." + filename.ToLower())
  420. };
  421. }
  422. }
  423. class DlnaProfileEntryPoint : IServerEntryPoint
  424. {
  425. private readonly IApplicationPaths _appPaths;
  426. private readonly IXmlSerializer _xmlSerializer;
  427. private readonly IFileSystem _fileSystem;
  428. public DlnaProfileEntryPoint(IApplicationPaths appPaths, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  429. {
  430. _appPaths = appPaths;
  431. _xmlSerializer = xmlSerializer;
  432. _fileSystem = fileSystem;
  433. }
  434. public void Run()
  435. {
  436. //DumpProfiles();
  437. }
  438. private void DumpProfiles()
  439. {
  440. var list = new List<DeviceProfile>
  441. {
  442. new SamsungSmartTvProfile(),
  443. new Xbox360Profile(),
  444. new XboxOneProfile(),
  445. new SonyPs3Profile(),
  446. new SonyPs4Profile(),
  447. new SonyBravia2010Profile(),
  448. new SonyBravia2011Profile(),
  449. new SonyBravia2012Profile(),
  450. new SonyBravia2013Profile(),
  451. new SonyBravia2014Profile(),
  452. new SonyBlurayPlayer2013Profile(),
  453. new SonyBlurayPlayerProfile(),
  454. new PanasonicVieraProfile(),
  455. new WdtvLiveProfile(),
  456. new DenonAvrProfile(),
  457. new LinksysDMA2100Profile(),
  458. new LgTvProfile(),
  459. new Foobar2000Profile(),
  460. new MediaMonkeyProfile(),
  461. //new Windows81Profile(),
  462. //new WindowsMediaCenterProfile(),
  463. //new WindowsPhoneProfile(),
  464. new DirectTvProfile(),
  465. new DishHopperJoeyProfile(),
  466. new DefaultProfile(),
  467. new PopcornHourProfile(),
  468. new VlcProfile(),
  469. new BubbleUpnpProfile(),
  470. new KodiProfile(),
  471. };
  472. foreach (var item in list)
  473. {
  474. var path = Path.Combine(_appPaths.ProgramDataPath, _fileSystem.GetValidFilename(item.Name) + ".xml");
  475. _xmlSerializer.SerializeToFile(item, path);
  476. }
  477. }
  478. public void Dispose()
  479. {
  480. }
  481. }
  482. }