wabbajack/Wabbajack.Lib/Downloaders/NexusDownloader.cs

281 lines
10 KiB
C#
Raw Normal View History

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
2020-01-07 05:44:05 +00:00
using System.Reactive;
2019-12-20 20:51:10 +00:00
using System.Reactive.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
2019-12-20 20:51:10 +00:00
using ReactiveUI;
using Wabbajack.Common;
using Wabbajack.Common.Serialization.Json;
2019-12-04 04:12:08 +00:00
using Wabbajack.Common.StatusFeed.Errors;
using Wabbajack.Lib.NexusApi;
using Wabbajack.Lib.Validation;
using Game = Wabbajack.Common.Game;
namespace Wabbajack.Lib.Downloaders
{
public class NexusDownloader : IDownloader, INeedsLogin
{
private bool _prepared;
2020-02-06 05:30:31 +00:00
private AsyncLock _lock = new AsyncLock();
private UserStatus? _status;
private NexusApiClient? _client;
2019-12-20 20:51:10 +00:00
public IObservable<bool> IsLoggedIn => Utils.HaveEncryptedJsonObservable("nexusapikey");
public string SiteName => "Nexus Mods";
public IObservable<string> MetaInfo => Observable.Return("");
2019-12-20 20:51:10 +00:00
public Uri SiteURL => new Uri("https://www.nexusmods.com");
public Uri IconUri => new Uri("https://www.nexusmods.com/favicon.ico");
2020-01-07 05:44:05 +00:00
public ReactiveCommand<Unit, Unit> TriggerLogin { get; }
public ReactiveCommand<Unit, Unit> ClearLogin { get; }
2019-12-20 20:51:10 +00:00
public NexusDownloader()
{
2020-01-05 13:14:53 +00:00
if (CLIArguments.ApiKey != null)
{
CLIArguments.ApiKey.ToEcryptedJson("nexusapikey");
}
TriggerLogin = ReactiveCommand.CreateFromTask(
execute: () => Utils.CatchAndLog(NexusApiClient.RequestAndCacheAPIKey),
2020-01-09 03:22:49 +00:00
canExecute: IsLoggedIn.Select(b => !b).ObserveOnGuiThread());
ClearLogin = ReactiveCommand.Create(
execute: () => Utils.CatchAndLog(() => Utils.DeleteEncryptedJson("nexusapikey")),
2020-01-09 03:22:49 +00:00
canExecute: IsLoggedIn.ObserveOnGuiThread());
}
public async Task<AbstractDownloadState?> GetDownloaderState(dynamic archiveINI, bool quickMode)
{
var general = archiveINI.General;
if (general.modID != null && general.fileID != null && general.gameName != null)
{
2020-04-02 21:46:11 +00:00
var game = GameRegistry.GetByFuzzyName((string)general.gameName).Game;
2020-04-03 03:57:59 +00:00
if (quickMode)
{
return new State
{
Game = GameRegistry.GetByFuzzyName((string)general.gameName).Game,
ModID = long.Parse(general.modID),
FileID = long.Parse(general.fileID),
};
}
2019-12-07 03:50:50 +00:00
var client = await NexusApiClient.Get();
2020-04-02 21:46:11 +00:00
ModInfo info;
try
{
2020-04-02 21:46:11 +00:00
info = await client.GetModInfo(game, long.Parse((string)general.modID));
}
catch (Exception)
{
Utils.Error($"Error getting mod info for Nexus mod with {general.modID}");
throw;
}
try
{
return new State
{
Name = NexusApiUtils.FixupSummary(info.name),
Author = NexusApiUtils.FixupSummary(info.author),
Version = general.version ?? "0.0.0.0",
ImageURL = info.picture_url,
IsNSFW = info.contains_adult_content,
Description = NexusApiUtils.FixupSummary(info.summary),
Game = GameRegistry.GetByFuzzyName((string)general.gameName).Game,
ModID = long.Parse(general.modID),
FileID = long.Parse(general.fileID)
};
}
catch (FormatException)
{
Utils.Log(
$"Cannot parse ModID/FileID from {(string)general.gameName} {(string)general.modID} {(string)general.fileID}");
throw;
}
}
return null;
}
2019-12-07 02:45:13 +00:00
public async Task Prepare()
{
if (!_prepared)
{
using var _ = await _lock.WaitAsync();
2020-02-06 05:30:31 +00:00
// Could have become prepared while we waited for the lock
if (!_prepared)
{
2020-02-06 05:30:31 +00:00
_client = await NexusApiClient.Get();
_status = await _client.GetUserStatus();
if (!_client.IsAuthenticated)
{
Utils.ErrorThrow(new UnconvertedError(
$"Authenticating for the Nexus failed. A nexus account is required to automatically download mods."));
return;
}
await Metrics.Send("nexus_login", _client.ApiKey!);
2020-02-06 05:30:31 +00:00
if (!await _client.IsPremium())
{
2020-02-06 05:30:31 +00:00
var result = await Utils.Log(new YesNoIntervention(
"Wabbajack can operate without a premium account, but downloads will be slower and the install process will require more user interactions (you will have to start each download by hand). Are you sure you wish to continue?",
"Continue without Premium?")).Task;
if (result == ConfirmationIntervention.Choice.Abort)
{
2020-02-06 05:30:31 +00:00
Utils.ErrorThrow(new UnconvertedError($"Aborting at the request of the user"));
}
}
_prepared = true;
}
}
}
[JsonName("NexusDownloader")]
2020-05-20 03:25:41 +00:00
public class State : AbstractDownloadState, IMetaState, IUpgradingState
{
[JsonIgnore]
public Uri URL => new Uri($"http://nexusmods.com/{Game.MetaData().NexusName}/mods/{ModID}");
public string? Name { get; set; }
public string? Author { get; set; }
public string? Version { get; set; }
2020-04-15 12:05:05 +00:00
public Uri? ImageURL { get; set; }
public bool IsNSFW { get; set; }
public string? Description { get; set; }
[JsonProperty("GameName")]
[JsonConverter(typeof(Utils.GameConverter))]
public Game Game { get; set; }
2020-03-27 03:10:23 +00:00
2020-04-03 03:57:59 +00:00
public long ModID { get; set; }
public long FileID { get; set; }
2020-03-27 03:10:23 +00:00
public async Task<bool> LoadMetaData()
{
return true;
}
2020-03-27 03:10:23 +00:00
[JsonIgnore]
public override object[] PrimaryKey { get => new object[]{Game, ModID, FileID};}
public override bool IsWhitelisted(ServerWhitelist whitelist)
{
// Nexus files are always whitelisted
return true;
}
2020-03-25 22:30:43 +00:00
public override async Task<bool> Download(Archive a, AbsolutePath destination)
{
string url;
try
{
2019-12-07 03:50:50 +00:00
var client = await NexusApiClient.Get();
url = await client.GetNexusDownloadLink(this);
}
catch (Exception ex)
{
2020-01-13 21:11:07 +00:00
Utils.Log($"{a.Name} - Error getting Nexus download URL - {ex.Message}");
return false;
}
Utils.Log($"Downloading Nexus Archive - {a.Name} - {Game} - {ModID} - {FileID}");
return await new HTTPDownloader.State(url).Download(a, destination);
}
public override async Task<bool> Verify(Archive a)
{
try
{
2019-12-07 03:50:50 +00:00
var client = await NexusApiClient.Get();
2020-04-03 03:57:59 +00:00
var modFiles = await client.GetModFiles(Game, ModID);
var found = modFiles.files
2020-04-03 03:57:59 +00:00
.FirstOrDefault(file => file.file_id == FileID && file.category_name != null);
if (found != null)
return true;
Utils.Log($"Could not validate {URL} with cache, validating manually");
modFiles = await client.GetModFiles(Game, ModID, false);
found = modFiles.files
.FirstOrDefault(file => file.file_id == FileID && file.category_name != null);
return found != null;
}
catch (Exception ex)
{
Utils.Log($"{Name} - {Game} - {ModID} - {FileID} - Error getting Nexus download URL - {ex}");
return false;
}
}
public override IDownloader GetDownloader()
{
return DownloadDispatcher.GetInstance<NexusDownloader>();
}
public override string GetManifestURL(Archive a)
{
return $"http://nexusmods.com/{Game.MetaData().NexusName}/mods/{ModID}";
}
public override string[] GetMetaIni()
{
2020-04-03 03:57:59 +00:00
return new[] {"[General]", $"gameName={Game.MetaData().MO2ArchiveName}", $"modID={ModID}", $"fileID={FileID}"};
}
2020-05-20 03:25:41 +00:00
public async Task<(Archive? Archive, TempFile NewFile)> FindUpgrade(Archive a)
{
var client = await NexusApiClient.Get();
var mod = await client.GetModInfo(Game, ModID);
var files = await client.GetModFiles(Game, ModID);
var oldFile = files.files.FirstOrDefault(f => f.file_id == FileID);
var newFile = files.files.OrderByDescending(f => f.uploaded_timestamp).FirstOrDefault();
if (!mod.available || oldFile == default || newFile == default)
{
return default;
}
var tempFile = new TempFile();
2020-05-21 21:25:44 +00:00
var newArchive = new Archive(new State {Game = Game, ModID = ModID, FileID = newFile.file_id})
2020-05-20 03:25:41 +00:00
{
Name = newFile.file_name,
};
await newArchive.State.Download(newArchive, tempFile.Path);
newArchive.Size = tempFile.Path.Size;
newArchive.Hash = await tempFile.Path.FileHashAsync();
return (newArchive, tempFile);
}
public bool ValidateUpgrade(AbstractDownloadState newArchiveState)
{
var state = (State)newArchiveState;
return Game == state.Game && ModID == state.ModID;
}
}
}
}