Ejemplo n.º 1
0
        public Message ToSlackMessage(BuildCompletionNotification notification, BotElement bot, string channel)
        {
            var lines = notification.ToMessage(bot, s => s);
            var color = notification.IsSuccessful ? bot.GetSetting("successColor") : bot.GetSetting("errorColor");

            return SlackHelper.CreateSlackMessage(lines, bot, channel, color);
        }
        public override async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var token = bot.GetSetting("token");
            if (string.IsNullOrEmpty(token)) throw new ArgumentException("Missing token!");

            var tasks = new List<Task>();
            var slackClient = new SlackClient();

            foreach (string tfsUserName in notification.TargetUserNames)
            {
                var userId = bot.GetMappedUser(tfsUserName);

                if (userId != null)
                {
                    Message slackMessage = ToSlackMessage((dynamic)notification, bot, null, true);
                    if (slackMessage != null)
                    {
                        slackMessage.AsUser = true;
                        var t = Task.Run(async () =>
                        {
                            var response = await slackClient.SendApiMessageAsync(slackMessage, token, userId);
                            response.EnsureSuccessStatusCode();
                            var content = await response.Content.ReadAsStringAsync();
                        });
                        tasks.Add(t);
                    }
                }
            }

            await Task.WhenAll(tasks);
        }
        public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
        {
            var lines = new List<string>();
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                ProjectName = transform(ProjectName),
                WiUrl,
                WiType = transform(WiType),
                WiId,
                WiTitle = transform(WiTitle),
                IsStateChanged,
                IsAssignmentChanged,
                AssignedTo = transform(AssignedTo),
                State = transform(State),
                UserName = transform(UserName),
                Action = FormatAction(bot)
            };
            lines.Add(bot.Text.WorkItemchangedFormat.FormatWith(formatter));

            var searchType = IsNew ? SearchFieldsType.Core : SearchFieldsType.Changed;
            var displayFieldsKey = IsNew ? "wiCreatedDisplayFields" : "wiChangedDisplayFields";
            var pattern = IsNew ? "{name}: {newValue}" : "{name}: " + bot.Text.WorkItemFieldTransitionFormat;

            foreach (var fieldId in bot.GetCsvSetting(displayFieldsKey, Defaults.WorkItemFields))
            {
                var field = GetUnifiedField(fieldId, searchType);
                if (field != null)
                    lines.Add(pattern.FormatWith(field));
            }

            return lines;
        }
Ejemplo n.º 4
0
        public static Message CreateSlackMessage(string text, IEnumerable<AttachmentField> fields, BotElement bot, string channel, string color, bool asUser)
        {
            if (text == null) return null;
            IEnumerable<Attachment> attachments = null;
            if (fields != null && fields.Any())
            {
                attachments = new[] {
                    new Attachment() {
                        Fallback = text,
                        Color = color,
                        Fields = fields
                    }
                };
            }
            var message = new Message()
            {
                Channel = channel,
                Text = text,
                Attachments = attachments
            };

            if (!asUser)
            {
                message.Username = bot.GetSetting("username");
                if (!string.IsNullOrEmpty(bot.GetSetting("iconUrl")))
                    message.IconUrl = bot.GetSetting("iconUrl");
                else if (!string.IsNullOrEmpty(bot.GetSetting("iconEmoji")))
                    message.IconEmoji = bot.GetSetting("iconEmoji");
            }

            return message;
        }
Ejemplo n.º 5
0
        public Message ToSlackMessage(WorkItemCommentNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();
            var fields = new[] {
                new AttachmentField(bot.Text.Comment, notification.Comment, false)
            };

            return SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor"));
        }
Ejemplo n.º 6
0
        public static Message CreateSlackMessage(IEnumerable<string> lines, BotElement bot, string channel, string color, bool asUser)
        {
            if (lines == null || !lines.Any()) return null;

            string header = lines.First();
            var fields = from line in lines.Skip(1) select new AttachmentField() { Value = line, IsShort = false };

            return CreateSlackMessage(header, fields, bot, channel, color, asUser);
        }
Ejemplo n.º 7
0
        public Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            if (!notification.TargetUserNames.Any())
                return Task.FromResult(0);

            var config = TfsNotificationRelaySection.Instance;
            string host = bot.GetSetting("host", "127.0.0.1");
            int port = bot.GetIntSetting("port", 25);
            string fromAddress = bot.GetSetting("fromAddress");
            string fromName = bot.GetSetting("fromName");
            string subjectTextId = bot.GetSetting("subjectTextId", "plaintext");
            bool isHtml = bot.GetSetting("isHtml") == "true";
            var subjectTextElement = config.Texts.FirstOrDefault(t => t.Id == subjectTextId) ?? bot.Text;
            string subject = notification.ToMessage(bot, subjectTextElement, s => s).First();

            var client = new SmtpClient(host, port);

            var message = new MailMessage();
            message.From = new MailAddress(fromAddress, fromName, Encoding.UTF8);
            message.SubjectEncoding = Encoding.UTF8;
            message.Subject = subject;
            message.IsBodyHtml = isHtml;
            message.BodyEncoding = Encoding.UTF8;
            message.Body = string.Join(isHtml ? "<br/>": "\n", notification.ToMessage(bot, s => s));

            var identityService = requestContext.GetService<ITeamFoundationIdentityService>();

            foreach (var username in notification.TargetUserNames)
            {
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.AccountName, username);
                var email = identityService.GetPreferredEmailAddress(requestContext, identity.TeamFoundationId);
                if (string.IsNullOrEmpty(email))
                {
                    string errmsg = $"TfsNotificationRelay.Smtp.SmtpNotifier: User {username} doesn't have an email address.";
                    TeamFoundationApplicationCore.Log(requestContext, errmsg, 0, EventLogEntryType.Warning);
                }
                else
                {
                    message.To.Add(email);
                }
            }

            if (message.To.Any())
            {
                requestContext.Trace(0, TraceLevel.Info, Constants.TraceArea, "SmtpNotifier",
                    string.Format("Sending {0} email notification to: {1}.", notification.GetType(), string.Join(", ", message.To.Select(m => m.Address))));

                return client.SendMailAsync(message);
            }
            else
            {
                requestContext.Trace(0, TraceLevel.Warning, Constants.TraceArea, "SmtpNotifier",
                    string.Format("No recipients to send {0} email notification to.", notification.GetType()));

                return Task.FromResult(0);
            }
        }
        public Message ToSlackMessage(WorkItemChangedNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();
            var fields = new[] {
                new AttachmentField(bot.Text.State, notification.State, true),
                new AttachmentField(bot.Text.AssignedTo, notification.AssignedTo, true)
            };

            return SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor"));
        }
 private string FormatAction(BotElement bot)
 {
     switch (Vote)
     {
         case -10: return bot.Text.VoteRejected;
         case 0: return bot.Text.VoteRescinded;
         case 10: return bot.Text.VoteApproved;
         default:
             return $"voted {Vote} on";
     }
 }
 private string FormatAction(BotElement bot)
 {
     switch (Status)
         {
             case PullRequestStatus.Abandoned: return bot.Text.Abandoned;
             case PullRequestStatus.Active: return bot.Text.Reactivated;
             case PullRequestStatus.Completed: return bot.Text.Completed;
             default:
                 return $"updated status to {Status} for";
         }
 }
        public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
        {
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                ProjectUrl,
                ProjectName = transform(ProjectName),
            };

            return new[] { text.ProjectCreatedFormat.FormatWith(formatter) };
        }
Ejemplo n.º 12
0
        public string ToString(BotElement bot, Func<string, string> transform)
        {
            string pattern = Type == GitRefType.Tag ? bot.Text.TagFormat : bot.Text.BranchFormat;
            var sb = new StringBuilder();
            if (Type == GitRefType.Branch && IsNew) sb.Append("+");
            sb.Append(Name);

            return pattern.FormatWith(new
            {
                Name = transform(sb.ToString())
            });
        }
Ejemplo n.º 13
0
 public override string ToString(BotElement bot, Func<string, string> transform)
 {
     var formatter = new
     {
         DisplayName = transform(DisplayName), RepoUri,
         ProjectName = transform(ProjectName),
         RepoName = transform(RepoName),
         Pushed = IsForcePush ? bot.Text.ForcePushed : bot.Text.Pushed,
         UserName = transform(UserName)
     };
     return bot.Text.PushFormat.FormatWith(formatter);
 }
Ejemplo n.º 14
0
        public static Message CreateSlackMessage(IEnumerable<string> lines, BotElement bot, string channel, bool asUser)
        {
            if (lines == null || !lines.Any()) return null;
            var sb = new StringBuilder();
            sb.AppendLine(lines.First());
            foreach(var line in lines.Skip(1))
            {
                sb.Append(">");
                sb.AppendLine(line);
            }

            return CreateSlackMessage(sb.ToString(), null, bot, channel, null, asUser);
        }
Ejemplo n.º 15
0
 public override string ToString(BotElement bot, TextElement text, Func<string, string> transform)
 {
     var formatter = new
     {
         DisplayName = transform(DisplayName), RepoUri,
         ProjectName = transform(ProjectName),
         RepoName = transform(RepoName),
         Pushed = IsForcePush ? text.ForcePushed : text.Pushed,
         UserName = transform(UserName),
         MappedUser = bot.GetMappedUser(UniqueName)
     };
     return text.PushFormat.FormatWith(formatter);
 }
Ejemplo n.º 16
0
        public void Notify(INotification notification, BotElement bot)
        {
            string servicEndpoint = bot.GetSetting("serviceEndpoint", "net.pipe://localhost/BotService");

            ChannelFactory<IBotService> factory = new ChannelFactory<IBotService>(new NetNamedPipeBinding(),
                    new EndpointAddress(servicEndpoint));
            IBotService service = factory.CreateChannel();

            foreach (string line in notification.ToMessage(bot))
            {
                service.SendMessage(line);
            }
        }
        public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
        {
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                UserName = transform(UserName),
                ProjectName = transform(ProjectName),
                RepoUri,
                RepoName = transform(RepoName)
            };

            return new[] { bot.Text.RepositoryCreatedFormat.FormatWith(formatter) };
        }
 public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
 {
     var formatter = new
     {
         TeamProjectCollection = transform(TeamProjectCollection),
         DisplayName = transform(DisplayName),
         ChangesetUrl,
         ChangesetId,
         Comment = transform(Comment),
         UserName = transform(UserName),
         ProjectLinks = FormatProjectLinks(bot, transform)
     };
     return new[] { bot.Text.CheckinFormat.FormatWith(formatter) };
 }
        public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
        {
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                UserName = transform(UserName),
                ProjectName = transform(ProjectName),
                ProjectUrl,
                RepoUri,
                RepoName = transform(RepoName),
                MappedUser = bot.GetMappedUser(UniqueName)
            };

            return new[] { GetFormat(text).FormatWith(formatter) };
        }
Ejemplo n.º 20
0
        public async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string room = bot.GetSetting("room");
            string baseUrl = bot.GetSetting("apiBaseUrl");
            string authToken = bot.GetSetting("roomNotificationToken");

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            string json = ToJson((dynamic)notification, bot);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            string url = baseUrl + "/room/" + room + "/notification";
            requestContext.Trace(0, TraceLevel.Verbose, Constants.TraceArea, "HipChatNotifier", "Sending notification to {0}\n{1}", url, json);

            await httpClient.PostAsync(url, content).ContinueWith(t => t.Result.EnsureSuccessStatusCode());
        }
Ejemplo n.º 21
0
        public async Task NotifyAsync(TeamFoundationRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var channels = bot.GetCsvSetting("channels");
            var tasks = new List<Task>();
            var slackClient = new SlackClient();

            foreach (string channel in channels)
            {
                Message slackMessage = ToSlackMessage((dynamic)notification, bot, channel);
                if (slackMessage != null)
                {
                    tasks.Add(slackClient.SendMessageAsync(slackMessage, bot.GetSetting("webhookUrl")).ContinueWith(t => t.Result.EnsureSuccessStatusCode()));
                }
            }

            await Task.WhenAll(tasks);
        }
        public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
        {
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                ProjectName = transform(ProjectName),
                RepoUri,
                RepoName = transform(RepoName),
                PrId,
                PrUrl,
                PrTitle = transform(PrTitle),
                UserName = transform(UserName),
                SourceBranchName = transform(SourceBranch.Name),
                TargetBranchName = transform(TargetBranch.Name)
            };

            return new[] { bot.Text.PullRequestCreatedFormat.FormatWith(formatter) };
        }
 public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
 {
     var formatter = new
     {
         TeamProjectCollection = transform(TeamProjectCollection),
         ProjectName = transform(ProjectName),
         ReleaseDefinition = transform(ReleaseDefinition),
         ReleaseStatus = transform(ReleaseStatus.ToString()),
         ReleaseUrl,
         ReleaseName = transform(ReleaseName),
         ReleaseReason = transform(ReleaseReason.ToString()),
         CreatedBy = transform(CreatedByUniqueName),
         CreatedByDisplayName = transform(CreatedByDisplayName),
         DisplayName = transform(CreatedByDisplayName),
         CreatedOn,
         UserName = transform(UserName),
         MappedUser = bot.GetMappedUser(CreatedByUniqueName)
     };
     return new[] { text.ReleaseCreatedFormat.FormatWith(formatter) };
 }
Ejemplo n.º 24
0
        public override string ToString(BotElement bot, Func<string, string> transform)
        {
            string formattedTime = string.IsNullOrEmpty(bot.Text.DateTimeFormat) ? AuthorTime.ToString() : AuthorTime.ToString(bot.Text.DateTimeFormat);
            var sb = new StringBuilder();
            if (Refs != null) sb.AppendFormat("{0} ", Refs.ToString(bot, transform));
            
            sb.Append(bot.Text.CommitFormat.FormatWith(new
            {
                Action = Type == CommitRowType.Commit ? bot.Text.Commit : bot.Text.RefPointer, CommitUri,
                CommitId = transform(CommitId.ToHexString(Settings.HashLength)),
                ChangeCounts = (ChangeCounts != null) ? ChangeCountsToString(bot, ChangeCounts) : "",
                AuthorTime = formattedTime,
                Author = transform(Author),
                AuthorName = transform(AuthorName),
                AuthorEmail = transform(AuthorEmail),
                Comment = transform(Comment.Truncate(Settings.CommentMaxLength, true))
            }));

            return sb.ToString();
        }
Ejemplo n.º 25
0
        public Message ToSlackMessage(WorkItemChangedNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();

            var fields = new List<AttachmentField>();

            var searchType = notification.IsNew ? SearchFieldsType.Core : SearchFieldsType.Changed;
            var displayFieldsKey = notification.IsNew ? "wiCreatedDisplayFields" : "wiChangedDisplayFields";

            foreach (var fieldId in bot.GetCsvSetting(displayFieldsKey, Defaults.WorkItemFields))
            {
                var field = notification.GetUnifiedField(fieldId, searchType);
                if (field != null)
                {
                    var fieldrep = notification.IsNew ? field.NewValue : bot.Text.WorkItemFieldTransitionFormat.FormatWith(field);
                    fields.Add(new AttachmentField(field.Name, fieldrep, true));
                }
            }

            return SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor"));
        }
Ejemplo n.º 26
0
        private JObject CreateHipChatMessage(INotification notification, BotElement bot, string color)
        {
            dynamic jobject = new JObject();

            if (bot.GetSetting("messageFormat") == "text")
            {
                var lines = notification.ToMessage(bot, s => s);
                if (lines == null || lines.Count() == 0) return null;
                jobject.message_format = "text";
                jobject.message = String.Join("\n", lines);
            } else {
                var lines = notification.ToMessage(bot, s => HttpUtility.HtmlEncode(s));
                if (lines == null || lines.Count() == 0) return null;
                jobject.message_format = "html";
                jobject.message = String.Join("<br/>", lines);
            }
            jobject.color = color;
            jobject.notify = bot.GetSetting("notify").Equals("true", StringComparison.OrdinalIgnoreCase);

            return jobject;
        }
        public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
        {
            var lines = new List<string>();
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                ProjectName = transform(ProjectName),
                AreaPath = transform(AreaPath),
                WiUrl,
                WiType = transform(WiType),
                WiId,
                WiTitle = transform(WiTitle),
                UserName = transform(UserName),
                Action = bot.Text.CommentedOn
            };
            lines.Add(bot.Text.WorkItemchangedFormat.FormatWith(formatter));
            lines.Add(TextHelper.Truncate(Comment, Settings.DiscussionCommentMaxLength));

            return lines;
        }
 public override IList<string> ToMessage(BotElement bot, Func<string, string> transform)
 {
     var formatter = new
     {
         TeamProjectCollection = transform(TeamProjectCollection),
         ProjectName = transform(ProjectName),
         BuildDefinition = transform(BuildDefinition),
         BuildStatus = transform(BuildStatus.ToString()),
         BuildUrl,
         BuildNumber = transform(BuildNumber),
         BuildReason = transform(BuildReason.ToString()),
         RequestedFor = transform(RequestedFor),
         RequestedForDisplayName = transform(RequestedForDisplayName),
         DisplayName = transform(RequestedForDisplayName),
         StartTime,
         FinishTime,
         UserName = transform(UserName),
         BuildDuration = FormatBuildDuration(bot),
         DropLocation
     };
     return new[] { bot.Text.BuildFormat.FormatWith(formatter), transform(BuildStatus.ToString()) };
 }
        public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
        {
            var formatter = new
            {
                TeamProjectCollection = transform(TeamProjectCollection),
                DisplayName = transform(DisplayName),
                ProjectName = transform(ProjectName),
                RepoUri,
                RepoName = transform(RepoName),
                PrId,
                PrUrl,
                PrTitle = transform(PrTitle),
                UserName = transform(UserName),
                SourceBranchName = transform(SourceBranch.Name),
                TargetBranchName = transform(TargetBranch.Name),
                CreatorUserName = transform(CreatorUserName),
                MappedCreatorUser = bot.GetMappedUser(CreatorUniqueName),
                MappedUser = bot.GetMappedUser(UniqueName)
            };

            return new[] { text.PullRequestCommentFormat.FormatWith(formatter), Comment };
        }
 public override IList<string> ToMessage(BotElement bot, TextElement text, Func<string, string> transform)
 {
     var formatter = new
     {
         TeamProjectCollection = transform(TeamProjectCollection),
         ProjectName = transform(ProjectName),
         BuildDefinition = transform(BuildDefinition),
         BuildStatus = transform(BuildStatus.ToString()), BuildUrl,
         BuildNumber = transform(BuildNumber),
         BuildReason = transform(BuildReason.ToString()),
         RequestedFor = transform(RequestedForUniqueName),
         RequestedForDisplayName = transform(RequestedForDisplayName),
         DisplayName = transform(RequestedForDisplayName),
         StartTime,
         FinishTime,
         UserName = transform(UserName),
         BuildDuration = FormatBuildDuration(text),
         DropLocation,
         NewValue = NewValue == null ? text.BuildQualityNotSet : transform(NewValue),
         OldValue = OldValue == null ? text.BuildQualityNotSet : transform(OldValue),
     };
     return new[] { text.BuildQualityChangedFormat.FormatWith(formatter) };
 }