DeviceId.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Text;
  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 object _syncLock = new object();
  16. private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt");
  17. private string GetCachedId()
  18. {
  19. try
  20. {
  21. lock (_syncLock)
  22. {
  23. var value = File.ReadAllText(CachePath, Encoding.UTF8);
  24. if (Guid.TryParse(value, out var 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. Directory.CreateDirectory(Path.GetDirectoryName(path));
  49. lock (_syncLock)
  50. {
  51. File.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", CultureInfo.InvariantCulture);
  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, ILoggerFactory loggerFactory)
  75. {
  76. _appPaths = appPaths;
  77. _logger = loggerFactory.CreateLogger<DeviceId>();
  78. }
  79. public string Value => _id ?? (_id = GetDeviceId());
  80. }
  81. }