DeviceId.cs 2.3 KB

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