DeviceId.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using MediaBrowser.Common.Configuration;
  5. using MediaBrowser.Model.IO;
  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 IFileSystem _fileSystem;
  14. private readonly object _syncLock = new object();
  15. private string CachePath
  16. {
  17. get { return Path.Combine(_appPaths.DataPath, "device.txt"); }
  18. }
  19. private string GetCachedId()
  20. {
  21. try
  22. {
  23. lock (_syncLock)
  24. {
  25. var value = File.ReadAllText(CachePath, Encoding.UTF8);
  26. Guid guid;
  27. if (Guid.TryParse(value, out guid))
  28. {
  29. return value;
  30. }
  31. _logger.LogError("Invalid value found in device id file");
  32. }
  33. }
  34. catch (DirectoryNotFoundException)
  35. {
  36. }
  37. catch (FileNotFoundException)
  38. {
  39. }
  40. catch (Exception ex)
  41. {
  42. _logger.LogError(ex, "Error reading file");
  43. }
  44. return null;
  45. }
  46. private void SaveId(string id)
  47. {
  48. try
  49. {
  50. var path = CachePath;
  51. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  52. lock (_syncLock)
  53. {
  54. _fileSystem.WriteAllText(path, id, Encoding.UTF8);
  55. }
  56. }
  57. catch (Exception ex)
  58. {
  59. _logger.LogError(ex, "Error writing to file");
  60. }
  61. }
  62. private string GetNewId()
  63. {
  64. return Guid.NewGuid().ToString("N");
  65. }
  66. private string GetDeviceId()
  67. {
  68. var id = GetCachedId();
  69. if (string.IsNullOrWhiteSpace(id))
  70. {
  71. id = GetNewId();
  72. SaveId(id);
  73. }
  74. return id;
  75. }
  76. private string _id;
  77. public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  78. {
  79. if (fileSystem == null) {
  80. throw new ArgumentNullException ("fileSystem");
  81. }
  82. _appPaths = appPaths;
  83. _logger = logger;
  84. _fileSystem = fileSystem;
  85. }
  86. public string Value
  87. {
  88. get { return _id ?? (_id = GetDeviceId()); }
  89. }
  90. }
  91. }