Skip to content

Commit 4267141

Browse files
authored
Merge pull request #15 from danzuep/13-Reconnect-IImapReceiver-and-IMailFolder_before-idle-fetch
Added _fetchClient.NoOpAsync() to re-sync with the idle client.
2 parents cbecf01 + 4d09215 commit 4267141

File tree

3 files changed

+36
-10
lines changed

3 files changed

+36
-10
lines changed

samples/WorkerServiceExample/Worker.cs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,26 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken =
3333

3434
private async Task NotReentrantAsync(CancellationToken cancellationToken = default)
3535
{
36+
var sendTask = DelayedSendAsync(5, cancellationToken);
37+
38+
var newestEmail = await GetNewestMessageSummaryAsync(cancellationToken);
3639
await _imapReceiver.MonitorFolder
37-
.OnMessageArrival(OnArrivalAsync)
38-
.IdleAsync(cancellationToken);
40+
.SetIgnoreExistingMailOnConnect()
41+
.OnMessageArrival(OnArrivalAsync)
42+
.IdleAsync(cancellationToken);
3943

4044
async Task OnArrivalAsync(IMessageSummary messageSummary)
4145
{
4246
try
4347
{
44-
_logger.LogInformation($"{_imapReceiver} message #{messageSummary.UniqueId} arrived.");
45-
//var mimeMessage = await _imapReceiver.ReadMail.GetMimeMessageAsync(messageSummary.UniqueId);
46-
//var mimeMessage = await messageSummary.GetMimeMessageAsync();
48+
if (messageSummary.UniqueId > newestEmail?.UniqueId)
49+
{
50+
var mimeMessage = await messageSummary.GetMimeMessageAsync();
51+
//var mimeMessage = await _imapReceiver.ReadMail.GetMimeMessageAsync(messageSummary.UniqueId);
52+
_logger.LogInformation($"{_imapReceiver} message #{messageSummary.UniqueId} arrived, {mimeMessage.MessageId}.");
53+
}
54+
else
55+
_logger.LogInformation($"{_imapReceiver} message #{messageSummary.UniqueId} arrived.");
4756
}
4857
catch (Exception ex)
4958
{
@@ -52,6 +61,17 @@ async Task OnArrivalAsync(IMessageSummary messageSummary)
5261
}
5362
}
5463

64+
public async Task<IMessageSummary?> GetNewestMessageSummaryAsync(CancellationToken cancellationToken = default)
65+
{
66+
using var mailFolderClient = _imapReceiver.MailFolderClient;
67+
var mailFolder = await mailFolderClient.ConnectAsync(false, cancellationToken).ConfigureAwait(false);
68+
var index = mailFolder.Count - 1;
69+
var filter = MessageSummaryItems.UniqueId;
70+
var messageSummaries = await mailFolder.FetchAsync(index, index, filter, cancellationToken).ConfigureAwait(false);
71+
await mailFolder.CloseAsync(false, CancellationToken.None).ConfigureAwait(false);
72+
return messageSummaries.FirstOrDefault();
73+
}
74+
5575
private async Task GetMessageSummaryRepliesAsync(CancellationToken cancellationToken = default)
5676
{
5777
var stopwatch = Stopwatch.StartNew();

source/MailKitSimplified.Receiver/Extensions/EmailReceiverExtensions.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using MailKit.Search;
1+
using MailKit;
2+
using MailKit.Search;
23
using System;
34
using System.Linq;
45
using System.Threading;
@@ -13,16 +14,15 @@ public static class EmailReceiverExtensions
1314
public static string ToEnumeratedString<T>(this IEnumerable<T> data, string div = ", ") =>
1415
data is null ? "" : string.Join(div, data.Select(o => o?.ToString() ?? ""));
1516

16-
public static IList<T> TryAddUniqueRange<T>(this IList<T> list, IEnumerable<T> items)
17-
{
17+
public static IList<T> TryAddUniqueRange<T>(this IList<T> list, IEnumerable<T> items) where T : IMessageSummary {
1818
var result = new List<T>();
1919
if (list is null)
2020
list = new List<T>();
2121
if (items != null)
2222
{
2323
foreach (T item in items)
2424
{
25-
if (item != null && !list.Contains(item))
25+
if (item != null && !list.Any(m => m.UniqueId == item.UniqueId))
2626
{
2727
list.Add(item);
2828
result.Add(item);

source/MailKitSimplified.Receiver/Services/MailFolderMonitor.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ public sealed class MailFolderMonitor : IMailFolderMonitor
3030
private CancellationTokenSource _arrival = new CancellationTokenSource();
3131
private CancellationTokenSource _cancel;
3232
private IImapClient _imapClient;
33+
private IImapClient _fetchClient;
3334
private IMailFolder _mailFolder;
3435
private IMailFolder _fetchFolder;
3536
private bool _canIdle;
@@ -151,6 +152,7 @@ private async Task IdleStartAsync(CancellationToken cancellationToken = default)
151152
{
152153
_imapClient = await _imapReceiver.ConnectAuthenticatedImapClientAsync(cancellationToken).ConfigureAwait(false);
153154
_canIdle = _imapClient.Capabilities.HasFlag(ImapCapabilities.Idle);
155+
_fetchClient = await _fetchReceiver.ConnectAuthenticatedImapClientAsync(cancellationToken).ConfigureAwait(false);
154156
_fetchFolder = await _fetchReceiver.ConnectMailFolderAsync(cancellationToken).ConfigureAwait(false);
155157
_ = await _fetchFolder.OpenAsync(FolderAccess.ReadOnly, cancellationToken).ConfigureAwait(false);
156158
_mailFolder = await _imapReceiver.ConnectMailFolderAsync(cancellationToken).ConfigureAwait(false);
@@ -295,9 +297,13 @@ private async ValueTask WaitForNewMessagesAsync(CancellationToken cancellationTo
295297
private async ValueTask<int> ProcessMessagesArrivedAsync(bool firstConnection = false, CancellationToken cancellationToken = default)
296298
{
297299
int startIndex = _messageCache.Count;
298-
_logger.LogTrace($"{_fetchReceiver} ({_fetchFolder.Count}) Fetching new message arrivals, starting from {startIndex}.");
300+
await _fetchClient.NoOpAsync(cancellationToken).ConfigureAwait(false);
301+
_logger.LogTrace($"{_fetchReceiver} ({_fetchFolder.Count}) fetching new message arrivals, starting from {startIndex}.");
299302
if (startIndex > _fetchFolder.Count)
303+
{
304+
_logger.LogTrace($"{_fetchReceiver} start index {startIndex} is higher than fetched folder count of {_fetchFolder.Count}, monitored count is {_mailFolder.Count}.");
300305
startIndex = _fetchFolder.Count;
306+
}
301307
var filter = _folderMonitorOptions.MessageSummaryItems | MessageSummaryItems.UniqueId;
302308
var fetched = await _fetchFolder.FetchAsync(startIndex, -1, filter, cancellationToken).ConfigureAwait(false);
303309
if (_arrival.IsCancellationRequested)

0 commit comments

Comments
 (0)