using System;
using System.Threading.Tasks;
using StardewModdingAPI.Toolkit.Framework.UpdateData;
using StardewModdingAPI.Web.Framework.Clients.GitHub;
namespace StardewModdingAPI.Web.Framework.ModRepositories
{
/// An HTTP client for fetching mod metadata from GitHub project releases.
internal class GitHubRepository : RepositoryBase
{
/*********
** Fields
*********/
/// The underlying GitHub API client.
private readonly IGitHubClient Client;
/*********
** Public methods
*********/
/// Construct an instance.
/// The underlying GitHub API client.
public GitHubRepository(IGitHubClient client)
: base(ModRepositoryKey.GitHub)
{
this.Client = client;
}
/// Get metadata about a mod in the repository.
/// The mod ID in this repository.
public override async Task GetModInfoAsync(string id)
{
ModInfoModel result = new ModInfoModel().SetBasicInfo(id, $"https://github.com/{id}/releases");
// validate ID format
if (!id.Contains("/") || id.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != id.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase))
return result.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'.");
// fetch info
try
{
// fetch repo info
GitRepo repository = await this.Client.GetRepositoryAsync(id);
if (repository == null)
return result.SetError(RemoteModStatus.DoesNotExist, "Found no GitHub repository for this ID.");
result
.SetBasicInfo(repository.FullName, $"{repository.WebUrl}/releases")
.SetLicense(url: repository.License?.Url, name: repository.License?.SpdxId ?? repository.License?.Name);
// get latest release (whether preview or stable)
GitRelease latest = await this.Client.GetLatestReleaseAsync(id, includePrerelease: true);
if (latest == null)
return result.SetError(RemoteModStatus.DoesNotExist, "Found no GitHub release for this ID.");
// split stable/prerelease if applicable
GitRelease preview = null;
if (latest.IsPrerelease)
{
GitRelease release = await this.Client.GetLatestReleaseAsync(id, includePrerelease: false);
if (release != null)
{
preview = latest;
latest = release;
}
}
// return data
return result.SetVersions(version: this.NormalizeVersion(latest.Tag), previewVersion: this.NormalizeVersion(preview?.Tag));
}
catch (Exception ex)
{
return result.SetError(RemoteModStatus.TemporaryError, ex.ToString());
}
}
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public override void Dispose()
{
this.Client.Dispose();
}
}
}