DeviceId.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Text;
  6. using CommonIO;
  7. using MediaBrowser.Common.IO;
  8. namespace MediaBrowser.Common.Implementations.Devices
  9. {
  10. public class DeviceId
  11. {
  12. private readonly IApplicationPaths _appPaths;
  13. private readonly ILogger _logger;
  14. private readonly IFileSystem _fileSystem;
  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. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  53. lock (_syncLock)
  54. {
  55. _fileSystem.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. return Guid.NewGuid().ToString("N");
  66. }
  67. private string GetDeviceId()
  68. {
  69. var id = GetCachedId();
  70. if (string.IsNullOrWhiteSpace(id))
  71. {
  72. id = GetNewId();
  73. SaveId(id);
  74. }
  75. return id;
  76. }
  77. private string _id;
  78. public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  79. {
  80. if (fileSystem == null) {
  81. throw new ArgumentNullException ("fileSystem");
  82. }
  83. _appPaths = appPaths;
  84. _logger = logger;
  85. _fileSystem = fileSystem;
  86. }
  87. public string Value
  88. {
  89. get { return _id ?? (_id = GetDeviceId()); }
  90. }
  91. }
  92. }