DlnaManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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.Drawing;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.Serialization;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Text.RegularExpressions;
  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. var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
  182. if (profile != null)
  183. {
  184. _logger.Debug("Found matching device profile: {0}", profile.Name);
  185. }
  186. else
  187. {
  188. string userAgent = null;
  189. headers.TryGetValue("User-Agent", out userAgent);
  190. var msg = "No matching device profile found. The default will be used. ";
  191. if (!string.IsNullOrEmpty(userAgent))
  192. {
  193. msg += "User-agent: " + userAgent + ". ";
  194. }
  195. _logger.Debug(msg);
  196. }
  197. return profile;
  198. }
  199. private bool IsMatch(IDictionary<string, string> headers, DeviceIdentification profileInfo)
  200. {
  201. return profileInfo.Headers.Any(i => IsMatch(headers, i));
  202. }
  203. private bool IsMatch(IDictionary<string, string> headers, HttpHeaderInfo header)
  204. {
  205. string value;
  206. if (headers.TryGetValue(header.Name, out value))
  207. {
  208. switch (header.Match)
  209. {
  210. case HeaderMatchType.Equals:
  211. return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
  212. case HeaderMatchType.Substring:
  213. return value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
  214. case HeaderMatchType.Regex:
  215. return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase);
  216. default:
  217. throw new ArgumentException("Unrecognized HeaderMatchType");
  218. }
  219. }
  220. return false;
  221. }
  222. private string UserProfilesPath
  223. {
  224. get
  225. {
  226. return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "user");
  227. }
  228. }
  229. private string SystemProfilesPath
  230. {
  231. get
  232. {
  233. return Path.Combine(_appPaths.ConfigurationDirectoryPath, "dlna", "system");
  234. }
  235. }
  236. private IEnumerable<DeviceProfile> GetProfiles(string path, DeviceProfileType type)
  237. {
  238. try
  239. {
  240. return new DirectoryInfo(path)
  241. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  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. try
  255. {
  256. var profile = (DeviceProfile)_xmlSerializer.DeserializeFromFile(typeof(DeviceProfile), path);
  257. profile.Id = path.ToLower().GetMD5().ToString("N");
  258. profile.ProfileType = type;
  259. return profile;
  260. }
  261. catch (Exception ex)
  262. {
  263. _logger.ErrorException("Error parsing profile xml: {0}", ex, path);
  264. return null;
  265. }
  266. }
  267. public DeviceProfile GetProfile(string id)
  268. {
  269. if (string.IsNullOrWhiteSpace(id))
  270. {
  271. throw new ArgumentNullException("id");
  272. }
  273. var info = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, id));
  274. return ParseProfileXmlFile(info.Path, info.Info.Type);
  275. }
  276. private IEnumerable<InternalProfileInfo> GetProfileInfosInternal()
  277. {
  278. ExtractProfilesIfNeeded();
  279. return GetProfileInfos(UserProfilesPath, DeviceProfileType.User)
  280. .Concat(GetProfileInfos(SystemProfilesPath, DeviceProfileType.System))
  281. .OrderBy(i => i.Info.Type == DeviceProfileType.User ? 0 : 1)
  282. .ThenBy(i => i.Info.Name);
  283. }
  284. public IEnumerable<DeviceProfileInfo> GetProfileInfos()
  285. {
  286. return GetProfileInfosInternal().Select(i => i.Info);
  287. }
  288. private IEnumerable<InternalProfileInfo> GetProfileInfos(string path, DeviceProfileType type)
  289. {
  290. try
  291. {
  292. return new DirectoryInfo(path)
  293. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  294. .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
  295. .Select(i => new InternalProfileInfo
  296. {
  297. Path = i.FullName,
  298. Info = new DeviceProfileInfo
  299. {
  300. Id = i.FullName.ToLower().GetMD5().ToString("N"),
  301. Name = _fileSystem.GetFileNameWithoutExtension(i),
  302. Type = type
  303. }
  304. })
  305. .ToList();
  306. }
  307. catch (DirectoryNotFoundException)
  308. {
  309. return new List<InternalProfileInfo>();
  310. }
  311. }
  312. private void ExtractSystemProfiles()
  313. {
  314. var assembly = GetType().Assembly;
  315. var namespaceName = GetType().Namespace + ".Profiles.Xml.";
  316. var systemProfilesPath = SystemProfilesPath;
  317. foreach (var name in assembly.GetManifestResourceNames()
  318. .Where(i => i.StartsWith(namespaceName))
  319. .ToList())
  320. {
  321. var filename = Path.GetFileName(name).Substring(namespaceName.Length);
  322. var path = Path.Combine(systemProfilesPath, filename);
  323. using (var stream = assembly.GetManifestResourceStream(name))
  324. {
  325. var fileInfo = new FileInfo(path);
  326. if (!fileInfo.Exists || fileInfo.Length != stream.Length)
  327. {
  328. Directory.CreateDirectory(systemProfilesPath);
  329. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  330. {
  331. stream.CopyTo(fileStream);
  332. }
  333. }
  334. }
  335. }
  336. // Not necessary, but just to make it easy to find
  337. Directory.CreateDirectory(UserProfilesPath);
  338. }
  339. public void DeleteProfile(string id)
  340. {
  341. var info = GetProfileInfosInternal().First(i => string.Equals(id, i.Info.Id));
  342. if (info.Info.Type == DeviceProfileType.System)
  343. {
  344. throw new ArgumentException("System profiles cannot be deleted.");
  345. }
  346. _fileSystem.DeleteFile(info.Path);
  347. }
  348. public void CreateProfile(DeviceProfile profile)
  349. {
  350. profile = ReserializeProfile(profile);
  351. if (string.IsNullOrWhiteSpace(profile.Name))
  352. {
  353. throw new ArgumentException("Profile is missing Name");
  354. }
  355. var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
  356. var path = Path.Combine(UserProfilesPath, newFilename);
  357. _xmlSerializer.SerializeToFile(profile, path);
  358. }
  359. public void UpdateProfile(DeviceProfile profile)
  360. {
  361. profile = ReserializeProfile(profile);
  362. if (string.IsNullOrWhiteSpace(profile.Id))
  363. {
  364. throw new ArgumentException("Profile is missing Id");
  365. }
  366. if (string.IsNullOrWhiteSpace(profile.Name))
  367. {
  368. throw new ArgumentException("Profile is missing Name");
  369. }
  370. var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase));
  371. var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml";
  372. var path = Path.Combine(UserProfilesPath, newFilename);
  373. if (!string.Equals(path, current.Path, StringComparison.Ordinal) &&
  374. current.Info.Type != DeviceProfileType.System)
  375. {
  376. _fileSystem.DeleteFile(current.Path);
  377. }
  378. _xmlSerializer.SerializeToFile(profile, path);
  379. }
  380. /// <summary>
  381. /// Recreates the object using serialization, to ensure it's not a subclass.
  382. /// If it's a subclass it may not serlialize properly to xml (different root element tag name)
  383. /// </summary>
  384. /// <param name="profile"></param>
  385. /// <returns></returns>
  386. private DeviceProfile ReserializeProfile(DeviceProfile profile)
  387. {
  388. if (profile.GetType() == typeof(DeviceProfile))
  389. {
  390. return profile;
  391. }
  392. var json = _jsonSerializer.SerializeToString(profile);
  393. return _jsonSerializer.DeserializeFromString<DeviceProfile>(json);
  394. }
  395. class InternalProfileInfo
  396. {
  397. internal DeviceProfileInfo Info { get; set; }
  398. internal string Path { get; set; }
  399. }
  400. public string GetServerDescriptionXml(IDictionary<string, string> headers, string serverUuId, string serverAddress)
  401. {
  402. var profile = GetProfile(headers) ??
  403. GetDefaultProfile();
  404. return new DescriptionXmlBuilder(profile, serverUuId, serverAddress, _appHost.FriendlyName, serverUuId.GetMD5().ToString("N")).GetXml();
  405. }
  406. public ImageStream GetIcon(string filename)
  407. {
  408. var format = filename.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
  409. ? ImageFormat.Png
  410. : ImageFormat.Jpg;
  411. return new ImageStream
  412. {
  413. Format = format,
  414. Stream = GetType().Assembly.GetManifestResourceStream("MediaBrowser.Dlna.Images." + filename.ToLower())
  415. };
  416. }
  417. }
  418. class DlnaProfileEntryPoint : IServerEntryPoint
  419. {
  420. private readonly IApplicationPaths _appPaths;
  421. private readonly IXmlSerializer _xmlSerializer;
  422. private readonly IFileSystem _fileSystem;
  423. public DlnaProfileEntryPoint(IApplicationPaths appPaths, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  424. {
  425. _appPaths = appPaths;
  426. _xmlSerializer = xmlSerializer;
  427. _fileSystem = fileSystem;
  428. }
  429. public void Run()
  430. {
  431. //DumpProfiles();
  432. }
  433. private void DumpProfiles()
  434. {
  435. var list = new List<DeviceProfile>
  436. {
  437. new SamsungSmartTvProfile(),
  438. new Xbox360Profile(),
  439. new XboxOneProfile(),
  440. new SonyPs3Profile(),
  441. new SonyBravia2010Profile(),
  442. new SonyBravia2011Profile(),
  443. new SonyBravia2012Profile(),
  444. new SonyBravia2013Profile(),
  445. new SonyBlurayPlayer2013Profile(),
  446. new SonyBlurayPlayerProfile(),
  447. new PanasonicVieraProfile(),
  448. new WdtvLiveProfile(),
  449. new DenonAvrProfile(),
  450. new LinksysDMA2100Profile(),
  451. new LgTvProfile(),
  452. new Foobar2000Profile(),
  453. new MediaMonkeyProfile(),
  454. //new Windows81Profile(),
  455. //new WindowsMediaCenterProfile(),
  456. //new WindowsPhoneProfile(),
  457. new DirectTvProfile(),
  458. new DishHopperJoeyProfile(),
  459. new DefaultProfile(),
  460. new PopcornHourProfile(),
  461. new VlcProfile(),
  462. new BubbleUpnpProfile()
  463. };
  464. foreach (var item in list)
  465. {
  466. var path = Path.Combine(_appPaths.ProgramDataPath, _fileSystem.GetValidFilename(item.Name) + ".xml");
  467. _xmlSerializer.SerializeToFile(item, path);
  468. }
  469. }
  470. public void Dispose()
  471. {
  472. }
  473. }
  474. }