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 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 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. Directory.CreateDirectory(Path.GetDirectoryName(path));
  48. lock (_syncLock)
  49. {
  50. File.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", CultureInfo.InvariantCulture);
  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(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
  74. {
  75. _appPaths = appPaths;
  76. _logger = loggerFactory.CreateLogger<DeviceId>();
  77. }
  78. public string Value => _id ?? (_id = GetDeviceId());
  79. }
  80. }