/
MailClient.cs
374 lines (325 loc) · 10.6 KB
/
MailClient.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Waher.Content.Multipart;
using Waher.Content.Xml;
using Waher.Events;
namespace Waher.Networking.XMPP.Mail
{
/// <summary>
/// Client providing support for server mail-extension.
/// </summary>
public class MailClient : XmppExtension
{
/// <summary>
/// http://jabber.org/protocol/pubsub
/// </summary>
public const string NamespaceMail = "urn:xmpp:smtp";
/// <summary>
/// Client providing support for server mail-extension.
/// </summary>
/// <param name="Client">XMPP Client to use.</param>
public MailClient(XmppClient Client)
: base(Client)
{
Client.RegisterMessageHandler("mailInfo", NamespaceMail, this.MailHandler, true);
}
/// <inheritdoc/>
public override void Dispose()
{
Client.UnregisterMessageHandler("mailInfo", NamespaceMail, this.MailHandler, true);
base.Dispose();
}
/// <summary>
/// Implemented extensions.
/// </summary>
public override string[] Extensions => new string[] { };
private async Task MailHandler(object Sender, MessageEventArgs e)
{
string ContentType = XML.Attribute(e.Content, "contentType");
string MessageId = XML.Attribute(e.Content, "id");
int Priority = XML.Attribute(e.Content, "priority", 3);
DateTimeOffset Date = XML.Attribute(e.Content, "date", DateTimeOffset.Now);
string FromMail = XML.Attribute(e.Content, "fromMail");
string FromHeader = XML.Attribute(e.Content, "fromHeader");
string Sender2 = XML.Attribute(e.Content, "sender");
int Size = XML.Attribute(e.Content, "size", 0);
string MailObjectId = XML.Attribute(e.Content, "cid");
List<KeyValuePair<string, string>> Headers = new List<KeyValuePair<string, string>>();
List<EmbeddedObjectReference> Attachments = null;
List<EmbeddedObjectReference> Inline = null;
foreach (XmlNode N in e.Content.ChildNodes)
{
if (N is XmlElement E)
{
switch (E.LocalName)
{
case "headers":
foreach (XmlNode N2 in E.ChildNodes)
{
switch (N2.LocalName)
{
case "header":
string Key = XML.Attribute((XmlElement)N2, "name");
string Value = N2.InnerText;
Headers.Add(new KeyValuePair<string, string>(Key, Value));
break;
}
}
break;
case "attachment":
case "inline":
string ContentType2 = XML.Attribute(E, "contentType");
string Description = XML.Attribute(E, "description");
string FileName = XML.Attribute(E, "fileName");
string Name = XML.Attribute(E, "name");
string ContentId = XML.Attribute(E, "id");
string EmbeddedObjectId = XML.Attribute(E, "cid");
int Size2 = XML.Attribute(E, "size", 0);
EmbeddedObjectReference Ref = new EmbeddedObjectReference(ContentType2, Description, FileName, Name,
ContentId, EmbeddedObjectId, Size);
if (E.LocalName == "inline")
{
if (Inline is null)
Inline = new List<EmbeddedObjectReference>();
Inline.Add(Ref);
}
else
{
if (Attachments is null)
Attachments = new List<EmbeddedObjectReference>();
Attachments.Add(Ref);
}
break;
}
}
}
string PlainText = e.Body;
string Html = null;
string Markdown = null;
foreach (XmlNode N in e.Message.ChildNodes)
{
if (N is XmlElement E)
{
switch (E.LocalName)
{
case "content":
if (E.NamespaceURI == "urn:xmpp:content")
{
switch (XML.Attribute(E, "type").ToLower())
{
case "text/plain":
PlainText = E.InnerText;
break;
case "text/html":
Html = E.InnerText;
break;
case "text/markdown":
Markdown = E.InnerText;
break;
}
}
break;
case "html":
if (E.NamespaceURI == "http://jabber.org/protocol/xhtml-im")
{
foreach (XmlNode N2 in E.ChildNodes)
{
if (N2 is XmlElement E2 && E2.LocalName == "body")
{
Html = E2.OuterXml; // InnerXml introduces xmlns attributes on all child elements.
int i = Html.IndexOf('>');
Html = Html.Substring(i + 1);
i = Html.LastIndexOf('<');
Html = Html.Substring(0, i);
break;
}
}
}
break;
}
}
}
MailEventHandler h = this.MailReceived;
if (!(h is null))
{
try
{
await h(this, new MailEventArgs(this, e, ContentType, MessageId, (Mail.Priority)Priority,
Date, FromMail, FromHeader, Sender2, Size, MailObjectId, Headers.ToArray(), Attachments?.ToArray(),
Inline?.ToArray(), PlainText, Html, Markdown));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}
/// <summary>
/// This event is raised when a mail message has been received.
/// </summary>
public event MailEventHandler MailReceived = null;
/// <summary>
/// Gets a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to get.</param>
/// <param name="Callback">Method to call when response has been returned.</param>
/// <param name="State">State object to pass on to callback method.</param>
public void Get(string ObjectId, MessageObjectEventHandler Callback, object State)
{
this.Get(ObjectId, string.Empty, Callback, State);
}
/// <summary>
/// Gets a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to get.</param>
/// <param name="ContentType">Content-Type of response, if only part of the mail object is desired.</param>
/// <param name="Callback">Method to call when response has been returned.</param>
/// <param name="State">State object to pass on to callback method.</param>
public void Get(string ObjectId, string ContentType, MessageObjectEventHandler Callback, object State)
{
StringBuilder Xml = new StringBuilder();
Xml.Append("<get xmlns='");
Xml.Append(NamespaceMail);
Xml.Append("' cid='");
Xml.Append(XML.Encode(ObjectId));
if (!string.IsNullOrEmpty(ContentType))
{
Xml.Append("' type='");
Xml.Append(XML.Encode(ContentType));
}
Xml.Append("'/>");
this.client.SendIqGet(this.client.Domain, Xml.ToString(), async (sender, e) =>
{
XmlElement E;
string ResponseContentType = null;
byte[] Data = null;
if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "content" && E.NamespaceURI == NamespaceMail)
{
try
{
ResponseContentType = XML.Attribute(E, "type");
Data = Convert.FromBase64String(E.InnerText);
}
catch (Exception)
{
e.Ok = false;
}
}
else
e.Ok = false;
if (!(Callback is null))
{
try
{
await Callback(this, new MessageObjectEventArgs(e, ResponseContentType, Data));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}, State);
}
/// <summary>
/// Gets a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to get.</param>
public Task<MessageObject> GetAsync(string ObjectId)
{
return GetAsync(ObjectId, string.Empty);
}
/// <summary>
/// Gets a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to get.</param>
/// <param name="ContentType">Content-Type of response, if only part of the mail object is desired.</param>
public Task<MessageObject> GetAsync(string ObjectId, string ContentType)
{
TaskCompletionSource<MessageObject> Result = new TaskCompletionSource<MessageObject>();
this.Get(ObjectId, ContentType, (sender, e) =>
{
if (e.Ok)
Result.TrySetResult(new MessageObject(e.Data, e.ContentType));
else
Result.TrySetException(e.StanzaError ?? new Exception("Unable to get message object."));
return Task.CompletedTask;
}, null);
return Result.Task;
}
/// <summary>
/// Deletes a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to delete.</param>
/// <param name="Callback">Method to call when response has been returned.</param>
/// <param name="State">State object to pass on to callback method.</param>
public void Delete(string ObjectId, IqResultEventHandlerAsync Callback, object State)
{
this.client.SendIqSet(this.client.Domain, "<delete xmlns='" + NamespaceMail + "' cid='" + XML.Encode(ObjectId) + "'/>",
Callback, State);
}
/// <summary>
/// Deletes a message object from the broker.
/// </summary>
/// <param name="ObjectId">ID of the message object to delete.</param>
public Task DeleteAsync(string ObjectId)
{
TaskCompletionSource<bool> Result = new TaskCompletionSource<bool>();
this.Delete(ObjectId, (sender, e) =>
{
if (e.Ok)
Result.TrySetResult(true);
else
Result.TrySetException(e.StanzaError ?? new Exception("Unable to delete message object."));
return Task.CompletedTask;
}, null);
return Result.Task;
}
/// <summary>
/// Appends embedded content to a message XML output.
/// </summary>
/// <param name="ContentId">Content ID</param>
/// <param name="ContentType">Content-Type of embedded content.</param>
/// <param name="ContentData">Binary encoding of content to embed.</param>
/// <param name="Disposition">Content disposition.</param>
/// <param name="Name">Name attribute</param>
/// <param name="FileName">File-name attribute</param>
/// <param name="Description">Content description.</param>
/// <param name="Xml">XML output.</param>
public void AppendContent(string ContentId, string ContentType, byte[] ContentData, ContentDisposition Disposition,
string Name, string FileName, string Description, StringBuilder Xml)
{
Xml.Append("<content xmlns='");
Xml.Append(NamespaceMail);
Xml.Append("' cid='");
Xml.Append(XML.Encode(ContentId));
Xml.Append("' type='");
Xml.Append(XML.Encode(ContentType));
if (Disposition != ContentDisposition.Unknown)
{
Xml.Append("' disposition='");
Xml.Append(XML.Encode(Disposition.ToString()));
}
if (!string.IsNullOrEmpty(Name))
{
Xml.Append("' name='");
Xml.Append(XML.Encode(Name));
}
if (!string.IsNullOrEmpty(FileName))
{
Xml.Append("' fileName='");
Xml.Append(XML.Encode(FileName));
}
if (!string.IsNullOrEmpty(Description))
{
Xml.Append("' description='");
Xml.Append(XML.Encode(Description));
}
Xml.Append("'>");
Xml.Append(Convert.ToBase64String(ContentData)); // TODO: Chunked transfer
Xml.Append("</content>");
}
}
}