public async Task <DailyChallengeImage> GetRandomLocation() { Random rnd = new Random(); double latitude = rnd.Next(-70000, 70000); latitude = latitude / 1000; double longitude = rnd.Next(-180000, 180000); longitude = longitude / 1000; MapResponse placesResponse = await this.SearchPlaces(latitude, longitude); if (placesResponse.Status == "OVER_QUERY_LIMIT") { throw new Exception("Over Google query limit"); } int iterationCount = 0; int maxCount = 50; bool validResponse = false; while (iterationCount < maxCount && !validResponse) { foreach (var place in placesResponse.Places) { if (place.Photos != null && place.Photos.Count > 0) { validResponse = true; break; } } if (!validResponse) { rnd = new Random(); latitude = rnd.Next(-70000, 70000); latitude = latitude / 1000; longitude = rnd.Next(-180000, 180000); longitude = longitude / 1000; placesResponse = await this.SearchPlaces(latitude, longitude); } iterationCount++; } if (iterationCount > maxCount || placesResponse.Places.Count == 0) { throw new Exception("Sorry, couldn't find a suitable image. Try again shortly."); } DailyChallengeImage image = new DailyChallengeImage() { ImageRegion = "Google", ImageText = placesResponse.Places[0].Name, Longitutde = float.Parse(placesResponse.Places[0].Geo.Location.Longitude.ToString()), Latitude = float.Parse(placesResponse.Places[0].Geo.Location.Latitude.ToString()), Url = $"https://maps.googleapis.com/maps/api/place/photo?maxwidth=2000&photoreference={placesResponse.Places[0].Photos[0].PhotoReference}&key={AppSecret}" }; return(image); }
public void GetBingImageUrlTest() { BingImageService service = new BingImageService(); DailyChallengeImage image = service.GetBingImageUrl(1); Assert.IsTrue(!string.IsNullOrEmpty(image.ImageText) && !string.IsNullOrEmpty(image.ImageRegion)); }
public async Task <DailyChallengeImage> getDailyChallengeImage() { string rowKey = DateTime.Now.ToString("yyyyMMdd"); string partitionKey = typeof(DailyChallengeImage).ToString(); try { TableOperation retrieveOperation = TableOperation.Retrieve <DailyChallengeImage>(partitionKey, rowKey); TableResult result = await cloudTable.ExecuteAsync(retrieveOperation); DailyChallengeImage image = result.Result as DailyChallengeImage; if (image == null) { image = new DailyChallengeImage() { PartitionKey = partitionKey, RowKey = rowKey }; } return(image); } catch (Exception exp) { // TODO: add logging throw exp; } }
public async Task SaveDailyChallengeImage(DailyChallengeImage image) { image.PartitionKey = typeof(DailyChallengeImage).ToString(); image.RowKey = DateTime.Now.ToString("yyyyMMdd"); TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(image); // Execute the operation. TableResult result = await cloudTable.ExecuteAsync(insertOrMergeOperation); }
private async Task <Attachment> GetDailyChallengeImageAttachment() { DailyChallengeImage image = await tableService.getDailyChallengeImage(); var heroCard = new HeroCard { Title = "Today's Daily Challenge", Subtitle = image.ImageRegion, Images = new List <CardImage> { new CardImage(image.Url) } }; return(heroCard.ToAttachment()); }
public DailyChallengeImage GetBingImageUrl(string locationCode) { HttpClient client = new HttpClient(); HttpResponseMessage response = client.GetAsync("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=" + locationCode).Result; string responseText = response.Content.ReadAsStringAsync().Result; dynamic bingImageResponse = JObject.Parse(responseText); var cultInfo = System.Globalization.CultureInfo.GetCultureInfo(locationCode); DailyChallengeImage bingImage = new DailyChallengeImage() { Url = "https://www.bing.com" + bingImageResponse.images[0].url, ImageText = bingImageResponse.images[0].copyright, ImageRegion = cultInfo.DisplayName }; return(bingImage); }
private async Task CheckResults(WaterfallStepContext stepContext, CancellationToken cancellationToken, DailyChallenge dailyChallenge, DailyChallengeInfo info) { List <DailyChallengeEntry> todayEntries = dailyChallenge.entries; string currentWinningUser = ""; string currentWinningEntry = ""; double currentWinningDistance = double.MaxValue; foreach (var entry in todayEntries) { if (entry.distanceFrom < currentWinningDistance) { currentWinningUser = entry.userName; currentWinningEntry = entry.imageResponse; currentWinningDistance = entry.distanceFrom; } } try { DailyChallengeImage image = await tableService.getDailyChallengeImage(); dailyChallenge.distanceToEntry = currentWinningDistance; dailyChallenge.winnerName = currentWinningUser; dailyChallenge.winnerGuess = currentWinningEntry; dailyChallenge.resultSet = true; await tableService.SaveDailyChallenge(dailyChallenge); IMessageActivity reply = MessageFactory.Attachment(new List <Attachment>()); reply.Attachments.Add(AttachmentHelper.ResultCardAttachment(currentWinningUser.ToString(), image.Url, currentWinningEntry, currentWinningDistance.ToString("#.##"), dailyChallenge.extractedLocation, dailyChallenge.text)); await stepContext.Context.SendActivityAsync(reply); } catch (Exception exp) { Console.WriteLine("Error checking results: " + exp.Message); } return; }
private async Task <Attachment> GetBingImageChoiceAttachment(int imageIndex) { BingImageService imageService = new BingImageService(); DailyChallengeImage image = imageService.GetBingImageUrl(imageIndex); await tableService.SaveDailyChallengeImage(image); var heroCard = new HeroCard { Title = "Today's Daily Challenge", Subtitle = image.ImageRegion, Text = "Click to choose the image for today or try another image.", Images = new List <CardImage> { new CardImage(image.Url) }, Buttons = new List <CardAction> { new CardAction(ActionTypes.ImBack, "Choose image", value: "Choose image"), new CardAction(ActionTypes.ImBack, "Try another image", value: "Try another image"), new CardAction(ActionTypes.ImBack, "Switch to Google", value: "Switch to Google") } }; return(heroCard.ToAttachment()); }
private async Task UpdateDailyChallengeImage(DailyChallengeImage image) { await tableService.SaveDailyChallengeImage(image); return; }
private async Task <Attachment> GetGoogleImageChoiceAttachment() { GoogleMapService mapService = new GoogleMapService(Configuration["GoogleMapsAPI"]); HeroCard heroCard = null; try { DailyChallengeImage image = await mapService.GetRandomLocation(); await tableService.SaveDailyChallengeImage(image); heroCard = new HeroCard { Title = "Today's Daily Challenge", Subtitle = image.ImageRegion, Text = "Click to choose the image for today or try another image.", Images = new List <CardImage> { new CardImage(image.Url) }, Buttons = new List <CardAction> { new CardAction(ActionTypes.ImBack, "Choose image", value: "Choose image"), new CardAction(ActionTypes.ImBack, "Try another Google image", value: "Try another image"), new CardAction(ActionTypes.ImBack, "Switch to Bing", value: "Switch to Bing") } }; } catch (Exception exp) { if (exp.Message == "Sorry, couldn't find a suitable image. Try again shortly.") { heroCard = new HeroCard { Title = "Today's Daily Challenge", Subtitle = "Not found", Text = "After trying 50 different locations, Google couldn't find a suitable image.", Buttons = new List <CardAction> { new CardAction(ActionTypes.ImBack, "Try another Google image", value: "Try another image"), new CardAction(ActionTypes.ImBack, "Switch to Bing", value: "Switch to Bing") } }; } else if (exp.Message == "Over Google query limit") { heroCard = new HeroCard { Title = "Today's Daily Challenge", Subtitle = "Not found", Text = "The Google Maps Search Service is on a low level and has exceeeded it's usage. Please wait a few minutes and try again or switch to Bing.", Buttons = new List <CardAction> { new CardAction(ActionTypes.ImBack, "Try another Google image", value: "Try another image"), new CardAction(ActionTypes.ImBack, "Switch to Bing", value: "Switch to Bing") } }; } else { throw exp; } } return(heroCard.ToAttachment()); }
private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var command = stepContext.Result.ToString(); if (command.ToLower().Contains("choose image")) { int imageIndex = await GetImageIndex(stepContext); BingImageService imageService = new BingImageService(); DailyChallengeImage image = await tableService.getDailyChallengeImage(); BingMapService mapService = new BingMapService(Configuration["BingMapsAPI"]); Logger.LogInformation("Image Text: " + image.ImageText); DailyChallengeEntry challengeEntry = await mapService.GetLocationDetails(image.ImageText, Logger); if (challengeEntry == null) { Logger.LogError("Unable to retrieve details of image"); throw new Exception("Unable to retrieve details from Google"); } Logger.LogInformation("Image Response: " + challengeEntry.imageResponse); Logger.LogInformation("Longitude: " + challengeEntry.longitude); Logger.LogInformation("Latitude: " + challengeEntry.latitude); Logger.LogInformation("Latitude: " + challengeEntry.distanceFrom); var dailyChallenge = await tableService.GetDailyChallenge(); dailyChallenge.photoUrl = image.Url; dailyChallenge.text = image.ImageText; dailyChallenge.latitude = challengeEntry.latitude; dailyChallenge.longitude = challengeEntry.longitude; dailyChallenge.extractedLocation = challengeEntry.imageResponse; dailyChallenge.entries = new List <DailyChallengeEntry>(); dailyChallenge.publishedTime = DateTime.Now; dailyChallenge.currentStatus = DailyChallengeStatus.Guessing; await tableService.SaveDailyChallenge(dailyChallenge); IMessageActivity reply = MessageFactory.Attachment(new List <Attachment>()); reply.Attachments.Add(AttachmentHelper.ImageChosen(dailyChallenge.photoUrl)); var activity = (Activity)reply; await stepContext.Context.SendActivityAsync((Activity)reply); return(await stepContext.EndDialogAsync(cancellationToken)); //return await stepContext.ReplaceDialogAsync(nameof(ChallengeGuesserDialog), promptOptions, cancellationToken); } else if (command.ToLower().Contains("try another image")) { int imageIndex = await IncrementAndReturnImageIndex(); } else if (command.ToLower().Contains("switch to google")) { try { var reply = MessageFactory.Attachment(new List <Attachment>()); var attachment = await GetGoogleImageChoiceAttachment(); await UpdateImageSource(ImageSource.Google); reply.Attachments.Add(attachment); } catch (Exception exp) { Logger.LogError(exp, $"Could not set Google Image: {exp.Message} - {exp.StackTrace}", null); throw exp; } } else if (command.ToLower().Contains("switch to bing")) { var reply = MessageFactory.Attachment(new List <Attachment>()); int imageIndex = await GetImageIndex(stepContext); await UpdateImageSource(ImageSource.Bing); var attachment = await GetBingImageChoiceAttachment(imageIndex); // reply.AttachmentLayout = AttachmentLayoutTypes.Carousel; reply.Attachments.Add(attachment); } else { await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry, not sure about that"), cancellationToken); } return(await stepContext.BeginDialogAsync(nameof(MainDialog), null, cancellationToken)); }