-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTetrioAPI.cs
203 lines (176 loc) · 5.66 KB
/
TetrioAPI.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Newtonsoft.Json;
using System;
using TetrLoader.JsonClass;
using TetrLoader.JsonClass.API;
using TetrLoader.JsonClass.Raw;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Minomuncher;
/// <summary>
/// スレッドセーフ
/// </summary>
public class TetrioAPI
{
public static string TOKEN { get; private set; }
public static async Task Initialize()
{
var authBody = new
{
username = DotNetEnv.Env.GetString("TETRIO_USERNAME"),
password = DotNetEnv.Env.GetString("TETRIO_PASSWORD")
};
var content = new StringContent(JsonConvert.SerializeObject(authBody), Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "https://tetr.io/api/users/authenticate")
{
Content = content,
};
SetRequestMessage(request, false);
using (var httpClient = new HttpClient())
{
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
using var jsonDocument = JsonDocument.Parse(responseContent);
var tokenValue = jsonDocument.RootElement.GetProperty("token").GetString();
TOKEN = tokenValue;
}
else
{
throw new System.Exception();
}
}
}
public static async Task<Record[]> DownloadListOfGameIds(string userId)
{
//https://ch.tetr.io/api/streams/league_userrecent_${userID}
var request =
new HttpRequestMessage(HttpMethod.Get, $"https://ch.tetr.io/api/streams/league_userrecent_{userId}");
SetRequestMessage(request, true);
HttpResponseMessage response;
using (var httpClient = new HttpClient())
response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var records = JsonSerializer.Deserialize<RawRecords>(responseContent);
return records.data.records.ToArray();
}
else
throw new System.Exception();
return null;
}
/// <summary>
/// idからゲームをダウンロード、一度読み込んだものはキャッシュされる。
/// </summary>
/// <param name="id"></param>
/// <param name="useCache"></param>
/// <returns></returns>
public static async Task<string> GetReplayFromIdAsync(string id, bool useCache = true)
{
//cache使う
//https://tetr.io/api/games/{id}
string? data = null;
if (useCache)
{
if (!Directory.Exists(".cache"))
Directory.CreateDirectory(".cache");
if (File.Exists(".cache/" + id))
data = File.ReadAllText(".cache/" + id);
}
if (data == null)
{
data = await DownloadReplayFromIdAsync(id);
if (useCache)
File.WriteAllText(".cache/" + id, data);
}
return data;
}
private static async Task<string> DownloadReplayFromIdAsync(string id)
{
var request = new HttpRequestMessage(HttpMethod.Get, $"https://tetr.io/api/games/{id}");
SetRequestMessage(request, true);
using (var httpClient = new HttpClient())
{
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var records = JsonSerializer.Deserialize<RawGame>(responseContent);
return records.game.ToString();
}
else
throw new System.Exception(id);
}
}
public static async Task<User> DownloadUserAsync(string username)
{
//https://ch.tetr.io/api/users/${username}
var request = new HttpRequestMessage(HttpMethod.Get, $"https://ch.tetr.io/api/users/{username}");
SetRequestMessage(request, true);
using (var httpClient = new HttpClient())
{
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var user = JsonSerializer.Deserialize<RawUser>(responseContent);
return user.data.user;
}
else
throw new System.Exception();
}
return null;
}
public static async Task<User?> SearchUserbyDsicordId(ulong discordId)
{
//https://ch.tetr.io/api/users/search/${discordId}
var request = new HttpRequestMessage(HttpMethod.Get, $"https://ch.tetr.io/api/users/search/{discordId}");
SetRequestMessage(request, true);
using (var httpClient = new HttpClient())
{
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var user = JsonSerializer.Deserialize<UserSearch>(responseContent);
if ((bool)user.success)
return user?.data?.user;
else return null;
}
else
return null;
}
}
public static async Task<List<User>?> DownloadLeagueUserList()
{
//https://ch.tetr.io/api/users/lists/league/all
var request = new HttpRequestMessage(HttpMethod.Get, $"https://ch.tetr.io/api/users/lists/league/all");
SetRequestMessage(request, false);
using (var httpClient = new HttpClient())
{
var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var leaderBoard = JsonSerializer.Deserialize<LeagueLeaderBoard>(responseContent);
if ((bool)leaderBoard.success)
return leaderBoard.data.users;
else return null;
}
else
throw new System.Exception();
}
return null;
}
private static void SetRequestMessage(HttpRequestMessage request, bool setToken)
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (request.Content != null)
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (setToken)
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", TOKEN);
}
}