jellyfin/Emby.Server.Implementations/Devices/DeviceId.cs
Erwin de Haan ec1f5dc317 Mayor code cleanup
Add Argument*Exceptions now use proper nameof operators.

Added exception messages to quite a few Argument*Exceptions.

Fixed rethorwing to be proper syntax.

Added a ton of null checkes. (This is only a start, there are about 500 places that need proper null handling)

Added some TODOs to log certain exceptions.

Fix sln again.

Fixed all AssemblyInfo's and added proper copyright (where I could find them)

We live in *current year*.

Fixed the use of braces.

Fixed a ton of properties, and made a fair amount of functions static that should be and can be static.

Made more Methods that should be static static.

You can now use static to find bad functions!

Removed unused variable. And added one more proper XML comment.
2019-01-10 20:38:53 +01:00

104 lines
2.5 KiB
C#

using System;
using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
namespace Emby.Server.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 => 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");
}
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading file");
}
return null;
}
private void SaveId(string id)
{
try
{
var path = CachePath;
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
lock (_syncLock)
{
_fileSystem.WriteAllText(path, id, Encoding.UTF8);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error writing to file");
}
}
private static 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(nameof(fileSystem));
}
_appPaths = appPaths;
_logger = logger;
_fileSystem = fileSystem;
}
public string Value => _id ?? (_id = GetDeviceId());
}
}