DlnaManager.cs 18 KB

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