DlnaManager.cs 21 KB

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