public static Attachment GetComposeExtensionPreviewAttachment(WikiHelperSearchResult wikiResult, string selectedType)
        {
            string invokeVal = GetCardActionInvokeValue(wikiResult);
            var    tapAction = new CardAction("invoke", value: invokeVal);

            CardType   cardType;
            Attachment cardAttachment = null;

            var images = new List <CardImage>
            {
                new CardImage(wikiResult.imageUrl)
            };

            if (Enum.TryParse(selectedType, out cardType))
            {
                switch (cardType)
                {
                case CardType.hero:
                    cardAttachment = new HeroCard()
                    {
                        Title  = wikiResult.highlightedTitle,
                        Tap    = tapAction,
                        Images = images
                    }.ToAttachment();
                    break;

                case CardType.thumbnail:
                    cardAttachment = new ThumbnailCard()
                    {
                        Title  = wikiResult.highlightedTitle,
                        Tap    = tapAction,
                        Images = images
                    }.ToAttachment();
                    break;
                }
            }

            return(cardAttachment);
        }
        public static Attachment GetComposeExtensionMainResultAttachment(WikiHelperSearchResult wikiResult, string selectedType)
        {
            CardType   cardType;
            Attachment cardAttachment = null;

            var images = new List <CardImage>
            {
                new CardImage(wikiResult.imageUrl)
            };

            if (Enum.TryParse(selectedType, out cardType))
            {
                switch (cardType)
                {
                case CardType.hero:
                    cardAttachment = new HeroCard()
                    {
                        Title  = wikiResult.highlightedTitle,
                        Text   = wikiResult.text,
                        Images = images
                    }.ToAttachment();
                    break;

                case CardType.thumbnail:
                    cardAttachment = new ThumbnailCard()
                    {
                        Title  = wikiResult.highlightedTitle,
                        Text   = wikiResult.text,
                        Images = images
                    }.ToAttachment();
                    break;
                }
            }

            return(cardAttachment);
        }
 public static MessagingExtensionAttachment CreateComposeExtensionCardsAttachmentsSelectedItem(WikiHelperSearchResult wikiResult, string selectedType)
 {
     return(GetComposeExtensionMainResultAttachment(wikiResult, selectedType).ToMessagingExtensionAttachment());
 }
        private static string GetCardActionInvokeValue(WikiHelperSearchResult wikiResult)
        {
            InvokeValue invokeValue = new InvokeValue(wikiResult.imageUrl, wikiResult.text, wikiResult.highlightedTitle);

            return(JsonConvert.SerializeObject(invokeValue));
        }
        public async Task <MessagingExtensionResponse> GetComposeExtensionResponseAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery query)
        {
            MessagingExtensionResponse composeExtensionResponse = null;
            ImageResult imageResult = null;
            List <MessagingExtensionAttachment> composeExtensionAttachments = new List <MessagingExtensionAttachment>();
            var userData = await TemplateUtility.GetBotUserDataObject(_userState, turnContext, query);

            var  userPreferredCardType = userData.ComposeExtensionCardType;
            var  activity     = turnContext.Activity;
            bool isSettingUrl = false;

            if (string.Equals(activity.Name.ToLower(), Strings.ComposeExtensionQuerySettingUrl))
            {
                isSettingUrl = true;
            }

            if (query.CommandId == null || query.Parameters == null)
            {
                return(null);
            }
            var initialRunParameter = GetQueryParameterByName(query, Strings.manifestInitialRun);
            var queryParameter      = GetQueryParameterByName(query, Strings.manifestParameterName);

            if (userData == null)
            {
                composeExtensionResponse = new MessagingExtensionResponse();
                string message = Strings.ComposeExtensionNoUserData;
                composeExtensionResponse.ComposeExtension = GetMessageResponseResult(message);
                return(composeExtensionResponse);
            }

            /**
             * Below are the checks for various states that may occur
             * Note that the order of many of these blocks of code do matter
             */

            // situation where the incoming payload was received from the config popup

            if (!string.IsNullOrEmpty(query.State))
            {
                /**
                 * // need to keep going to return a response so do not return here
                 * // these variables are changed so if the word 'setting' kicked off the compose extension,
                 * // then the word setting will not retrigger the config experience
                 **/

                queryParameter      = "";
                initialRunParameter = "true";
            }

            // this is a sitaution where the user's preferences have not been set up yet
            if (userData.ComposeExtensionCardType == null)
            {
                composeExtensionResponse = GetConfig();
                return(composeExtensionResponse);
            }

            /**
             * // this is the situation where the user has entered the word 'reset' and wants
             * // to clear his/her settings
             * // resetKeyword for English is "reset"
             **/

            if (string.Equals(queryParameter.ToLower(), Strings.ComposeExtensionResetKeyword))
            {
                composeExtensionResponse = new MessagingExtensionResponse();
                composeExtensionResponse.ComposeExtension = GetMessageResponseResult(Strings.ComposeExtensionResetText);
                return(composeExtensionResponse);
            }

            /**
             * // this is the situation where the user has entered "setting" or "settings" in order
             * // to repromt the config experience
             * // keywords for English are "setting" and "settings"
             **/

            if (string.Equals(queryParameter.ToLower(), Strings.ComposeExtensionSettingKeyword) || string.Equals(queryParameter.ToLower(), Strings.ComposeExtensionSettingsKeyword) || (isSettingUrl))
            {
                composeExtensionResponse = GetConfig();
                return(composeExtensionResponse);
            }

            /**
             * // this is the situation where the user in on the initial run of the compose extension
             * // e.g. when the user first goes to the compose extension and the search bar is still blank
             * // in order to get the compose extension to run the initial run, the setting "initialRun": true
             * // must be set in the manifest for the compose extension
             **/

            if (initialRunParameter == "true")
            {
                // Signin Experience, please uncomment below code for Signin Experience
                // ComposeExtensionResponse = GetSignin(composeExtensionResponse);
                // Return composeExtensionResponse;

                composeExtensionResponse = new MessagingExtensionResponse();

                var historySearchWikiResult = userData.ComposeExtensionSelectedResults;
                if (historySearchWikiResult != null)
                {
                    foreach (var searchResult in historySearchWikiResult)
                    {
                        WikiHelperSearchResult wikiSearchResult = new WikiHelperSearchResult(searchResult.imageUrl, searchResult.highlightedTitle, searchResult.text);

                        // Create the card itself and the preview card based upon the information
                        var createdCardAttachment = TemplateUtility.CreateComposeExtensionCardsAttachments(wikiSearchResult, userPreferredCardType);
                        composeExtensionAttachments.Add(createdCardAttachment);
                    }

                    composeExtensionResponse = GetComposeExtensionQueryResult(composeExtensionAttachments);
                }
                else
                {
                    composeExtensionResponse.ComposeExtension = GetMessageResponseResult(Strings.ComposeExtensionInitialRunText);
                }
                return(composeExtensionResponse);
            }

            /**
             * Below here is simply the logic to call the Wikipedia API and create the response for
             * a query; the general flow is to call the Wikipedia API for the query and then call the
             * Wikipedia API for each entry for the query to see if that entry has an image; in order
             * to get the asynchronous sections handled, an array of Promises for cards is used; each
             * Promise is resolved when it is discovered if an image exists for that entry; once all
             * of the Promises are resolved, the response is sent back to Teams
             */

            WikiResult wikiResult = await SearchWiki(queryParameter, query);

            // enumerate search results and build Promises for cards for response
            foreach (var searchResult in wikiResult.query.search)
            {
                //Get the Image result on the basis of Image Title one by one
                imageResult = await SearchWikiImage(searchResult);

                //Get the Image Url from imageResult
                string imageUrl = GetImageURL(imageResult);

                string cardText = searchResult.snippet + " ...";

                WikiHelperSearchResult wikiSearchResult = new WikiHelperSearchResult(imageUrl, searchResult.title, cardText);

                // Create the card itself and the preview card based upon the information
                var createdCardAttachment = TemplateUtility.CreateComposeExtensionCardsAttachments(wikiSearchResult, userPreferredCardType);
                composeExtensionAttachments.Add(createdCardAttachment);
            }

            composeExtensionResponse = GetComposeExtensionQueryResult(composeExtensionAttachments);

            return(composeExtensionResponse);
        }
        /// <summary>
        /// Handle the callback received when the user selects an item from the results list
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        public async Task <MessagingExtensionResponse> HandleComposeExtensionSelectedItem(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery query)
        {
            // Keep a history of recently-selected items in bot user data. The history will be returned in response to the initialRun query
            var userData = await TemplateUtility.GetBotUserDataObject(_userState, turnContext, query);

            //Get the Max number of History items from config file
            int maxComposeExtensionHistoryCount = Convert.ToInt32(ConfigurationManager.AppSettings[MaxComposeExtensionHistoryCountKey]);

            WikiHelperSearchResult selectedItem = JsonConvert.DeserializeObject <WikiHelperSearchResult>(turnContext.Activity.Value.ToString());

            var historySearchWikiResult = userData.ComposeExtensionSelectedResults;

            //Removing other occurrences of the current selectedItem so there are not duplicates in the most recently used list
            if (historySearchWikiResult != null && historySearchWikiResult.Count > 0)
            {
                int index = 0;
                while (index < historySearchWikiResult.Count)
                {
                    if (string.Equals(historySearchWikiResult[index].highlightedTitle.ToLower(), selectedItem.highlightedTitle.ToLower()))
                    {
                        historySearchWikiResult.RemoveAt(index);
                    }
                    else
                    {
                        index++;
                    }
                }
            }
            else
            {
                historySearchWikiResult = new List <WikiHelperSearchResult>();
            }

            //Add new item in list
            historySearchWikiResult.Insert(0, selectedItem);

            //Restrict the transaction History with Max Items.
            if (historySearchWikiResult.Count > maxComposeExtensionHistoryCount)
            {
                historySearchWikiResult = historySearchWikiResult.GetRange(0, maxComposeExtensionHistoryCount);
            }

            //Save the history Items in user Data
            await TemplateUtility.SaveBotUserDataObject(_userState, turnContext, historySearchWikiResult);

            MessagingExtensionResponse          composeExtensionResponse   = new MessagingExtensionResponse();
            List <MessagingExtensionAttachment> composeExtensionAttachment = new List <MessagingExtensionAttachment>();

            if (selectedItem != null)
            {
                // create the card itself and the preview card based upon the information
                // check user preference for which type of card to create
                var userPreferredCardType = userData.ComposeExtensionCardType;
                var createdCardAttachment = TemplateUtility.CreateComposeExtensionCardsAttachmentsSelectedItem(selectedItem, userPreferredCardType);
                composeExtensionAttachment.Add(createdCardAttachment);

                composeExtensionResponse = GetComposeExtensionQueryResult(composeExtensionAttachment);
            }
            else
            {
                composeExtensionResponse.ComposeExtension = GetMessageResponseResult(Strings.ComposeExtensionInitialRunText);
            }

            return(composeExtensionResponse);
        }
예제 #7
0
 public static ComposeExtensionAttachment CreateComposeExtensionCardsAttachments(WikiHelperSearchResult wikiResult, string selectedType)
 {
     return(GetComposeExtensionMainResultAttachment(wikiResult, selectedType).ToComposeExtensionAttachment(GetComposeExtensionPreviewAttachment(wikiResult, selectedType)));
 }