forked from ppy/osu-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiCommand.cs
More file actions
71 lines (58 loc) · 2.64 KB
/
ApiCommand.cs
File metadata and controls
71 lines (58 loc) · 2.64 KB
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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Net.Http;
using JetBrains.Annotations;
using McMaster.Extensions.CommandLineUtils;
using osu.Framework.IO.Network;
namespace PerformanceCalculator
{
public abstract class ApiCommand : ProcessorCommand
{
[UsedImplicitly]
[Required]
[Argument(98, Name = "client id", Description = "API Client ID, which you can get from here: https://osu.ppy.sh/home/account/edit#new-oauth-application")]
public string ClientId { get; } = null!;
[UsedImplicitly]
[Required]
[Argument(99, Name = "client secret", Description = "API Client Secret, which you can get from here: https://osu.ppy.sh/home/account/edit#new-oauth-application")]
public string ClientSecret { get; } = null!;
private string? apiAccessToken;
// WARN: keep in sync with /osu.Game/Online/API/APIAccess.cs APIVersion
private const int api_version = 20220705;
public override void OnExecute(CommandLineApplication app, IConsole console)
{
getAccessToken();
base.OnExecute(app, console);
}
protected T GetJsonFromApi<T>(string request, HttpMethod? method = null, Dictionary<string, string>? parameters = null)
{
using var req = new JsonWebRequest<T>($"{Program.ENDPOINT_CONFIGURATION.APIUrl}/api/v2/{request}");
req.Method = method ?? HttpMethod.Get;
req.AddHeader("x-api-version", api_version.ToString(CultureInfo.InvariantCulture));
req.AddHeader(nameof(System.Net.HttpRequestHeader.Authorization), $"Bearer {apiAccessToken}");
if (parameters != null)
{
foreach ((string key, string value) in parameters)
req.AddParameter(key, value);
}
req.Perform();
return req.ResponseObject;
}
private void getAccessToken()
{
using var req = new JsonWebRequest<dynamic>($"{Program.ENDPOINT_CONFIGURATION.APIUrl}/oauth/token")
{
Method = HttpMethod.Post
};
req.AddParameter("client_id", ClientId);
req.AddParameter("client_secret", ClientSecret);
req.AddParameter("grant_type", "client_credentials");
req.AddParameter("scope", "public");
req.Perform();
apiAccessToken = req.ResponseObject.access_token.ToString();
}
}
}