-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
357 lines (302 loc) · 14.3 KB
/
MainForm.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Net;
using ININ.PureCloudApi.Api;
using ININ.PureCloudApi.Model;
using System.Threading.Tasks;
namespace PureCloudAgent
{
public partial class MainForm : Form
{
// *** FILL IN YOUR INFO HERE ***
private const string UserName = ""; // YOUR DUMMY USERNAME
private const string Password = ""; // YOUR DUMMY USER PASSWORD
private const string ClientId = ""; // YOUR OAUTH CLIENT ID
private const string OrgShortName = ""; // YOUR ORG SHORT NAME (PureCloud > Admin > Organization Settings)
private const string DefaultRecipientEmail = ""; // DEFAULT EMAIL ADDRESS TO RECEIVE UNASSIGNED VMs/FAXES
private const string EmailFromAddress = ""; // FROM ADDRESS FOR VM/FAX EMAILS
private const string EmailServer = ""; // YOUR EMAIL SERVER
private const int EmailPort = 587; // EMAIL SERVER PORT
private const string EmailServerUsername = ""; // EMAIL SERVER USERNAME
private const string EmailServerPassword = ""; // EMAIL SERVER PASSWORD
// *******************************
private readonly string nl = System.Environment.NewLine;
private int vmFaxCountdown;
private string user;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
Log("Starting");
String[] arguments = Environment.GetCommandLineArgs();
user = (arguments.Length >= 2) ? arguments[1] : UserName;
this.Text += " - " + user;
vmFaxCountdown = Properties.Settings.Default.vmFaxInterval;
vmFaxCountdownLabel.Text = vmFaxCountdown.ToString();
Authenticate();
}
private void Authenticate()
{
Log("Authenticating");
this.WindowState = FormWindowState.Normal;
//Redirect the browser to the login window.
webBrowser1.Url = new Uri("https://login.mypurecloud.com/oauth/authorize?" +
"response_type=token" +
"&client_id=" + ClientId +
"&redirect_uri=http://localhost:8085/oauth2/callback");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var url = e.Url.ToString();
if (url.Contains("https://login.mypurecloud.com/?rid") &&
url.Contains("/authenticate-adv/org/" + OrgShortName))
{
loginWaitTimer.Start();
}
}
private void loginWaitTimer_Tick(object sender, EventArgs e)
{
loginWaitTimer.Stop();
AutoLogin();
}
private void AutoLogin()
{
string javaScript = @"
function submitLogin()
{
document.getElementById('email').value = '" + user + @"';
document.getElementById('password').value = '" + Password + @"';
document.getElementById('password').focus();
document.getElementById('password').blur();
document.getElementsByTagName('button')[0].click();
}
";
HtmlDocument doc = webBrowser1.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text", javaScript);
head.AppendChild(s);
webBrowser1.Document.InvokeScript("submitLogin");
}
private void OnWebBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
//When the web browser control navigates, check if the url is the callback and contains the access_token
var url = e.Url.ToString();
if (url.Contains("access_token"))
{
var queryString = url.Substring(url.LastIndexOf("#") + 1);
var props = queryString.Split('&');
string accessToken = props[0].Split('=')[1];
ININ.PureCloudApi.Client.Configuration.Default.AccessToken = accessToken;
Log("Successfully authenticated");
}
}
private async void CheckVoicemailAndFax()
{
vmFaxCountdown = Properties.Settings.Default.vmFaxInterval;
try
{
ProcessVoicemail();
ProcessFax();
}
catch (ININ.PureCloudApi.Client.ApiException ex)
{
if (ex.ErrorCode == 401)
{
Log("Need to authenticate first. Try again in a few seconds.");
Logout();
await Delay(7000);
Authenticate();
}
else
{
Log("Error: " + ex.Message);
}
}
}
private void ProcessVoicemail()
{
// Check Voicemail
var vmApi = new VoicemailApi();
var convApi = new ConversationsApi();
var vms = vmApi.GetMessages();
VoicemailMediaInfo vmMedia;
foreach (VoicemailMessage vm in vms.Entities.Where(x => !(x.Read ?? false))) // Unread VMs only
{
DateTime vmDate = vm.CreatedDate != null ? ((DateTime)vm.CreatedDate).ToLocalTime() : DateTime.Now;
Log("VM from " + vm.CallerAddress + " at " + vmDate);
// Check for Group attribute so we know where to send it (use default if nothing found)
string group = "unknown";
string groupEmail = DefaultRecipientEmail;
var call = convApi.GetCallsCallId(vm.Conversation.Id);
CallMediaParticipant participant = null;
try
{
participant = call.Participants.First(x => x.Attributes != null && x.Attributes.ContainsKey("Group"));
}
catch { }
if (participant != null)
{
group = participant.Attributes["Group"];
// Try to look up the email for this group in Settings. If it's not found, just move on with the default
try
{
groupEmail = Properties.Settings.Default[group].ToString();
}
catch { }
}
else
{
participant = call.Participants[0];
}
// Download the WAV file
string fileName;
vmMedia = vmApi.GetMessagesMessageIdMedia(vm.Id, "WAV");
using (var client = new WebClient())
{
fileName = Path.GetTempPath() +
"PureCloud_VM_" + group + "_" +
vmDate.ToString("yyyyMMdd-HHmmss") + ".wav";
client.DownloadFile(vmMedia.MediaFileUri, fileName);
}
// Email to the proper group
string callerName = (vm.CallerName ?? participant.Name ?? vm.CallerAddress);
string subject = "Voicemail from " + callerName;
string body = ComposeVoicemailEmail(vmDate, group, vm.CallerAddress, callerName);
SendEmail(groupEmail, EmailFromAddress, body, subject, fileName);
Log(" Sent to " + group + ": " + groupEmail);
// Mark the VM as read so it won't get sent again next time
vm.Read = true;
vmApi.PutMessagesMessageId(vm.Id, vm);
}
}
private void ProcessFax()
{
// Check Fax
var faxApi = new FaxApi();
var faxes = faxApi.GetDocuments();
foreach (FaxDocument fax in faxes.Entities.Where(x => !(x.Read ?? false)))
{
DateTime faxDate = fax.DateCreated != null ? ((DateTime)fax.DateCreated).ToLocalTime() : DateTime.Now;
string fromNumber = fax.CallerAddress.Replace("tel:+", "");
string toNumber = fax.ReceiverAddress.Replace("tel:+", "");
Log("FAX from " + fax.CallerAddress + " at " + faxDate);
// Try to look up the email for this fax # in Settings. If it's not found, just move on with the default
string groupEmail = DefaultRecipientEmail;
try
{
groupEmail = Properties.Settings.Default["n"+toNumber].ToString();
}
catch { }
// Download the fax file
string fileName;
DownloadResponse faxFile = faxApi.GetDocumentsDocumentIdContent(fax.Id);
using (var client = new WebClient())
{
// Replace any characters not allowed in a file name
string fromNumberSafeString = fromNumber
.Replace(@"\", "")
.Replace(@"/", "")
.Replace(@":", "")
.Replace(@"*", "")
.Replace(@"?", "")
.Replace(@"""", "")
.Replace(@"<", "")
.Replace(@">", "")
.Replace(@"|", "")
.Replace(@" ", "");
fileName = Path.GetTempPath() +
"PureCloud_FAX_" + fromNumberSafeString + "_" +
faxDate.ToString("yyyyMMdd-HHmmss") + ".pdf";
client.DownloadFile(faxFile.ContentLocationUri, fileName);
}
// Email to the proper group
string subject = "Fax from " + fromNumber;
string body = ComposeFaxEmail(faxDate, fromNumber, toNumber);
SendEmail(groupEmail, EmailFromAddress, body, subject, fileName);
Log(" Sent to " + toNumber + ": " + groupEmail);
// Mark the fax as read so it won't get sent again next time
fax.Read = true;
faxApi.PutDocumentsDocumentId(fax.Id, fax);
}
}
private void Logout()
{
// Log Out
webBrowser1.Url = new Uri("https://login.mypurecloud.com/logout");
}
private void oneSecondTimer_Tick(object sender, EventArgs e)
{
vmFaxCountdown--;
vmFaxCountdownLabel.Text = vmFaxCountdown.ToString();
if (vmFaxCountdown <= 0)
{
CheckVoicemailAndFax();
}
}
private void vmFaxButton_Click(object sender, EventArgs e)
{
CheckVoicemailAndFax();
}
private void Log(string message)
{
textBox1.AppendText(message + nl);
textBox1.Select(textBox1.TextLength - 1, 0);
}
private void SendEmail(string strTo, string strFrom, string strMessage, string strSubject, string attachmentPath, bool htmlFormat = true)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.MailAddress mto = new System.Net.Mail.MailAddress(strTo);
System.Net.Mail.MailAddress mfrom = new System.Net.Mail.MailAddress(strFrom);
mail.Subject = strSubject;
mail.From = mfrom;
mail.To.Add(mto);
mail.Body = strMessage;
mail.IsBodyHtml = htmlFormat;
mail.Attachments.Add(new System.Net.Mail.Attachment(attachmentPath));
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(EmailServer, EmailPort);
mailClient.Timeout = 1000000;
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = new System.Net.NetworkCredential(EmailServerUsername, EmailServerPassword);
mailClient.Send(mail);
}
private string ComposeVoicemailEmail(DateTime vmDate, string group, string callerNumber, string callerName)
{
string body = @"
<span style='font-weight:bold'>Date/Time:</span> " + vmDate.ToString("MM/dd/yy HH:mm") + @"<br />
<span style='font-weight:bold'>Group:</span> " + group + @"<br />
<span style='font-weight:bold'>Caller Name:</span> " + callerName + @"<br />
<span style='font-weight:bold'>Caller #:</span> " + callerNumber + @"<br />
";
return body;
}
private string ComposeFaxEmail(DateTime faxDate, string fromNumber, string toNumber)
{
string body = @"
<span style='font-weight:bold'>Date/Time:</span> " + faxDate.ToString("MM/dd/yy HH:mm") + @"<br />
<span style='font-weight:bold'>From:</span> " + fromNumber + @"<br />
<br />
<span style='font-size:0.8em'><span style='font-weight:bold'>Sent to:</span> " + toNumber + @"</span>
";
return body;
}
private void logoutButton_Click(object sender, EventArgs e)
{
Logout();
}
async Task Delay(int millisecondsDelay)
{
await Task.Delay(millisecondsDelay);
}
private void authenticateButton_Click(object sender, EventArgs e)
{
Authenticate();
}
}
}