Пример #1
0
        protected async Task ExtractSendersReceiversAndSubject(string chatId)
        {
            if (ctx == null || !ctx.HasValue)
            {
                return;
            }
            var nonNullContext = ctx.Value;


            var messageFromTeams = false;
            var messageFromMe    = false;

            if (Internal_FromContactUrl?.EndsWith(chatId, StringComparison.InvariantCultureIgnoreCase) ?? false)
            {
                messageFromTeams = true;
            }

#pragma warning disable CS8604 // Possible null reference argument.
            if (Internal_FromContactUrl?.ToString().EndsWith(nonNullContext.Tenant.UserId, StringComparison.InvariantCultureIgnoreCase) ?? false)
#pragma warning restore CS8604 // Possible null reference argument.
            {
                messageFromMe = true;
            }

            // determine senders
            if (messageFromTeams)
            {
                var teamsChatUser = new ProcessedTeamsUser(nonNullContext, (TeamsParticipant)chatId);
                teamsChatUser.RegisterAlternateDisplayName(Constants.MicrosoftTeamsChatSenderName, OriginalArrivalTime);
                teamsChatUser.RegisterAlternateEmailAddress(Constants.MicrosoftTeamsChatSenderEmailAddress, OriginalArrivalTime);
                From.Add(teamsChatUser);
            }
            else
            {
                var userId = (TeamsParticipant)Internal_FromContactUrl;
                if (userId.IsValid)
                {
                    await teamsUserRegistry.RegisterDisplayNameForUserIdAsync(nonNullContext, userId, Internal_DisplayName, OriginalArrivalTime);

                    var user = await teamsUserRegistry.GetUserByIdOrDummyAsync(nonNullContext, userId);

                    if (user.HasDisplayName && user.HasEmailAddress)
                    {
                        From.Add(user);
                    }
                }
                else
                {
                    if (From.Count == 0)
                    {
                        // no valid user id? phew...
                        var dummyUser = new ProcessedTeamsUser(nonNullContext, userId);
                        dummyUser.RegisterAlternateDisplayName(Internal_DisplayName, OriginalArrivalTime);
                        From.Add(dummyUser);
                    }
                }
            }

            // determine receivers
            if (Internal_Mentions?.Count > 0)
            {
                foreach (var mention in Internal_Mentions)
                {
                    var userId = (TeamsParticipant)mention.mri;
                    var user   = await teamsUserRegistry.GetUserByIdAsync(nonNullContext, userId, true);

                    if (user != null && user.HasDisplayName && user.HasEmailAddress)
                    {
                        To.Add(user);
                    }
                    else
                    {
                        var toUser = new ProcessedTeamsUser(nonNullContext, userId);
                        toUser.RegisterAlternateDisplayName(mention.displayName, OriginalArrivalTime);
                        toUser.RegisterAlternateEmailAddress(mention.IsChannelMention ? Constants.ChannelMentionEmailAddress : Constants.UnknownUserEmailAddress, OriginalArrivalTime);
                        To.Add(toUser);
                    }
                }
            }
            else
            {
                var toUser = new ProcessedTeamsUser(nonNullContext, TeamsParticipant.Null);
                toUser.RegisterAlternateDisplayName(Constants.UnknownReceiversDisplayName, OriginalArrivalTime);
                toUser.RegisterAlternateEmailAddress(Constants.UnknownUserEmailAddress, OriginalArrivalTime);
                To.Add(toUser);
            }

            // determine subject
            if (!string.IsNullOrWhiteSpace(Internal_Subject))
            {
                MessageSubject = Internal_Subject;
            }
            else
            {
                string displayName = Internal_DisplayName ?? "";
                if (displayName == null && (Messagetype != MessageType.Text || Messagetype != MessageType.RichText_Html))
                {
                    displayName = "Microsoft Teams";
                }

                await teamsUserRegistry.RegisterDisplayNameForUserIdAsync(nonNullContext, (TeamsParticipant)Internal_FromContactUrl, displayName, OriginalArrivalTime);

                displayName = await teamsUserRegistry.ReplaceUserIdsWithDisplayNamesAsync(nonNullContext, displayName);

                var messagePreview = "Message";
                if (Messagetype == MessageType.RichText_Html)
                {
                    // not sure if needed
                    string       html = string.Format("<html><head></head><body>{0}</body></html>", Internal_Content);
                    HtmlDocument doc  = new HtmlDocument();
                    doc.LoadHtml(html);
                    var body = doc.DocumentNode.SelectSingleNode("//body");
                    messagePreview = body.InnerText ?? "";
                }
                else if (Messagetype == MessageType.Text)
                {
                    messagePreview = Internal_Content ?? "";
                }
                messagePreview = HttpUtility.HtmlDecode(messagePreview).Trim(); // need to replace &nbsp; etc.
                if (messagePreview.Length > 100)
                {
                    messagePreview = messagePreview.Truncate(100) + "...";
                }
                else
                if (messagePreview.Length == 0)
                {
                    messagePreview = $"Message";
                }
                var truncatedDisplayName = displayName.Truncate(10)?.Trim() ?? "";
                MessageSubject = $"[{(messageFromMe ? "ME" : truncatedDisplayName)}] {messagePreview}";
            }
        }
        public static async Task <(bool, List <string>)> ResolveParticipantPlaceholders(ILogger logger, ITeamsUserRegistry userRegistry, TeamsDataContext ctx, IMutableChatMessage message)
        {
            var replacedSomething = false;
            var notes             = new List <string>();

            var pattern   = TeamsParticipant.PlaceholderPattern;
            var replacers = new List <(Func <IMutableChatMessage, string?>, Action <IMutableChatMessage, string>, string)>
            {
                (m => m.MessageSubject, (m, s) => m.MessageSubject = s, "subject"),
                (m => m.TextContent, (m, s) => m.TextContent = s, "text content"),
                (m => m.HtmlContent, (m, s) => m.HtmlContent = s, "HTML content")
            };

            foreach (var stringReplacer in replacers)
            {
                var(stringGetter, stringSetter, replacementTarget) = stringReplacer;
                var stringToHandle = stringGetter(message);
                if (stringToHandle == null)
                {
                    continue;
                }

                var matches = Regex.Matches(stringToHandle, pattern);
                if (matches.Count == 0)
                {
                    continue;
                }

                var resolvedUserNames = new Dictionary <TeamsParticipant, ProcessedTeamsUser>();
                foreach (Match?match in matches)
                {
                    var userId = (TeamsParticipant)match?.Groups[1].Value;
                    if (!userId.IsValid)
                    {
                        continue;
                    }

                    var user = await userRegistry.GetUserByIdAsync(ctx, userId, false);

                    if (user != null && user.HasDisplayName)
                    {
                        logger.Debug("[{TenantName}] Found unresolved user id {UserId} and resolved it to name {Name}", ctx.Tenant.TenantName, userId, user.DisplayName);
                        resolvedUserNames[userId] = user;
                    }
                    else
                    {
                        logger.Verbose("[{TenantName}] Found unresolved user id {UserId} and could not resolve it to display name", ctx.Tenant.TenantName, userId);
                    }
                }

                if (resolvedUserNames.Count > 0)
                {
                    var stringToHandleWithPlaceholdersReplaced = Regex.Replace(stringToHandle, pattern, (match) =>
                    {
                        var userId = (TeamsParticipant)match.Groups[1].Value;
                        if (resolvedUserNames.TryGetValue(userId, out var user))
                        {
                            notes.Add($"Replacing '{match.Value}' with '{user.DisplayName}' in {replacementTarget}");
                            return(user.DisplayName);
                        }
                        else
                        {
                            return(match.Value);
                        }
                    });
                    if (!stringToHandle.Equals(stringToHandleWithPlaceholdersReplaced))
                    {
                        stringSetter(message, stringToHandleWithPlaceholdersReplaced);
                        replacedSomething = true;
                    }
                }
            }
            return(replacedSomething, notes);
        }