Skip to content

Commit

Permalink
Move to new api. Migrate virtual tables and lines.
Browse files Browse the repository at this point in the history
  • Loading branch information
angelinn committed Jul 19, 2024
1 parent b1276e7 commit 04b1ca1
Show file tree
Hide file tree
Showing 30 changed files with 384 additions and 261 deletions.
53 changes: 14 additions & 39 deletions src/TramlineFive/SkgtService/Models/ArrivalInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,62 +14,37 @@ public class ArrivalInformation
public string Start { get; set; }
public string Direction { get; set; }
public TransportType VehicleType { get; set; }
public List<Arrival> Arrivals { get; set; }
public List<Arrival> Arrivals { get; set; }
public int Minutes => Arrivals[0].Minutes;

public ArrivalInformation(Line line)
public ArrivalInformation(LineArrivalInfo line)
{
LineName = line.Name;
Start = line.Start;
Direction = line.Direction;
Arrivals = line.Arrivals;
//Start = line.Start;
string[] route = line.RouteName.Split('-');
if (route.Length > 1)
Direction = route[1].Trim();
else
Direction = line.RouteName;

Arrivals = line.Details;

if (LineName[0] == 'E')
VehicleType = Models.TransportType.Electrobus;
if (LineName.Length == 3 && LineName[0] == '8' && VehicleType == Models.TransportType.Bus)
VehicleType = Models.TransportType.Additional;

char[] vehicleType = line.VehicleType.ToCharArray();
vehicleType[0] = char.ToUpper(vehicleType[0]);

Enum.TryParse(typeof(TransportType), vehicleType, out object type);
VehicleType = (TransportType)type;
VehicleType = line.Type;
}

public string LastTimings => "Следващи: " + String.Join(", ", Arrivals.Take(3).Select(t => t.Time));
public string LastTimings => "Следващи: " + String.Join(", ", Arrivals.Take(3).Select(t => t.Minutes));


public string LastCalculated => Arrivals.Skip(1).Count() > 0 ? "Следващи: " + String.Join(", ", Arrivals.Skip(1).Take(3).Select(t =>
{
TimeSpan arrival = DateTime.Parse(t.Time) - DateTime.Now;
int minutes = arrival.Minutes;
if (arrival.Hours > 0)
minutes += arrival.Hours * 60;
return minutes + " мин";
return t.Minutes + " мин";
})) : "Последен";

public int Minutes
{
get
{
DateTime closest = DateTime.Parse(Arrivals[0].Time);

int minutes = (int)Math.Round((closest - DateTime.Now).TotalMinutes);
if (minutes < 0)
{
if (Arrivals.Count > 1)
{
closest = DateTime.Parse(Arrivals[1].Time);
minutes = (int)Math.Round((closest - DateTime.Now).TotalMinutes);
}
else
minutes = 0;
}

return minutes;
}
}
public string TransportType
{
get
Expand Down
9 changes: 7 additions & 2 deletions src/TramlineFive/SkgtService/Models/Json/Arrival.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
using System;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SkgtService.Models.Json;

public class Arrival
{
public string Time { get; set; }
[JsonProperty("t")]
public int Minutes { get; set; }
public bool AC { get; set; }
public bool Bikes { get; set; }
}
17 changes: 0 additions & 17 deletions src/TramlineFive/SkgtService/Models/Json/Line.cs

This file was deleted.

19 changes: 19 additions & 0 deletions src/TramlineFive/SkgtService/Models/Json/LineArrivalInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace SkgtService.Models.Json;

public class LineArrivalInfo
{
public int Id { get; set; }
public string Name { get; set; }
public TransportType Type { get; set; }
[JsonProperty("route_name")]
public string RouteName { get; set; }
[JsonProperty("st_name")]
public string StName { get; set; }
public List<Arrival> Details { get; set; }
}
6 changes: 6 additions & 0 deletions src/TramlineFive/SkgtService/Models/Json/Route.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ public class Routes
public string Type { get; set; }
public List<Route> Lines { get; set; }
}

public class Line
{
public string Name { get; set; }
public TransportType Type { get; set; }
}
}
13 changes: 0 additions & 13 deletions src/TramlineFive/SkgtService/Models/Json/StopInfo.cs

This file was deleted.

8 changes: 4 additions & 4 deletions src/TramlineFive/SkgtService/Models/Json/StopLocation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ namespace SkgtService.Models.Json
{
public class StopLocation
{
[JsonProperty("y")]
[JsonProperty("latitude")]
public double Lat { get; set; }
[JsonProperty("x")]
[JsonProperty("longitude")]
public double Lon { get; set; }
[JsonProperty("n")]
[JsonProperty("name")]
public string PublicName { get; set; }
[JsonProperty("c")]
[JsonProperty("code")]
public string Code { get; set; }
}
}
6 changes: 3 additions & 3 deletions src/TramlineFive/SkgtService/Models/StopInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ public class StopResponse
public List<ArrivalInformation> Arrivals { get; set; } = new();
public bool IsFavourite { get; set; }

public StopResponse(StopInfo stop)
public StopResponse(string stopCode, string name)
{
Code = stop.Code;
PublicName = stop.Name;
Code = stopCode;
PublicName = name;
}
}
14 changes: 8 additions & 6 deletions src/TramlineFive/SkgtService/Models/TransportType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ namespace SkgtService.Models;

public enum TransportType
{
MissingNo = -1,
Tram,
Bus,
Trolley,
Electrobus,
Additional
MissingNo = 0,
Bus = 1,
Tram = 2,
Subway = 3,
Trolley = 4,
NightBus = 5,
Electrobus = 6,
Additional = 7
}
59 changes: 20 additions & 39 deletions src/TramlineFive/SkgtService/Parsers/ArrivalsService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sentry;
using SkgtService.Exceptions;
using SkgtService.Models;
using SkgtService.Models.Json;
Expand All @@ -13,21 +16,24 @@ namespace SkgtService.Parsers;

public class ArrivalsService
{
private const string ARRIVALS_API_URL = @"https://api-arrivals.sofiatraffic.bg/api/v1/arrivals";
private const string ARRIVALS_API_URL = @"https://sofiatraffic.bg/bg/trip/getVirtualTable";
private const string OPERA_USER_AGENT = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 OPR/48.0.2685.35";

private readonly HttpClient client = new HttpClient();
private readonly PublicTransport publicTransport;
private readonly SofiaHttpClient sofiaHttpClient;

public ArrivalsService(PublicTransport publicTransport)
public ArrivalsService(PublicTransport publicTransport, SofiaHttpClient sofiaHttpClient)
{
client.DefaultRequestHeaders.Add("User-Agent", OPERA_USER_AGENT);
this.publicTransport = publicTransport;
this.sofiaHttpClient = sofiaHttpClient;
}

public async Task<StopResponse> GetByStopCodeAsync(string stopCode)
{
HttpResponseMessage response = await client.GetAsync($"{ARRIVALS_API_URL}/{stopCode}/");
string payload = $"{{ \"stop\": \"{stopCode}\" }}";

HttpResponseMessage response = await sofiaHttpClient.PostAsync(ARRIVALS_API_URL, new StringContent(payload, Encoding.UTF8, "application/json"));

if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
Expand All @@ -37,43 +43,18 @@ public async Task<StopResponse> GetByStopCodeAsync(string stopCode)
}

string json = await response.Content.ReadAsStringAsync();
StopInfo info = JsonConvert.DeserializeObject<StopInfo>(json);

StopResponse stopResponse = new StopResponse(info);
JObject jsonO = JObject.Parse(json);

foreach (Line line in info.Lines)
List<LineArrivalInfo> stopsInfos = new List<LineArrivalInfo>();
foreach (JToken child in jsonO.Children().Values())
{
DateTime firstArrival = DateTime.Parse(line.Arrivals[0].Time);
// some lines come with negative arrival times
if ((DateTime.Now - firstArrival) > TimeSpan.FromMinutes(5) || firstArrival > DateTime.Now.AddHours(5))
{
line.Name += " (R)";
//pendingDelete.Add(line);
//continue;
}

LineInformation lineInformation = publicTransport.FindByTypeAndLine(line.VehicleType, line.Name);

// routes.json comes with cyrilic E
if (lineInformation != null && lineInformation.Routes.Count > 0)
{
List<LineRoute> waysWithStop = lineInformation.Routes.Where(w => w.Codes.FirstOrDefault(code => code == stopCode) != null).ToList();
if (waysWithStop.Count == 0)
{
continue;
}

LineRoute way = waysWithStop.Count > 1 ? waysWithStop.FirstOrDefault(w => w.Codes[0] == stopCode) : waysWithStop[0];
LineArrivalInfo info = JsonConvert.DeserializeObject<LineArrivalInfo>(child.ToString());
stopsInfos.Add(info);
}

if (way != null)
{
line.Start = publicTransport.FindStop(way.Codes[0]).PublicName;
line.Direction = publicTransport.FindStop(way.Codes[^1]).PublicName;
}
}
StopResponse stopResponse = new StopResponse(stopCode, publicTransport.FindStop(stopCode).PublicName);

stopResponse.Arrivals.Add(new ArrivalInformation(line));
}
stopResponse.Arrivals.AddRange(stopsInfos.Select(s => new ArrivalInformation(s)));

return stopResponse;
}
Expand Down
52 changes: 52 additions & 0 deletions src/TramlineFive/SkgtService/Parsers/SofiaHttpClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SkgtService.Parsers
{
public class SofiaHttpClient
{
private HttpClient httpClient;
private HttpClientHandler clientHandler;
private CookieContainer cookies;

private const string BASE_URL = "https://sofiatraffic.bg";

public SofiaHttpClient()
{
cookies = new CookieContainer();
clientHandler = new HttpClientHandler() { CookieContainer = cookies };
httpClient = new HttpClient(clientHandler);
}

public async Task<HttpResponseMessage> PostAsync(string url, HttpContent content)
{
if (cookies.Count == 0)
{
await httpClient.GetAsync(BASE_URL);
}

Cookie token = cookies.GetAllCookies()["XSRF-TOKEN"];
if (token == null)
{
return null;
}

HttpRequestMessage request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = content,
RequestUri = new Uri(url)
};


request.Headers.Add("X-Xsrf-Token", Uri.UnescapeDataString(token.Value));
return await httpClient.SendAsync(request);
}

}
}
Loading

0 comments on commit 04b1ca1

Please sign in to comment.