//DelegateCommand _ShowBusyCommand;
        //public DelegateCommand ShowBusyCommand
        //    => _ShowBusyCommand ?? (_ShowBusyCommand = new DelegateCommand(async () =>
        //    {
        //        Views.Busy.SetBusy(true, _BusyText);
        //        await Task.Delay(5000);
        //        Views.Busy.SetBusy(false);
        //    }, () => !string.IsNullOrEmpty(BusyText)));

        public async Task GotoDetailsPage()
        {
            Views.Busy.SetBusy(true, "Getting your score...");
            UnconsciousBiasResult result = null;
            var graphClient = await AuthenticationHelper.GetAuthenticatedClientAsync();

            if (graphClient != null)
            {
                var emails = await graphClient.Me
                             .Messages
                             .Request()
                             .Search($"\"to:{Value}\"")
                             .Select("UniqueBody")
                             .GetAsync();

                StringBuilder sb = new StringBuilder();
                sb.Append("{\"documents\":[");
                int i = 1;
                foreach (var email in emails)
                {
                    Debug.WriteLine(email.UniqueBody);

                    // This is super-hacky processing out the HTML tags from the email.
                    // TODO: replace this with a proper library that will do this better.
                    string body = email.UniqueBody.Content;
                    string bodyWithoutHTMLtags = WebUtility.HtmlDecode(Regex.Replace(body, "<[^>]*(>|$)", string.Empty));
                    string step2 = Regex.Replace(bodyWithoutHTMLtags, @"[\s\r\n]+", " ");
                    sb.Append("{\"id\":\"" + i + "\",\"text\":\"" + step2 + "\"},");
                    i++;
                }

                // Remove the trailing comma to get well-formatted JSON
                string tempString = sb.ToString();
                if (tempString.LastIndexOf(",") == tempString.Length - 1)
                {
                    sb.Remove(tempString.Length - 1, 1);
                }

                // Close JSON message
                sb.Append("]}");

                List <double> sentimentScores = await TextAnalyticsHelper.GetSentiment(sb.ToString());

                // Calculate average sentiment score
                double scoreSum   = 0.0;
                int    scoreCount = 0;
                foreach (double sentimentScore in sentimentScores)
                {
                    scoreSum += sentimentScore;
                    scoreCount++;
                }
                double averageSentimentScore = scoreSum / scoreCount;
                int    sentimentPercentage   = Convert.ToInt32(averageSentimentScore * 100);

                result = new UnconsciousBiasResult()
                {
                    Positivity      = sentimentPercentage,
                    KeyWords        = "TODO",
                    Topics          = "TODO",
                    PositivityGraph = sentimentScores,
                    Person          = Value
                };
            }

            // can pass value to other screen and do fancy display
            NavigationService.Navigate(typeof(Views.DetailPage), result);

            await Task.CompletedTask;
        }
Ejemplo n.º 2
0
        private async Task <DialogTurnResult> CheckTodaysEntry(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await PopulateStateObjects(stepContext);

            _graphHelper.Authenticate();

            var section      = stepContext.Values["Section"] as OnenoteSection;
            var contextId    = _discussionState.SignedInUserId;
            var currentPages = await _graphHelper.GetNotebookPagesInSection(section);

            DateTime entryDate = DateTime.Today;

            List <JournalPageMetadata> journalPages = new List <JournalPageMetadata>();
            int currentDay  = entryDate.Day;
            int daysInMonth = DateTime.DaysInMonth(entryDate.Year, entryDate.Month);
            int year        = entryDate.Year;
            int month       = entryDate.Month;
            List <JournalEntry> userEntries = DBHelper.GetJournalEntries(contextId,
                                                                         new DateTime(year, month, 1),
                                                                         new DateTime(year, month, daysInMonth));

            var invalidEntries = new KeyValuePair <string, List <string> >(
                contextId, new List <string>());

            // Remove pages that do not exist in the current pages collection
            for (int i = userEntries.Count - 1; i >= 0; i--)
            {
                var expectedPage = userEntries[i];
                if (!currentPages.Exists(ce => ce.Id == expectedPage.Id))
                {
                    invalidEntries.Value.Add(expectedPage.Id);
                    userEntries.Remove(expectedPage);
                }
            }
            if (invalidEntries.Value.Count > 0)
            {
                DBHelper.RemoveInvalidJournalEntries(invalidEntries);
            }

            var sentimentNeeded = userEntries.Where(j => {
                var cp = currentPages.First(p => p.Id == j.Id);
                return(
                    (j.Sentiment == null) ||
                    ((j.Sentiment != null) &&
                     (cp.LastModifiedDateTime > j.LastModified)));
            }).ToList();

            if (sentimentNeeded.Count > 0)
            {
                var sentimentDocuments = new Dictionary <String, TextDocumentInput[]>();
                foreach (var item in sentimentNeeded)
                {
                    var prompt = "Checking out your" +
                                 (item.Sentiment != null ? " updated" : "") +
                                 $" entry for {item.EntryDate.ToLongDateString()}";
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));

                    string content = await _graphHelper.GetNotebookPageContent(item.Id);

                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(content);
                    var body      = doc.DocumentNode.SelectSingleNode("//body");
                    var divHeader = doc.DocumentNode.SelectSingleNode("//div[@data-id='_default']");

                    var paragraphs     = new List <String>();
                    var paragraphNodes = divHeader.SelectNodes(".//p");
                    if (paragraphNodes?.Count > 0)
                    {
                        paragraphs.AddRange(paragraphNodes.Select(p => p.InnerText).ToArray());
                    }

                    var remainingHtml = body.InnerHtml.Replace(divHeader.OuterHtml, "");
                    var remainingDoc  = new HtmlDocument();
                    remainingDoc.LoadHtml(remainingHtml);

                    paragraphNodes = remainingDoc.DocumentNode.SelectNodes("//p");
                    if (paragraphNodes?.Count > 0)
                    {
                        paragraphs.AddRange(paragraphNodes.Select(p => p.InnerText).ToArray());
                    }

                    if (paragraphs.Count > 0)
                    {
                        var combinedText = System.Web.HttpUtility.HtmlDecode(String.Join("\n", paragraphs));
                        AddInputDocument(sentimentDocuments, item.Id, combinedText);
                        prompt = "That's new.. I'll have to consider what you wrote.";
                    }
                    else
                    {
                        prompt = "Nothing new for me to check out here!";
                    }
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));
                }

                if (sentimentDocuments.Count > 0)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Assessing what you wrote..."));
                }

                var sentimentResults = TextAnalyticsHelper.GetSentiment(sentimentDocuments);
                foreach (var entryKey in sentimentResults.Keys)
                {
                    var assessedPage = currentPages.First(e => e.Id == entryKey);
                    var lastModified = assessedPage.LastModifiedDateTime;
                    var ds           = sentimentResults[entryKey];
                    DBHelper.SaveJournalEntryAssessment(new JournalEntryAssessment
                    {
                        Id           = entryKey,
                        Sentiment    = ds,
                        LastModified = lastModified?.UtcDateTime
                    });

                    var prompt = $"Your entry on {assessedPage.Title} was {ds.Sentiment}";
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(prompt));
                }
            }

            var         monthMode   = false;
            var         createdPage = false;
            OnenotePage currentPage = null;
            var         pageId      = String.Empty;

            //Month mode
            if (monthMode)
            {
                for (int i = currentDay; i <= daysInMonth; i++)
                {
                    DateTime current = new DateTime(year, month, i);
                    if (!userEntries.Exists(e => e.EntryDate == current))
                    {
                        journalPages.Add(new JournalPageMetadata(current));
                    }
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                "Looking for today's journal entry"));

                var existingPage = userEntries.FirstOrDefault(e => e.EntryDate == entryDate);
                if (existingPage == null)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Hmmm... didn't find today's entry. Don't worry I'll create one for you."));

                    journalPages.Add(new JournalPageMetadata(entryDate));
                }
                else
                {
                    pageId = existingPage.Id;
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                    "Found it!"));
                }
            }

            if (String.IsNullOrEmpty(pageId))
            {
                var weeks        = journalPages.GroupBy(p => p.Week).ToList();
                var pageTemplate = ResourceHelper
                                   .ReadManifestData <JournalingDialog>("JournalPageTemplate.htm");
                var headerPageTemplate = ResourceHelper
                                         .ReadManifestData <JournalingDialog>("JournalHeaderTemplate.htm");

                foreach (var grp in weeks)
                {
                    var headerPageTitle = $"Week {grp.Key}";
                    var headerEntryDate = entryDate.ToString("yyyy-MM-ddTHH:mm:ss.0000000");
                    Console.Write($" {headerPageTitle} ");
                    var headerPage = currentPages.FirstOrDefault(p => p.Title == headerPageTitle);

                    if (headerPage == null)
                    {
                        var headerHtml   = String.Format(headerPageTemplate, headerPageTitle, headerEntryDate);
                        var headerPageId = await _graphHelper.CreateNotebookPage(section.Id, headerHtml);

                        Console.WriteLine(headerPageId);
                    }
                    else
                    {
                        Console.WriteLine(headerPage.Id);
                    }

                    foreach (var item in grp)
                    {
                        var jp = DBHelper.GetJournalPrompt();

                        var pageTitle = $"{item.DayOfWeek} the {item.Day.AsOrdinal()}";
                        Console.Write($"\t{pageTitle} ");
                        var newEntryDate = item.EntryDate.ToString("yyyy-MM-ddTHH:mm:ss.0000000");

                        var prompt       = jp.Prompt;
                        var details      = jp.Details;
                        var promptSource = jp.Source;

                        var html = String.Format(pageTemplate, pageTitle, newEntryDate,
                                                 prompt, details, promptSource,
                                                 entryDate.Ticks, jp.SourceIndex, jp.PromptIndex);

                        currentPage = await _graphHelper.CreateNotebookPage(section.Id, html);

                        pageId      = currentPage.Id;
                        createdPage = true;
                        var je = new JournalEntry
                        {
                            UserContextId  = contextId,
                            Id             = pageId,
                            PromptSourceId = jp.SourceIndex,
                            PromptIndexId  = jp.PromptIndex,
                            EntryDate      = item.EntryDate
                        };
                        DBHelper.CreateJournalEntry(je);
                        await _graphHelper.UpdateNotebookPageLevel(pageId, 1);

                        await stepContext.Context.SendActivityAsync(MessageFactory.Text(
                                                                        "All done setting up today's entry for you!. Ping me when you want me to take a look."));

                        Console.WriteLine($"{pageId}");
                    }
                }
            }

            if ((currentPage == null) && !String.IsNullOrEmpty(pageId))
            {
                currentPage = await _graphHelper.GetNotebookPage(pageId);
            }
            AddUpdateStepContextValue(stepContext, "CurrentPage", currentPage);
            return(await stepContext.NextAsync(null, cancellationToken));
        }