using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pathoschild.Http.Client;
using StardewModdingAPI.Common.Models;
namespace StardewModdingAPI.Web.Framework.ModRepositories
{
/// An HTTP client for fetching mod metadata from Nexus Mods.
internal class NexusRepository : RepositoryBase
{
/*********
** Properties
*********/
/// The URL for a Nexus Mods API query excluding the base URL, where {0} is the mod ID.
private readonly string ModUrlFormat;
/// The underlying HTTP client.
private readonly IClient Client;
/*********
** Public methods
*********/
/// Construct an instance.
/// The unique key for this vendor.
/// The user agent for the Nexus Mods API client.
/// The base URL for the Nexus Mods API.
/// The URL for a Nexus Mods API query excluding the , where {0} is the mod ID.
public NexusRepository(string vendorKey, string userAgent, string baseUrl, string modUrlFormat)
: base(vendorKey)
{
this.ModUrlFormat = modUrlFormat;
this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
}
/// Get metadata about a mod in the repository.
/// The mod ID in this repository.
public override async Task GetModInfoAsync(string id)
{
// validate ID format
if (!uint.TryParse(id, out uint _))
return new ModInfoModel($"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID.");
// fetch info
try
{
NexusResponseModel response = await this.Client
.GetAsync(string.Format(this.ModUrlFormat, id))
.As();
return response != null
? new ModInfoModel(response.Name, this.NormaliseVersion(response.Version), response.Url)
: new ModInfoModel("Found no mod with this ID.");
}
catch (Exception ex)
{
return new ModInfoModel(ex.ToString());
}
}
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public override void Dispose()
{
this.Client.Dispose();
}
/*********
** Private models
*********/
/// A mod metadata response from Nexus Mods.
private class NexusResponseModel
{
/*********
** Accessors
*********/
/// The mod name.
public string Name { get; set; }
/// The mod's semantic version number.
public string Version { get; set; }
/// The mod's web URL.
[JsonProperty("mod_page_uri")]
public string Url { get; set; }
}
}
}