DeviceId.cs 2.4 KB

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