diff options
| author | Luke <luke.pulverenti@gmail.com> | 2016-10-30 03:29:27 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2016-10-30 03:29:27 -0400 |
| commit | d31b0f7be4b14e4ada999c97e675b856ad68352b (patch) | |
| tree | a4619513efbb3be62a6204c996526df606cb62c5 /Emby.Common.Implementations/Devices | |
| parent | b19f75fcae017cb51f1e58eb2d54ca84620b6ee0 (diff) | |
| parent | 3094cd7ff3e51578808ce1b6f56b141930c18004 (diff) | |
Merge pull request #2258 from MediaBrowser/dev
Dev
Diffstat (limited to 'Emby.Common.Implementations/Devices')
| -rw-r--r-- | Emby.Common.Implementations/Devices/DeviceId.cs | 109 |
1 files changed, 109 insertions, 0 deletions
diff --git a/Emby.Common.Implementations/Devices/DeviceId.cs b/Emby.Common.Implementations/Devices/DeviceId.cs new file mode 100644 index 0000000000..3d23ab872b --- /dev/null +++ b/Emby.Common.Implementations/Devices/DeviceId.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using System.Text; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Logging; + +namespace Emby.Common.Implementations.Devices +{ + public class DeviceId + { + private readonly IApplicationPaths _appPaths; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + + private readonly object _syncLock = new object(); + + private string CachePath + { + get { return Path.Combine(_appPaths.DataPath, "device.txt"); } + } + + private string GetCachedId() + { + try + { + lock (_syncLock) + { + var value = File.ReadAllText(CachePath, Encoding.UTF8); + + Guid guid; + if (Guid.TryParse(value, out guid)) + { + return value; + } + + _logger.Error("Invalid value found in device id file"); + } + } + catch (DirectoryNotFoundException) + { + } + catch (FileNotFoundException) + { + } + catch (Exception ex) + { + _logger.ErrorException("Error reading file", ex); + } + + return null; + } + + private void SaveId(string id) + { + try + { + var path = CachePath; + + _fileSystem.CreateDirectory(Path.GetDirectoryName(path)); + + lock (_syncLock) + { + _fileSystem.WriteAllText(path, id, Encoding.UTF8); + } + } + catch (Exception ex) + { + _logger.ErrorException("Error writing to file", ex); + } + } + + private string GetNewId() + { + return Guid.NewGuid().ToString("N"); + } + + private string GetDeviceId() + { + var id = GetCachedId(); + + if (string.IsNullOrWhiteSpace(id)) + { + id = GetNewId(); + SaveId(id); + } + + return id; + } + + private string _id; + + public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem) + { + if (fileSystem == null) { + throw new ArgumentNullException ("fileSystem"); + } + + _appPaths = appPaths; + _logger = logger; + _fileSystem = fileSystem; + } + + public string Value + { + get { return _id ?? (_id = GetDeviceId()); } + } + } +} |
