using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
using StardewModdingAPI.Models;
namespace StardewModdingAPI.Framework
{
/// Provides methods for interacting with the SMAPI web API.
internal class WebApiClient
{
/*********
** Properties
*********/
/// The base URL for the web API.
private readonly Uri BaseUrl;
/// The API version number.
private readonly ISemanticVersion Version;
/*********
** Public methods
*********/
/// Construct an instance.
/// The base URL for the web API.
/// The web API version.
public WebApiClient(string baseUrl, ISemanticVersion version)
{
#if !SMAPI_FOR_WINDOWS
baseUrl = baseUrl.Replace("https://", "http://"); // workaround for OpenSSL issues with the game's bundled Mono on Linux/Mac
#endif
this.BaseUrl = new Uri(baseUrl);
this.Version = version;
}
/// Get the latest SMAPI version.
/// The mod keys for which to fetch the latest version.
public IDictionary GetModInfo(params string[] modKeys)
{
return this.Post>(
$"v{this.Version}/mods",
new ModSearchModel(modKeys)
);
}
/*********
** Private methods
*********/
/// Fetch the response from the backend API.
/// The body content type.
/// The expected response type.
/// The request URL, optionally excluding the base URL.
/// The body content to post.
private TResult Post(string url, TBody content)
{
/***
** Note: avoid HttpClient for Mac compatibility.
***/
using (WebClient client = new WebClient())
{
Uri fullUrl = new Uri(this.BaseUrl, url);
string data = JsonConvert.SerializeObject(content);
client.Headers["Content-Type"] = "application/json";
client.Headers["User-Agent"] = $"SMAPI/{this.Version}";
string response = client.UploadString(fullUrl, data);
return JsonConvert.DeserializeObject(response);
}
}
}
}