jellyfin/Emby.Server.Implementations/Devices/DeviceId.cs

110 lines
2.5 KiB
C#
Raw Normal View History

2016-10-29 05:40:15 +00:00
using System;
using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
2016-10-29 05:40:15 +00:00
namespace Emby.Server.Implementations.Devices
2016-10-29 05:40:15 +00:00
{
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.LogError("Invalid value found in device id file");
2016-10-29 05:40:15 +00:00
}
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error reading file");
2016-10-29 05:40:15 +00:00
}
return null;
}
private void SaveId(string id)
{
try
{
var path = CachePath;
2017-05-04 18:14:45 +00:00
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
2016-10-29 05:40:15 +00:00
lock (_syncLock)
{
_fileSystem.WriteAllText(path, id, Encoding.UTF8);
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error writing to file");
2016-10-29 05:40:15 +00:00
}
}
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()); }
}
}
}