DeviceId.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 (FileNotFoundException ex)
  33. {
  34. }
  35. catch (Exception ex)
  36. {
  37. _logger.ErrorException("Error reading file", ex);
  38. }
  39. return null;
  40. }
  41. private void SaveId(string id)
  42. {
  43. try
  44. {
  45. var path = CachePath;
  46. Directory.CreateDirectory(Path.GetDirectoryName(path));
  47. lock (_syncLock)
  48. {
  49. File.WriteAllText(path, id, Encoding.UTF8);
  50. }
  51. }
  52. catch (Exception ex)
  53. {
  54. _logger.ErrorException("Error writing to file", ex);
  55. }
  56. }
  57. private string GetNewId()
  58. {
  59. return Guid.NewGuid().ToString("N");
  60. }
  61. private string GetDeviceId()
  62. {
  63. var id = GetCachedId();
  64. if (string.IsNullOrWhiteSpace(id))
  65. {
  66. id = GetNewId();
  67. SaveId(id);
  68. }
  69. return id;
  70. }
  71. private string _id;
  72. public DeviceId(IApplicationPaths appPaths, ILogger logger)
  73. {
  74. _appPaths = appPaths;
  75. _logger = logger;
  76. }
  77. public string Value
  78. {
  79. get { return _id ?? (_id = GetDeviceId()); }
  80. }
  81. }
  82. }