forked from sim0n00ps/OF-DL
73 lines
2.1 KiB
C#
73 lines
2.1 KiB
C#
using Newtonsoft.Json;
|
|
using OF_DL.Entities;
|
|
using OF_DL.Helpers.Interfaces;
|
|
using Serilog;
|
|
|
|
namespace OF_DL.Services
|
|
{
|
|
public class AuthService(IAuthHelper authHelper) : IAuthService
|
|
{
|
|
public Auth? CurrentAuth { get; set; }
|
|
|
|
public async Task<bool> LoadFromFileAsync(string filePath = "auth.json")
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(filePath))
|
|
{
|
|
Log.Debug("Auth file not found: {FilePath}", filePath);
|
|
return false;
|
|
}
|
|
|
|
var json = await File.ReadAllTextAsync(filePath);
|
|
CurrentAuth = JsonConvert.DeserializeObject<Auth>(json);
|
|
Log.Debug("Auth file loaded and deserialized successfully");
|
|
return CurrentAuth != null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Error(ex, "Failed to load auth from file");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> LoadFromBrowserAsync()
|
|
{
|
|
try
|
|
{
|
|
bool runningInDocker = Environment.GetEnvironmentVariable("OFDL_DOCKER") != null;
|
|
|
|
await authHelper.SetupBrowser(runningInDocker);
|
|
CurrentAuth = await authHelper.GetAuthFromBrowser();
|
|
|
|
return CurrentAuth != null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Error(ex, "Failed to load auth from browser");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task SaveToFileAsync(string filePath = "auth.json")
|
|
{
|
|
if (CurrentAuth == null)
|
|
{
|
|
Log.Warning("Attempted to save null auth to file");
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var json = JsonConvert.SerializeObject(CurrentAuth, Formatting.Indented);
|
|
await File.WriteAllTextAsync(filePath, json);
|
|
Log.Debug($"Auth saved to file: {filePath}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Error(ex, "Failed to save auth to file");
|
|
}
|
|
}
|
|
}
|
|
}
|