| | 1 | | #pragma warning disable CS1591 |
| | 2 | |
|
| | 3 | | using System; |
| | 4 | | using System.Globalization; |
| | 5 | | using System.IO; |
| | 6 | | using System.Text; |
| | 7 | | using MediaBrowser.Common.Configuration; |
| | 8 | | using Microsoft.Extensions.Logging; |
| | 9 | |
|
| | 10 | | namespace Emby.Server.Implementations.Devices |
| | 11 | | { |
| | 12 | | public class DeviceId |
| | 13 | | { |
| | 14 | | private readonly IApplicationPaths _appPaths; |
| | 15 | | private readonly ILogger<DeviceId> _logger; |
| 22 | 16 | | private readonly object _syncLock = new object(); |
| | 17 | |
|
| | 18 | | private string? _id; |
| | 19 | |
|
| | 20 | | public DeviceId(IApplicationPaths appPaths, ILogger<DeviceId> logger) |
| | 21 | | { |
| 22 | 22 | | _appPaths = appPaths; |
| 22 | 23 | | _logger = logger; |
| 22 | 24 | | } |
| | 25 | |
|
| 111 | 26 | | public string Value => _id ??= GetDeviceId(); |
| | 27 | |
|
| 44 | 28 | | private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt"); |
| | 29 | |
|
| | 30 | | private string? GetCachedId() |
| | 31 | | { |
| | 32 | | try |
| | 33 | | { |
| 22 | 34 | | lock (_syncLock) |
| | 35 | | { |
| 22 | 36 | | var value = File.ReadAllText(CachePath, Encoding.UTF8); |
| | 37 | |
|
| 0 | 38 | | if (Guid.TryParse(value, out _)) |
| | 39 | | { |
| 0 | 40 | | return value; |
| | 41 | | } |
| | 42 | |
|
| 0 | 43 | | _logger.LogError("Invalid value found in device id file"); |
| 0 | 44 | | } |
| 0 | 45 | | } |
| 0 | 46 | | catch (DirectoryNotFoundException) |
| | 47 | | { |
| 0 | 48 | | } |
| 22 | 49 | | catch (FileNotFoundException) |
| | 50 | | { |
| 22 | 51 | | } |
| 0 | 52 | | catch (Exception ex) |
| | 53 | | { |
| 0 | 54 | | _logger.LogError(ex, "Error reading file"); |
| 0 | 55 | | } |
| | 56 | |
|
| 22 | 57 | | return null; |
| 0 | 58 | | } |
| | 59 | |
|
| | 60 | | private void SaveId(string id) |
| | 61 | | { |
| | 62 | | try |
| | 63 | | { |
| 22 | 64 | | var path = CachePath; |
| | 65 | |
|
| 22 | 66 | | Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't |
| | 67 | |
|
| 22 | 68 | | lock (_syncLock) |
| | 69 | | { |
| 22 | 70 | | File.WriteAllText(path, id, Encoding.UTF8); |
| 22 | 71 | | } |
| 22 | 72 | | } |
| 0 | 73 | | catch (Exception ex) |
| | 74 | | { |
| 0 | 75 | | _logger.LogError(ex, "Error writing to file"); |
| 0 | 76 | | } |
| 22 | 77 | | } |
| | 78 | |
|
| | 79 | | private static string GetNewId() |
| | 80 | | { |
| 22 | 81 | | return Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); |
| | 82 | | } |
| | 83 | |
|
| | 84 | | private string GetDeviceId() |
| | 85 | | { |
| 22 | 86 | | var id = GetCachedId(); |
| | 87 | |
|
| 22 | 88 | | if (string.IsNullOrWhiteSpace(id)) |
| | 89 | | { |
| 22 | 90 | | id = GetNewId(); |
| 22 | 91 | | SaveId(id); |
| | 92 | | } |
| | 93 | |
|
| 22 | 94 | | return id; |
| | 95 | | } |
| | 96 | | } |
| | 97 | | } |