-
Notifications
You must be signed in to change notification settings - Fork 100
/
TimeAligner.cs
87 lines (79 loc) · 2.96 KB
/
TimeAligner.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
using System;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Text;
namespace SteamAuth
{
/// <summary>
/// Class to help align system time with the Steam server time. Not super advanced; probably not taking some things into account that it should.
/// Necessary to generate up-to-date codes. In general, this will have an error of less than a second, assuming Steam is operational.
/// </summary>
public class TimeAligner
{
private static bool _aligned = false;
private static int _timeDifference = 0;
public static long GetSteamTime()
{
if (!TimeAligner._aligned)
{
TimeAligner.AlignTime();
}
return DateTimeOffset.UtcNow.ToUnixTimeSeconds() + _timeDifference;
}
public static async Task<long> GetSteamTimeAsync()
{
if (!TimeAligner._aligned)
{
await TimeAligner.AlignTimeAsync();
}
return DateTimeOffset.UtcNow.ToUnixTimeSeconds() + _timeDifference;
}
public static void AlignTime()
{
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
try
{
string response = client.UploadString(APIEndpoints.TWO_FACTOR_TIME_QUERY, "steamid=0");
TimeQuery query = JsonConvert.DeserializeObject<TimeQuery>(response);
TimeAligner._timeDifference = (int)(query.Response.ServerTime - currentTime);
TimeAligner._aligned = true;
}
catch (WebException)
{
return;
}
}
}
public static async Task AlignTimeAsync()
{
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
WebClient client = new WebClient();
try
{
client.Encoding = Encoding.UTF8;
string response = await client.UploadStringTaskAsync(new Uri(APIEndpoints.TWO_FACTOR_TIME_QUERY), "steamid=0");
TimeQuery query = JsonConvert.DeserializeObject<TimeQuery>(response);
TimeAligner._timeDifference = (int)(query.Response.ServerTime - currentTime);
TimeAligner._aligned = true;
}
catch (WebException)
{
return;
}
}
internal class TimeQuery
{
[JsonProperty("response")]
internal TimeQueryResponse Response { get; set; }
internal class TimeQueryResponse
{
[JsonProperty("server_time")]
public long ServerTime { get; set; }
}
}
}
}