DeviceId.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. if (Guid.TryParse(value, out var guid))
  24. {
  25. return value;
  26. }
  27. _logger.LogError("Invalid value found in device id file");
  28. }
  29. }
  30. catch (DirectoryNotFoundException)
  31. {
  32. }
  33. catch (FileNotFoundException)
  34. {
  35. }
  36. catch (Exception ex)
  37. {
  38. _logger.LogError(ex, "Error reading file");
  39. }
  40. return null;
  41. }
  42. private void SaveId(string id)
  43. {
  44. try
  45. {
  46. var path = CachePath;
  47. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  48. lock (_syncLock)
  49. {
  50. _fileSystem.WriteAllText(path, id, Encoding.UTF8);
  51. }
  52. }
  53. catch (Exception ex)
  54. {
  55. _logger.LogError(ex, "Error writing to file");
  56. }
  57. }
  58. private static string GetNewId()
  59. {
  60. return Guid.NewGuid().ToString("N");
  61. }
  62. private string GetDeviceId()
  63. {
  64. var id = GetCachedId();
  65. if (string.IsNullOrWhiteSpace(id))
  66. {
  67. id = GetNewId();
  68. SaveId(id);
  69. }
  70. return id;
  71. }
  72. private string _id;
  73. public DeviceId(
  74. IApplicationPaths appPaths,
  75. ILoggerFactory loggerFactory,
  76. IFileSystem fileSystem)
  77. {
  78. if (fileSystem == null)
  79. {
  80. throw new ArgumentNullException(nameof(fileSystem));
  81. }
  82. _appPaths = appPaths;
  83. _logger = loggerFactory.CreateLogger("SystemId");
  84. _fileSystem = fileSystem;
  85. }
  86. public string Value => _id ?? (_id = GetDeviceId());
  87. }
  88. }