Exemplo n.º 1
0
        public void Move(string outputMessage, List <string> targetFolder)
        {
            try
            {
                // Get subfolder
                // Try to create subfolder on error
                IMailFolder currentFolder = Client.GetFolder(Client.PersonalNamespaces[0]);
                foreach (var folder in targetFolder)
                {
                    try
                    {
                        currentFolder = currentFolder.GetSubfolder(folder);
                    }
                    catch (Exception)
                    {
                        currentFolder = currentFolder.Create(folder, true);
                    }
                }

                // Move
                Inbox.MoveTo(Index, currentFolder);
                Inbox.Expunge();

                ConsoleUtils.WriteSuccess(outputMessage);
            }
            catch (Exception e)
            {
                ConsoleUtils.WriteError(e.ToString());
            }
        }
        private void ProcessAnalysis(IMailFolder inbox) {
            if ((_mailBox.Spam == null) || (_mailBox.Spam.EnableSpamProtection == false)) {
                return;
            }

            _learningData = _learningStorage.Read();
            var needToUpdateData = _learningData.LastUpdate < DateTime.Now.Subtract(TimeSpan.FromMinutes(_mailBox.Spam.AnalysisInterval));
            if (needToUpdateData) {
                var targetFolder = inbox.GetSubfolder(_mailBox.Spam.Target);
                targetFolder.Open(FolderAccess.ReadOnly);

                MailBoxFolderAnalyzer.Analyze(targetFolder, _learningData);

                _learningStorage.Save(_learningData);
            }
        }
Exemplo n.º 3
0
        private IMailFolder GetOrCreateLockFolder(IMailFolder parentFolderOfLockFolder, string resourceName, CancellationToken cancellationToken = default)
        {
            var         lockFolderName = parentFolderOfLockFolder.MakeSafeFolderName(resourceName);
            IMailFolder lockFolder     = null;

            try
            {
                lockFolder = parentFolderOfLockFolder.GetSubfolder(lockFolderName, cancellationToken);
            }
            catch
            {
                logger.Information("Could not get lock folder '{LockFolderName}' - maybe it does not yet exist or there was an error", lockFolderName);
            }
            if (lockFolder == null)
            {
                try
                {
                    logger.Information("Creating new lock folder with name '{LockFolderName}'", lockFolderName);
                    // note: on some mail servers (Greenmail) this will throw if the folder already exists, other servers don't throw and return any existing foldre with this name (Dovecot)
                    lockFolder = parentFolderOfLockFolder.Create(lockFolderName, true);
                }
                catch
                {
                    logger.Information("Error while creating lock folder '{LockFolderName}' - maybe it already exists or ther was an error", lockFolderName);
                }
            }

            if (lockFolder == null)
            {
                throw new TeasmCompanionException($"Could not get or create lock folder '{lockFolderName}'");
            }

            lockFolder.Open(FolderAccess.ReadOnly);
            var existingLockMessages = lockFolder.Search(SearchQuery.SubjectContains(LockMessageSubject), cancellationToken);

            if (existingLockMessages.Count == 0)
            {
                // note: this might create duplicates if run by multiple clients; we'll remove the duplicates later
                lockFolder.Append(CreateLockMimeMessage());
                Thread.Sleep(1000); // give other parallel clients the chance to produce their duplicates if any; we then always choose the first one (selected by UniqueId)
            }

            return(lockFolder);
        }
        private void ProcessRules(IMailFolder inbox) {
            inbox.Open(FolderAccess.ReadWrite);
            inbox.Status(StatusItems.Unread);

            if (inbox.Unread > 0) {
                var unreadMessageUids = inbox.Search(SearchQuery.NotSeen);
                var toMove = new Dictionary<string, List<UniqueId>>();
                var markAsRead = new List<UniqueId>();

                // process unread messages
                foreach (var unreadMessageUid in unreadMessageUids) {
                    var message = inbox.GetMessage(unreadMessageUid);

                    var matchingRule = GetMatchingRule(message);
                    if (matchingRule != null) {
                        if (!toMove.ContainsKey(matchingRule.Destination)) {
                            toMove.Add(matchingRule.Destination, new List<UniqueId>());
                        }

                        toMove[matchingRule.Destination].Add(unreadMessageUid);

                        if (matchingRule.MarkAsRead) {
                            markAsRead.Add(unreadMessageUid);
                        }
                    }
                }

                // mark as read
                if (markAsRead.Any()) {
                    inbox.AddFlags(markAsRead, MessageFlags.Seen, true);
                }

                // move to destination
                if (toMove.Any()) {
                    foreach (var destination in toMove.Keys) {
                        inbox.MoveTo(toMove[destination], inbox.GetSubfolder(destination));
                    }
                }
            }
        }
        /// <summary>
        /// Rally is authenticated in the constructor
        /// </summary>
        /// <param name="workspace"></param>

        public void SyncThroughLabels(string workspace)
        {
            #region variables
            SlackClient       _slackClient = new SlackClient(SLACK.SlackApiToken, 100);
            DynamicJsonObject toCreate     = new DynamicJsonObject();
            toCreate[RALLY.WorkSpace] = workspace;
            DynamicJsonObject           attachmentContent   = new DynamicJsonObject();
            DynamicJsonObject           attachmentContainer = new DynamicJsonObject();
            CreateResult                createUserStory;
            CreateResult                attachmentContentCreateResult;
            CreateResult                attachmentContainerCreateResult;
            string[]                    allAttachments;
            Dictionary <string, string> attachmentsDictionary = new Dictionary <string, string>();
            string userStorySubject;
            string userStoryDescription;
            string userStoryReference;
            string attachmentReference;
            int    anotherOne = 0;
            string base64String;
            string attachmentFileName;
            string fileName;
            string _objectId;
            string _userStoryUrl;
            string _slackAttachmentString;
            string slackChannel;
            #endregion

            using (ImapClient client = new ImapClient())
            {
                AuthenticateWithGoogleImap(client);

                client.Inbox.Open(FolderAccess.ReadWrite);
                IMailFolder parentFolder    = client.GetFolder(EMAIL.EnrollmentStudentServicesFolder);
                IMailFolder processedFolder = parentFolder.GetSubfolder(RALLYQUERY.ProcessedEnrollmentStudentServices);

                foreach (IMailFolder childFolder in parentFolder.GetSubfolders())
                {
                    #region Folders
                    if (childFolder.Name.Equals(RALLYQUERY.GmailFolderCatalyst2016))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectCatalyst2016;
                        slackChannel            = SLACK.Channelcatalyst2016;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderHonorsEnhancements))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectHonorsEnhancements;
                        slackChannel            = SLACK.ChannelHonorsEnhancements;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPalHelp))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPalHelp;
                        slackChannel            = SLACK.ChannelPalHelp;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPciAzureTouchNetImplementation))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPciAzureTouchNetImplementation;
                        slackChannel            = SLACK.ChannelAzureTouchNet;
                    }
                    else
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectScrumptious;
                        slackChannel            = SLACK.ChannelScrumptious;
                    }
                    #endregion

                    Console.WriteLine(childFolder.Name);
                    childFolder.Open(FolderAccess.ReadWrite);
                    IList <UniqueId> childFolderMsgUniqueIds = childFolder.Search(SearchQuery.NotSeen);

                    if (childFolderMsgUniqueIds.Any())
                    {
                        foreach (UniqueId uid in childFolderMsgUniqueIds)
                        {
                            MimeMessage message = childFolder.GetMessage(uid);
                            userStorySubject     = message.Subject;
                            userStoryDescription =
                                "From: " + message.From +
                                "<br>" + "Date Sent: " + message.Date + "</br>" +
                                "<br>" + "Subject: " + userStorySubject + "</br>" +
                                "<br>" + "Request: " + message.GetTextBody(TextFormat.Plain) + "<br>";

                            if (userStorySubject.IsEmpty())
                            {
                                userStorySubject = "<No Subject User Story>";
                            }

                            toCreate[RALLY.Name]        = userStorySubject;
                            toCreate[RALLY.Description] = userStoryDescription;
                            createUserStory             = _rallyRestApi.Create(RALLY.HierarchicalRequirement, toCreate);
                            userStoryReference          = createUserStory.Reference;

                            #region Download Attachments

                            foreach (MimeEntity attachment in message.BodyParts)
                            {
                                string attachmentFile = attachment.ContentDisposition?.FileName ??
                                                        attachment.ContentType.Name;
                                string attachmentFilePath = Concat(STORAGE.MimeKitAttachmentsDirectoryWork,
                                                                   Path.GetFileName(attachmentFile));

                                if (!IsNullOrWhiteSpace(attachmentFile))
                                {
                                    if (File.Exists(attachmentFilePath))
                                    {
                                        string extension = Path.GetExtension(attachmentFilePath);
                                        string fileNameWithoutExtension =
                                            Path.GetFileNameWithoutExtension(attachmentFilePath);
                                        attachmentFile = Format(fileNameWithoutExtension + "-{0}" + "{1}", ++anotherOne,
                                                                extension);
                                        attachmentFilePath =
                                            Path.Combine(STORAGE.MimeKitAttachmentsDirectoryWork, attachmentFile);
                                    }

                                    using (var attachmentStream = File.Create(attachmentFilePath))
                                    {
                                        MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                                        part.ContentObject.DecodeTo(attachmentStream);
                                    }

                                    Console.WriteLine("Downloaded: " + attachmentFile);
                                }
                            }

                            #endregion

                            #region Process Attachments

                            allAttachments = Directory.GetFiles(STORAGE.MimeKitAttachmentsDirectoryWork);
                            foreach (string file in allAttachments)
                            {
                                base64String       = FileToBase64(file);
                                attachmentFileName = Path.GetFileName(file);
                                fileName           = Empty;

                                if (!(attachmentsDictionary.TryGetValue(base64String, out fileName)))
                                {
                                    Console.WriteLine("Added to Dictionary: " + file);
                                    attachmentsDictionary.Add(base64String, attachmentFileName);
                                }

                                File.Delete(file);
                            }

                            #endregion

                            #region Upload to Rally
                            foreach (KeyValuePair <string, string> attachmentPair in attachmentsDictionary)
                            {
                                try
                                {
                                    //create attachment content
                                    attachmentContent[RALLY.Content] = attachmentPair.Key;
                                    attachmentContentCreateResult    = _rallyRestApi.Create(
                                        RALLY.AttachmentContent,
                                        attachmentContent);
                                    attachmentReference = attachmentContentCreateResult.Reference;

                                    //create attachment contianer
                                    attachmentContainer[RALLY.Artifact]    = userStoryReference;
                                    attachmentContainer[RALLY.Content]     = attachmentReference;
                                    attachmentContainer[RALLY.Name]        = attachmentPair.Value;
                                    attachmentContainer[RALLY.Description] = RALLY.EmailAttachment;
                                    attachmentContainer[RALLY.ContentType] = "file/";

                                    //Create & associate the attachment
                                    attachmentContainerCreateResult = _rallyRestApi.Create(RALLY.Attachment,
                                                                                           attachmentContainer);
                                    Console.WriteLine("Uploaded to Rally: " + attachmentPair.Value);
                                }
                                catch (WebException e)
                                {
                                    Console.WriteLine("Attachment: " + e.Message);
                                }
                            }
                            attachmentsDictionary.Clear();

                            #endregion

                            #region See and Move

                            childFolder.SetFlags(uid, MessageFlags.Seen, true);
                            childFolder.MoveTo(uid, processedFolder);

                            #endregion

                            #region Slack

                            if (userStoryReference != null)
                            {
                                _objectId              = Ref.GetOidFromRef(userStoryReference);
                                _userStoryUrl          = string.Concat(SLACK.UserStoryUrlFormat, _objectId);
                                _slackAttachmentString = string.Format("User Story: <{0} | {1} >", _userStoryUrl, message.Subject);

                                SlackMessage slackMessage = new SlackMessage
                                {
                                    //Channel is set according to the source of the email message folder
                                    Channel   = slackChannel,
                                    Text      = SLACK.SlackNotificationBanner,
                                    IconEmoji = Emoji.SmallRedTriangle,
                                    Username  = SLACK.SlackUser
                                };

                                SlackAttachment slackAttachment = new SlackAttachment
                                {
                                    Fallback = _slackAttachmentString,
                                    Text     = _slackAttachmentString,
                                    Color    = SLACK.HexColor
                                };

                                slackMessage.Attachments = new List <SlackAttachment> {
                                    slackAttachment
                                };
                                _slackClient.Post(slackMessage);
                            }
                            else
                            {
                                throw new NullReferenceException();
                            }

                            #endregion

                            #region Email
                            using (SmtpClient smtpClient = new SmtpClient())
                            {
                                if (!smtpClient.IsAuthenticated)
                                {
                                    AuthenticateWithGoogleSmtp(smtpClient);
                                }

                                //iterate throught the email addresses, to send the emails
                                List <MailboxAddress> emailNoticationList = new List <MailboxAddress>();
                                emailNoticationList.Add(new MailboxAddress("*****@*****.**"));

                                foreach (var mailboxAddress in emailNoticationList)
                                {
                                    MimeMessage emailNotificationMessage = new MimeMessage();
                                    emailNotificationMessage.From.Add(new MailboxAddress("Rally Integration", EMAIL.GoogleUsername));
                                    emailNotificationMessage.To.Add(mailboxAddress);
                                    emailNotificationMessage.Subject = "Rally Notification: " + userStorySubject;
                                    emailNotificationMessage.Body    = new TextPart("plain")
                                    {
                                        Text = "User Story: " + _userStoryUrl
                                    };

                                    smtpClient.Send(emailNotificationMessage);
                                }

                                //disconnect here...
                                //this will make the program connect and disconnect in a loop
                            }
                            #endregion

                            Console.WriteLine(message.Subject + " Created");
                        }
                    }
                    else
                    {
                        Console.WriteLine(childFolder + "-No Unread Messages");
                    }
                }
                Console.WriteLine("Done");
                client.Disconnect(true);
            }
        }