using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
/// <summary>
/// This is a static class that handles all communication with the matchmaker. If you need a state or
/// you need to use dependency injection, you should use a regular class.
/// We used a static class to "mimic" the behavior of other utility class in unity.
/// You can adjust any method signature to meet your needs.
/// This code use the library Newtonsoft. It is available in unity
/// </summary>
static class MatchmakerUtility
{
private static readonly HttpClient _httpClient = new HttpClient();
// You can found the URL on your matchmaker details page
private static readonly string _matchmakerUrl = "https://supermatchmaker-a979815d099f47.edgegap.net";
private static readonly string _apiToken = "ABCDEF12345";
static MatchmakerUtility()
{
// Only if your matchmaker is in staging and the TLS certificate is self signed
// Disabling certificate validation can expose you to a man-in-the-middle attack
// which may allow your encrypted message to be read by an attacker.
// Works for .NET framework not .NET core
ServicePointManager.ServerCertificateValidationCallback += (s, certificate, chain, sslPolicyErrors) => true;
_httpClient.BaseAddress = new Uri(_matchmakerUrl);
_httpClient.DefaultRequestHeaders.Add("Authorization", _apiToken);
_httpClient.Timeout = TimeSpan.FromSeconds(30);
}
/// <summary>
/// Create a ticket by calling the matchmaker. If the call fails or the status code < 200 or > 299 it returns null
/// </summary>
public static async Task<string> CreateTicket()
{
// Setup the post data
var dataObject = new
{
edgegap_profile_id = "ffa",
matchmaking_data = new
{
selector_data = new
{
mode = "rank",
map = "Dust II",
},
filter_data = new
{
elo = 734
}
}
};
string json = JsonConvert.SerializeObject(dataObject);
StringContent postData = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
// Make the HTTP POST
HttpResponseMessage response = await _httpClient.PostAsync("/v1/tickets", postData).ConfigureAwait(false);
TicketData? parsedData = null;
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
parsedData = JsonConvert.DeserializeObject<Response<TicketData>>(result).data;
}
return parsedData?.Id;
}
public struct TicketData
{
[JsonProperty("ticket_id")]
public string Id { get; set; }
[JsonProperty("assignment")]
public string Connection { get; set; }
}
public struct Response<T>
{
[JsonProperty("request_id")]
public string RequestId { get; set; }
[JsonProperty("data")]
public T data { get; set; }
}
}