DeviceId.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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 (DirectoryNotFoundException)
  36. {
  37. }
  38. catch (FileNotFoundException)
  39. {
  40. }
  41. catch (Exception ex)
  42. {
  43. _logger.ErrorException("Error reading file", ex);
  44. }
  45. return null;
  46. }
  47. private void SaveId(string id)
  48. {
  49. try
  50. {
  51. var path = CachePath;
  52. Directory.CreateDirectory(Path.GetDirectoryName(path));
  53. lock (_syncLock)
  54. {
  55. File.WriteAllText(path, id, Encoding.UTF8);
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. _logger.ErrorException("Error writing to file", ex);
  61. }
  62. }
  63. private string GetNewId()
  64. {
  65. // When generating an Id, base it off of the app path + mac address
  66. // But we can't fail here, so if we can't get the mac address then just use a random guid
  67. string mac;
  68. try
  69. {
  70. mac = _networkManager.GetMacAddress();
  71. }
  72. catch
  73. {
  74. mac = Guid.NewGuid().ToString("N");
  75. }
  76. mac += "-" + _appPaths.ApplicationPath;
  77. return mac.GetMD5().ToString("N");
  78. }
  79. private string GetDeviceId()
  80. {
  81. var id = GetCachedId();
  82. if (string.IsNullOrWhiteSpace(id))
  83. {
  84. id = GetNewId();
  85. SaveId(id);
  86. }
  87. return id;
  88. }
  89. private string _id;
  90. public DeviceId(IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager)
  91. {
  92. _appPaths = appPaths;
  93. _logger = logger;
  94. _networkManager = networkManager;
  95. }
  96. public string Value
  97. {
  98. get { return _id ?? (_id = GetDeviceId()); }
  99. }
  100. }
  101. }