DlnaManager.cs 21 KB

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