jellyfin/MediaBrowser.Common.Implementations/Devices/DeviceId.cs

111 lines
2.6 KiB
C#
Raw Normal View History

2014-09-05 03:48:53 +00:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Logging;
using System;
using System.IO;
using System.Text;
2015-10-04 04:23:11 +00:00
using CommonIO;
2015-09-13 21:32:02 +00:00
using MediaBrowser.Common.IO;
2014-09-05 03:48:53 +00:00
namespace MediaBrowser.Common.Implementations.Devices
{
public class DeviceId
{
private readonly IApplicationPaths _appPaths;
2015-09-13 21:32:02 +00:00
private readonly ILogger _logger;
private readonly IFileSystem _fileSystem;
2014-09-05 03:48:53 +00:00
private readonly object _syncLock = new object();
private string CachePath
{
get { return Path.Combine(_appPaths.DataPath, "device.txt"); }
}
private string GetCachedId()
{
try
{
lock (_syncLock)
{
2015-09-13 23:07:54 +00:00
var value = File.ReadAllText(CachePath, Encoding.UTF8);
2014-09-05 03:48:53 +00:00
Guid guid;
if (Guid.TryParse(value, out guid))
{
return value;
}
_logger.Error("Invalid value found in device id file");
}
}
2014-12-23 03:58:14 +00:00
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
2014-09-05 03:48:53 +00:00
{
}
catch (Exception ex)
{
_logger.ErrorException("Error reading file", ex);
}
return null;
}
private void SaveId(string id)
{
try
{
var path = CachePath;
2015-09-13 21:32:02 +00:00
_fileSystem.CreateDirectory(Path.GetDirectoryName(path));
2014-09-05 03:48:53 +00:00
lock (_syncLock)
{
2015-09-13 21:32:02 +00:00
_fileSystem.WriteAllText(path, id, Encoding.UTF8);
2014-09-05 03:48:53 +00:00
}
}
catch (Exception ex)
{
_logger.ErrorException("Error writing to file", ex);
}
}
private string GetNewId()
{
2015-01-06 03:25:23 +00:00
return Guid.NewGuid().ToString("N");
2014-09-05 03:48:53 +00:00
}
private string GetDeviceId()
{
var id = GetCachedId();
if (string.IsNullOrWhiteSpace(id))
{
id = GetNewId();
SaveId(id);
}
return id;
}
private string _id;
2015-09-13 21:32:02 +00:00
public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
2014-09-05 03:48:53 +00:00
{
2015-09-13 21:32:02 +00:00
if (fileSystem == null) {
throw new ArgumentNullException ("fileSystem");
}
2014-09-05 03:48:53 +00:00
_appPaths = appPaths;
_logger = logger;
2015-09-13 21:32:02 +00:00
_fileSystem = fileSystem;
2014-09-05 03:48:53 +00:00
}
public string Value
{
get { return _id ?? (_id = GetDeviceId()); }
}
}
}