Esempio n. 1
0
        public async Task <GetRoutesResponse> GetRoutes(E_Station origin, E_Station destination, DateTime dateTime, bool isGoing)
        {
            NameValueCollection parameters = HttpUtility.ParseQueryString(string.Empty);

            parameters["OId"]     = ((int)origin).ToString();
            parameters["TId"]     = ((int)destination).ToString();
            parameters["Date"]    = dateTime.ToString("yyyyMMdd");
            parameters["Hour"]    = dateTime.ToString("HHmm");
            parameters["isGoing"] = isGoing.ToString();
            parameters["c"]       = "1574944324761";
            UriBuilder ub = new UriBuilder()
            {
                Path  = "apiinfo/api/Plan/GetRoutes",
                Query = HttpUtility.UrlDecode(parameters.ToString())
            };
            string     uri    = ub.Uri.PathAndQuery;
            HttpClient client = _clientFactory.CreateClient("RailApi");

            using (HttpResponseMessage response = await client.GetAsync(uri))
            {
                response.EnsureSuccessStatusCode();
                GetRoutesResponse result = await response.Content.ReadAsAsync <GetRoutesResponse>();

                if (result.Data.Error != null)
                {
                    throw new Exception(result.Data.Error.Description);
                }
                return(result);
            }
        }
        public async Task <IActionResult> StationUpdates(int oId, int dId)
        {
            try
            {
                E_Station origin                = (E_Station)oId;
                E_Station destination           = (E_Station)dId;
                GetStationsInfoResponse updates = await _rail.GetStationsInfo(origin, destination);

                List <StationUpdate> stationUpdates = new List <StationUpdate>();
                foreach (GetStationsInfoResponseData update in updates.Data.OrderBy(x => x.Order))
                {
                    StationUpdate stationUpdate = new StationUpdate(update, E_Language.Hebrew);
                    stationUpdates.Add(stationUpdate);
                }
                return(PartialView("_Updates", stationUpdates));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, $"Failed StationUpdates({oId}, {dId})");
                return(PartialView("Error", new ErrorViewModel()
                {
                    Exception = ex
                }));
            }
        }
        public async Task <IActionResult> Advanced(int origin, int destination, DateTime dateTime, bool isDepart)
        {
            try
            {
                DateTime          nextWeek = dateTime.AddDays(7);
                GetRoutesResponse getNextWeekRoutesResponse = await _rail.GetRoutes((E_Station)origin, (E_Station)destination, nextWeek, isDepart);

                IEnumerable <TrainAvailableChairsResponse> nextWeekChairsResponses = await GetChairsResponses(getNextWeekRoutesResponse);

                IEnumerable <Models.ViewModels.Route> nextWeekRoutes = _railRouteBuilder.BuildRoutes(getNextWeekRoutesResponse, nextWeekChairsResponses);
                if (nextWeekRoutes == null || !nextWeekRoutes.Any())
                {
                    return(PartialView("_NoRoutes"));
                }
                Models.ViewModels.Route selectedRoute = Tools.SelectRoute(nextWeekRoutes, nextWeek, isDepart);
                DateTime nowNextWeek = _time.NowInLocal().AddDays(7);
                Models.ViewModels.Train selectedTrain = selectedRoute.Trains.FirstOrDefault(x => x.DestinationStop.StopTime.FirstOrDefault() >= nowNextWeek);
                Stop      selectedStop  = selectedTrain.Stops.FirstOrDefault(x => x.StopTime.FirstOrDefault() >= nowNextWeek);
                E_Station currentOrigin = selectedStop.Station;
                if (currentOrigin == (E_Station)destination)
                {
                    int selectedIndex = selectedTrain.Stops.IndexOf(selectedStop);
                    selectedStop  = selectedTrain.Stops.ElementAtOrDefault(selectedIndex - 1);
                    currentOrigin = selectedStop.Station;
                }

                GetRoutesResponse getRoutesResponse = await _rail.GetRoutes(currentOrigin, (E_Station)destination, dateTime, isDepart);

                IEnumerable <TrainAvailableChairsResponse> chairsResponses = await GetChairsResponses(getRoutesResponse);

                IEnumerable <Models.ViewModels.Route> routes = _railRouteBuilder.BuildRoutes(getRoutesResponse, chairsResponses);
                routes = routes.Where(x => nextWeekRoutes.Contains(x));
                if (routes == null || !routes.Any())
                {
                    return(PartialView("_NoRoutes"));
                }

                foreach (Models.ViewModels.Route route in routes)
                {
                    Stop ori = route.Trains.FirstOrDefault().Stops.FirstOrDefault(x => x.Station == (E_Station)origin);
                    if (ori != null)
                    {
                        route.Trains.FirstOrDefault().OrigintStop = ori;
                    }
                }

                Models.ViewModels.Route routeToShow = Tools.SelectRoute(routes, dateTime, isDepart);
                ViewBag.ToShow = routeToShow != null ? routeToShow.Index : 0;
                return(PartialView("_Routes", routes));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, $"Failed Advanced({origin}, {destination}, {dateTime:yyyy-MM-ddTHH:mm}, {isDepart})");
                return(PartialView("Error", new ErrorViewModel()
                {
                    Exception = ex
                }));
            }
        }
Esempio n. 4
0
        public string GetStation(E_Station station)
        {
            StationLightData lightData = _stations.FirstOrDefault(x => x.Station == station);

            if (lightData != null)
            {
                return(lightData.Name);
            }
            return(null);
        }
Esempio n. 5
0
        public async Task <IActionResult> GetStationData(int id)
        {
            try
            {
                E_Station station = (E_Station)id;
                GetStationsInforResponse stationInfo = await _rail.GetStationsInfor(station);

                StationData stationData = new StationData(stationInfo.Data.FirstOrDefault(x => x.StationCode == id.ToString()), E_Language.Hebrew);
                return(Ok(stationData));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, $"Failed GetStationData({id})");
                return(StatusCode(500, ex));
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> Station(int id)
        {
            try
            {
                E_Station station = (E_Station)id;
                GetStationsInforResponse stationInfo = await _rail.GetStationsInfor(station);

                StationData stationData = new StationData(stationInfo.Data.FirstOrDefault(x => x.StationCode == id.ToString()), E_Language.Hebrew);
                ViewBag.GoogleMapsUrl = _google.GetGoogleMapsUrl(stationData);
                return(PartialView("_Station", stationData));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, $"Failed Station({id})");
                return(PartialView("Error", new ErrorViewModel()
                {
                    Exception = ex
                }));
            }
        }
Esempio n. 7
0
        public async Task <GetStationsInforResponse> GetStationsInfor(E_Station station)
        {
            NameValueCollection parameters = HttpUtility.ParseQueryString(string.Empty);

            parameters["stations"] = ((int)station).ToString();
            UriBuilder ub = new UriBuilder()
            {
                Path  = "apiinfo/api/infor/GetStationsInfor",
                Query = HttpUtility.UrlDecode(parameters.ToString())
            };
            string     uri    = ub.Uri.PathAndQuery;
            HttpClient client = _clientFactory.CreateClient("RailApi");

            using (HttpResponseMessage response = await client.GetAsync(uri))
            {
                response.EnsureSuccessStatusCode();
                GetStationsInforResponse result = await response.Content.ReadAsAsync <GetStationsInforResponse>();

                return(result);
            }
        }
Esempio n. 8
0
        public IEnumerable <Route> BuildRoutes(GetRoutesResponse routesResponse, IEnumerable <TrainAvailableChairsResponse> chairsResponses)
        {
            List <Route> routes = new List <Route>();
            int          index  = 0;

            foreach (ApiModels.Route r in routesResponse.Data.Routes)
            {
                TimeSpan.TryParseExact(r.EstTime, "g", null, out TimeSpan estimatedTime);
                Route route = new Route()
                {
                    Index         = index++,
                    EstimatedTime = estimatedTime,
                    IsExchange    = r.IsExchange,
                    Trains        = new List <Train>()
                };
                foreach (ApiModels.Train t in r.Train)
                {
                    int.TryParse(t.Trainno, out int trainNumber);
                    Trainposition pos            = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber);
                    Omasim        omasim         = routesResponse.Data.Omasim.FirstOrDefault(x => x.TrainNumber == trainNumber);
                    E_Station     currentStation = pos != null ? (E_Station)pos.CurrentStation : E_Station.None;
                    E_Station     nextStation    = pos != null ? (E_Station)pos.NextStation : E_Station.None;
                    Delay         currentDelay   = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno);

                    Train train = new Train()
                    {
                        TrainNumber        = trainNumber,
                        LineNumber         = t.LineNumber,
                        Midnight           = t.Midnight,
                        Accesability       = t.Handicap,
                        Direct             = t.DirectTrain,
                        ReservedSeats      = t.ReservedSeat,
                        Carriages          = int.Parse(pos?.TotalKronot ?? "0"),
                        CurrentStation     = currentStation,
                        CurrentStationName = _staticStations.GetStation(currentStation),
                        NextStation        = nextStation,
                        NextStationName    = _staticStations.GetStation(nextStation),
                        Equipment          = pos?.SugNayad,
                        StopPoint          = pos?.StopPoint,
                        Delay = Tools.StopDelay(pos, currentDelay),
                        Stops = new List <Stop>()
                    };
                    List <Stop> midwayStops = new List <Stop>();

                    int.TryParse(t.OrignStation, out int originStation);
                    DateTime.TryParseExact(t.DepartureTime, "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime departureTime);
                    Trainposition originPos   = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber && x.CurrentStation == originStation);
                    Delay         originDelay = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno && x.Station == t.OrignStation);
                    Stop          firstStop   = new Stop()
                    {
                        Station     = (E_Station)originStation,
                        StationName = _staticStations.GetStation((E_Station)originStation),
                        StopTime    = new List <DateTime>()
                        {
                            departureTime
                        },
                        Platform   = t.Platform,
                        Congestion = omasim.Stations.FirstOrDefault(x => x.StationNumber == originStation && x.OmesPercent >= 0)?.OmesPercent,
                        Delay      = Tools.StopDelay(originPos, originDelay),
                        IsCurrent  = (E_Station)originStation == currentStation && nextStation == E_Station.None
                    };
                    train.OrigintStop = firstStop;
                    midwayStops.Add(firstStop);

                    foreach (Stopstation st in t.StopStations)
                    {
                        int.TryParse(st.StationId, out int stopStation);
                        DateTime.TryParseExact(st.ArrivalTime, "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime stopArrivalTime);
                        DateTime.TryParseExact(st.DepartureTime, "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime stopDepartureTime);
                        Trainposition stopPos   = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber && x.CurrentStation == stopStation);
                        Delay         stopDelay = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno && x.Station == st.StationId);
                        Stop          stop      = new Stop()
                        {
                            Station     = (E_Station)stopStation,
                            StationName = _staticStations.GetStation((E_Station)stopStation),
                            StopTime    = new List <DateTime>()
                            {
                                stopArrivalTime,
                                stopDepartureTime
                            },
                            Platform   = st.Platform,
                            Congestion = omasim.Stations.FirstOrDefault(x => x.StationNumber == stopStation && x.OmesPercent >= 0)?.OmesPercent,
                            Delay      = Tools.StopDelay(stopPos, stopDelay),
                            IsCurrent  = (E_Station)stopStation == currentStation && nextStation == E_Station.None
                        };
                        midwayStops.Add(stop);
                    }

                    int.TryParse(t.DestinationStation, out int destinationStation);
                    DateTime.TryParseExact(t.ArrivalTime, "dd/MM/yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime arrivalTime);
                    Trainposition destPos   = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber && x.CurrentStation == destinationStation);
                    Delay         destDelay = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno && x.Station == t.DestinationStation);
                    Stop          lastStop  = new Stop()
                    {
                        Station     = (E_Station)destinationStation,
                        StationName = _staticStations.GetStation((E_Station)destinationStation),
                        StopTime    = new List <DateTime>()
                        {
                            arrivalTime
                        },
                        Platform   = t.DestPlatform,
                        Congestion = omasim.Stations.FirstOrDefault(x => x.StationNumber == destinationStation && x.OmesPercent >= 0)?.OmesPercent,
                        Delay      = Tools.StopDelay(destPos, destDelay),
                        IsCurrent  = (E_Station)destinationStation == currentStation && nextStation == E_Station.None
                    };
                    train.DestinationStop = lastStop;
                    midwayStops.Add(lastStop);

                    IEnumerable <Station> omasimUntilOrigin = omasim.Stations.TakeWhile(x => x.StationNumber != originStation);
                    List <Stop>           stopsUntilOrigin  = new List <Stop>();
                    foreach (Station s in omasimUntilOrigin)
                    {
                        Trainposition stopPos     = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber && x.CurrentStation == s.StationNumber);
                        Delay         stopDelay   = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno && x.Station == s.StationNumber.ToString());
                        string        stopTimeStr = $"{train.OrigintStop.StopTime.FirstOrDefault():dd/MM/yyyy} {s.Time}";
                        DateTime.TryParseExact(stopTimeStr, "dd/MM/yyyy HH:mm", null, DateTimeStyles.None, out DateTime stopTime);
                        Stop stop = new Stop()
                        {
                            Station     = (E_Station)s.StationNumber,
                            StationName = _staticStations.GetStation((E_Station)s.StationNumber),
                            StopTime    = new List <DateTime>()
                            {
                                stopTime
                            },
                            Congestion = s.OmesPercent >= 0 ? s.OmesPercent : (float?)null,
                            Delay      = Tools.StopDelay(stopPos, stopDelay),
                            IsCurrent  = (E_Station)s.StationNumber == currentStation && nextStation == E_Station.None
                        };
                        stopsUntilOrigin.Add(stop);
                    }
                    IEnumerable <Station> omasimAfterDestination = omasim.Stations.SkipWhile(x => x.StationNumber != destinationStation).Skip(1);
                    List <Stop>           stopsAfterDestination  = new List <Stop>();
                    foreach (Station s in omasimAfterDestination)
                    {
                        Trainposition stopPos     = routesResponse.Data.TrainPositions.FirstOrDefault(x => x.TrainNumber == trainNumber && x.CurrentStation == s.StationNumber);
                        Delay         stopDelay   = routesResponse.Data.Delays.FirstOrDefault(x => x.Train == t.Trainno && x.Station == s.StationNumber.ToString());
                        string        stopTimeStr = $"{train.DestinationStop.StopTime.FirstOrDefault():dd/MM/yyyy} {s.Time}";
                        DateTime.TryParseExact(stopTimeStr, "dd/MM/yyyy HH:mm", null, DateTimeStyles.None, out DateTime stopTime);
                        Stop stop = new Stop()
                        {
                            Station     = (E_Station)s.StationNumber,
                            StationName = _staticStations.GetStation((E_Station)s.StationNumber),
                            StopTime    = new List <DateTime>()
                            {
                                stopTime
                            },
                            Congestion = s.OmesPercent >= 0 ? s.OmesPercent : (float?)null,
                            Delay      = Tools.StopDelay(stopPos, stopDelay),
                            IsCurrent  = (E_Station)s.StationNumber == currentStation && nextStation == E_Station.None
                        };
                        stopsAfterDestination.Add(stop);
                    }
                    train.Stops.AddRange(stopsUntilOrigin);
                    train.Stops.AddRange(midwayStops);
                    train.Stops.AddRange(stopsAfterDestination);

                    if (chairsResponses != null && chairsResponses.Any(x => x.ListTrainAvailableChairs != null && x.ListTrainAvailableChairs.Length > 0))
                    {
                        TrainAvailableChairsResponse chairsResponse = chairsResponses.FirstOrDefault(x => x.ListTrainAvailableChairs.Any(y => y.TrainNumber == trainNumber && y.TrainDate.Date == departureTime.Date));
                        if (chairsResponse != null)
                        {
                            TrainAvailableChairsResponseItem chairsResponseItem = chairsResponse.ListTrainAvailableChairs.FirstOrDefault(x => x.TrainNumber == trainNumber && x.TrainDate.Date == departureTime.Date);
                            if (chairsResponseItem != null)
                            {
                                train.AvailableSeats = chairsResponseItem.SeatsAvailable;
                            }
                        }
                    }

                    route.Trains.Add(train);
                }
                routes.Add(route);
            }
            return(routes);
        }