DeviceId.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using MediaBrowser.Common.Configuration;
  5. using MediaBrowser.Model.IO;
  6. using Microsoft.Extensions.Logging;
  7. namespace Emby.Server.Implementations.Devices
  8. {
  9. public class DeviceId
  10. {
  11. private readonly IApplicationPaths _appPaths;
  12. private readonly ILogger _logger;
  13. private readonly IFileSystem _fileSystem;
  14. private readonly object _syncLock = new object();
  15. private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt");
  16. private string GetCachedId()
  17. {
  18. try
  19. {
  20. lock (_syncLock)
  21. {
  22. var value = File.ReadAllText(CachePath, Encoding.UTF8);
  23. Guid guid;
  24. if (Guid.TryParse(value, out guid))
  25. {
  26. return value;
  27. }
  28. _logger.LogError("Invalid value found in device id file");
  29. }
  30. }
  31. catch (DirectoryNotFoundException)
  32. {
  33. }
  34. catch (FileNotFoundException)
  35. {
  36. }
  37. catch (Exception ex)
  38. {
  39. _logger.LogError(ex, "Error reading file");
  40. }
  41. return null;
  42. }
  43. private void SaveId(string id)
  44. {
  45. try
  46. {
  47. var path = CachePath;
  48. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  49. lock (_syncLock)
  50. {
  51. _fileSystem.WriteAllText(path, id, Encoding.UTF8);
  52. }
  53. }
  54. catch (Exception ex)
  55. {
  56. _logger.LogError(ex, "Error writing to file");
  57. }
  58. }
  59. private static string GetNewId()
  60. {
  61. return Guid.NewGuid().ToString("N");
  62. }
  63. private string GetDeviceId()
  64. {
  65. var id = GetCachedId();
  66. if (string.IsNullOrWhiteSpace(id))
  67. {
  68. id = GetNewId();
  69. SaveId(id);
  70. }
  71. return id;
  72. }
  73. private string _id;
  74. public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  75. {
  76. if (fileSystem == null)
  77. {
  78. throw new ArgumentNullException(nameof(fileSystem));
  79. }
  80. _appPaths = appPaths;
  81. _logger = logger;
  82. _fileSystem = fileSystem;
  83. }
  84. public string Value => _id ?? (_id = GetDeviceId());
  85. }
  86. }