private void TryProcessGmLabels(string data) { // Fix by kirchik var match = Expressions.GMailLabelsRex.Match(data); if (match.Success) { _downloadProgress = _downloadProgress | MessageFetchMode.GMailLabels; } var labelsMatches = Expressions.GMailLabelSplitRex.Matches(match.Groups[1].Value); if (labelsMatches.Count == 0) { return; //.Success || labelsMatch.Groups.Count <= 1) return; } foreach (Match labelsMatch in labelsMatches) { Labels.AddRangeInternal( labelsMatch.Groups.Cast <Group>() .Skip(1) .Select(_ => (_.Value.StartsWith("&") ? ImapUTF7.Decode(_.Value) : _.Value).Replace("\"", ""))); } }
private void TryProcessGmThreadId(string data) { Match threadMatch = Expressions.GMailThreadRex.Match(data); if (!threadMatch.Success) { return; } long threadId; if (!long.TryParse(threadMatch.Groups[1].Value, out threadId)) { return; } GmailThread = Folder.GMailThreads.FirstOrDefault(_ => _.Id == threadId); if (GmailThread == null) { GmailThread = new GMailMessageThread(_client, Folder, threadId); Folder.GMailThreads.AddInternal(GmailThread); } GmailThread.Messages.AddInternal(this); _downloadProgress = _downloadProgress | MessageFetchMode.GMailThreads; }
internal Message[] Fetch(IEnumerable <long> uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { if (_client.SelectedFolder != this && !Select()) { throw new OperationFailedException("The folder couldn't be selected for search."); } var result = new List <Message>(); foreach ( Message msg in uIds.Select(uId => Messages.FirstOrDefault(_ => _.UId == uId) ?? new Message(uId, _client, this)) ) { msg.Download(mode); if (!Messages.Contains(msg)) { Messages.AddInternal(msg); } result.Add(msg); } return(result.ToArray()); }
private void TryProcessSize(string data) { Match sizeMatch = Expressions.SizeRex.Match(data); if (!sizeMatch.Success) { return; } Size = long.Parse(sizeMatch.Groups[1].Value); _downloadProgress = _downloadProgress | MessageFetchMode.Size; }
private void TryProcessFlags(string data) { Match flagsMatch = Expressions.FlagsRex.Match(data); if (!flagsMatch.Success) { return; } Flags.AddRangeInternal(flagsMatch.Groups[1].Value.Split(' ').Where(_ => !string.IsNullOrEmpty(_))); _downloadProgress = _downloadProgress | MessageFetchMode.Flags; }
private void TryProcessInternalDate(string data) { Match dateMatch = Expressions.InternalDateRex.Match(data); if (!dateMatch.Success) { return; } InternalDate = HeaderFieldParser.ParseDate(dateMatch.Groups[1].Value); _downloadProgress = _downloadProgress | MessageFetchMode.InternalDate; }
public override void ProcessCommandResult(string data) { if (_client.Capabilities.XGMExt1 && !_downloadProgress.HasFlag(MessageFetchMode.GMailThreads)) { TryProcessGmThreadId(data); } if (_client.Capabilities.XGMExt1 && !_downloadProgress.HasFlag(MessageFetchMode.GMailMessageId)) { TryProcessGmMsgId(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.Size)) { TryProcessSize(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.Flags)) { TryProcessFlags(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.GMailLabels)) { TryProcessGmLabels(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.InternalDate)) { TryProcessInternalDate(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.BodyStructure)) { TryProcessBodyStructure(data); } if (Expressions.HeaderRex.IsMatch(data)) { _fetchState = MessageFetchState.Headers; _downloadProgress = _downloadProgress | MessageFetchMode.Headers; } else if (string.IsNullOrEmpty(data)) { _fetchState = MessageFetchState.None; } else if (_fetchState == MessageFetchState.Headers) { TryProcessHeader(data); } }
private void TryProcessGmLabels(string data) { Match labelsMatch = Expressions.GMailLabelSplitRex.Match(Expressions.GMailLabelsRex.Match(data).Groups[1].Value); if (!labelsMatch.Success || labelsMatch.Groups.Count <= 1) { return; } Labels.AddRangeInternal( labelsMatch.Groups.Cast <Group>() .Skip(1) .Select(_ => (_.Value.StartsWith("&") ? ImapUTF7.Decode(_.Value) : _.Value).Replace("\"", ""))); _downloadProgress = _downloadProgress | MessageFetchMode.GMailLabels; }
internal Message[] Fetch(IEnumerable <long> uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { var result = new List <Message>(); foreach ( Message msg in uIds.Select(uId => Messages.FirstOrDefault(_ => _.UId == uId) ?? new Message(uId, _client, this)) ) { msg.Download(mode); if (!Messages.Contains(msg)) { Messages.AddInternal(msg); } result.Add(msg); } return(result.ToArray()); }
private void TryProcessGmMsgId(string data) { Match msgIdMatch = Expressions.GMailMessageIdRex.Match(data); if (!msgIdMatch.Success) { return; } long msgId; if (!long.TryParse(msgIdMatch.Groups[1].Value, out msgId)) { return; } GMailMessageId = msgId; _downloadProgress = _downloadProgress | MessageFetchMode.GMailMessageId; }
private void TryProcessBodyStructure(string data) { Match bstructMatch = Expressions.BodyStructRex.Match(data); if (!bstructMatch.Success) { return; } using (var parser = new BodyStructureParser(bstructMatch.Groups[1].Value, _client, this)) BodyParts = parser.Parse(); Body = new MessageBody(_client, BodyParts.FirstOrDefault( _ => _.ContentDisposition == null && _.ContentType != null && _.ContentType.MediaType.Equals("text/plain", StringComparison.OrdinalIgnoreCase)), BodyParts.FirstOrDefault( _ => _.ContentDisposition == null && _.ContentType != null && _.ContentType.MediaType.Equals("text/html", StringComparison.OrdinalIgnoreCase))); Attachments = (from part in BodyParts where part.ContentDisposition != null && part.ContentDisposition.DispositionType == DispositionTypeNames.Attachment select new Attachment(part)).ToArray(); EmbeddedResources = (from part in BodyParts where part.ContentDisposition != null && (part.ContentDisposition.DispositionType == DispositionTypeNames.Inline || !string.IsNullOrEmpty(part.ContentId)) select new Attachment(part)).ToArray(); _downloadProgress = _downloadProgress | MessageFetchMode.BodyStructure; }
private void TryProcessGmLabels(string data) { // Fix by kirchik var match = Expressions.GMailLabelsRex.Match(data); if (match.Success) { _downloadProgress = _downloadProgress | MessageFetchMode.GMailLabels; } var labelsMatches = Expressions.GMailLabelSplitRex.Matches(match.Groups[1].Value); if (labelsMatches.Count == 0) { return; } foreach (Match labelsMatch in labelsMatches) { Labels.AddRangeInternal(labelsMatch.Groups.Cast<Group>() .Skip(1) .Select(_ => (_.Value.StartsWith("&") ? ImapUTF7.Decode(_.Value) : _.Value).Replace("\"", ""))); } }
private void TryProcessGmMsgId(string data) { Match msgIdMatch = Expressions.GMailMessageIdRex.Match(data); if (!msgIdMatch.Success) { return; } long msgId; if (!long.TryParse(msgIdMatch.Groups[1].Value, out msgId)) { return; } GMailMessageId = msgId; _downloadProgress = _downloadProgress | MessageFetchMode.GMailMessageId; }
private void TryProcessGmThreadId(string data) { Match threadMatch = Expressions.GMailThreadRex.Match(data); if (!threadMatch.Success) { return; } long threadId; if (!long.TryParse(threadMatch.Groups[1].Value, out threadId)) { return; } GmailThread = Folder.GMailThreads.FirstOrDefault(_ => _.Id == threadId); if (GmailThread == null) { GmailThread = new GMailMessageThread(_client, Folder, threadId); Folder.GMailThreads.AddInternal(GmailThread); } GmailThread.Messages.AddInternal(this); _downloadProgress = _downloadProgress | MessageFetchMode.GMailThreads; }
private void TryProcessInternalDate(string data) { Match dateMatch = Expressions.InternalDateRex.Match(data); if (!dateMatch.Success) { return; } InternalDate = HeaderFieldParser.ParseDate(dateMatch.Groups[1].Value); _downloadProgress = _downloadProgress | MessageFetchMode.InternalDate; }
public Message[] Search(string query = "ALL", MessageFetchMode mode = MessageFetchMode.ClientDefault, int count = -1) { return Fetch(SearchMessageIds(query, count), mode); }
public override void ProcessCommandResult(string data) { if (_client.Capabilities.XGMExt1 && !_downloadProgress.HasFlag(MessageFetchMode.GMailThreads)) { TryProcessGmThreadId(data); } if (_client.Capabilities.XGMExt1 && !_downloadProgress.HasFlag(MessageFetchMode.GMailMessageId)) { TryProcessGmMsgId(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.Size)) { TryProcessSize(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.Flags)) { TryProcessFlags(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.GMailLabels)) { TryProcessGmLabels(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.InternalDate)) { TryProcessInternalDate(data); } if (!_downloadProgress.HasFlag(MessageFetchMode.BodyStructure)) { TryProcessBodyStructure(data); } if (Expressions.HeaderRex.IsMatch(data)) { _fetchState = MessageFetchState.Headers; _downloadProgress = _downloadProgress | MessageFetchMode.Headers; } else if (string.IsNullOrEmpty(data)) { _fetchState = MessageFetchState.None; } else if (_fetchState == MessageFetchState.Headers) { TryProcessHeader(data); } }
/// <summary> /// Downloads messages from server using default or given mode. /// </summary> /// <param name="query">The search query to filter messages. <code>ALL</code> by default</param> /// <param name="mode">The message fetch mode, allows to select which parts of the message will be requested.</param> /// <param name="count"> /// The maximum number of messages that will be requested. Set <code>count</code> to <code>-1</code> /// will request all messages which match the given query. /// </param> public Message[] Search(string query = "ALL", MessageFetchMode mode = MessageFetchMode.ClientDefault, int count = -1) { return(Fetch(SearchMessageIds(query, count), mode)); }
public List <Message> ObtainMessages() { using (ImapClient client = new ImapClient(Hostname, Port, UseSsl, false)) { if (!client.Connect()) { Console.WriteLine("Не подключился к серверу"); return(allNewMessages); } if (!client.Login(Username, Password)) { Console.WriteLine("Неверный логин или пароль"); return(allNewMessages); } else { if (client.IsConnected) { Console.WriteLine("Connection established"); } /// <summary> /// Сообщения скачиваются из нужной папки /// </summary> string query = "ALL"; MessageFetchMode mode = (MessageFetchMode)(-1); client.Folders["INBOX"].SubFolders[Folder].Messages.Download(query, mode, 50); int messageCount = client.Folders.Inbox.SubFolders[Folder].Messages.Count(); MessageCollection messages = client.Folders.Inbox.SubFolders[Folder].Messages; XmlSerializer formatter = new XmlSerializer(typeof(Message__c)); allNewMessages = new List <Message>(); messageCount--; /// <summary> /// Начальное присваивание /// </summary> for (int i = messageCount; i >= 0; i--) { if (messages[i].From.Address.Equals(Sender) && messages[i].Subject.StartsWith(Title) ) { latestDate = messages[i].Date; latestMessageText = messages[i].Body.Html; break; } else if (i == 0) { Console.WriteLine("Новых сообщений нет"); return(allNewMessages); } } /// <summary> /// Поиск наиболее позднего /// </summary> for (int i = messageCount; i >= 1; i--) { if (latestDate < messages[i - 1].Date && messages[i - 1].From.Address.Equals(Sender) && messages[i - 1].Subject.StartsWith(Title) ) { latestDate = messages[i - 1].Date; latestMessageText = messages[i - 1].Body.Html; } } /// <summary> /// Десериализация сообщения из прошлой сессии /// </summary> try { using (FileStream fs = new FileStream("message.xml", FileMode.Open)) { Message__c newMessage = (Message__c)formatter.Deserialize(fs); if (newMessage.DateSent < latestDate) { latestMessage = new Message__c(latestDate, latestMessageText); } else { return(allNewMessages); } for (int i = messageCount; i >= 0; i--) { if (messages[i].Date > newMessage.DateSent && messages[i].From.Address.Equals(Sender) && messages[i].Subject.StartsWith(Title) ) { allNewMessages.Add(messages[i]); } } } } catch (FileNotFoundException) { Console.WriteLine("Анализ всех входящих писем"); latestMessage = new Message__c(latestDate, latestMessageText); for (int i = messageCount; i >= 0; i--) { if (messages[i].Date > StdDate && messages[i].From.Address.Equals(Sender) && messages[i].Subject.StartsWith(Title) ) { allNewMessages.Add(messages[i]); } } } catch (Exception ex) { Console.WriteLine($"Error in \"EmailHandler\": {ex}"); } /// <summary> /// Сериализация последнего сообщения /// </summary> using (FileStream fs = new FileStream("message.xml", FileMode.Create)) { formatter.Serialize(fs, latestMessage); } return(allNewMessages); } } }
internal Message[] Fetch(IEnumerable<long> uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { if (_client.SelectedFolder != this && !Select()) { throw new OperationFailedException("The folder couldn't be selected for search."); } var result = new List<Message>(); foreach (Message msg in uIds.Select(uId => Messages.FirstOrDefault(_ => _.UId == uId) ?? new Message(uId, _client, this))) { msg.Download(mode); if (!Messages.Contains(msg)) { Messages.AddInternal(msg); } result.Add(msg); } return result.ToArray(); }
public Message[] Search(long[] uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { return Fetch(uIds, mode); }
private void TryProcessFlags(string data) { Match flagsMatch = Expressions.FlagsRex.Match(data); if (!flagsMatch.Success) { return; } Flags.AddRangeInternal(flagsMatch.Groups[1].Value.Split(' ').Where(_ => !string.IsNullOrEmpty(_))); _downloadProgress = _downloadProgress | MessageFetchMode.Flags; }
/// <summary> /// Downloads messages by their UIds from server using default or given mode. /// </summary> /// <param name="uIds">The uIds of the messages to download.</param> /// <param name="mode">The message fetch mode, allows to select which parts of the message will be requested.</param> public void Download(long[] uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { _folder.Search(uIds, mode); }
private void TryProcessBodyStructure(string data) { Match bstructMatch = Expressions.BodyStructRex.Match(data); if (!bstructMatch.Success) { return; } using (var parser = new BodyStructureParser(bstructMatch.Groups[1].Value, _client, this)) { BodyParts = parser.Parse(); } Body = new MessageBody(_client, BodyParts.FirstOrDefault( _ => _.ContentDisposition == null && _.ContentType != null && _.ContentType.MediaType.Equals("text/plain", StringComparison.OrdinalIgnoreCase)), BodyParts.FirstOrDefault( _ => _.ContentDisposition == null && _.ContentType != null && _.ContentType.MediaType.Equals("text/html", StringComparison.OrdinalIgnoreCase))); Attachments = (from part in BodyParts where part.ContentDisposition != null && part.ContentDisposition.DispositionType == DispositionTypeNames.Attachment select new Attachment(part)).ToArray(); EmbeddedResources = (from part in BodyParts where part.ContentDisposition != null && (part.ContentDisposition.DispositionType == DispositionTypeNames.Inline || !string.IsNullOrEmpty(part.ContentId)) select new Attachment(part)).ToArray(); _downloadProgress = _downloadProgress | MessageFetchMode.BodyStructure; }
/// <summary> /// Downloads all messages associated with the current thread /// </summary> /// <param name="mode">The message fetch mode, allows to select which parts of the message will be requested.</param> /// <param name="count"> /// The maximum number of messages that will be requested. Set <code>count</code> to <code>-1</code> /// will request all messages which match the given query. /// </param> public void FetchAssocicatedMessages(MessageFetchMode mode = MessageFetchMode.ClientDefault, int count = -1) { Messages.Download("X-GM-THRID " + Id, mode, count); }
public bool Download(MessageFetchMode mode = MessageFetchMode.ClientDefault, bool reloadHeaders = false) { if (mode == MessageFetchMode.ClientDefault) { mode = _client.Behavior.MessageFetchMode; } if (mode == MessageFetchMode.None) { return(true); } var fetchParts = new StringBuilder(); if (mode.HasFlag(MessageFetchMode.Flags) && !_downloadProgress.HasFlag(MessageFetchMode.Flags)) { fetchParts.Append("FLAGS "); } if (mode.HasFlag(MessageFetchMode.InternalDate) && !_downloadProgress.HasFlag(MessageFetchMode.InternalDate)) { fetchParts.Append("INTERNALDATE "); } if (mode.HasFlag(MessageFetchMode.Size) && !_downloadProgress.HasFlag(MessageFetchMode.Size)) { fetchParts.Append("RFC822.SIZE "); } if (mode.HasFlag(MessageFetchMode.Headers) && (!_downloadProgress.HasFlag(MessageFetchMode.Headers) || reloadHeaders)) { Headers.Clear(); if (_client.Behavior.RequestedHeaders == null || _client.Behavior.RequestedHeaders.Length == 0) { fetchParts.Append("BODY.PEEK[HEADER] "); } else { fetchParts.Append("BODY.PEEK[HEADER.FIELDS (" + string.Join(" ", _client.Behavior.RequestedHeaders.Where(_ => !string.IsNullOrEmpty(_)) .Select(_ => _.ToUpper()) .ToArray()) + ")] "); } } if (mode.HasFlag(MessageFetchMode.BodyStructure) && !_downloadProgress.HasFlag(MessageFetchMode.BodyStructure)) { fetchParts.Append("BODYSTRUCTURE "); } if (_client.Capabilities.XGMExt1) { if (mode.HasFlag(MessageFetchMode.GMailMessageId) && !_downloadProgress.HasFlag(MessageFetchMode.GMailMessageId)) { fetchParts.Append("X-GM-MSGID "); } if (mode.HasFlag(MessageFetchMode.GMailThreads) && !_downloadProgress.HasFlag(MessageFetchMode.GMailThreads)) { fetchParts.Append("X-GM-THRID "); } if (mode.HasFlag(MessageFetchMode.GMailLabels) && !_downloadProgress.HasFlag(MessageFetchMode.GMailLabels)) { fetchParts.Append("X-GM-LABELS "); } } IList <string> data = new List <string>(); if (fetchParts.Length > 0 && !_client.SendAndReceive(string.Format(ImapCommands.Fetch, UId, fetchParts.ToString().Trim()), ref data)) { return(false); } else { NormalizeAndProcessFetchResult(data); } BindHeadersToFields(); if (!mode.HasFlag(MessageFetchMode.Body) || BodyParts == null) { return(true); } foreach (MessageContent bodyPart in BodyParts) { if (mode.HasFlag(MessageFetchMode.Full) || (bodyPart.ContentDisposition == null && bodyPart.ContentType != null && (bodyPart.ContentType.MediaType == "text/plain" || bodyPart.ContentType.MediaType == "text/html"))) { bodyPart.Download(); } } return(true); }
private void TryProcessSize(string data) { Match sizeMatch = Expressions.SizeRex.Match(data); if (!sizeMatch.Success) { return; } Size = long.Parse(sizeMatch.Groups[1].Value); _downloadProgress = _downloadProgress | MessageFetchMode.Size; }
public void FetchAssocicatedMessages(MessageFetchMode mode = MessageFetchMode.ClientDefault, int count = -1) { Messages.Download("X-GM-THRID " + Id, mode, count); }
/// <summary> /// Downloads messages from server using default or given mode. /// </summary> /// <param name="query">The search query to filter messages. <code>ALL</code> by default</param> /// <param name="mode">The message fetch mode, allows to select which parts of the message will be requested.</param> /// <param name="count"> /// The maximum number of messages that will be requested. Set <code>count</code> to <code>-1</code> /// will request all messages which match the given query. /// </param> public void Download(string query = "ALL", MessageFetchMode mode = MessageFetchMode.ClientDefault, int count = -1) { _folder.Search(query, mode, count); }
/// <summary> /// Downloads messages by their UIds from server using default or given mode. /// </summary> /// <param name="uIds">The uIds of the messages to download.</param> /// <param name="mode">The message fetch mode, allows to select which parts of the message will be requested.</param> public Message[] Search(long[] uIds, MessageFetchMode mode = MessageFetchMode.ClientDefault) { return(Fetch(uIds, mode)); }
public bool Download(MessageFetchMode mode = MessageFetchMode.ClientDefault, bool reloadHeaders = false) { if (mode == MessageFetchMode.ClientDefault) { mode = _client.Behavior.MessageFetchMode; } if (mode == MessageFetchMode.None) { return true; } var fetchParts = new StringBuilder(); if (mode.HasFlag(MessageFetchMode.Flags) && !_downloadProgress.HasFlag(MessageFetchMode.Flags)) { fetchParts.Append("FLAGS "); } if (mode.HasFlag(MessageFetchMode.InternalDate) && !_downloadProgress.HasFlag(MessageFetchMode.InternalDate)) { fetchParts.Append("INTERNALDATE "); } if (mode.HasFlag(MessageFetchMode.Size) && !_downloadProgress.HasFlag(MessageFetchMode.Size)) { fetchParts.Append("RFC822.SIZE "); } if (mode.HasFlag(MessageFetchMode.Headers) && (!_downloadProgress.HasFlag(MessageFetchMode.Headers) || reloadHeaders)) { Headers.Clear(); if (_client.Behavior.RequestedHeaders == null || _client.Behavior.RequestedHeaders.Length == 0) { fetchParts.Append("BODY.PEEK[HEADER] "); } else { fetchParts.Append("BODY.PEEK[HEADER.FIELDS (" + string.Join(" ", _client.Behavior.RequestedHeaders.Where(_ => !string.IsNullOrEmpty(_)) .Select(_ => _.ToUpper()) .ToArray()) + ")] "); } } if (mode.HasFlag(MessageFetchMode.BodyStructure) && !_downloadProgress.HasFlag(MessageFetchMode.BodyStructure)) { fetchParts.Append("BODYSTRUCTURE "); } if (_client.Capabilities.XGMExt1) { if (mode.HasFlag(MessageFetchMode.GMailMessageId) && !_downloadProgress.HasFlag(MessageFetchMode.GMailMessageId)) { fetchParts.Append("X-GM-MSGID "); } if (mode.HasFlag(MessageFetchMode.GMailThreads) && !_downloadProgress.HasFlag(MessageFetchMode.GMailThreads)) { fetchParts.Append("X-GM-THRID "); } if (mode.HasFlag(MessageFetchMode.GMailLabels) && !_downloadProgress.HasFlag(MessageFetchMode.GMailLabels)) { fetchParts.Append("X-GM-LABELS "); } } IList<string> data = new List<string>(); if (fetchParts.Length > 0 && !_client.SendAndReceive(string.Format(ImapCommands.Fetch, UId, fetchParts.ToString().Trim()), ref data)) { return false; } else { NormalizeAndProcessFetchResult(data); } BindHeadersToFields(); if (!mode.HasFlag(MessageFetchMode.Body) || BodyParts == null) { return true; } foreach (MessageContent bodyPart in BodyParts) { if (mode.HasFlag(MessageFetchMode.Full) || (bodyPart.ContentDisposition == null && bodyPart.ContentType != null && (bodyPart.ContentType.MediaType == "text/plain" || bodyPart.ContentType.MediaType == "text/html"))) { bodyPart.Download(); } } return true; }