1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
|
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Costasdev.VigoTransitApi;
using System.Text.Json;
using Costasdev.Busurbano.Backend.Types;
using Costasdev.VigoTransitApi.Types;
namespace Costasdev.Busurbano.Backend;
[ApiController]
[Route("api/vigo")]
public class VigoController : ControllerBase
{
private readonly VigoTransitApiClient _api;
private readonly IMemoryCache _cache;
private readonly HttpClient _httpClient;
public VigoController(HttpClient http, IMemoryCache cache)
{
_api = new VigoTransitApiClient(http);
_cache = cache;
_httpClient = http;
}
[HttpGet("GetStopEstimates")]
public async Task<IActionResult> Run(
[FromQuery] int id
)
{
try
{
var response = await _api.GetStopEstimates(id);
// Return only the estimates array, not the stop metadata
return new OkObjectResult(response.Estimates);
}
catch (InvalidOperationException)
{
return BadRequest("Stop not found");
}
}
[HttpGet("GetStopTimetable")]
public async Task<IActionResult> GetStopTimetable(
[FromQuery] int stopId,
[FromQuery] string date
)
{
// Validate date format
if (!DateTime.TryParseExact(date, "yyyy-MM-dd", null, DateTimeStyles.None, out _))
{
return BadRequest("Invalid date format. Please use yyyy-MM-dd format.");
}
// Create cache key
var cacheKey = $"timetable_{date}_{stopId}";
// Try to get from cache first
if (_cache.TryGetValue(cacheKey, out var cachedData))
{
Response.Headers.Append("App-CacheUsage", "HIT");
return new OkObjectResult(cachedData);
}
try
{
var timetableData = await LoadTimetable(stopId.ToString(), date);
// Cache the data for 12 hours
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12),
SlidingExpiration = TimeSpan.FromHours(6), // Refresh cache if accessed within 6 hours of expiry
Priority = CacheItemPriority.Normal
};
_cache.Set(cacheKey, timetableData, cacheOptions);
Response.Headers.Append("App-CacheUsage", "MISS");
return new OkObjectResult(timetableData);
}
catch (HttpRequestException ex)
{
return StatusCode((int?)ex.StatusCode ?? 500, $"Error fetching timetable data: {ex.Message}");
}
catch (JsonException ex)
{
return StatusCode(500, $"Error parsing timetable data: {ex.Message}");
}
catch (Exception ex)
{
return StatusCode(500, $"Unexpected error: {ex.Message}");
}
}
/*private StopEstimate[] LoadDebugEstimates()
{
var file = @"C:\Users\ariel\Desktop\GetStopEstimates.json";
var contents = System.IO.File.ReadAllText(file);
return JsonSerializer.Deserialize<StopEstimate[]>(contents, JsonSerializerOptions.Web)!;
}
private ScheduledStop[] LoadDebugTimetable()
{
var file = @"C:\Users\ariel\Desktop\GetStopTimetable.json";
var contents = System.IO.File.ReadAllText(file);
return JsonSerializer.Deserialize<ScheduledStop[]>(contents)!;
}*/
[HttpGet("GetStopArrivalsMerged")]
public async Task<IActionResult> GetStopArrivalsMerged(
[FromQuery] int stopId
)
{
StringBuilder outputBuffer = new();
var now = DateTime.Now.AddSeconds(60 - DateTime.Now.Second);
var realtimeTask = _api.GetStopEstimates(stopId);
var timetableTask = LoadTimetable(stopId.ToString(), now.ToString("yyyy-MM-dd"));
Task.WaitAll(realtimeTask, timetableTask);
var realTimeEstimates = realtimeTask.Result.Estimates;
var timetable = timetableTask.Result;
/*var now = DateTime.Today.AddHours(17).AddMinutes(59);
var realTimeEstimates = LoadDebugEstimates();
var timetable = LoadDebugTimetable();*/
foreach (var estimate in realTimeEstimates)
{
outputBuffer.AppendLine($"Parsing estimate with line={estimate.Line}, route={estimate.Route} and minutes={estimate.Minutes} - Arrives at {now.AddMinutes(estimate.Minutes):HH:mm}");
var fullArrivalTime = now.AddMinutes(estimate.Minutes);
var possibleCirculations = timetable
.Where(c => c.Line.Name.Trim() == estimate.Line.Trim() && c.Trip.Headsign.Trim() == estimate.Route.Trim())
.OrderBy(c => c.DepartureDateTime())
.ToArray();
outputBuffer.AppendLine($"Found {possibleCirculations.Length} potential circulations");
ScheduledStop? closestCirculation = null;
int closestCirculationTime = int.MaxValue;
foreach (var circulation in possibleCirculations)
{
var diffBetweenScheduleAndTrip = (int)Math.Round((fullArrivalTime - circulation.DepartureDateTime()).TotalMinutes);
var diffBetweenNowAndSchedule = (int)(fullArrivalTime - now).TotalMinutes;
var tolerance = Math.Max(2, diffBetweenNowAndSchedule * 0.15); // Positive amount of minutes
if (diffBetweenScheduleAndTrip <= -tolerance)
{
break;
}
if (diffBetweenScheduleAndTrip < closestCirculationTime)
{
closestCirculation = circulation;
closestCirculationTime = diffBetweenScheduleAndTrip;
}
}
if (closestCirculation == null)
{
outputBuffer.AppendLine("**No circulation matched. List of all of them:**");
foreach (var circulation in possibleCirculations)
{
// Circulation A 03LP000_008003_16 stopping at 05/11/2025 22:06:00 (diff: -03:29:59.2644092)
outputBuffer.AppendLine($"Circulation {circulation.Trip.Id} stopping at {circulation.DepartureDateTime()} (diff: {fullArrivalTime - circulation.DepartureDateTime():HH:mm})");
}
outputBuffer.AppendLine();
continue;
}
if (closestCirculationTime > 0)
{
outputBuffer.Append($"Closest circulation is {closestCirculation.Trip.Id} and arriving {closestCirculationTime} minutes LATE");
}
else if (closestCirculationTime == 0)
{
outputBuffer.Append($"Closest circulation is {closestCirculation.Trip.Id} and arriving ON TIME");
}
else
{
outputBuffer.Append($"Closest circulation is {closestCirculation.Trip.Id} and arriving {Math.Abs(closestCirculationTime)} minutes EARLY");
}
outputBuffer.AppendLine(
$" -- Circulation expected at {closestCirculation.DepartureDateTime():HH:mm)}");
outputBuffer.AppendLine();
}
return Ok(outputBuffer.ToString());
}
private async Task<List<ScheduledStop>> LoadTimetable(string stopId, string dateString)
{
var url = $"https://www.costas.dev/static-storage/vitrasa_svc/stops/{dateString}/{stopId}.json";
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var jsonContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<ScheduledStop>>(jsonContent) ?? [];
}
}
|