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

100 lines
2.4 KiB
C#
Raw Normal View History

#nullable disable
2019-11-01 18:38:54 +01:00
#pragma warning disable CS1591
using System;
using System.Globalization;
2016-10-29 07:40:15 +02:00
using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
using Microsoft.Extensions.Logging;
2016-10-29 07:40:15 +02:00
namespace Emby.Server.Implementations.Devices
2016-10-29 07:40:15 +02:00
{
public class DeviceId
{
private readonly IApplicationPaths _appPaths;
2020-06-06 02:15:56 +02:00
private readonly ILogger<DeviceId> _logger;
2016-10-29 07:40:15 +02:00
private readonly object _syncLock = new object();
2021-10-02 20:06:00 +02:00
private string _id;
public DeviceId(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
{
_appPaths = appPaths;
_logger = loggerFactory.CreateLogger<DeviceId>();
}
public string Value => _id ?? (_id = GetDeviceId());
private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt");
2016-10-29 07:40:15 +02:00
private string GetCachedId()
{
try
{
lock (_syncLock)
{
2019-01-08 00:24:34 +01:00
var value = File.ReadAllText(CachePath, Encoding.UTF8);
2016-10-29 07:40:15 +02:00
2021-12-15 18:25:36 +01:00
if (Guid.TryParse(value, out _))
2016-10-29 07:40:15 +02:00
{
return value;
}
_logger.LogError("Invalid value found in device id file");
2016-10-29 07:40:15 +02:00
}
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
2018-12-20 13:11:26 +01:00
_logger.LogError(ex, "Error reading file");
2016-10-29 07:40:15 +02:00
}
return null;
}
private void SaveId(string id)
{
try
{
var path = CachePath;
Directory.CreateDirectory(Path.GetDirectoryName(path));
2016-10-29 07:40:15 +02:00
lock (_syncLock)
{
File.WriteAllText(path, id, Encoding.UTF8);
2016-10-29 07:40:15 +02:00
}
}
catch (Exception ex)
{
2018-12-20 13:11:26 +01:00
_logger.LogError(ex, "Error writing to file");
2016-10-29 07:40:15 +02:00
}
}
private static string GetNewId()
2016-10-29 07:40:15 +02:00
{
return Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
2016-10-29 07:40:15 +02:00
}
private string GetDeviceId()
{
var id = GetCachedId();
if (string.IsNullOrWhiteSpace(id))
{
id = GetNewId();
SaveId(id);
}
return id;
}
}
}