using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pathoschild.Http.Client;
using StardewModdingAPI.Models;
namespace StardewModdingAPI.Web.Framework.ModRepositories
{
/// An HTTP client for fetching mod metadata from GitHub project releases.
internal class GitHubRepository : IModRepository
{
/*********
** Properties
*********/
/// The underlying HTTP client.
private readonly IClient Client;
/*********
** Accessors
*********/
/// The unique key for this vendor.
public string VendorKey { get; }
/// The URL for a Nexus Mods API query excluding the base URL, where {0} is the mod ID.
public string ReleaseUrlFormat { get; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The unique key for this vendor.
/// The base URL for the Nexus Mods API.
/// The URL for a Nexus Mods API query excluding the , where {0} is the mod ID.
/// The user agent for the API client.
/// The Accept header value expected by the GitHub API.
/// The username with which to authenticate to the GitHub API.
/// The password with which to authenticate to the GitHub API.
public GitHubRepository(string vendorKey, string baseUrl, string releaseUrlFormat, string userAgent, string acceptHeader, string username, string password)
{
this.VendorKey = vendorKey;
this.ReleaseUrlFormat = releaseUrlFormat;
this.Client = new FluentClient(baseUrl)
.SetUserAgent(userAgent)
.AddDefault(req => req.WithHeader("Accept", acceptHeader));
if (!string.IsNullOrWhiteSpace(username))
this.Client = this.Client.SetBasicAuthentication(username, password);
}
/// Get metadata about a mod in the repository.
/// The mod ID in this repository.
public async Task GetModInfoAsync(string id)
{
try
{
// fetch data
GitRelease release = await this.Client
.GetAsync(string.Format(this.ReleaseUrlFormat, id))
.As();
// extract fields
string name = id;
string version = release.Tag;
if (version.StartsWith("v")) // common format on GitHub
version = version.Substring(1);
string url = $"https://github.com/{id}/releases";
return new ModInfoModel(name, version, url);
}
catch (Exception ex)
{
return new ModInfoModel(ex.ToString());
}
}
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
{
this.Client.Dispose();
}
/*********
** Private models
*********/
/// Metadata about a GitHub release tag.
private class GitRelease
{
/*********
** Accessors
*********/
/// The display name.
[JsonProperty("name")]
public string Name { get; set; }
/// The semantic version string.
[JsonProperty("tag_name")]
public string Tag { get; set; }
}
}
}