-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
166 lines (134 loc) · 7.19 KB
/
Copy pathProgram.cs
File metadata and controls
166 lines (134 loc) · 7.19 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
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
using System.Text.Json;
using System.Net.Http.Headers;
using System.Net.Http.Json;
namespace CherryServersTrafficBuyer
{
internal class Program
{
static string? apiKey = Environment.GetEnvironmentVariable("API_KEY");
static string? projectId = Environment.GetEnvironmentVariable("PROJECT_ID");
static string? trafficThresholdPercentString = Environment.GetEnvironmentVariable("TRAFFIC_THRESHOLD_PERCENT");
static int trafficThresholdPercent;
static string? refreshIntervalMinutesString = Environment.GetEnvironmentVariable("REFRESH_INTERVAL_MINUTES");
static int refreshIntervalMinutes;
const string retrieveProjectTrafficUrl = "https://api.cherryservers.com/v1/projects/{projectId}/traffic";
const string requestMoreTrafficUrl = "https://api.cherryservers.com/v1/traffic/{trafficId}";
static async Task Main(string[] args)
{
#region Validate and parse environment variables
if (apiKey == null)
{
Console.WriteLine("[FATAL]: No API key provided! You must provide an API key with the \"API_KEY\" environment variable!");
return;
}
if (projectId == null)
{
Console.WriteLine("[FATAL]: No project ID provided! You must provide a project ID with the \"PROJECT_ID\" environment variable!");
return;
}
if (trafficThresholdPercentString != null)
{
try
{
trafficThresholdPercent = Convert.ToInt32(trafficThresholdPercentString);
}
catch
{
Console.WriteLine("[ERROR]: Unable to parse \"TRAFFIC_THRESHOLD_PERCENT\" environment variable! Defaulting to 90 percent.");
trafficThresholdPercent = 90;
}
}
else
{
Console.WriteLine("[INFO]: \"TRAFFIC_THRESHOLD_PERCENT\" environment variable not provided. Defaulting to 90 percent.");
trafficThresholdPercent = 90;
}
if(trafficThresholdPercent < 1 || trafficThresholdPercent > 100)
{
Console.WriteLine("[ERROR]: \"TRAFFIC_THRESHOLD_PERCENT\" environment variable not in valid range (expected: 1-100, actual: {0}). Defaulting to 90 percent.", trafficThresholdPercent);
trafficThresholdPercent = 90;
}
if (refreshIntervalMinutesString != null)
{
try
{
refreshIntervalMinutes = Convert.ToInt32(refreshIntervalMinutesString);
}
catch
{
Console.WriteLine("[ERROR]: Unable to parse \"REFRESH_INTERVAL_MINUTES\" environment variable! Defaulting to 65 minutes.");
refreshIntervalMinutes = 65;
}
}
else
{
Console.WriteLine("[INFO]: \"REFRESH_INTERVAL_MINUTES\" environment variable not provided. Defaulting to 65 minutes.");
refreshIntervalMinutes = 65;
}
if (refreshIntervalMinutes < 1)
{
Console.WriteLine("[ERROR]: \"REFRESH_INTERVAL_MINUTES\" environment variable not in valid range (expected: 1 or greater, actual: {0}). Defaulting to 65 minutes.", refreshIntervalMinutes);
refreshIntervalMinutes = 65;
}
#endregion
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var saveTimer = new PeriodicTimer(TimeSpan.FromMinutes(refreshIntervalMinutes));
do
{
Console.WriteLine("[INFO]: Refreshing...");
var retrieveProjectTrafficRequest = new HttpRequestMessage(HttpMethod.Get,
retrieveProjectTrafficUrl.Replace("{projectId}", projectId));
var retrieveProjectTrafficResponse = await client.SendAsync(retrieveProjectTrafficRequest);
string retrieveProjectTrafficResult = await retrieveProjectTrafficResponse.Content.ReadAsStringAsync();
if (!retrieveProjectTrafficResponse.IsSuccessStatusCode)
{
Console.WriteLine("[ERROR]: Retrieve Project Traffic request failed with code {0}", retrieveProjectTrafficResponse.StatusCode);
Console.WriteLine(retrieveProjectTrafficResult);
continue;
}
var retrieveProjectTrafficResultsObjects = JsonSerializer.Deserialize<RetrieveProjectTrafficResponseObject[]>(retrieveProjectTrafficResult);
if (retrieveProjectTrafficResultsObjects == null)
{
Console.WriteLine("[ERROR]: Unable to deserialize response from Retrieve Project Traffic endpoint!");
continue;
}
foreach (var resultsObject in retrieveProjectTrafficResultsObjects)
{
//Check for valid entry
if (resultsObject == null || resultsObject.id == null || resultsObject.limited_bytes == null || resultsObject.used_bytes == null || resultsObject.limited_bytes == 0 || resultsObject.used_bytes == 0)
continue;
double percentUsed = Math.Round(((double)resultsObject.used_bytes / (double)resultsObject.limited_bytes) * 100, 1);
Console.WriteLine("[INFO]: ID: {0} is at {1} bytes used out of {2} bytes available ({3}%)",
resultsObject.id, resultsObject.used_bytes, resultsObject.limited_bytes, percentUsed);
if (percentUsed >= trafficThresholdPercent)
{
Console.WriteLine("[INFO]: Requesting more traffic...");
var requestMoreTrafficRequest = new HttpRequestMessage(HttpMethod.Patch,
requestMoreTrafficUrl.Replace("{trafficId}", resultsObject.id));
requestMoreTrafficRequest.Content = JsonContent.Create(new
{
adjust = 1
});
var requestMoreTrafficResponse = await client.SendAsync(requestMoreTrafficRequest);
string requestMoreTrafficResult = await requestMoreTrafficResponse.Content.ReadAsStringAsync();
if (requestMoreTrafficResponse.IsSuccessStatusCode)
Console.WriteLine("[INFO]: Successfully bought more traffic for ID: {0}", resultsObject.id);
else
{
Console.WriteLine("[ERROR]: Unable to buy more traffic!");
Console.WriteLine(requestMoreTrafficResult);
}
}
}
} while (await saveTimer.WaitForNextTickAsync());
client.Dispose();
}
}
}
class RetrieveProjectTrafficResponseObject
{
public string? id { get; set; }
public long? used_bytes { get; set; }
public long? limited_bytes { get; set; }
}