DeviceId.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 _id;
  17. public DeviceId(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
  18. {
  19. _appPaths = appPaths;
  20. _logger = loggerFactory.CreateLogger<DeviceId>();
  21. }
  22. public string Value => _id ?? (_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));
  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. }