Path: redb-route/redb.Route.Mail/MailSearchTerm.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Mail/MailSearchTerm.cs ---- using System.Globalization; using System.Text.RegularExpressions; using MailKit.Search; using MimeKit; using redb.Route.Core; namespace redb.Route.Mail; /// /// Apache Camel's mail searchTerm: which mails the consumer takes. Written on the URI as an option group, /// searchTerm.subject=invoice&searchTerm.fromSentDate=now-24h (Camel's SimpleSearchTerm), or as /// searchTerm=#name, a MailKit registered under that name, which then wins over the /// simple options (IMAP only). The terms that are set are ANDed. A set search term replaces fetchFilter. /// /// IMAP sends the terms to the server as one SEARCH. IMAP compares dates by whole days, so a date bound is also checked /// on the client against the exact time: the Date header for the sent dates, the arrival time (INTERNALDATE) for the /// received dates. POP3 has no search: the consumer checks every term but (POP3 keeps no flags) on /// the client, and refuses at start what it cannot check: a registry search query and the received dates. /// /// public sealed class MailSearchTerm { /// The format of a fixed date: yyyy-MM-dd HH:mm:ss, in the host's time zone. public const string DateFormat = "yyyy-MM-dd HH:mm:ss"; /// /// searchTerm=#name: a MailKit in the registry, sent to the IMAP server as it is. /// The simple options are not read beside it. /// [OptionGroupValue] [RegistryReference(typeof(SearchQuery))] public string? Reference { get; set; } /// Only mails not yet seen (default true, as in Camel). IMAP only: POP3 keeps no flags. public bool Unseen { get; set; } = true; /// Text the subject or the body contains. public string? SubjectOrBody { get; set; } /// Text the subject contains. public string? Subject { get; set; } /// Text the body contains. public string? Body { get; set; } /// Text the From address contains. public string? From { get; set; } /// Text a To address contains. public string? To { get; set; } /// Sent at or after: , or now with an offset (now-24h, now - 1d12h). public string? FromSentDate { get; set; } /// Sent at or before: , or now with an offset. public string? ToSentDate { get; set; } /// Received (arrived on the server) at or after: , or now with an offset. IMAP only. public string? FromReceivedDate { get; set; } /// Received at or before: , or now with an offset. IMAP only. public string? ToReceivedDate { get; set; } /// Whether a registry search query is named. internal bool HasReference => !string.IsNullOrWhiteSpace(Reference); /// Whether a received date bound is set. internal bool HasReceivedBounds => FromReceivedDate is not null || ToReceivedDate is not null; /// Refuses a date the format does not take, naming the option. internal void Validate() { foreach (var (name, value) in Dates()) if (value is not null) _ = SearchDate.Parse(name, value); } private IEnumerable<(string Name, string? Value)> Dates() => [ ("searchTerm.fromSentDate", FromSentDate), ("searchTerm.toSentDate", ToSentDate), ("searchTerm.fromReceivedDate", FromReceivedDate), ("searchTerm.toReceivedDate", ToReceivedDate), ]; /// /// The IMAP SEARCH of the simple options at : the terms ANDed, the date bounds widened to the /// whole day (IMAP compares days; then checks the exact time). /// internal SearchQuery ToImapQuery(DateTimeOffset now) { var terms = new List(); if (Unseen) terms.Add(SearchQuery.NotSeen); if (SubjectOrBody is not null) terms.Add(SearchQuery.SubjectContains(SubjectOrBody).Or(SearchQuery.BodyContains(SubjectOrBody))); if (Subject is not null) terms.Add(SearchQuery.SubjectContains(Subject)); if (Body is not null) terms.Add(SearchQuery.BodyContains(Body)); if (From is not null) terms.Add(SearchQuery.FromContains(From)); if (To is not null) terms.Add(SearchQuery.ToContains(To)); // SENTSINCE d: on or after day d; SENTBEFORE d: before day d, so the day of the bound is d + 1. if (Bound(nameof(FromSentDate), FromSentDate, now) is { } fromSent) terms.Add(SearchQuery.SentSince(fromSent.LocalDateTime.Date)); if (Bound(nameof(ToSentDate), ToSentDate, now) is { } toSent) terms.Add(SearchQuery.SentBefore(toSent.LocalDateTime.Date.AddDays(1))); if (Bound(nameof(FromReceivedDate), FromReceivedDate, now) is { } fromReceived) terms.Add(SearchQuery.DeliveredAfter(fromReceived.LocalDateTime.Date.AddDays(-1))); if (Bound(nameof(ToReceivedDate), ToReceivedDate, now) is { } toReceived) terms.Add(SearchQuery.DeliveredBefore(toReceived.LocalDateTime.Date.AddDays(1))); return terms.Count == 0 ? SearchQuery.All : terms.Aggregate(SearchQuery.And); } /// /// Whether a fetched mail meets the terms, checked on the client: what POP3, which has no search, does for every term /// but (POP3 keeps no flags). The received dates are refused on POP3 at start. /// internal bool Matches(MimeMessage mime, DateTimeOffset now) { if (SubjectOrBody is not null && !Contains(mime.Subject, SubjectOrBody) && !Contains(BodyText(mime), SubjectOrBody)) return false; if (Subject is not null && !Contains(mime.Subject, Subject)) return false; if (Body is not null && !Contains(BodyText(mime), Body)) return false; if (From is not null && !mime.From.Mailboxes.Any(m => Contains(m.ToString(), From))) return false; if (To is not null && !mime.To.Mailboxes.Any(m => Contains(m.ToString(), To))) return false; return MatchesDates(mime.Date == default ? null : mime.Date, received: null, now); } /// Whether a mail sent at and received at is within the date bounds. internal bool MatchesDates(DateTimeOffset? sent, DateTimeOffset? received, DateTimeOffset now) => Within(sent, Bound(nameof(FromSentDate), FromSentDate, now), Bound(nameof(ToSentDate), ToSentDate, now)) && (!HasReceivedBounds || Within(received, Bound(nameof(FromReceivedDate), FromReceivedDate, now), Bound(nameof(ToReceivedDate), ToReceivedDate, now))); /// Whether a date bound is set. internal bool HasDateBounds => FromSentDate is not null || ToSentDate is not null || HasReceivedBounds; // A mail without the date a bound reads does not match it, as Camel's NowSearchTerm. private static bool Within(DateTimeOffset? date, DateTimeOffset? from, DateTimeOffset? to) => (from is null && to is null) || (date is { } d && (from is null || d >= from) && (to is null || d <= to)); private static DateTimeOffset? Bound(string member, string? value, DateTimeOffset now) => value is null ? null : SearchDate.Parse("searchTerm." + char.ToLowerInvariant(member[0]) + member[1..], value).At(now); private static bool Contains(string? text, string term) => text?.Contains(term, StringComparison.OrdinalIgnoreCase) == true; private static string? BodyText(MimeMessage mime) => mime.TextBody ?? mime.HtmlBody; /// A date bound: a fixed time, or now with an offset. internal readonly record struct SearchDate(DateTimeOffset? Fixed, TimeSpan Offset) { // Camel's "now-24h", "now - 24h", "now+1d"; the offset in Camel's TimeUtils units. private static readonly Regex Now = new(@"^now\s*(?:([+-])\s*(.+))?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private static readonly Regex Duration = new( @"^\s*(?:(\d+)\s*d(?:ays?)?)?\s*(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?(?!s))?\s*(?:(\d+)\s*s(?:ec(?:onds?)?)?)?\s*(?:(\d+)\s*ms)?\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); /// The time the bound names at . public DateTimeOffset At(DateTimeOffset now) => Fixed ?? now + Offset; /// Parses a bound, refusing anything else with the option's name. public static SearchDate Parse(string option, string value) { var text = value.Trim(); if (Now.Match(text) is { Success: true } now) return new SearchDate(null, now.Groups[1].Success ? (now.Groups[1].Value == "-" ? -ParseOffset(option, value, now.Groups[2].Value) : ParseOffset(option, value, now.Groups[2].Value)) : TimeSpan.Zero); if (DateTime.TryParseExact(text, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date)) return new SearchDate(new DateTimeOffset(date), TimeSpan.Zero); throw Refused(option, value); } private static TimeSpan ParseOffset(string option, string value, string offset) { offset = offset.Trim(); if (long.TryParse(offset, NumberStyles.None, CultureInfo.InvariantCulture, out var millis)) return TimeSpan.FromMilliseconds(millis); var match = Duration.Match(offset); if (!match.Success || offset.Length == 0) throw Refused(option, value); long Part(int group) => match.Groups[group].Success ? long.Parse(match.Groups[group].Value, CultureInfo.InvariantCulture) : 0; return TimeSpan.FromDays(Part(1)) + TimeSpan.FromHours(Part(2)) + TimeSpan.FromMinutes(Part(3)) + TimeSpan.FromSeconds(Part(4)) + TimeSpan.FromMilliseconds(Part(5)); } private static ArgumentException Refused(string option, string value) => new( $"'{option}={value}' is not a valid value: {option} takes a date '{DateFormat}' or now with an offset " + "('now-24h', 'now+1d12h'; units d, h, m, s, ms, or milliseconds).", option); } }