DeviceId.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.IO;
  7. using System.Text;
  8. namespace MediaBrowser.Common.Implementations.Devices
  9. {
  10. public class DeviceId
  11. {
  12. private readonly IApplicationPaths _appPaths;
  13. private readonly INetworkManager _networkManager;
  14. private readonly ILogger _logger;
  15. private readonly object _syncLock = new object();
  16. private string CachePath
  17. {
  18. get { return Path.Combine(_appPaths.DataPath, "device.txt"); }
  19. }
  20. private string GetCachedId()
  21. {
  22. try
  23. {
  24. lock (_syncLock)
  25. {
  26. var value = File.ReadAllText(CachePath, Encoding.UTF8);
  27. Guid guid;
  28. if (Guid.TryParse(value, out guid))
  29. {
  30. return value;
  31. }
  32. _logger.Error("Invalid value found in device id file");
  33. }
  34. }
  35. catch (FileNotFoundException ex)
  36. {
  37. }
  38. catch (Exception ex)
  39. {
  40. _logger.ErrorException("Error reading file", ex);
  41. }
  42. return null;
  43. }
  44. private void SaveId(string id)
  45. {
  46. try
  47. {
  48. var path = CachePath;
  49. Directory.CreateDirectory(Path.GetDirectoryName(path));
  50. lock (_syncLock)
  51. {
  52. File.WriteAllText(path, id, Encoding.UTF8);
  53. }
  54. }
  55. catch (Exception ex)
  56. {
  57. _logger.ErrorException("Error writing to file", ex);
  58. }
  59. }
  60. private string GetNewId()
  61. {
  62. // When generating an Id, base it off of the app path + mac address
  63. // But we can't fail here, so if we can't get the mac address then just use a random guid
  64. string mac;
  65. try
  66. {
  67. mac = _networkManager.GetMacAddress();
  68. }
  69. catch
  70. {
  71. mac = Guid.NewGuid().ToString("N");
  72. }
  73. mac += "-" + _appPaths.ApplicationPath;
  74. return mac.GetMD5().ToString("N");
  75. }
  76. private string GetDeviceId()
  77. {
  78. var id = GetCachedId();
  79. if (string.IsNullOrWhiteSpace(id))
  80. {
  81. id = GetNewId();
  82. SaveId(id);
  83. }
  84. return id;
  85. }
  86. private string _id;
  87. public DeviceId(IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager)
  88. {
  89. _appPaths = appPaths;
  90. _logger = logger;
  91. _networkManager = networkManager;
  92. }
  93. public string Value
  94. {
  95. get { return _id ?? (_id = GetDeviceId()); }
  96. }
  97. }
  98. }