-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGmailDataStore.cs
106 lines (95 loc) · 3.35 KB
/
GmailDataStore.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
using Google.Apis.Json;
using Google.Apis.Util.Store;
using Streamer.bot.Plugin.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmailBot
{
internal class GmailDataStore : IDataStore
{
private readonly IInlineInvokeProxy BotProxy;
private readonly Dictionary<string, string> DataStore;
private readonly DateTime Expiration;
public GmailDataStore(IInlineInvokeProxy botProxy)
{
BotProxy = botProxy;
DataStore = new Dictionary<string, string>();
Expiration = DateTime.Now.AddDays(7);
try
{
Expiration = BotProxy.GetGlobalVar<DateTime>("GmailTokenExpiration");
if (Expiration != null && Expiration.Subtract(DateTime.Now).TotalDays >= 1)
{
BotProxy.LogVerbose("[Email.bot] Cache is valid. Loading DataStore...");
string json = BotProxy.GetGlobalVar<string>("GmailToken", true);
if (json != null)
{
DataStore = json.ToUnprotectedObject<Dictionary<string, string>>();
}
}
else
{
BotProxy.LogVerbose("[Email.bot] Cache is either invalid or expired. Authorization will be renewed.");
BotProxy.UnsetGlobalVar("GmailToken");
BotProxy.UnsetGlobalVar("GmailTokenExpiration");
Expiration = DateTime.Now.AddDays(7);
}
}
catch (Exception e)
{
BotProxy.LogDebug("[Email.bot] An error occured during DataStore initialization : " + e);
}
}
private void Persist()
{
BotProxy.LogVerbose("[Email.bot] Saving cache data...");
BotProxy.SetGlobalVar("GmailToken", DataStore.ToProtectedData());
BotProxy.SetGlobalVar("GmailTokenExpiration", Expiration);
}
public Task ClearAsync()
{
DataStore.Clear();
Persist();
return Task.CompletedTask;
}
public Task DeleteAsync<T>(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
DataStore.Remove(key);
Persist();
return Task.CompletedTask;
}
public Task<T> GetAsync<T>(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
if (DataStore.TryGetValue(key, out var value))
{
return Task.FromResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(value));
}
else
{
return Task.FromResult((T)default);
}
}
public Task StoreAsync<T>(string key, T value)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
DataStore.Remove(key);
DataStore.Add(key, NewtonsoftJsonSerializer.Instance.Serialize(value));
Persist();
return Task.CompletedTask;
}
}
}