public static bool SearchFlights(APIAirlineSearch filter)
        {
            bool result = false;

            try
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***  START British Airways  ***");
                MakeRequest(filter);
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***  END British Airways  ***");
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filter.ToSpecialString());
            }
            return(result);
        }
        static bool MakeRequest(APIAirlineSearch filters)
        {
            bool result = false;

            try
            {
                int AttemptsNumber     = 0;
                int MaxRequestAttempts = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;

                var context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                TripsService _tripService           = new TripsService(context);
                int          MaxDaysNumberForSearch = 30;

                DateTime originalFromDateMin = filters.FromDateMin;
                DateTime originalToDateMax   = (filters.ToDateMax ?? filters.FromDateMax);

                DateTime FromDateMin = originalFromDateMin;
                DateTime ToDateMax   = originalToDateMax;

                if ((originalToDateMax - originalFromDateMin).TotalDays > MaxDaysNumberForSearch)
                {
                    ToDateMax = FromDateMin.AddDays(MaxDaysNumberForSearch);
                }

                int SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.BritishAirways);

                List <TripItem> Trips = new List <TripItem>();

                while (ToDateMax < originalToDateMax)
                {
                    AttemptsNumber = 1;
                    result         = false;
                    while (!result && AttemptsNumber <= MaxRequestAttempts)
                    {
                        AttemptsNumber++;
                    }
                }
                _tripService.InsertTrips(Trips);
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
            }
            return(result);
        }
        // Limits : 5/ second, 5000/day
        // https://developer.airfranceklm.com/docs/read/opendata/flightoffer/POST_lowestfareoffers_v3

        public static int SearchFlights(APIAirlineSearch filter, int Provider, string Key)
        {
            int RequestsNumbers = 0;

            try
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***  START " + Providers.ToString(Provider) + " ***");
                if (Provider == Providers.KLM)
                {
                    RequestsNumbers = MakeRequest(filter, AIRFranceKLMTravelHost.KL, Key);
                }
                else if (Provider == Providers.AirFrance)
                {
                    RequestsNumbers = MakeRequest(filter, AIRFranceKLMTravelHost.AF, Key);
                }
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ***  END " + Providers.ToString(Provider) + " ***");
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filter.ToSpecialString() + " and Provider = " + Provider + " and Key = " + Key);
            }
            return(RequestsNumbers);
        }
Esempio n. 4
0
        static async Task MakeRequest(APIAirlineSearch filters)
        {
            int             MaxRequestAttempts   = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;
            int             AttemptsNumber       = 1;
            bool            IsSuccessfullAttempt = false;
            List <TripItem> Trips = new List <TripItem>();

            try
            {
                DateTime originalFromDateMin = filters.FromDateMin;
                DateTime originalToDateMax   = (filters.ToDateMax ?? filters.FromDateMax);

                DateTime FromDateMin = originalFromDateMin;
                DateTime ToDateMax   = originalToDateMax;

                if ((originalToDateMax - originalFromDateMin).TotalDays > FlightsEngine.Models.Constants.Constants.APIMaxDaysNumberForSearch)
                {
                    ToDateMax = FromDateMin.AddDays(FlightsEngine.Models.Constants.Constants.APIMaxDaysNumberForSearch);
                }

                var context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                int SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.Kiwi);
                for (int i = 0; i <= filters.MaxStopsNumber; i++)
                {
                    while (ToDateMax <= originalToDateMax)
                    {
                        AttemptsNumber       = 1;
                        IsSuccessfullAttempt = false;
                        while (!IsSuccessfullAttempt && AttemptsNumber <= MaxRequestAttempts)
                        {
                            AttemptsNumber++;
                            try
                            {
                                var client      = new HttpClient();
                                var queryString = HttpUtility.ParseQueryString(string.Empty);


                                // Request parameters
                                if (!String.IsNullOrWhiteSpace(filters.FromAirportCode))
                                {
                                    queryString["flyFrom"] = filters.FromAirportCode;
                                }
                                if (!String.IsNullOrWhiteSpace(filters.ToAirportCode))
                                {
                                    queryString["to"] = filters.ToAirportCode;
                                }

                                queryString["dateFrom"] = filters.FromDateMin.ToString("dd'/'MM'/'yyyy");
                                queryString["dateTo"]   = filters.FromDateMax.ToString("dd'/'MM'/'yyyy");

                                if (filters.ToDateMin != null)
                                {
                                    queryString["returnFrom"] = filters.ToDateMin.Value.ToString("dd'/'MM'/'yyyy");
                                    queryString["returnTo"]   = filters.ToDateMax.Value.ToString("dd'/'MM'/'yyyy");
                                    queryString["typeFlight"] = "round";
                                    if (filters.DurationMin != null)
                                    {
                                        queryString["daysInDestinationFrom"] = filters.DurationMin.ToString();
                                    }
                                    if (filters.DurationMax != null)
                                    {
                                        queryString["daysInDestinationTo"] = filters.DurationMax.ToString();
                                    }
                                }
                                else
                                {
                                    queryString["typeFlight"] = "oneway";
                                }


                                queryString["partner"]      = Key;
                                queryString["maxstopovers"] = i.ToString();
                                queryString["curr"]         = FlightsEngine.Models.Constants.Constants.DefaultCurrency;
                                queryString["adults"]       = filters.AdultsNumber.ToString();
                                queryString["children"]     = filters.ChildrenNumber.ToString();
                                queryString["limit"]        = "12";
                                queryString["sort"]         = "price";
                                queryString["asc"]          = "1";
                                queryString["price_from"]   = "1";
                                queryString["price_to"]     = "2000";

                                /*
                                 * queryString["DestinationDepartureDate"] = "{string}";
                                 * queryString["DestinationArrivalDate"] = "{string}";
                                 * queryString["OriginDepartureTime"] = "{string}";
                                 * queryString["OriginArrivalTime"] = "{string}";
                                 * queryString["DestinationDepartureTime"] = "{string}";
                                 * queryString["DestinationArrivalTime"] = "{string}";
                                 * queryString["OriginDepartureDayOfWeek"] = "{string}";
                                 * queryString["OriginArrivalDayOfWeek"] = "{string}";
                                 * queryString["DestinationDepartureDayOfWeek"] = "{string}";
                                 * queryString["DestinationArrivalDayOfWeek"] = "{string}";
                                 * queryString["DaysAtDestination"] = "{string}";
                                 *
                                 * queryString["Price"] = "{string}";
                                 * queryString["GroupPricing"] = "{string}";
                                 * queryString["ProductClass"] = "{string}";
                                 * queryString["Offset"] = "{string}";
                                 * queryString["Include"] = "{string}";
                                 * queryString["OrderBy"] = "{string}";
                                 * queryString["LowestPricePerDestination"] = "{string}";
                                 * queryString["Loyalty"] = "{string}";
                                 * queryString["Limit"] = "{string}";
                                 */
                                var uri      = "https://api.skypicker.com/flights?" + queryString;
                                var response = await client.GetAsync(uri);


                                if (response != null)
                                {
                                    if (response.IsSuccessStatusCode)
                                    {
                                        var contents = await response.Content.ReadAsStringAsync();

                                        JavaScriptSerializer srRequestResult = new JavaScriptSerializer();
                                        dynamic jsondataRequestResult        = srRequestResult.DeserializeObject(contents);
                                        if (jsondataRequestResult != null)
                                        {
                                            IsSuccessfullAttempt = true;
                                        }
                                        if (jsondataRequestResult != null && FlightsEngine.Utils.Utils.IsPropertyExist(jsondataRequestResult, "data"))
                                        {
                                            dynamic flightsJson = jsondataRequestResult["data"];
                                            foreach (var flightJson in flightsJson)
                                            {
                                                try
                                                {
                                                    TripItem Trip = new TripItem();
                                                    Trip.ProviderId = Providers.Kiwi;
                                                    string lastCity          = null;
                                                    string lastAirportCode   = null;
                                                    string LastDepartureDate = null;
                                                    string LastArrivalDate   = null;
                                                    string FlyFrom           = Convert.ToString(flightJson["flyFrom"]);
                                                    string FlyTo             = Convert.ToString(flightJson["flyTo"]);

                                                    DateTime?ReturnTrip_DepartureDate = null;
                                                    DateTime?OneWayTrip_DepartureDate = null;

                                                    dynamic[] routes     = flightJson["route"];
                                                    bool      returnTrip = false;

                                                    foreach (var route in routes)
                                                    {
                                                        string airlineCode = Convert.ToString(route["airline"]);

                                                        if (lastCity == null)
                                                        {
                                                            Trip.OneWayTrip_FromAirportCode = Convert.ToString(route["flyFrom"]);
                                                            OneWayTrip_DepartureDate        = FlightsEngine.Utils.Utils.GetDateFromunixTimeStamp(Convert.ToString(route["dTime"]));
                                                            Trip.OneWayTrip_DepartureDate   = OneWayTrip_DepartureDate.Value.ToString(DateFormat.Trip).Replace("-", "/");
                                                        }
                                                        else if (FlyTo == Convert.ToString(route["flyFrom"]))
                                                        {
                                                            returnTrip = true;
                                                            Trip.OneWayTrip_ToAirportCode   = lastAirportCode;
                                                            Trip.OneWayTrip_ArrivalDate     = LastArrivalDate;
                                                            ReturnTrip_DepartureDate        = FlightsEngine.Utils.Utils.GetDateFromunixTimeStamp(Convert.ToString(route["dTime"]));
                                                            Trip.ReturnTrip_DepartureDate   = ReturnTrip_DepartureDate.Value.ToString(DateFormat.Trip).Replace("-", "/");
                                                            Trip.ReturnTrip_FromAirportCode = Convert.ToString(route["flyFrom"]);
                                                        }
                                                        string flightNumber = Convert.ToString(route["flight_no"]);
                                                        if (returnTrip)
                                                        {
                                                            if (Trip.ReturnTrip_Stops == null)
                                                            {
                                                                Trip.ReturnTrip_Stops = 0;
                                                            }
                                                            Trip.ReturnTrip_AirlineName  = airlineCode;
                                                            Trip.ReturnTrip_Stops        = Trip.ReturnTrip_Stops + 1;
                                                            Trip.ReturnTrip_FlightNumber = Trip.ReturnTrip_FlightNumber == null ? flightNumber : Trip.ReturnTrip_FlightNumber + FlightsEngine.Models.Constants.Constants.Separator + flightNumber;
                                                            if (Trip.ReturnTrip_Stops > 1)
                                                            {
                                                                Trip.ReturnTrip_StopInformation = Trip.ReturnTrip_StopInformation == null ? lastCity + " (" + lastAirportCode + ")" : Trip.ReturnTrip_StopInformation + FlightsEngine.Models.Constants.Constants.Separator + lastCity + " (" + lastAirportCode + ")";
                                                            }
                                                        }
                                                        else
                                                        {
                                                            Trip.OneWayTrip_Stops        = Trip.OneWayTrip_Stops + 1;
                                                            Trip.OneWayTrip_AirlineName  = airlineCode;
                                                            Trip.OneWayTrip_FlightNumber = Trip.OneWayTrip_FlightNumber == null ? flightNumber : Trip.OneWayTrip_FlightNumber + FlightsEngine.Models.Constants.Constants.Separator + flightNumber;
                                                            if (Trip.OneWayTrip_Stops > 1)
                                                            {
                                                                Trip.OneWayTrip_StopInformation = Trip.OneWayTrip_StopInformation == null ? lastCity + " (" + lastAirportCode + ")" : Trip.OneWayTrip_StopInformation + FlightsEngine.Models.Constants.Constants.Separator + lastCity + " (" + lastAirportCode + ")";
                                                            }
                                                        }

                                                        lastCity        = Convert.ToString(route["cityTo"]);
                                                        lastAirportCode = Convert.ToString(route["flyTo"]);
                                                        Trip.ReturnTrip_ToAirportCode = lastAirportCode;
                                                        LastDepartureDate             = FlightsEngine.Utils.Utils.GetDateFromunixTimeStamp(Convert.ToString(route["dTime"])).ToString(DateFormat.Trip).Replace("-", "/");
                                                        LastArrivalDate             = FlightsEngine.Utils.Utils.GetDateFromunixTimeStamp(Convert.ToString(route["aTime"])).ToString(DateFormat.Trip).Replace("-", "/");
                                                        Trip.ReturnTrip_ArrivalDate = LastArrivalDate;
                                                    }
                                                    Trip.OneWayTrip_Stops = Trip.OneWayTrip_Stops - 1;
                                                    Trip.ReturnTrip_Stops = Trip.ReturnTrip_Stops - 1;


                                                    Trip.SearchTripProviderId = SearchTripProviderId;
                                                    Trip.CurrencyCode         = FlightsEngine.Models.Constants.Constants.DefaultCurrency;
                                                    Trip.Price = Convert.ToDecimal(flightJson["price"]);
                                                    Trip.Url   = Convert.ToString(flightJson["deep_link"]);
                                                    Trip.OneWayTrip_Duration = ScrappingHelper.GetDurationFromHtml(Convert.ToString(flightJson["fly_duration"]));
                                                    if (FlightsEngine.Utils.Utils.IsPropertyExist(flightJson, "return_duration"))
                                                    {
                                                        Trip.ReturnTrip_Duration = ScrappingHelper.GetDurationFromHtml(Convert.ToString(flightJson["return_duration"]));
                                                    }

                                                    Trips.Add(Trip);
                                                }
                                                catch (Exception ex2)
                                                {
                                                    FlightsEngine.Utils.Logger.GenerateError(ex2, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
                                                }
                                            }
                                            FromDateMin = FromDateMin.AddDays(FlightsEngine.Models.Constants.Constants.APIMaxDaysNumberForSearch - ((filters.DurationMax ?? 0) + 1));
                                            ToDateMax   = FromDateMin.AddDays(FlightsEngine.Models.Constants.Constants.APIMaxDaysNumberForSearch);
                                        }
                                    }
                                    else
                                    {
                                        FlightsEngine.Utils.Logger.GenerateInfo("Kiwi Response unsucessfull :  " + response.ReasonPhrase + " " + response.RequestMessage + " " + response.StatusCode + " and " + response.ToString() + " and " + filters.ToSpecialString());
                                    }
                                }
                                else
                                {
                                    FlightsEngine.Utils.Logger.GenerateInfo("Kiwi Response null :  " + filters.ToSpecialString());
                                }
                            }
                            catch (Exception ex)
                            {
                                IsSuccessfullAttempt = false;
                                FlightsEngine.Utils.Logger.GenerateError(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
                            }
                        }
                    }
                }
                TripsService _tripService = new TripsService(context);
                _tripService.InsertTrips(Trips);
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
            }
        }
        static bool MakeRequest(APIAirlineSearch filters)
        {
            bool result = false;

            try
            {
                int MaxRequestAttempts = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;
                int AttemptsNumber     = 1;



                DateTime originalFromDateMin = filters.FromDateMin;
                DateTime originalToDateMax   = (filters.ToDateMax ?? filters.FromDateMax);

                DateTime FromDateMin = originalFromDateMin;
                DateTime ToDateMax   = originalToDateMax;

                var context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                int SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.TurkishAirlines);



                List <TripItem> Trips = new List <TripItem>();

                AttemptsNumber = 1;
                result         = false;
                while (!result && AttemptsNumber <= MaxRequestAttempts)
                {
                    try
                    {
                        AttemptsNumber = AttemptsNumber + 1;
                        string url            = "https://api.turkishairlines.com/test/getAvailability";
                        var    httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                        httpWebRequest.ContentType = "application/json";
                        httpWebRequest.Method      = "POST";
                        httpWebRequest.Headers.Add("Accept-Language", "en-US");
                        httpWebRequest.Headers.Add("apisecret", Secret);
                        httpWebRequest.Headers.Add("apikey", Key);

                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                        {
                            RequestBody body = new RequestBody();
                            body.ReducedDataIndicator = false;
                            if (filters.Return)
                            {
                                body.RoutingType = "r";
                            }
                            else
                            {
                                body.RoutingType = "o";
                            }
                            body.PassengerTypeQuantity.Add(new PassengerTypeQuantity("adult", filters.AdultsNumber));
                            body.PassengerTypeQuantity.Add(new PassengerTypeQuantity("child", filters.ChildrenNumber));
                            body.PassengerTypeQuantity.Add(new PassengerTypeQuantity("infant", filters.BabiesNumber));

                            OriginDestinationInformation OneWayItem = new OriginDestinationInformation();
                            OneWayItem.CabinPreferences.Add(new CabinPreference("ECONOMY"));
                            OneWayItem.CabinPreferences.Add(new CabinPreference("BUSINESS"));

                            OneWayItem.DepartureDateTime.Date         = "10DEC";
                            OneWayItem.DepartureDateTime.WindowAfter  = "P3D";
                            OneWayItem.DepartureDateTime.WindowBefore = "P3D";

                            OneWayItem.OriginLocation.LocationCode        = "IST";
                            OneWayItem.OriginLocation.MultiAirportCityInd = false;

                            OneWayItem.DestinationLocation.LocationCode   = "ESB";
                            OneWayItem.OriginLocation.MultiAirportCityInd = false;

                            body.OriginDestinationInformation.Add(OneWayItem);

                            if (filters.Return)
                            {
                                OriginDestinationInformation ReturnItem = new OriginDestinationInformation();
                                ReturnItem.CabinPreferences.Add(new CabinPreference("ECONOMY"));
                                ReturnItem.CabinPreferences.Add(new CabinPreference("BUSINESS"));

                                ReturnItem.DepartureDateTime.Date         = "27DEC";
                                ReturnItem.DepartureDateTime.WindowAfter  = "P3D";
                                ReturnItem.DepartureDateTime.WindowBefore = "P3D";

                                ReturnItem.OriginLocation.LocationCode        = "ESB";
                                ReturnItem.OriginLocation.MultiAirportCityInd = false;

                                ReturnItem.DestinationLocation.LocationCode   = "IST";
                                ReturnItem.OriginLocation.MultiAirportCityInd = false;

                                body.OriginDestinationInformation.Add(ReturnItem);
                            }



                            string json = new JavaScriptSerializer().Serialize(body);
                            streamWriter.Write(json);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }

                        HttpWebResponse httpResponse = null;
                        try
                        {
                            httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                            result       = true;
                        }
                        catch (WebException e)
                        {
                            result = false;
                            string webError = FlightsEngine.Utils.Logger.GenerateWebError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
                        }

                        if (result)
                        {
                            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                            {
                                var requestResult = streamReader.ReadToEnd();

                                if (!String.IsNullOrWhiteSpace(requestResult))
                                {
                                }
                            }
                        }

                        System.Threading.Thread.Sleep(200);
                    }
                    catch (Exception ex)
                    {
                        result = false;
                        FlightsEngine.Utils.Logger.GenerateError(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "MakeRequest LOOP ERROR :" + filters.ToSpecialString());
                    }
                }
                TripsService _tripService = new TripsService(context);
                _tripService.InsertTrips(Trips);
            }
            catch (Exception e)
            {
                result = false;
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "MakeRequest ERROR :" + filters.ToSpecialString());
            }
            return(result);
        }
Esempio n. 6
0
        static bool MakeRequest(APIAirlineSearch filters)
        {
            bool result = false;

            try
            {
                int AttemptsNumber     = 0;
                int MaxRequestAttempts = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;

                var context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                TripsService _tripService           = new TripsService(context);
                int          MaxDaysNumberForSearch = 30;

                DateTime originalFromDateMin = filters.FromDateMin;
                DateTime originalToDateMax   = (filters.ToDateMax ?? filters.FromDateMax);

                DateTime FromDateMin = originalFromDateMin;
                DateTime ToDateMax   = originalToDateMax;

                if ((originalToDateMax - originalFromDateMin).TotalDays > MaxDaysNumberForSearch)
                {
                    ToDateMax = FromDateMin.AddDays(MaxDaysNumberForSearch);
                }

                int SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.RyanAir);

                List <TripItem> Trips = new List <TripItem>();

                while (ToDateMax < originalToDateMax)
                {
                    AttemptsNumber = 1;
                    result         = false;
                    while (!result && AttemptsNumber <= MaxRequestAttempts)
                    {
                        AttemptsNumber++;
                        string url = "https://apigateway.ryanair.com/pub/v1/farefinder/3/roundTripFares?apikey=" + Key + "&departureAirportIataCode=" + filters.FromAirportCode + "&outboundDepartureDateFrom=" + FromDateMin.ToString("yyyy-MM-dd") + "&outboundDepartureDateTo=" + ToDateMax.ToString("yyyy-MM-dd") + "&inboundDepartureDateFrom=" + FromDateMin.ToString("yyyy-MM-dd") + "&inboundDepartureDateTo=" + ToDateMax.ToString("yyyy-MM-dd") + "&arrivalAirportIataCode=" + filters.ToAirportCode + "&durationFrom=" + filters.DurationMin.Value + "&durationTo=" + filters.DurationMax.Value;

                        WebClient client   = new WebClient();
                        string    response = "";
                        try
                        {
                            response = client.DownloadString(url);
                            result   = true;
                        }
                        catch (WebException e)
                        {
                            result = false;
                            string webError = FlightsEngine.Utils.Logger.GenerateWebError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "url= " + url + " and " + filters.ToSpecialString());
                            System.Threading.Thread.Sleep(5000);
                        }

                        if (result)
                        {
                            if (!String.IsNullOrWhiteSpace(response))
                            {
                                RyanAirTripsResponse Item = JsonConvert.DeserializeObject <RyanAirTripsResponse>(response);
                                if (Item != null)
                                {
                                    foreach (var trip in Item.fares)
                                    {
                                        TripItem Trip = new TripItem();
                                        Trip.OneWayTrip_AirlineName = "Ryanair";
                                        Trip.ReturnTrip_AirlineName = "Ryanair";
                                        Trip.OneWayTrip_Stops       = 0;
                                        Trip.ReturnTrip_Stops       = 0;
                                        Trip.Url                        = "https://www.ryanair.com/gb/en/booking/home/" + trip.outbound.departureAirport.iataCode + "/" + trip.outbound.arrivalAirport.iataCode + "/" + trip.outbound.departureDate.ToString("yyyy-MM-dd") + "/" + trip.inbound.departureDate.ToString("yyyy-MM-dd") + "/" + filters.AdultsNumber + "/" + filters.ChildrenNumber + "/" + filters.BabiesNumber + "/" + filters.ChildrenNumber;
                                        Trip.ProviderId                 = Providers.RyanAir;
                                        Trip.Price                      = Convert.ToDecimal(trip.summary.price.value);
                                        Trip.CurrencyCode               = trip.summary.price.currencyCode;
                                        Trip.SearchTripProviderId       = SearchTripProviderId;
                                        Trip.OneWayTrip_FromAirportCode = trip.outbound.departureAirport.iataCode;
                                        Trip.OneWayTrip_ToAirportCode   = trip.outbound.arrivalAirport.iataCode;
                                        Trip.ReturnTrip_FromAirportCode = trip.inbound.departureAirport.iataCode;
                                        Trip.ReturnTrip_ToAirportCode   = trip.inbound.arrivalAirport.iataCode;
                                        Trip.OneWayTrip_DepartureDate   = trip.outbound.departureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                        Trip.OneWayTrip_ArrivalDate     = trip.outbound.arrivalDate.ToString(DateFormat.Trip).Replace("-", "/");
                                        Trip.ReturnTrip_DepartureDate   = trip.inbound.departureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                        Trip.ReturnTrip_ArrivalDate     = trip.inbound.arrivalDate.ToString(DateFormat.Trip).Replace("-", "/");
                                        Trip.OneWayTrip_Duration        = _tripService.GetTripDuration(trip.outbound.departureDate, trip.outbound.arrivalDate, trip.outbound.departureAirport.iataCode, trip.outbound.arrivalAirport.iataCode);
                                        Trip.ReturnTrip_Duration        = _tripService.GetTripDuration(trip.inbound.departureDate, trip.inbound.arrivalDate, trip.inbound.departureAirport.iataCode, trip.inbound.arrivalAirport.iataCode);
                                        Trips.Add(Trip);
                                    }
                                }
                            }

                            FromDateMin = FromDateMin.AddDays(MaxDaysNumberForSearch - (filters.DurationMax + 1 ?? 0));

                            if (ToDateMax == originalToDateMax)
                            {
                                ToDateMax = ToDateMax.AddDays(1);
                            }
                            else if (ToDateMax.AddDays(MaxDaysNumberForSearch) > originalToDateMax)
                            {
                                ToDateMax = originalToDateMax;
                            }
                            else
                            {
                                ToDateMax = FromDateMin.AddDays(MaxDaysNumberForSearch);
                            }
                            System.Threading.Thread.Sleep(700);
                        }
                    }
                }
                _tripService.InsertTrips(Trips);
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
            }
            return(result);
        }
Esempio n. 7
0
        static async Task MakeRequest(APIAirlineSearch filters)
        {
            bool result = false;

            try
            {
                int                       MaxRequestAttempts = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;
                var                       ListMonthsFrom     = MonthsBetween(filters.FromDateMin, filters.FromDateMax).ToList();
                var                       ListMonthsTo       = MonthsBetween(filters.ToDateMin.Value, filters.ToDateMax.Value).ToList();
                List <TripItem>           Trips   = new List <TripItem>();
                var                       context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                TripsService              _tripService = new TripsService(context);

                foreach (var tupleFromDateMonth in ListMonthsFrom)
                {
                    foreach (var tupleToDateMonth in ListMonthsTo)
                    {
                        int fromDateMonth = tupleFromDateMonth.Item2 * 100 + tupleFromDateMonth.Item1;
                        int toDateMonth   = tupleToDateMonth.Item2 * 100 + tupleToDateMonth.Item1;

                        if (fromDateMonth <= toDateMonth)
                        {
                            int AttemptsNumber = 1;
                            result = false;
                            while (!result && AttemptsNumber <= MaxRequestAttempts)
                            {
                                try
                                {
                                    AttemptsNumber++;
                                    var client      = new HttpClient();
                                    var queryString = HttpUtility.ParseQueryString(string.Empty);

                                    // Request headers
                                    client.DefaultRequestHeaders.Add("apikey", Key);

                                    // Request parameters
                                    if (!String.IsNullOrWhiteSpace(filters.FromAirportCode))
                                    {
                                        queryString["Origin"] = filters.FromAirportCode;
                                    }
                                    if (!String.IsNullOrWhiteSpace(filters.ToAirportCode))
                                    {
                                        queryString["Destination"] = filters.ToAirportCode;
                                    }
                                    queryString["OriginDepartureDate"]      = fromDateMonth.ToString();
                                    queryString["DestinationDepartureDate"] = toDateMonth.ToString();
                                    //     if (filters.FromDate != null)
                                    //      queryString["OriginDepartureDate"] = filters.FromDate.Value.ToString("yyyyMMdd");
                                    //   if (filters.ToDate != null)
                                    //     queryString["DestinationDepartureDate"] = filters.ToDate.Value.ToString("yyyyMMdd");
                                    if (filters.MaxStopsNumber == 0)
                                    {
                                        queryString["DirectFlight"] = "true";
                                    }

                                    queryString["Adults"]   = filters.AdultsNumber.ToString();
                                    queryString["Children"] = filters.ChildrenNumber.ToString();
                                    queryString["Limit"]    = "200";

                                    var uri      = "https://api.transavia.com/v1/flightoffers/?" + queryString;
                                    var response = await client.GetAsync(uri);


                                    if (response != null)
                                    {
                                        result = true;
                                        if (response.IsSuccessStatusCode && response.StatusCode.ToString() != "NoContent")
                                        {
                                            var contents = await response.Content.ReadAsStringAsync();

                                            if (!String.IsNullOrWhiteSpace(contents))
                                            {
                                                TransaviaResponse ResultItem = JsonConvert.DeserializeObject <TransaviaResponse>(contents);
                                                if (ResultItem != null && ResultItem.flightOffer != null)
                                                {
                                                    foreach (var route in ResultItem.flightOffer)
                                                    {
                                                        int daysAtDestination = Utils.Utils.GetDaysAtDestination(route.outboundFlight.departureDateTime, route.inboundFlight.departureDateTime);
                                                        if (route.outboundFlight.departureDateTime >= filters.FromDateMin && route.outboundFlight.departureDateTime <= filters.FromDateMax.AddDays(1) &&
                                                            route.inboundFlight.departureDateTime >= filters.ToDateMin && route.inboundFlight.departureDateTime <= filters.ToDateMax.Value.AddDays(1) &&
                                                            daysAtDestination >= filters.DurationMin && daysAtDestination <= filters.DurationMax)
                                                        {
                                                            TripItem Trip = new TripItem();
                                                            Trip.OneWayTrip_AirlineName     = Providers.ToString(Providers.Transavia);
                                                            Trip.ReturnTrip_AirlineName     = Providers.ToString(Providers.Transavia);
                                                            Trip.OneWayTrip_Stops           = 0;
                                                            Trip.ReturnTrip_Stops           = 0;
                                                            Trip.ProviderId                 = Providers.Transavia;
                                                            Trip.OneWayTrip_Duration        = _tripService.GetTripDuration(route.outboundFlight.departureDateTime, route.outboundFlight.arrivalDateTime, route.outboundFlight.departureAirport.locationCode, route.outboundFlight.arrivalAirport.locationCode);
                                                            Trip.ReturnTrip_Duration        = _tripService.GetTripDuration(route.inboundFlight.departureDateTime, route.inboundFlight.arrivalDateTime, route.inboundFlight.departureAirport.locationCode, route.inboundFlight.arrivalAirport.locationCode);
                                                            Trip.OneWayTrip_FromAirportCode = route.outboundFlight.departureAirport.locationCode;
                                                            Trip.OneWayTrip_ToAirportCode   = route.outboundFlight.arrivalAirport.locationCode;
                                                            Trip.ReturnTrip_FromAirportCode = route.inboundFlight.departureAirport.locationCode;
                                                            Trip.ReturnTrip_ToAirportCode   = route.inboundFlight.arrivalAirport.locationCode;
                                                            Trip.OneWayTrip_FlightNumber    = route.outboundFlight.flightNumber.ToString();
                                                            Trip.ReturnTrip_FlightNumber    = route.inboundFlight.flightNumber.ToString();
                                                            Trip.OneWayTrip_DepartureDate   = route.outboundFlight.departureDateTime.ToString(DateFormat.Trip).Replace("-", "/");
                                                            Trip.OneWayTrip_ArrivalDate     = route.outboundFlight.arrivalDateTime.ToString(DateFormat.Trip).Replace("-", "/");
                                                            Trip.ReturnTrip_DepartureDate   = route.inboundFlight.departureDateTime.ToString(DateFormat.Trip).Replace("-", "/");
                                                            Trip.ReturnTrip_ArrivalDate     = route.inboundFlight.arrivalDateTime.ToString(DateFormat.Trip).Replace("-", "/");
                                                            Trip.SearchTripProviderId       = _searchTripProviderService.GetSearchTripProviderId(route.outboundFlight.departureDateTime, route.inboundFlight.departureDateTime, filters.SearchTripWishesId, Providers.Transavia);
                                                            Trip.Price        = Convert.ToDecimal(route.pricingInfoSum.totalPriceAllPassengers);
                                                            Trip.CurrencyCode = route.pricingInfoSum.currencyCode;
                                                            Trip.Url          = route.deeplink.href;
                                                            Trips.Add(Trip);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        FlightsEngine.Utils.Logger.GenerateInfo("Transavia Response null : " + filters.ToSpecialString());
                                    }
                                }
                                catch (Exception e)
                                {
                                    FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString() + " and fromDateMonth = " + fromDateMonth + " and toDateMonth = " + toDateMonth + " and AttemptsNumber = " + AttemptsNumber);
                                }
                            }
                        }
                    }
                }
                _tripService.InsertTrips(Trips);
            }
            catch (Exception e)
            {
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
            }
        }
        static int MakeRequest(APIAirlineSearch filters, string TravelHost, string Key)
        {
            int  RequestsNumbers = 0;
            bool result          = false;

            try
            {
                int    MaxRequestAttempts     = FlightsEngine.Models.Constants.Constants.MaxRequestAttempts;
                int    MaxDaysNumberForSearch = 35;
                int    AttemptsNumber         = 1;
                String OriginalSearchType     = "OVERALL";
                String SearchType             = OriginalSearchType;
                bool   endOfPreSearch         = false;


                DateTime originalFromDateMin = filters.FromDateMin;
                DateTime originalToDateMax   = (filters.ToDateMax ?? filters.FromDateMax);

                DateTime FromDateMin = originalFromDateMin;
                DateTime ToDateMax   = originalToDateMax;

                if ((originalToDateMax - originalFromDateMin).TotalDays > MaxDaysNumberForSearch)
                {
                    ToDateMax = FromDateMin.AddDays(MaxDaysNumberForSearch);
                }
                var context = new TemplateEntities1();
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                int SearchTripProviderId = -1;
                if (TravelHost == AIRFranceKLMTravelHost.AF)
                {
                    SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.AirFrance);
                }
                else
                {
                    SearchTripProviderId = _searchTripProviderService.GetSearchTripProviderId(originalFromDateMin, originalToDateMax, filters.SearchTripWishesId, Providers.KLM);
                }

                List <TripItem> Trips = new List <TripItem>();
                bool            NeedToContinueSearch = true;
                while (ToDateMax <= originalToDateMax && NeedToContinueSearch)
                {
                    AttemptsNumber = 1;
                    result         = false;
                    SearchType     = OriginalSearchType;
                    while (!result && AttemptsNumber <= MaxRequestAttempts && NeedToContinueSearch)
                    {
                        try
                        {
                            AttemptsNumber = AttemptsNumber + 1;
                            string url            = "https://api.klm.com/opendata/flightoffers/v3/lowest-fare-offers?expand-suggested-flights=true&type=" + SearchType;
                            var    httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                            httpWebRequest.ContentType = "application/json";
                            httpWebRequest.Method      = "POST";
                            httpWebRequest.Headers.Add("Accept-Language", "en-US");
                            httpWebRequest.Headers.Add("AFKL-TRAVEL-Host", TravelHost);
                            httpWebRequest.Headers.Add("Api-Key", Key);

                            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                            {
                                RequestBody body = new RequestBody();
                                body.passengerCount.ADT = filters.AdultsNumber;
                                body.passengerCount.CHD = filters.ChildrenNumber;
                                body.passengerCount.INF = filters.BabiesNumber;


                                connection connection = new connection();
                                connection.dateInterval  = FromDateMin.ToString("yyyy-MM-dd") + "/" + ToDateMax.ToString("yyyy-MM-dd"); //filters.FromDate.Value.ToString("yyyy-MM-dd");
                                connection.minDaysOfStay = filters.DurationMin;
                                connection.minDaysOfStay = filters.DurationMax;
                                if (!String.IsNullOrWhiteSpace(filters.FromAirportCode))
                                {
                                    connection.origin.airport.code = filters.FromAirportCode;
                                }
                                if (!String.IsNullOrWhiteSpace(filters.ToAirportCode))
                                {
                                    connection.destination.airport.code = filters.ToAirportCode;
                                }
                                body.requestedConnections.Add(connection);



                                if (filters.Return)
                                {
                                    connection returnFlight = new connection();
                                    if (!String.IsNullOrWhiteSpace(filters.FromAirportCode))
                                    {
                                        returnFlight.destination.airport.code = filters.FromAirportCode;
                                    }
                                    if (!String.IsNullOrWhiteSpace(filters.ToAirportCode))
                                    {
                                        returnFlight.origin.airport.code = filters.ToAirportCode;
                                    }
                                    body.requestedConnections.Add(returnFlight);
                                }

                                string json = new JavaScriptSerializer().Serialize(body);
                                streamWriter.Write(json);
                                streamWriter.Flush();
                                streamWriter.Close();
                            }

                            HttpWebResponse httpResponse = null;
                            try
                            {
                                RequestsNumbers++;
                                httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                result       = true;
                            }
                            catch (WebException e)
                            {
                                result = false;
                                string webError = FlightsEngine.Utils.Logger.GenerateWebError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, filters.ToSpecialString());
                                if (webError.ToUpper().Contains("UNSPECIFIED/TIME_OUT") && MaxDaysNumberForSearch > 10)
                                {
                                    MaxDaysNumberForSearch = MaxDaysNumberForSearch - 5;
                                    ToDateMax      = FromDateMin.AddDays(MaxDaysNumberForSearch);
                                    endOfPreSearch = false;
                                }
                                else if (webError.ToLower().Contains("requestedconnections[0].destination.airport.code"))
                                {
                                    NeedToContinueSearch = false;
                                    endOfPreSearch       = true;
                                }
                                else
                                {
                                    SearchType             = "OVERALL";
                                    MaxDaysNumberForSearch = MaxDaysNumberForSearch - 5;
                                    ToDateMax      = FromDateMin.AddDays(MaxDaysNumberForSearch);
                                    endOfPreSearch = false;
                                }
                            }

                            if (result)
                            {
                                endOfPreSearch = true;
                                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                {
                                    var requestResult = streamReader.ReadToEnd();

                                    if (!String.IsNullOrWhiteSpace(requestResult))
                                    {
                                        AirFranceKLMResponse ResultItem = JsonConvert.DeserializeObject <AirFranceKLMResponse>(requestResult);
                                        if (ResultItem != null && ResultItem.itineraries != null)
                                        {
                                            foreach (Itinerary itinerary in ResultItem.itineraries)
                                            {
                                                bool     AddTrip = true;
                                                TripItem Trip    = new TripItem();
                                                Trip.SearchTripProviderId = SearchTripProviderId;
                                                Trip.Comment = AIRFranceKLMTravelHost.ToString(TravelHost);
                                                bool returnTrip = false;
                                                if (TravelHost == AIRFranceKLMTravelHost.AF)
                                                {
                                                    Trip.Url        = "https://www.airfrance.com";
                                                    Trip.ProviderId = Providers.AirFrance;
                                                }
                                                else
                                                {
                                                    Trip.Url        = "https://www.klm.com";
                                                    Trip.ProviderId = Providers.KLM;
                                                }
                                                foreach (var connexion in itinerary.connections)
                                                {
                                                    string   stopInfo          = "";
                                                    string   flightNumber      = "";
                                                    string   airlineCode       = "";
                                                    int      stopNumber        = 0;
                                                    DateTime DepartureDate     = new DateTime();
                                                    DateTime LastDepartureDate = DepartureDate;

                                                    foreach (var stop in connexion.segments)
                                                    {
                                                        stopNumber++;
                                                        flightNumber = flightNumber + stop.marketingFlight.number + FlightsEngine.Models.Constants.Constants.Separator;
                                                        if (String.IsNullOrWhiteSpace(airlineCode))
                                                        {
                                                            airlineCode = stop.marketingFlight.carrier.code;
                                                        }
                                                        else if (airlineCode != stop.marketingFlight.carrier.code)
                                                        {
                                                            airlineCode = "SEVERAL";
                                                        }
                                                        if (stopNumber > 1)
                                                        {
                                                            stopInfo = stopInfo + stop.origin.city.name + " (" + stop.origin.code + ")" + FlightsEngine.Models.Constants.Constants.Separator;
                                                        }
                                                        else
                                                        {
                                                            DepartureDate = Convert.ToDateTime(stop.departureDateTime);
                                                        }
                                                        LastDepartureDate = Convert.ToDateTime(stop.departureDateTime);
                                                    }

                                                    if (!String.IsNullOrWhiteSpace(stopInfo))
                                                    {
                                                        stopInfo = stopInfo.Substring(0, stopInfo.Length - 3);
                                                    }
                                                    else
                                                    {
                                                        stopInfo = null;
                                                    }

                                                    if (!String.IsNullOrWhiteSpace(flightNumber))
                                                    {
                                                        flightNumber = flightNumber.Substring(0, flightNumber.Length - 3);
                                                    }
                                                    else
                                                    {
                                                        flightNumber = null;
                                                    }

                                                    if (!returnTrip)
                                                    {
                                                        Trip.OneWayTrip_Stops           = connexion.segments.Count - 1;
                                                        Trip.OneWayTrip_FromAirportCode = connexion.origin.airport.code;
                                                        Trip.OneWayTrip_ToAirportCode   = connexion.destination.airport.code;
                                                        Trip.OneWayTrip_StopInformation = stopInfo;
                                                        Trip.OneWayTrip_AirlineName     = airlineCode;
                                                        Trip.OneWayTrip_FlightNumber    = flightNumber;
                                                        Trip.OneWayTrip_DepartureDate   = DepartureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                                        Trip.OneWayTrip_ArrivalDate     = LastDepartureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                                        Trip.OneWayTrip_Duration        = -1;
                                                    }
                                                    else
                                                    {
                                                        Trip.ReturnTrip_Stops           = connexion.segments.Count - 1;
                                                        Trip.ReturnTrip_FromAirportCode = connexion.origin.airport.code;
                                                        Trip.ReturnTrip_ToAirportCode   = connexion.destination.airport.code;
                                                        Trip.ReturnTrip_StopInformation = stopInfo;
                                                        Trip.ReturnTrip_FlightNumber    = flightNumber;
                                                        Trip.ReturnTrip_AirlineName     = airlineCode;
                                                        Trip.ReturnTrip_DepartureDate   = DepartureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                                        Trip.ReturnTrip_ArrivalDate     = LastDepartureDate.ToString(DateFormat.Trip).Replace("-", "/");
                                                        Trip.ReturnTrip_Duration        = -1;
                                                    }

                                                    returnTrip = true;
                                                }
                                                Trip.Price        = Convert.ToDecimal(itinerary.flightProducts[0].price.totalPrice);
                                                Trip.CurrencyCode = itinerary.flightProducts[0].price.currency;
                                                AddTrip           = Trip.OneWayTrip_Stops <= filters.MaxStopsNumber && (Trip.ReturnTrip_Stops == null || Trip.ReturnTrip_Stops.Value <= filters.MaxStopsNumber);
                                                if (AddTrip)
                                                {
                                                    Trips.Add(Trip);
                                                    NeedToContinueSearch = false;
                                                }
                                            }
                                        }
                                    }
                                }

                                FromDateMin = FromDateMin.AddDays(MaxDaysNumberForSearch);
                                if (ToDateMax == originalToDateMax)
                                {
                                    ToDateMax = ToDateMax.AddDays(1);
                                }
                                else if (ToDateMax.AddDays(MaxDaysNumberForSearch) > originalToDateMax)
                                {
                                    ToDateMax = originalToDateMax;
                                }
                                else
                                {
                                    ToDateMax = FromDateMin.AddDays(MaxDaysNumberForSearch);
                                }
                            }

                            System.Threading.Thread.Sleep(200);
                        }
                        catch (Exception ex)
                        {
                            result = false;
                            FlightsEngine.Utils.Logger.GenerateError(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "MakeRequest LOOP ERROR :" + filters.ToSpecialString() + " and Provider = " + TravelHost + " and Key = " + Key);
                        }
                    }
                }
                TripsService _tripService = new TripsService(context);
                _tripService.InsertTrips(Trips);
                if (endOfPreSearch)
                {
                    SearchTripWishesService _searchTripWishesService = new SearchTripWishesService(context);
                    _searchTripWishesService.DisableSearchTripWishes(filters.SearchTripWishesId);
                }
            }
            catch (Exception e)
            {
                result = false;
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "MakeRequest ERROR :" + filters.ToSpecialString() + " and Provider = " + TravelHost + " and Key = " + Key);
            }
            return(RequestsNumbers);
        }
Esempio n. 9
0
        public static bool SearchFlights(int?SearchTripWishesId, string ScrappingFolder, string FirefoxExeFolder, int?ProviderId = null)
        {
            bool result = false;

            try
            {
                var context = new TemplateEntities1();
                SearchTripWishesService   _searchTripWishesService   = new SearchTripWishesService(context);
                SearchTripProviderService _searchTripProviderService = new SearchTripProviderService(context);
                TripsService _tripService = new TripsService(context);



                List <ProxyItem> Proxies = null;

                string lastSuccessfullProxy = null;

                List <SearchTripWishesItem> SearchTripWishesItems = _searchTripWishesService.GetSearchTripWishesById(SearchTripWishesId, ProviderId);
                foreach (var SearchTripWishesItem in SearchTripWishesItems)
                {
                    if (SearchTripWishesItem != null && SearchTripWishesItem._SearchTripWishes != null)
                    {
                        var SearchTripWishes = SearchTripWishesItem._SearchTripWishes;

                        #region api

                        APIAirlineSearch APIAirlineSearchItem = new APIAirlineSearch();
                        APIAirlineSearchItem.SearchTripWishesId = SearchTripWishes.Id;
                        if (SearchTripWishes.FromAirport != null)
                        {
                            APIAirlineSearchItem.FromAirportCode = SearchTripWishes.FromAirport.Code;
                        }
                        APIAirlineSearchItem.FromDateMax = SearchTripWishes.FromDateMax;
                        APIAirlineSearchItem.FromDateMin = SearchTripWishes.FromDateMin;
                        if (SearchTripWishes.ToAirport != null)
                        {
                            APIAirlineSearchItem.ToAirportCode = SearchTripWishes.ToAirport.Code;
                        }
                        if (SearchTripWishes.ToDateMin != null)
                        {
                            APIAirlineSearchItem.Return    = true;
                            APIAirlineSearchItem.ToDateMin = SearchTripWishes.ToDateMin;
                            APIAirlineSearchItem.ToDateMax = SearchTripWishes.ToDateMax;
                        }
                        APIAirlineSearchItem.AdultsNumber   = 1;
                        APIAirlineSearchItem.MaxStopsNumber = SearchTripWishes.MaxStopNumber;
                        APIAirlineSearchItem.DurationMin    = SearchTripWishes.DurationMin;
                        APIAirlineSearchItem.DurationMax    = SearchTripWishes.DurationMax;
                        APIAirlineSearchItem.MaxStopsNumber = SearchTripWishes.MaxStopNumber;

                        List <APIKey> AFKLMKeys = FlightsEngine.FlighsAPI.AirFranceKLM.GetAPIKeys();

                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.Kiwi))
                        {
                            Kiwi.SearchFlights(APIAirlineSearchItem);
                        }
                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.AirFrance))
                        {
                            APIKey KeyToUse = AFKLMKeys.Where(k => k.RequestsNumber < 5000).OrderBy(k => k.RequestsNumber).FirstOrDefault();
                            if (KeyToUse != null)
                            {
                                AFKLMKeys.Where(k => k.Key == KeyToUse.Key).FirstOrDefault().RequestsNumber = KeyToUse.RequestsNumber + FlightsEngine.FlighsAPI.AirFranceKLM.SearchFlights(APIAirlineSearchItem, Providers.AirFrance, KeyToUse.Key);
                            }
                        }
                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.KLM))
                        {
                            APIKey KeyToUse = AFKLMKeys.Where(k => k.RequestsNumber < 5000).OrderBy(k => k.RequestsNumber).FirstOrDefault();
                            if (KeyToUse != null)
                            {
                                AFKLMKeys.Where(k => k.Key == KeyToUse.Key).FirstOrDefault().RequestsNumber = KeyToUse.RequestsNumber + FlightsEngine.FlighsAPI.AirFranceKLM.SearchFlights(APIAirlineSearchItem, Providers.KLM, KeyToUse.Key);
                            }
                        }
                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.Transavia))
                        {
                            FlightsEngine.FlighsAPI.Transavia.SearchFlights(APIAirlineSearchItem);
                        }
                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.TurkishAirlines))
                        {
                            FlightsEngine.FlighsAPI.TurkishAirlines.SearchFlights(APIAirlineSearchItem);
                        }
                        if (SearchTripWishesItem.ProvidersToSearch.Select(p => p.Id).Contains(Providers.RyanAir))
                        {
                            FlightsEngine.FlighsAPI.RyanAir.SearchFlights(APIAirlineSearchItem);
                        }
                        #endregion kiwi

                        result = true;
                        bool newProxy = true;
                        foreach (var searchTrip in SearchTripWishes.SearchTrips)
                        {
                            try
                            {
                                AirlineSearch filter = new AirlineSearch();
                                if (SearchTripWishes.FromAirport != null)
                                {
                                    filter.FromAirportCode = SearchTripWishes.FromAirport.Code;
                                }

                                filter.FromDate = searchTrip.FromDate;
                                if (SearchTripWishes.ToAirport != null)
                                {
                                    filter.ToAirportCode = SearchTripWishes.ToAirport.Code;
                                }
                                if (searchTrip.ToDate != null)
                                {
                                    filter.Return = true;
                                    filter.ToDate = searchTrip.ToDate.Value;
                                }
                                filter.AdultsNumber   = 1;
                                filter.MaxStopsNumber = SearchTripWishes.MaxStopNumber;



                                foreach (var provider in SearchTripWishesItem.ProvidersToSearch)
                                {
                                    if (!provider.HasAPI)
                                    {
                                        string Proxy = lastSuccessfullProxy;
                                        if (String.IsNullOrWhiteSpace(Proxy))
                                        {
                                            if (Proxies == null)
                                            {
                                                Proxies = ProxyHelper.GetProxies();
                                            }

                                            Proxy = ProxyHelper.GetBestProxy(Proxies);
                                            if (Proxy == null)
                                            {
                                                Proxies = ProxyHelper.GetProxies();
                                                Proxy   = ProxyHelper.GetBestProxy(Proxies);
                                            }
                                            newProxy = true;
                                        }

                                        ScrappingSearch scrappingSearch = new ScrappingSearch();
                                        if (provider.Id == Providers.Edreams)
                                        {
                                            scrappingSearch.Url = ScrappingHelper.GetEdreamsUrl(filter);
                                        }
                                        else if (provider.Id == Providers.Kayak)
                                        {
                                            scrappingSearch.Url = ScrappingHelper.GetKayakUrl(filter);
                                        }
                                        int SearchTripProviderId = _searchTripProviderService.InsertSearchTripProvider(provider.Id, searchTrip.Id, Proxy, scrappingSearch.Url);
                                        if (!String.IsNullOrWhiteSpace(scrappingSearch.Url) && SearchTripProviderId > 0)
                                        {
                                            scrappingSearch.Proxy            = Proxy;
                                            scrappingSearch.FirefoxExeFolder = FirefoxExeFolder;
                                            scrappingSearch.ScrappingFolder  = ScrappingFolder;
                                            scrappingSearch.NewProxy         = newProxy;
                                            if (SearchTripProviderId > 0 && !String.IsNullOrWhiteSpace(Proxy))
                                            {
                                                filter.SearchTripProviderId = SearchTripProviderId;
                                                scrappingSearch.Provider    = provider.Name;
                                                scrappingSearch.ProxiesList = Proxies;

                                                var ScrappingResult = ScrappingHelper.SearchViaScrapping(scrappingSearch, filter.SearchTripProviderId);
                                                Proxies = ScrappingResult.ProxiesList;
                                                _searchTripProviderService.SetSearchTripProviderAsEnded(SearchTripProviderId, ScrappingResult.Success, ScrappingResult.LastProxy, ScrappingResult.AttemptsNumber);
                                                result = result && ScrappingResult.Success;
                                                if (ScrappingResult.Success)
                                                {
                                                    lastSuccessfullProxy = ScrappingResult.LastProxy;
                                                    _tripService.InsertTrips(SearchTripProviderId);
                                                    newProxy = false;
                                                    //Task.Factory.StartNew(() => { _tripService.InsertTrips(SearchTripProviderId); });
                                                }
                                                else
                                                {
                                                    lastSuccessfullProxy = null;
                                                }
                                            }
                                            else
                                            {
                                                result = false;
                                            }
                                        }
                                        else
                                        {
                                            FlightsEngine.Utils.Logger.GenerateInfo("No url for SearchTripProviderId : " + SearchTripProviderId + " and provider = " + provider.Name);
                                        }
                                    }
                                    else
                                    {
                                        if (provider.Id == Providers.Transavia)
                                        {
                                            //  FlightsEngine.FlighsAPI.Transavia.SearchFlights(filter);
                                        }

                                        int SearchTripProviderId = _searchTripProviderService.InsertSearchTripProvider(provider.Id, searchTrip.Id, null, null);
                                        filter.SearchTripProviderId = SearchTripProviderId;
                                    }
                                }

                                //  Task.Factory.StartNew(() => FlighsBot.PythonHelper.Run(filter, scrappingSearch));
                                // Console.WriteLine("Pythonresult = "+ Pythonresult.Success+" and Error = "+ (Pythonresult.Error??""));

                                //   FlighsBot.Kayak.SearchFlights(filter);
                                //   FlighsBot.Kayak.SearchFlights(filter);

                                //   FlightsEngine.FlighsAPI.AirFranceKLM.SearchFlights(filter);
                                //    FlightsEngine.FlighsAPI.AirHob.SearchFlights(filter);
                                //   FlightsEngine.FlighsAPI.Kiwi.SearchFlights(filter);
                                // FlightsEngine.FlighsAPI.RyanAir.SearchFlights(filter);
                                //  FlightsEngine.FlighsAPI.Transavia.SearchFlights(filter);
                            }
                            catch (Exception e2)
                            {
                                result = false;
                                FlightsEngine.Utils.Logger.GenerateError(e2, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "searchTrip.Id = " + searchTrip.Id);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                result = false;
                FlightsEngine.Utils.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SearchTripWishesId = " + (SearchTripWishesId ?? -1) + " and ScrappingFolder = " + ScrappingFolder + " and FirefoxExeFolder = " + FirefoxExeFolder);
            }
            return(result);
        }