-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAPI.cs
188 lines (167 loc) · 6.82 KB
/
API.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using System.Net;
using System.Text.RegularExpressions;
using MowChat.Data;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MowChat
{
public class API
{
/// <summary>
/// The base URL to prepend to all API calls.
/// </summary>
private const string BaseUrl = "https://marchofwar.isotx.com/api/v6/";
/// <summary>
/// The instance of the API singleton.
/// </summary>
private static API _instance;
/// <summary>
/// The instance of the API singleton.
/// </summary>
public static API Instance
{
get { return _instance ?? (_instance = new API()); }
}
/// <summary>
/// The RestSharp client used to send the requests.
/// </summary>
private readonly RestClient _restClient;
/// <summary>
/// The latest recorded value of the session cookie.
/// </summary>
private string _cookieValue;
/// <summary>
/// The currently logged in user, if any.
/// </summary>
public User CurrentUser { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
private API()
{
_restClient = new RestClient(BaseUrl);
}
/// <summary>
/// Send a GET API request.
/// </summary>
/// <typeparam name="T">The expected response type.</typeparam>
/// <param name="callback">The function to call when the API call completes.</param>
/// <param name="endpoint">The API request to send.</param>
/// <param name="args">A dictionary of arguments to passs.</param>
public void Get<T>(Action<T> callback, string endpoint, Dictionary<string, string> args = null) where T : new()
{
Call(callback, Method.GET, endpoint, args);
}
/// <summary>
/// Send a POST API request.
/// </summary>
/// <typeparam name="T">The expected response type.</typeparam>
/// <param name="callback">The function to call when the API call completes.</param>
/// <param name="endpoint">The API request to send.</param>
/// <param name="args">A dictionary of arguments to passs.</param>
public void Post<T>(Action<T> callback, string endpoint, Dictionary<string, string> args = null) where T : new()
{
Call(callback, Method.POST, endpoint, args);
}
/// <summary>
/// Send an API request.
/// </summary>
/// <typeparam name="T">The expected response type.</typeparam>
/// <param name="callback">The function to call when the API call completes.</param>
/// <param name="method">The HTTP method to use for this request.</param>
/// <param name="endpoint">The API request to send.</param>
/// <param name="args">A dictionary of arguments to passs.</param>
private void Call<T>(Action<T> callback, Method method, string endpoint, Dictionary<string, string> args) where T : new()
{
var request = new RestRequest(endpoint, method);
if (args != null)
{
foreach (var kvp in args.Where(kvp => kvp.Key != null && kvp.Value != null))
{
request.AddParameter(kvp.Key, kvp.Value);
}
}
if (!string.IsNullOrEmpty(_cookieValue))
{
request.AddCookie("mow_session", _cookieValue);
}
Logger.Print(string.Format("Request to API, {0} {1}, {2}", method, endpoint,
args != null
? string.Join(",", args.Select(x => x.Key + "=" + x.Value))
: "(no params)"));
_restClient.ExecuteAsync<T>(request, response => OnCallCompleted(response, callback));
}
/// <summary>
/// Handle a response from the API.
/// </summary>
/// <typeparam name="T">The expected response type.</typeparam>
/// <param name="response">The API response.</param>
/// <param name="callback">The function to call when the API call completes.</param>
private void OnCallCompleted<T>(IRestResponse<T> response, Action<T> callback)
{
Logger.Print(string.Format("Response from API, {0} {1}, {2} {3}, {4}", response.Request.Method,
response.Request.Resource, response.ResponseStatus, response.StatusCode,
response.Content));
foreach (var cookie in response.Cookies.Where(cookie => cookie.Name == "mow_session"))
{
_cookieValue = cookie.Value;
}
// Don't call callback if unauthorized, connectivity issues, or in maintenance
if (CheckLogin<T>(response) || CheckConnectiviy(response) || CheckMaintenance(response) || CheckError<T>(response)) return;
if (response.Request.Resource == "auth/current" || response.Request.Resource == "auth/consume")
{
CurrentUser = response.Data as User;
}
else if (Regex.IsMatch(response.Request.Resource, "players/[0-9]+/select") && CurrentUser != null)
{
CurrentUser.SelectedCharacter = response.Data as Character;
}
if (callback != null)
callback(response.Data);
}
/// <summary>
/// Check that the response status is not unauthorized, unless that's expected.
/// </summary>
/// <typeparam name="T">The type of response.</typeparam>
/// <param name="response">The API response.</param>
/// <returns>True if the response code is unauthorized.</returns>
private static bool CheckLogin<T>(IRestResponse response)
{
return response.ResponseStatus == ResponseStatus.Completed &&
response.StatusCode == HttpStatusCode.Unauthorized &&
typeof(T) != typeof(AuthToken);
}
/// <summary>
/// Checks that the response status is completed.
/// </summary>
/// <param name="response">The API response.</param>
/// <returns>True if the response status is not completed.</returns>
private static bool CheckConnectiviy(IRestResponse response)
{
return response.ResponseStatus != ResponseStatus.Completed;
}
/// <summary>
/// Checks that the response does not indicate the server is down for maintenance.
/// </summary>
/// <param name="response">The API response.</param>
/// <returns>True if the server is in maintenance.</returns>
private static bool CheckMaintenance(IRestResponse response)
{
return response.ResponseStatus == ResponseStatus.Completed &&
response.StatusCode == HttpStatusCode.ServiceUnavailable;
}
/// <summary>
/// Checks that the response status code is not okay.
/// </summary>
/// <typeparam name="T">The type of response.</typeparam>
/// <param name="response">The API response.</param>
/// <returns>True if the response status is not okay.</returns>
private static bool CheckError<T>(IRestResponse response)
{
return response.StatusCode != HttpStatusCode.OK &&
typeof(T) != typeof(AuthToken);
}
}
}