DlnaManager.cs 20 KB

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