2
0

DeviceId.cs 2.4 KB

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