-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
301 lines (255 loc) · 9.59 KB
/
Program.cs
File metadata and controls
301 lines (255 loc) · 9.59 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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
using System;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
using System.Net;
using MailKit.Security;
using System.Collections.Generic;
using MailKit.Net.Pop3;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
using System.Threading;
using Discord;
using System.Text.RegularExpressions;
using System.Linq;
using NUnit.Framework;
using Discord.WebSocket;
using System.Timers;
using HtmlAgilityPack;
using System.Runtime.InteropServices;
//MailKit documentation http://www.mimekit.net/docs/html/Introduction.htm
//Json.NET documentation https://www.newtonsoft.com/json/help/html/Introduction.htm
/*
* Email service and everything related to it regularly check for emails,
* when one is recieved, the program creates a message and sends it to the
* Discord section.
*
* The discord section will send a message to a specific server and channel
* based on information extraced from the email.
*/
namespace AutomaticAnnouncements
{
class Program
{
//If true, changes announcement channel and removes some of the first emails
public static readonly bool debug = false;
private static int numberOfEmailsToCheck = 10;
private static readonly System.Timers.Timer timer = new System.Timers.Timer(2 * 60 * 1000) { AutoReset = true, }; //When testing, don't set this to less than 10 sec to avoid annoying things getting on top of each other
private DiscordSocketClient _client;
// To avoid checking every every email recieved since the start of time, this stores the x last ones
// There *is* a risk that too many emails will be recieved at the same time, and some get ignored,
// but that is extremly unlikely
private List<EmailMessage> checkedEmails = new List<EmailMessage>(numberOfEmailsToCheck);
private readonly Stack<Tuple<ulong, string>> messageStack = new Stack<Tuple<ulong, string>>();
private int checkIndex = 0;
static void Main() => new Program().MainAsync().GetAwaiter().GetResult();
// Sets up the email service to recieve and check emails
public EmailService SetupEmail()
{
EmailConfiguration config = ExternalData.GetEmailConfiguration();
EmailService service = new EmailService(config);
return service;
}
// Sends an email, unused
//public void SendEmail(EmailService service)
//{
// EmailMessage message = new EmailMessage
// {
// FromAddresses = new List<EmailAddress>() { new EmailAddress("TorNiklas", "torniklas@outlook.com") },
// ToAddresses = new List<EmailAddress>() { new EmailAddress("TorNiklas", "torniklas@outlook.com") },
// Subject = "This day is nice",
// Content = "You'd be surprised, it really is."
// };
// service.Send(message);
//}
// Checks for new emails, pushes any new emails to messageStack
public void StackNewEmailsAsync(EmailService service)
{
ulong serverID;
ulong channelID;
string message ="";
string chapterTitle;
string novelTitle = "";
string url;
string mention;
List<EmailMessage> emails = service.ReceiveLatestEmail(numberOfEmailsToCheck);
foreach (EmailMessage email in emails)
{
if (checkedEmails.Contains(email)) { continue; }
string announcements = "Announcements";
string patreon = "Patreon";
if(debug)
{
announcements = "FAnnouncements";
patreon = "FPatreon";
}
// Filter emails based on sender
switch (email.FromAddresses[0].Address)
{
// Redirected
case "torniklas@outlook.com":
if (email.Subject.Contains("Novels by Mecanimus"))
{
// All emails from this address are on a certain format, the top code here
//is to extrace certain information from those emails
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(email.Content);
chapterTitle = email.Subject.Split("\"")[1];
string link = doc.DocumentNode.SelectNodes("//a")[2].Attributes["href"].Value;
link = link.Split("?")[0];
JObject novels = (JObject)ExternalData.GetSection("Novels");
//TODO: Don't hardcode this
bool neither = !chapterTitle.Contains("Journey") && !chapterTitle.Contains("Bob");
if (chapterTitle.Contains("Journey") || neither)
{
JObject novel = (JObject)novels["A Journey of Black and Red"];
serverID = (ulong)novel["Server"];
channelID = (ulong)novel[patreon];
mention = (string)novel["PatreonMention"];
message = MakeMessage(mention, chapterTitle, link);
messageStack.Push(new Tuple<ulong, string>(channelID, message));
}
if (chapterTitle.Contains("Bob") || neither)
{
JObject novel = (JObject)novels["The Calamitous Bob"];
serverID = (ulong)novel["Server"];
channelID = (ulong)novel[patreon];
mention = (string)novel["PatreonMention"];
message = MakeMessage(mention, chapterTitle, link);
messageStack.Push(new Tuple<ulong, string>(channelID, message));
}
}
ReportCheckedEmail(email);
break;
case "noreply@royalroad.com":
if (email.Subject.StartsWith("New Chapter of "))
{
ReportCheckedEmail(email);
try
{
// All emails from this address are on a certain format, the top code here
//is to extrace certain information from those emails
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(email.Content);
//Console.WriteLine(doc.DocumentNode.SelectNodes("//a")[3].Attributes["href"].Value);
//for (int i = 0; i < doc.DocumentNode.SelectNodes("//a").Count; i++)
//{
// Console.WriteLine(i + ": " + doc.DocumentNode.SelectNodes("//a")[i].Attributes["href"].Value);
//}
chapterTitle = doc.DocumentNode.SelectNodes("//td")[15].InnerText.Split("\n")[74].Trim();
string link = doc.DocumentNode.SelectNodes("//a")[1].Attributes["href"].Value;
novelTitle = email.Subject.Split("New Chapter of ")[1];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(link);
req.AllowAutoRedirect = true;
HttpWebResponse myResp = (HttpWebResponse)req.GetResponse();
url = myResp.ResponseUri.ToString();
JObject jid = (JObject)ExternalData.GetSection("Novels")[novelTitle];
if (jid == null) continue;
serverID = (ulong)jid["Server"];
channelID = (ulong)jid[announcements];
mention = (string)jid["Mention"];
// Pushes a message with extracted onformaion to messageStack
message = MakeMessage(mention, chapterTitle, url);
messageStack.Push(new Tuple<ulong, string>(channelID, message));
}
catch (Exception e)
{
Console.WriteLine("Update failed for " + novelTitle);
Console.WriteLine(e);
}
}
break;
case "bingo@patreon.com":
//Console.WriteLine("Mail from patreon");
//Console.WriteLine(email.Subject);
//Console.WriteLine(email.Content);
break;
default:
//Console.WriteLine("Unrecognised email adress");
//Console.WriteLine(email.Subject);
//Console.WriteLine(email.FromAddresses[0].Address);
break;
}
}
}
// Sends stacked messages in messageStack
public async void PopMessageStack(DiscordSocketClient client) {
while (messageStack.Count > 0)
{
Tuple<ulong, string> tuple = messageStack.Pop();
if (tuple == null) continue;
await (client.GetChannel(tuple.Item1) as IMessageChannel).SendMessageAsync(tuple.Item2);
}
}
//Depricated (I think)
// Don't want to resend old messages when the system starts,
// this prevents that
public void ListOldEmails(EmailService service)
{
checkedEmails = service.ReceiveLatestEmail(numberOfEmailsToCheck);
//Remove some emails. Only for testing purposes
if (debug)
{
int numOfEmailsToRemove = 1;
var newCheckedEmails = checkedEmails.GetRange(numOfEmailsToRemove, checkedEmails.Count - numOfEmailsToRemove);
for (int i = 0; i < checkedEmails.Count; i++)
{
if(i < newCheckedEmails.Count)
{
checkedEmails[i] = newCheckedEmails[i];
}
else
{
checkedEmails[i] = null;
}
}
}
checkedEmails.Reverse();
}
// When at the end of the list, start at the beginning again and overwrite the oldest one
public void ReportCheckedEmail(EmailMessage email)
{
checkedEmails[checkIndex] = email;
checkIndex = ++checkIndex % numberOfEmailsToCheck;
}
// Creates the message to be sent
public string MakeMessage(string mention, string chapterTitle, string url, string chapterType = "chapter")
{
return mention + "\nHEAR YE, HEAR YE!\nNew " + chapterType + ":** " + chapterTitle + "\n**" + url;
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
// Sets up and starts everything, making sure the program check for emails regularly
private async Task MainAsync()
{
string token = (string)ExternalData.GetSection("Discord")["Token"];
DiscordSocketConfig _config = new DiscordSocketConfig { MessageCacheSize = 100 };
_client = new DiscordSocketClient(_config);
_client.Log += Log;
var service = SetupEmail();
ListOldEmails(service);
timer.Elapsed += (source, e) =>
{
StackNewEmailsAsync(service);
PopMessageStack(_client);
Console.WriteLine("Last pop: " + e.SignalTime);
};
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
StackNewEmailsAsync(service);
PopMessageStack(_client);
Console.WriteLine("Last pop: initial");
timer.Start();
//StackNewEmailsAsync(service);
//PopMessageStack(_client);
//Console.WriteLine("Last pop: initial");
await Task.Delay(-1);
}
}
}