DeviceId.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Text;
  6. namespace MediaBrowser.Common.Implementations.Devices
  7. {
  8. public class DeviceId
  9. {
  10. private readonly IApplicationPaths _appPaths;
  11. private readonly ILogger _logger;
  12. private readonly object _syncLock = new object();
  13. private string CachePath
  14. {
  15. get { return Path.Combine(_appPaths.DataPath, "device.txt"); }
  16. }
  17. private string GetCachedId()
  18. {
  19. try
  20. {
  21. lock (_syncLock)
  22. {
  23. var value = File.ReadAllText(CachePath, Encoding.UTF8);
  24. Guid guid;
  25. if (Guid.TryParse(value, out guid))
  26. {
  27. return value;
  28. }
  29. _logger.Error("Invalid value found in device id file");
  30. }
  31. }
  32. catch (DirectoryNotFoundException)
  33. {
  34. }
  35. catch (FileNotFoundException)
  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. return Guid.NewGuid().ToString("N");
  63. }
  64. private string GetDeviceId()
  65. {
  66. var id = GetCachedId();
  67. if (string.IsNullOrWhiteSpace(id))
  68. {
  69. id = GetNewId();
  70. SaveId(id);
  71. }
  72. return id;
  73. }
  74. private string _id;
  75. public DeviceId(IApplicationPaths appPaths, ILogger logger)
  76. {
  77. _appPaths = appPaths;
  78. _logger = logger;
  79. }
  80. public string Value
  81. {
  82. get { return _id ?? (_id = GetDeviceId()); }
  83. }
  84. }
  85. }