private async Task ShowDetailsAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var teamId      = turnContext.Activity.TeamsGetTeamInfo().Id;
            var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamId, cancellationToken);

            await SendMessageAndLogActivityIdAsync(turnContext, $"The team name is {teamDetails.Name}. The team ID is {teamDetails.Id}. The ADD GroupID is {teamDetails.AadGroupId}.", cancellationToken);
        }
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionBotMessagePreviewSendAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var        submitData       = action.ToSubmitExampleData();
            var        adaptiveCard     = submitData.ToAdaptiveCard();
            var        responseActivity = Activity.CreateMessageActivity();
            Attachment attachment       = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = adaptiveCard,
            };

            responseActivity.Attachments.Add(attachment);
            try
            {
                // Send to channel where messaging extension invoked.
                var channelId = turnContext.Activity.TeamsGetChannelId();
                await turnContext.TeamsCreateConversationAsync(channelId, responseActivity);

                // Send card to "General" channel.
                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext);

                await turnContext.TeamsCreateConversationAsync(teamDetails.Id, responseActivity);
            }
            catch (Exception ex)
            {
                // In group chat or personal scope..
                await turnContext.SendActivityAsync($"In Group Chat or Personal Teams scope. Sending card to compose-only.");
            }

            return(adaptiveCard.ToComposeExtensionResultResponse());
        }
        //// <inheritdoc/>
        public override async Task <DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (options is CancellationToken)
            {
                throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
            }

            if (Disabled != null && Disabled.GetValue(dc.State))
            {
                return(await dc.EndDialogAsync(cancellationToken : cancellationToken).ConfigureAwait(false));
            }

            if (dc.Context.Activity.ChannelId != Channels.Msteams)
            {
                throw new InvalidOperationException($"{Kind} works only on the Teams channel.");
            }

            string teamId = TeamId.GetValueOrNull(dc.State);
            var    result = await TeamsInfo.GetTeamDetailsAsync(dc.Context, teamId, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (Property != null)
            {
                dc.State.SetValue(Property.GetValue(dc.State), result);
            }

            return(await dc.EndDialogAsync(result, cancellationToken : cancellationToken).ConfigureAwait(false));
        }
示例#4
0
        /// <summary>
        /// Get Azure Active Directory group Id of the team in which bot is installed.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>Return Active Directory group Id of the team.</returns>
        public async Task <string> GetTeamAadGroupIdAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
            var teamInformation = turnContext.Activity.TeamsGetTeamInfo();
            var teamDetails     = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamInformation.Id, cancellationToken).ConfigureAwait(false);

            return(teamDetails.AadGroupId);
        }
示例#5
0
        private async Task ShowDetailsAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, cancellationToken);

            var message = $"The team name is <b>{teamDetails.Name}</b>. The team ID is <b>{teamDetails.Id}</b>. The ADDGroupID is <b>{teamDetails.AadGroupId}</b>.";

            await SendMessageAndLogActivityId(turnContext, message, cancellationToken);
        }
示例#6
0
        private async Task ShowDetailsAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, cancellationToken);

            var replyActivity = MessageFactory.Text($"The team name is <b>{teamDetails.Name}</b>. The team ID is <b>{teamDetails.Id}</b>. The ADDGroupID is <b>{teamDetails.AadGroupId}</b>.");

            await turnContext.SendActivityAsync(replyActivity, cancellationToken);
        }
            private async Task CallGetTeamDetailsAsync(ITurnContext turnContext)
            {
                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext);

                Assert.AreEqual("team-id", teamDetails.Id);
                Assert.AreEqual("team-name", teamDetails.Name);
                Assert.AreEqual("team-aadgroupid", teamDetails.AadGroupId);
            }
示例#8
0
        private async Task <IReportBodyDetails> GetReportBodyDetailsAsync(ITurnContext context, IEnumerable <IMessageDetails> messages, ReportParameters parameters, CancellationToken cancellationToken)
        {
            var details = new ReportBodyDetails()
            {
                IsChannel      = parameters.ReportType == ReportSourceType.Channel,
                IsConversation = parameters.ReportType == ReportSourceType.Conversation,
                IsGroupChat    = parameters.ReportType == ReportSourceType.Chat,
                Messages       = messages,
                Since          = parameters.Since,
                Till           = parameters.Till,
                Author         = context.Activity.From?.Name,
            };

            if (context.Activity.Conversation.ConversationType == Constants.ChannelConversationType)
            {
                var channelData = context.Activity.GetChannelData <TeamsChannelData>();
                var teamDetails = new TeamDetails(channelData.Team.Id, channelData.Team.Name);
                details.ChannelName = channelData.Channel.Name;
                if (channelData.Team.Id == channelData.Channel.Id)
                {
                    // The channel ID for the General channel always matches the team ID (from MS documentation).
                    // The name of the default General channel is returned as null to allow for localization. (from MS documentation).
                    details.ChannelName = Resources.Strings.TeamGeneralChannelDefaultTitle;
                }

                try
                {
                    teamDetails = await TeamsInfo.GetTeamDetailsAsync(context, channelData.Team.Id, cancellationToken);

                    if (teamDetails != null)
                    {
                        details.TeamName = teamDetails.Name;
                        details.TeamId   = teamDetails.AadGroupId;
                        if (string.IsNullOrEmpty(details.ChannelName))
                        {
                            var channels = await TeamsInfo.GetTeamChannelsAsync(context, channelData.Team.Id, cancellationToken);

                            details.ChannelName = channels?.FirstOrDefault(x => channelData.Channel.Id.Equals(x.Id))?.Name;
                        }
                    }
                }
                catch
                {
                    // Bot is not aaded to the team, Forbidden exception here
                    details.TeamName = channelData.Team.Id; // Team name is not available here
                    details.TeamId   = channelData.Team.Id;
                    logger.LogWarning($"Bot is not added to team {channelData.Team.Id}");
                }

                if (string.IsNullOrEmpty(details.ChannelName))
                {
                    // Fill it with channel id if name is not available.
                    details.ChannelName = channelData.Channel.Id;
                }
            }

            return(details);
        }
示例#9
0
        private async Task ShowDetailsAsync(ITurnContext <IMessageActivity> turnContext, TeamsSkillBot bot, CancellationToken cancellationToken)
        {
            var teamInfo = turnContext.Activity.TeamsGetTeamInfo();

            if (await TeamScopeCheck(turnContext, cancellationToken).ConfigureAwait(false))
            {
                var teamId      = teamInfo.Id;
                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamId, cancellationToken).ConfigureAwait(false);

                await bot.SendMessageAndLogActivityIdAsync(turnContext, $"The team name is {teamDetails.Name}. The team ID is {teamDetails.Id}. The ADD GroupID is {teamDetails.AadGroupId}.", cancellationToken).ConfigureAwait(false);
            }
        }
示例#10
0
        /// <inheritdoc/>
        public async Task <Course> GetCourseAsync(TeamInfo teamInfo, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamInfo.Id, cancellationToken);

            return(new Course()
            {
                Id = teamDetails.Id,
                TeamId = teamDetails.Id,
                TeamAadObjectId = teamDetails.AadGroupId,
                Name = teamDetails.Name,
            });
        }
示例#11
0
        private async Task ShowDetailsAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var teamInfo = turnContext.Activity.TeamsGetTeamInfo();

            if (teamInfo == null)
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("This only works in the team scope"), cancellationToken).ConfigureAwait(false);
            }
            else
            {
                var teamId      = teamInfo.Id;
                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamId, cancellationToken).ConfigureAwait(false);

                await turnContext.SendActivityAsync(MessageFactory.Text($"The team name is {teamDetails.Name}. The team ID is {teamDetails.Id}. The ADD GroupID is {teamDetails.AadGroupId}."), cancellationToken).ConfigureAwait(false);
            }
        }
        private async Task <string> GetTeamAadId(ITurnContext turnContext, string channelDataTeamId, CancellationToken cancellationToken)
        {
            try
            {
                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, channelDataTeamId, cancellationToken);

                if (teamDetails != null)
                {
                    return(teamDetails.AadGroupId);
                }
            }
            catch
            {
                // Bot is not aaded to the team, Forbidden exception here
            }

            return(string.Empty);
        }
示例#13
0
 /// <summary>
 /// Gets the details for the given team id. This only works in teams scoped conversations.
 /// </summary>
 /// <param name="turnContext"> Turn context. </param>
 /// <param name="teamId"> The id of the Teams team. </param>
 /// <param name="cancellationToken"> Cancellation token. </param>
 /// <returns>Team Details.</returns>
 public virtual async Task <TeamDetails> GetTeamDetailsAsync(ITurnContext turnContext, string teamId, CancellationToken cancellationToken)
 {
     return(await TeamsInfo.GetTeamDetailsAsync(turnContext, teamId, cancellationToken));
 }
示例#14
0
        // 1. Will be called when user triggers messaging extension which then calls CreateTaskModuleCommand
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            // Check if the bot has been installed in the team by getting the team rooster
            try
            {
                var teamsMembers = await TeamsInfo.GetMembersAsync(turnContext);
            }
            catch
            {
                // if not installed we will send out the card instructing the user to install the bot
                string jitCardPath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "jitCard.json");
                var    jitCard      = File.ReadAllText(jitCardPath, Encoding.UTF8);
                string jitCardJson  = jitCard;
                var    jitCardTeams = AdaptiveCard.FromJson(jitCardJson);
                return(await Task.FromResult(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = new Attachment
                            {
                                Content = jitCardTeams.Card,
                                ContentType = AdaptiveCard.ContentType,
                            },
                            Height = 300,
                            Width = 600,
                            Title = "Install bot",
                        },
                    },
                }));
            }


            var magicCode = string.Empty;
            var state     = (turnContext.Activity.Value as Newtonsoft.Json.Linq.JObject).Value <string>("state");

            if (!string.IsNullOrEmpty(state))
            {
                int parsed = 0;
                if (int.TryParse(state, out parsed))
                {
                    magicCode = parsed.ToString();
                }
            }

            var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.

                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);

                return(new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Sign in Please",
                                },
                            },
                        },
                    },
                });
            }
            var accessToken = tokenResponse.Token;

            if (accessToken != null || !string.IsNullOrEmpty(accessToken))
            {
                // Create Graph Client
                var client = new SimpleGraphClient(accessToken);
                // Get Group details
                var channel = turnContext.Activity.TeamsGetChannelId();
                if (channel != null)
                {
                    var    members           = new List <TeamsChannelAccount>();
                    string continuationToken = null;
                    do
                    {
                        var currentPage = await TeamsInfo.GetPagedMembersAsync(turnContext, 100, continuationToken, cancellationToken);

                        continuationToken = currentPage.ContinuationToken;
                        members           = members.Concat(currentPage.Members).ToList();
                    }while (continuationToken != null);
                    TeamDetails teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, turnContext.Activity.TeamsGetTeamInfo().Id, cancellationToken);

                    if (teamDetails != null)
                    {
                        var groupId = teamDetails.AadGroupId;
                        plannerGroupId = groupId;
                        //Get Plans
                        var currentGroupPlan = await client.GetCurrentPlan(groupId);

                        var favoritePlans = await client.GetFavoritePlans();

                        // Fill Adaptive Card data
                        var exampleData = new ExampleData();
                        exampleData.MultiSelect = "false";
                        if (currentGroupPlan.CurrentPage.Count == 0)
                        {
                            exampleData.Option1      = favoritePlans.CurrentPage[4].Title;
                            exampleData.Option1Value = favoritePlans.CurrentPage[4].Id;
                        }
                        else
                        {
                            exampleData.Option1      = currentGroupPlan.CurrentPage[0].Title;
                            exampleData.Option1Value = currentGroupPlan.CurrentPage[0].Id;
                        }
                        exampleData.Option2      = favoritePlans.CurrentPage[0].Title;
                        exampleData.Option3      = favoritePlans.CurrentPage[1].Title;
                        exampleData.Option4      = favoritePlans.CurrentPage[2].Title;
                        exampleData.Option2Value = favoritePlans.CurrentPage[0].Id;
                        exampleData.Option3Value = favoritePlans.CurrentPage[1].Id;
                        exampleData.Option4Value = favoritePlans.CurrentPage[2].Id;
                        // Create and return card
                        var adaptiveCardEditor = AdaptiveCardHelper.CreateAdaptiveCardEditor(exampleData);
                        //var adaptiveCardEditor = CreateAdaptiveCard();

                        return(await Task.FromResult(new MessagingExtensionActionResponse
                        {
                            Task = new TaskModuleContinueResponse
                            {
                                Value = new TaskModuleTaskInfo
                                {
                                    Card = new Microsoft.Bot.Schema.Attachment
                                    {
                                        Content = adaptiveCardEditor,
                                        ContentType = AdaptiveCard.ContentType,
                                    },
                                    Height = 600,
                                    Width = 600,
                                    Title = "Task creation",
                                },
                            },
                        }));
                    }
                }
                else
                {
                    // Return only favorite plans without current plan as in 1:1 or group chat
                    var favoritePlans = await client.GetFavoritePlans();

                    // Fill Adaptive Card data
                    var exampleData = new ExampleData();
                    exampleData.MultiSelect = "false";
                    exampleData.Option1     = favoritePlans.CurrentPage[0].Title;
                    exampleData.Option2     = favoritePlans.CurrentPage[1].Title;
                    exampleData.Option3     = favoritePlans.CurrentPage[2].Title;

                    exampleData.Option1Value = favoritePlans.CurrentPage[0].Id;
                    exampleData.Option3Value = favoritePlans.CurrentPage[1].Id;
                    exampleData.Option4Value = favoritePlans.CurrentPage[2].Id;

                    // Create and return card
                    var adaptiveCardEditor = AdaptiveCardHelper.CreateAdaptiveCardEditor(exampleData);
                    //var adaptiveCardEditor = CreateAdaptiveCard();

                    return(await Task.FromResult(new MessagingExtensionActionResponse
                    {
                        Task = new TaskModuleContinueResponse
                        {
                            Value = new TaskModuleTaskInfo
                            {
                                Card = new Microsoft.Bot.Schema.Attachment
                                {
                                    Content = adaptiveCardEditor,
                                    ContentType = AdaptiveCard.ContentType,
                                },
                                Height = 600,
                                Width = 600,
                                Title = "Task creation",
                            },
                        },
                    }));
                }
            }
            //Needs to be replaced with OAuth Prompt
            return(null);
        }
        /// <summary>
        /// Handle message extension action fetch task received by the bot.
        /// </summary>
        /// <param name="turnContext">Provides context for a turn of a bot.</param>
        /// <param name="action">Messaging extension action value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that returns messagingExtensionActionResponse.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            var activityState = ((JObject)activity.Value).GetValue("state")?.ToString();
            var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, this.connectionName, activityState, cancellationToken);

            if (tokenResponse == null)
            {
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, this.connectionName, cancellationToken);

                return(new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = MessagingExtensionAuthType,
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = Strings.SigninCardText,
                                },
                            },
                        },
                    },
                });
            }

            var teamInformation = activity.TeamsGetTeamInfo();

            if (teamInformation == null || string.IsNullOrEmpty(teamInformation.Id))
            {
                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = GroupActivityCard.GetTeamNotFoundErrorCard(),
                            Height = TaskModuleValidationHeight,
                            Width = TaskModuleValidationWidth,
                            Title = Strings.GroupActivityTitle,
                        },
                    },
                });
            }

            TeamDetails teamDetails;

            try
            {
                teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamInformation.Id, cancellationToken);
            }
            catch (Exception ex)
            {
                // if bot is not installed in team or not able to team roster, then show error response.
                this.logger.LogError("Bot is not part of team roster", ex);
                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo()
                        {
                            Card = GroupActivityCard.GetTeamNotFoundErrorCard(),
                            Height = TaskModuleHeight,
                            Width = TaskModuleHeight,
                        },
                    },
                });
            }

            if (teamDetails == null)
            {
                this.logger.LogInformation($"Team details obtained is null.");
                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = GroupActivityCard.GetErrorMessageCard(),
                            Height = TaskModuleValidationHeight,
                            Width = TaskModuleValidationWidth,
                            Title = Strings.GroupActivityTitle,
                        },
                    },
                });
            }

            var isTeamOwner = await this.teamUserHelper.VerifyIfUserIsTeamOwnerAsync(tokenResponse.Token, teamDetails.AadGroupId, activity.From.AadObjectId);

            if (isTeamOwner == null)
            {
                await turnContext.SendActivityAsync(Strings.CustomErrorMessage);

                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = GroupActivityCard.GetErrorMessageCard(),
                            Height = TaskModuleValidationHeight,
                            Width = TaskModuleValidationWidth,
                            Title = Strings.GroupActivityTitle,
                        },
                    },
                });
            }

            // If user is team member validation message is shown as only team owner can create a group activity.
            if (isTeamOwner == false)
            {
                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = GroupActivityCard.GetTeamOwnerErrorCard(),
                            Height = TaskModuleValidationHeight,
                            Width = TaskModuleValidationWidth,
                            Title = Strings.GroupActivityTitle,
                        },
                    },
                });
            }

            // Team owner can create group activity.
            return(new MessagingExtensionActionResponse
            {
                Task = new TaskModuleContinueResponse
                {
                    Value = new TaskModuleTaskInfo
                    {
                        Card = GroupActivityCard.GetCreateGroupActivityCard(),
                        Height = TaskModuleHeight,
                        Width = TaskModuleWidth,
                        Title = Strings.GroupActivityTitle,
                    },
                },
            });
        }
        /// <summary>
        /// Handle message extension submit action received by the bot.
        /// </summary>
        /// <param name="turnContext">Provides context for a turn of a bot.</param>
        /// <param name="action">Messaging extension action request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents messaging extension response.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;
            Dictionary <int, IList <TeamsChannelAccount> > membersGroupingWithChannel = null;

            try
            {
                var valuesFromTaskModule = JsonConvert.DeserializeObject <GroupDetail>(action.Data?.ToString());
                var teamInformation      = activity.TeamsGetTeamInfo();

                TokenResponse tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, this.connectionName, null, cancellationToken);
                string        token         = tokenResponse.Token;

                if (token == null || valuesFromTaskModule == null)
                {
                    this.logger.LogInformation($"Either token obtained is null. Token : {token} or values obtained from task module is null for {teamInformation.Id}");
                    await turnContext.SendActivityAsync(Strings.CustomErrorMessage);

                    return(new MessagingExtensionActionResponse());
                }

                // Activity local timestamp provides offset value which can be used to convert user input time with offset.
                valuesFromTaskModule.DueDate = new DateTimeOffset(
                    valuesFromTaskModule.DueDate.Year,
                    valuesFromTaskModule.DueDate.Month,
                    valuesFromTaskModule.DueDate.Day,
                    valuesFromTaskModule.DueTime.Hour,
                    valuesFromTaskModule.DueTime.Minute,
                    valuesFromTaskModule.DueTime.Second,
                    turnContext.Activity.LocalTimestamp.Value.Offset).ToUniversalTime();

                // Validate task module values entered by user to create group activity.
                if (!this.IsValidGroupActivityInputFields(valuesFromTaskModule))
                {
                    return(this.ShowValidationForCreateChannel(valuesFromTaskModule, isSplittingValid: true));
                }

                var teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, teamInformation.Id, cancellationToken);

                // Get all channel members and owners in a team.
                var teamMembers = await TeamsInfo.GetTeamMembersAsync(turnContext, teamInformation.Id, cancellationToken);

                if (teamMembers == null)
                {
                    this.logger.LogError($"List of channel members and owners in a team obtained is null for team id : {teamInformation.Id}");
                    return(new MessagingExtensionActionResponse());
                }

                // Get list of members to perform grouping excluding team owners of the team.
                var groupMembers = await this.teamUserHelper.GetGroupMembersAsync(token, teamDetails.AadGroupId, teamMembers);

                if (groupMembers.Count() <= 0 || groupMembers == null)
                {
                    await turnContext.SendActivityAsync(Strings.TeamMembersDoesNotExistsText);

                    this.logger.LogInformation($"Group members obtained to perform grouping is null for team id : {teamInformation.Id}.");
                    return(new MessagingExtensionActionResponse());
                }

                // Identify the team owner who initiated the group activity.
                var groupActivityCreator = teamMembers.Where(members => members.AadObjectId.Contains(activity.From.AadObjectId)).FirstOrDefault();

                // Group members based on splitting criteria entered by user.
                switch (valuesFromTaskModule.SplittingCriteria)
                {
                case Constants.SplitInGroupOfGivenMembers:
                    membersGroupingWithChannel = this.groupingHelper.SplitInGroupOfGivenMembers(groupMembers, groupActivityCreator, valuesFromTaskModule.ChannelOrMemberUnits);
                    break;

                case Constants.SplitInGivenNumberOfGroups:
                    int numberOfMembersInEachGroup = groupMembers.Count() / valuesFromTaskModule.ChannelOrMemberUnits;

                    // Validation to not allow for grouping if member in each group is 1.
                    if (groupMembers.Count() <= valuesFromTaskModule.ChannelOrMemberUnits)
                    {
                        return(this.ShowValidationForCreateChannel(valuesFromTaskModule, isSplittingValid: false));
                    }

                    membersGroupingWithChannel = this.groupingHelper.SplitInGivenNumberOfGroups(groupMembers, groupActivityCreator, valuesFromTaskModule.ChannelOrMemberUnits, numberOfMembersInEachGroup);
                    break;
                }

                if (membersGroupingWithChannel == null || membersGroupingWithChannel.Count <= 0)
                {
                    this.logger.LogError($"Error while grouping members to channel: {activity.Conversation.Id}");
                    return(new MessagingExtensionActionResponse());
                }

                string groupActivityId = Guid.NewGuid().ToString();
                string groupingMessage = await this.SendAndStoreGroupingMessageAsync(groupActivityId, teamDetails.Id, valuesFromTaskModule, membersGroupingWithChannel, groupActivityCreator, turnContext, cancellationToken);

                // If field auto create channel is yes then create channels and send grouping message else send only grouping message in channel.
                if (valuesFromTaskModule.AutoCreateChannel == Constants.AutoCreateChannelYes)
                {
                    await this.channelHelper.ValidateAndCreateChannelAsync(token, groupActivityId, teamInformation.Id, teamDetails.AadGroupId, groupingMessage, valuesFromTaskModule, membersGroupingWithChannel, groupActivityCreator, turnContext, cancellationToken);
                }

                // Logs Click through on activity created.
                this.telemetryClient.TrackEvent("Group activity created", new Dictionary <string, string>()
                {
                    { "Team", teamInformation.Id }, { "AADObjectId", activity.From.AadObjectId }
                });
                return(new MessagingExtensionActionResponse());
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error while submitting data from task module through messaging extension action.");
                return(null);
            }
        }
示例#17
0
        // 2. Will be called after OnTeamsMessagingExtensionFetchTaskAsync when user has entered all data in the Messaging Extension Adaptive Card
        private async Task <MessagingExtensionActionResponse> CreateTaskModuleCommand(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var msg     = action.MessagePayload.Body.Content;
            var data    = action.Data;
            var channel = turnContext.Activity.TeamsGetChannelId();
            var groupId = "";

            if (channel != null)
            {
                TeamDetails teamDetails = await TeamsInfo.GetTeamDetailsAsync(turnContext, turnContext.Activity.TeamsGetTeamInfo().Id, cancellationToken);

                groupId = teamDetails.AadGroupId;
            }
            var     subject   = ((JObject)action.Data)["Title"]?.ToString();
            var     dueDate   = ((JObject)action.Data)["DueDate"]?.ToString();
            var     startDate = ((JObject)action.Data)["StartDate"]?.ToString();
            var     type      = ((JObject)action.Data)["Type"]?.ToString();
            var     url       = turnContext.Activity.Value.ToString();
            JObject jsonUrl   = JObject.Parse(url);
            var     link      = jsonUrl["messagePayload"]["linkToMessage"];
            var     magicCode = string.Empty;
            var     state     = (turnContext.Activity.Value as Newtonsoft.Json.Linq.JObject).Value <string>("state");

            if (!string.IsNullOrEmpty(state))
            {
                int parsed = 0;
                if (int.TryParse(state, out parsed))
                {
                    magicCode = parsed.ToString();
                }
            }
            var tokenResponse = await(turnContext.Adapter as IUserTokenProvider).GetUserTokenAsync(turnContext, _connectionName, magicCode, cancellationToken: cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.
                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
                return(new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Bot Service OAuth",
                                },
                            },
                        },
                    },
                });
            }
            var accessToken = tokenResponse.Token;

            if (accessToken != null || !string.IsNullOrEmpty(accessToken))
            {
                var client = new SimpleGraphClient(accessToken);
                if (type == "todo")
                {
                    var body = new Beta.ItemBody
                    {
                        Content = msg + " - " + link
                    };
                    var taskResult = await client.CreateTaskAsync(subject, dueDate, startDate, body);

                    var todoUrl = "https://to-do.office.com/tasks/id/" + taskResult.Id + "/details";
                    List <ChannelAccount> participants = new List <ChannelAccount>();
                    participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                    var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                    var conversationParameters = new ConversationParameters()
                    {
                        ChannelData = new TeamsChannelData
                        {
                            Tenant = new TenantInfo
                            {
                                Id = tenantId,
                            }
                        },
                        Members = new List <ChannelAccount>()
                        {
                            participants[0]
                        }
                    };
                    var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                    string taskCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "todoCardTeams.json");
                    var    r            = File.ReadAllText(taskCardPath, Encoding.UTF8);
                    string taskCardJson = r;
                    taskCardJson = taskCardJson.Replace("replaceUrl", todoUrl ?? "", true, culture: CultureInfo.InvariantCulture);
                    taskCardJson = taskCardJson.Replace("ReplaceTitel", taskResult.Subject.ToString() ?? "", true, culture: CultureInfo.InvariantCulture);
                    var        card       = AdaptiveCard.FromJson(taskCardJson);
                    Attachment attachment = new Attachment()
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content     = card.Card
                    };
                    IMessageActivity cardMsg = MessageFactory.Attachment(attachment);
                    await connectorClient.Conversations.SendToConversationAsync(response.Id, (Activity)cardMsg, cancellationToken);
                }
                if (type == "planner")
                {
                    var username      = turnContext.Activity.From.AadObjectId;
                    var taskTitle     = ((JObject)action.Data)["Title"]?.ToString();
                    var taskStartDate = ((JObject)action.Data)["StartDate"]?.ToString();
                    var taskDueDate   = ((JObject)action.Data)["DueDate"]?.ToString();
                    var taskSPlanId   = ((JObject)action.Data)["Choices"]?.ToString();
                    var planResult    = await client.CreatePlannerTaskAsync(taskSPlanId, taskTitle, taskDueDate, taskStartDate, username);

                    if (!string.IsNullOrEmpty(groupId))
                    {
                        var taskUrl = "https://tasks.office.com/solviondemo.net/en-US/Home/Planner/#/plantaskboard?groupId=" + groupId + "&planId=" + planResult.PlanId + "&taskId=" + planResult.Id;
                        List <ChannelAccount> participants = new List <ChannelAccount>();
                        participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                        var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                        var conversationParameters = new ConversationParameters()
                        {
                            ChannelData = new TeamsChannelData
                            {
                                Tenant = new TenantInfo
                                {
                                    Id = tenantId,
                                }
                            },
                            Members = new List <ChannelAccount>()
                            {
                                participants[0]
                            }
                        };
                        var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                        string taskCardPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cards", "plannerCardTeams.json");
                        var    r            = File.ReadAllText(taskCardPath, Encoding.UTF8);
                        string taskCardJson = r;
                        taskCardJson = taskCardJson.Replace("replaceUrl", taskUrl ?? "", true, culture: CultureInfo.InvariantCulture);
                        taskCardJson = taskCardJson.Replace("ReplaceTitel", planResult.Title.ToString() ?? "", true, culture: CultureInfo.InvariantCulture);
                        var        card       = AdaptiveCard.FromJson(taskCardJson);
                        Attachment attachment = new Attachment()
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = card.Card
                        };
                        IMessageActivity cardMsg = MessageFactory.Attachment(attachment);
                        await connectorClient.Conversations.SendToConversationAsync(response.Id, (Activity)cardMsg, cancellationToken);
                    }
                    else
                    {
                        List <ChannelAccount> participants = new List <ChannelAccount>();
                        participants.Add(new ChannelAccount(turnContext.Activity.From.Id, turnContext.Activity.From.Name));
                        var connectorClient        = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret));
                        var conversationParameters = new ConversationParameters()
                        {
                            ChannelData = new TeamsChannelData
                            {
                                Tenant = new TenantInfo
                                {
                                    Id = tenantId,
                                }
                            },
                            Members = new List <ChannelAccount>()
                            {
                                participants[0]
                            }
                        };
                        var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

                        var personalMessageActivity = MessageFactory.Text($"I've created a new Planner task with the title **" + planResult.Title.ToString() + "** in the Plan you have chosen");
                        await connectorClient.Conversations.SendToConversationAsync(response.Id, personalMessageActivity);
                    }
                }
            }
            return(null);
        }