Example #1
0
        public object NearByPlaces(RequestNearByPlaces req)
        {
            ValidationResponse<List<Place>> nearPlacesResp = new ValidationResponse<List<Place>>();
            if (string.IsNullOrEmpty(req.Place))
            {
                nearPlacesResp.Errors.Add("place name", "place name can not be empty");
                return Json(nearPlacesResp);
            }
            if (req.Distance < 0 || req.Distance > 10000)
            {
                nearPlacesResp.Errors.Add("distance limit", "distanse can be only between 0.1 and 10 km");
                return Json(nearPlacesResp);
            }

            try
            {
                using (GooglePlacesClient placesClient = new GooglePlacesClient())
                {
                    ValidationResponse<List<Place>> placesResp = placesClient.GetPlacesByQuery(new ReqQueryPlaces()
                    {
                        query = req.Place
                    });
                    if (!placesResp.Obj.IsNullOrEmpty())
                    {
                        Place pl = placesResp.Obj.FirstOrDefault();
                        nearPlacesResp = placesClient.GetNearByPlaces(new ReqNearByPlaces()
                        {
                            location = pl.geometry.location.lat + "," + pl.geometry.location.lng,
                            radius = req.Distance, // req.Rankby == RankBy.distance ? new Nullable<int>() : req.Distance,
                            keyword = req.Keywords
                            //rankby = req.Rankby.ToString()
                        });
                        if (nearPlacesResp.IsValid && !nearPlacesResp.Obj.IsNullOrEmpty())
                        {
                            return Json(new { IsValid = true, NearByPlaces = nearPlacesResp.Obj, CenterPlace = pl });
                        }
                    }
                    else
                    {
                        return Json(placesResp);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Place controller NearByPlaces error", "", ex, Level.Error);
                nearPlacesResp.Errors.Add("Unexpected error", "Unexpected error " + ex.Message);
            }
            return Json(nearPlacesResp);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("=== Google Places API Client ===\n");

            Console.WriteLine("API key : ");
            string apiKey = Console.ReadLine();

            Console.WriteLine("Search spot latitude : ");
            string latitude = Console.ReadLine();

            Console.WriteLine("Search spot longitude : ");
            string longitude = Console.ReadLine();

            Console.WriteLine("Search radius (meter) : ");
            string radius = Console.ReadLine();

            Console.WriteLine("Search type : ");
            string type = Console.ReadLine();

            Console.WriteLine("Name filter (optional) : ");
            string name = Console.ReadLine();

            Console.WriteLine("Search language (optional) : ");
            string language = Console.ReadLine();

            Console.WriteLine("Result file name : ");
            string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + Console.ReadLine() + ".xlsx";

            if (File.Exists(filepath))
            {
                Console.WriteLine("File exists already, change file name");
                throw new Exception("File exists already, change file name");
            }

            Console.WriteLine("\n=== ATTENTION : The API returns 20 results per call, Google allows only 45 calls per day===");
            Console.WriteLine("API calls number : ");
            int nb = int.Parse(Console.ReadLine());

            if (nb > 45)
            {
                Console.WriteLine("More than 45 calls required.");
                throw new Exception("More than 45 calls required.");
            }

            var places = new List <PlaceDetail>();

            var client = new GooglePlacesClient(apiKey, latitude, longitude, radius, type, name, language);

            Task.Run(async() =>
            {
                string token = null;
                while (nb > 0)
                {
                    try
                    {
                        var temp = await client.GetPlaceDetailList(token);
                        token    = temp.Key;
                        places.AddRange(temp.Value);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    nb--;
                }
            }).Wait();

            Application excel = new Application
            {
                DisplayAlerts = false
            };

            excel.Workbooks.Add();
            Worksheet worksheet = (Worksheet)excel.ActiveSheet;

            worksheet.Cells[1, "A"] = "Name";
            worksheet.Cells[1, "B"] = "Address";
            worksheet.Cells[1, "C"] = "Url";
            worksheet.Cells[1, "D"] = "Telephone";
            worksheet.Cells[1, "E"] = "Website";
            worksheet.Cells[1, "F"] = "Rating";
            worksheet.Cells[1, "G"] = "Location";
            worksheet.Cells[1, "H"] = "Types";

            Console.WriteLine("Copying the contents to Excel");
            int rowIndex = 3;

            foreach (var place in places)
            {
                worksheet.Cells[rowIndex, "A"] = place.Name;
                worksheet.Cells[rowIndex, "B"] = place.Vicinity;
                worksheet.Cells[rowIndex, "C"] = place.Url;
                worksheet.Cells[rowIndex, "D"] = place.International_phone_number;
                worksheet.Cells[rowIndex, "E"] = place.Website;
                worksheet.Cells[rowIndex, "F"] = place.Rating;
                worksheet.Cells[rowIndex, "G"] = place.Geometry.Location.Lat + "," + place.Geometry.Location.Lng;
                worksheet.Cells[rowIndex, "H"] = string.Join(",", place.Types);
                rowIndex++;
                //Console.Write("List Title: {0}", list.Title);
                //Console.WriteLine("\t"+"Item Count:"+list.ItemCount);
            }

            worksheet.Cells[rowIndex + 2, "A"] = "Web Request : " + client.Request;

            worksheet.SaveAs(filepath);
            Console.WriteLine("Export Completed : " + filepath);
            Console.ReadLine();
            excel.Quit();
            GC.Collect();
        }
        public static ValidationResponse<PlaceSummary> PrepareSummary(string placeIDToSummarize, string mainPlaceNearByName, string lang = "en")
        {
            ValidationResponse<PlaceSummary> response = new ValidationResponse<PlaceSummary>();

            if (string.IsNullOrEmpty(placeIDToSummarize))
            {
                throw new ArgumentException("placeIDToSummarize");
            }
            PlaceSummary summary;
            string cacheKey = "Summary-" + placeIDToSummarize + "-" + lang;
            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                summary = HttpContext.Current.Cache[cacheKey] as PlaceSummary;
                if (summary != null)
                {
                    response.Obj = summary;
                    return response;
                }
            }
            summary = new PlaceSummary(placeIDToSummarize);

            // step 0 - gt place details from places api.
            using (GooglePlacesClient placesClient = new GooglePlacesClient())
            {
                var placeRes = placesClient.GetPlacesDetails(new ReqPlaceDetails()
                {
                    placeid = summary.PlaceIDToSummarize,
                    language = lang
                });
                if (placeRes.Obj != null)
                {
                    summary.Place = placeRes.Obj;
                }
                else
                {
                    foreach (var error in placeRes.Errors)
                    {
                        response.Errors.Add(error.Key, error.Value);
                    }
                }
            }
            if (summary.Place != null)
            {
                // step 2 - Create summary
                summary.MainSummaryText = summary.Place.name;
                summary.MainSummarySources = new List<string>();

                using (AylienClient summClient = new AylienClient())
                {
                    ReqSummarise summReq = new ReqSummarise();
                    summReq.sentences_number = 6;
                    summReq.language = "auto";
                    List<string> summarizedArticles = new List<string>();

                    string SourcesToSummarizeNumberStr = System.Configuration.ConfigurationManager.AppSettings["SourcesToSummarizeNumber"];
                    short SourcesToSummarizeNumber;
                    Int16.TryParse(SourcesToSummarizeNumberStr, out SourcesToSummarizeNumber);
                    if (SourcesToSummarizeNumber == 0)
                    {
                        SourcesToSummarizeNumber = 3;
                    }

                    // Try to retrieve summary from place website
                    if (!string.IsNullOrEmpty(summary.Place.website))
                    {
                        summReq.url = summary.Place.website;
                        var summResp = summClient.Summarise(summReq);
                        if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0)
                        {
                            summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences));
                            summary.MainSummarySources.Add(summary.Place.website);
                        }
                    }

                    // Try to retrieve summary from google search results

                    // Google search
                    List<Result> googleSearchResults = null;
                    using (GoogleSearchClient clWebPages = new GoogleSearchClient())
                    {
                        ReqGoogleSearch req = new ReqGoogleSearch();
                        req.q = summary.Place.name + ", " + mainPlaceNearByName;
                        req.hl = lang;
                        req.lr = "lang_" + lang;
                        var googleSearchResultsResp = clWebPages.GetSearchResults(req);
                        if (googleSearchResultsResp.Obj != null && googleSearchResultsResp.Obj.Items != null && googleSearchResultsResp.Obj.Items.Count > 0)
                        {
                            googleSearchResults = googleSearchResultsResp.Obj.Items.ToList();
                        }
                    }

                    // Summaries from search results
                    if (googleSearchResults != null && googleSearchResults.Count > 0)
                    {
                        int maxResultsToSearchIn = 4;
                        for (int i = 0; i < googleSearchResults.Count
                            && i < maxResultsToSearchIn
                            && summarizedArticles.Count < SourcesToSummarizeNumber
                            && !summary.MainSummarySources.Contains(googleSearchResults[i].Link)
                            ; i++)
                        {
                            summReq.url = googleSearchResults[i].Link;
                            var summResp = summClient.Summarise(summReq);
                            if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0)
                            {
                                summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences));
                                summary.MainSummarySources.Add(googleSearchResults[i].Link);
                            }
                        }
                    }

                    // Summarise all summaries to one big summary.
                    if (summarizedArticles.Count > 0)
                    {
                        ReqSummarise summFuncReq = new ReqSummarise();
                        summFuncReq.title = summary.Place.name;
                        summFuncReq.text = string.Join("\n\r\\s", summarizedArticles.OrderByDescending(s => s.Length)); // Combine all summarized articles.
                        summFuncReq.sentences_number = 5;
                        var summFuncResp = summClient.Summarise(summFuncReq);
                        if (summFuncResp.Obj != null && summFuncResp.Obj.sentences != null && summFuncResp.Obj.sentences.Count > 0)
                        {
                            summary.MainSummaryText = string.Join(" ", summFuncResp.Obj.sentences);
                        }
                        else
                        {
                            // fallback just print combined text.
                            summary.MainSummaryText = summFuncReq.text;
                        }
                    }

                }

                // step 3 - Retrieve images
                using (GoogleSearchClient clImages = new GoogleSearchClient())
                {
                    ReqGoogleSearch req = new ReqGoogleSearch();
                    req.q = summary.Place.name + ", " + mainPlaceNearByName;
                    req.searchType = PlacesIR.GoogleSearch.ReqGoogleSearch.SearchTypeEnum.image;
                    req.hl = lang;
                    var imgResp = clImages.GetSearchResults(req);
                    if (imgResp.Obj != null && imgResp.Obj.Items != null)
                    {
                        foreach (var item in imgResp.Obj.Items)
                        {
                            Image img = new Image();
                            img.title = item.Title;
                            img.url = item.Link;
                            img.thumb_url = item.Image.ThumbnailLink;
                            summary.Images.Add(img);
                        }
                    }
                }

                // step 4 - Retrieve videos
                using (YouTubeClient YouTubeClient = new YouTubeClient())
                {
                    ReqSearch req = new ReqSearch();
                    req.q = summary.Place.name + ", " + mainPlaceNearByName;
                    req.relevanceLanguage = lang;
                    var youResp = YouTubeClient.GetSearchResults(req);
                    if (youResp.Obj != null && youResp.Obj.items != null)
                    {
                        summary.Videos = youResp.Obj.items;
                    }
                }

                // step 5 - get prices if available.
                // TODO Retrieve prices if available

                HttpRuntime.Cache.Insert(cacheKey, summary, null, DateTime.Now.AddHours(4), TimeSpan.Zero);
            }

            response.Obj = summary;
            return response;
        }