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
|
using System.Net;
using Enmarcha.Sources.OpenTripPlannerGql;
using Enmarcha.Sources.OpenTripPlannerGql.Queries;
using Enmarcha.Backend.Configuration;
using Enmarcha.Backend.Services;
using Enmarcha.Backend.Services.Geocoding;
using Enmarcha.Backend.Types.Planner;
using FuzzySharp;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace Enmarcha.Backend.Controllers;
[ApiController]
[Route("api/planner")]
public partial class RoutePlannerController : ControllerBase
{
private readonly ILogger<RoutePlannerController> _logger;
private readonly OtpService _otpService;
private readonly IGeocodingService _geocodingService;
private readonly AppConfiguration _config;
private readonly HttpClient _httpClient;
private readonly IMemoryCache _cache;
private readonly FeedService _feedService;
private const string GaliciaBounds = "-9.3,43.8,-6.7,41.7";
public RoutePlannerController(
ILogger<RoutePlannerController> logger,
OtpService otpService,
IGeocodingService geocodingService,
IOptions<AppConfiguration> config,
HttpClient httpClient,
IMemoryCache cache,
FeedService feedService
)
{
_logger = logger;
_otpService = otpService;
_geocodingService = geocodingService;
_config = config.Value;
_httpClient = httpClient;
_cache = cache;
_feedService = feedService;
}
[HttpGet("autocomplete")]
public async Task<ActionResult<List<PlannerSearchResult>>> Autocomplete([FromQuery] string query)
{
if (string.IsNullOrWhiteSpace(query))
{
return BadRequest("Query cannot be empty");
}
var nominatimTask = _geocodingService.GetAutocompleteAsync(query);
var stopsTask = GetCachedStopsAsync();
await Task.WhenAll(nominatimTask, stopsTask);
var geocodingResults = await nominatimTask;
var allStops = await stopsTask;
// 1. Exact or prefix matches by stop code
var codeMatches = allStops
.Where(s => s.StopCode != null && s.StopCode.StartsWith(query, StringComparison.OrdinalIgnoreCase))
.OrderBy(s => s.StopCode?.Length) // Shorter codes (more exact matches) first
.Take(5)
.ToList();
// 2. Fuzzy search stops by label (Name + Code)
var fuzzyResults = Process.ExtractSorted(
query,
allStops.Select(s => s.Label ?? string.Empty),
cutoff: 60
).Take(6).Select(r => allStops[r.Index]).ToList();
// Merge stops, prioritizing code matches
var stopResults = codeMatches.Concat(fuzzyResults)
.GroupBy(s => s.StopId)
.Select(g => g.First())
.Take(6)
.ToList();
// Merge results: geocoding first, then stops, deduplicating by coordinates (approx)
var finalResults = new List<PlannerSearchResult>(geocodingResults);
foreach (var res in stopResults)
{
if (!finalResults.Any(f => Math.Abs(f.Lat - res.Lat) < 0.00001 && Math.Abs(f.Lon - res.Lon) < 0.00001))
{
finalResults.Add(res);
}
}
return Ok(finalResults);
}
[HttpGet("reverse")]
public async Task<ActionResult<PlannerSearchResult>> Reverse([FromQuery] double lat, [FromQuery] double lon)
{
var result = await _geocodingService.GetReverseGeocodeAsync(lat, lon);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
[HttpGet("plan")]
public async Task<ActionResult<RoutePlan>> Plan(
[FromQuery] double fromLat,
[FromQuery] double fromLon,
[FromQuery] double toLat,
[FromQuery] double toLon,
[FromQuery] DateTimeOffset? time,
[FromQuery] bool arriveBy = false)
{
try
{
var requestContent = PlanConnectionContent.Query(
new PlanConnectionContent.Args(fromLat, fromLon, toLat, toLon, time ?? DateTimeOffset.Now, arriveBy)
);
var request = new HttpRequestMessage(HttpMethod.Post, $"{_config.OpenTripPlannerBaseUrl}/gtfs/v1");
request.Content = JsonContent.Create(new GraphClientRequest
{
Query = requestContent
});
var response = await _httpClient.SendAsync(request);
var responseBody = await response.Content.ReadFromJsonAsync<GraphClientResponse<PlanConnectionResponse>>();
if (responseBody is not { IsSuccess: true })
{
LogErrorFetchingRoutes(response.StatusCode, await response.Content.ReadAsStringAsync());
return StatusCode(500, "An error occurred while planning the route.");
}
var plan = _otpService.MapPlanResponse(responseBody.Data!);
return Ok(plan);
}
catch (Exception e)
{
_logger.LogError("Exception planning route: {e}", e);
return StatusCode(500, "An error occurred while planning the route.");
}
}
[LoggerMessage(LogLevel.Error, "Error fetching route planning, received {statusCode} {responseBody}")]
partial void LogErrorFetchingRoutes(HttpStatusCode? statusCode, string responseBody);
private async Task<List<PlannerSearchResult>> GetCachedStopsAsync()
{
const string cacheKey = "planner_mapped_stops";
if (_cache.TryGetValue(cacheKey, out List<PlannerSearchResult>? cachedStops))
{
return cachedStops!;
}
var allStopsRaw = await _otpService.GetStopsByBboxAsync(-9.3, 41.7, -6.7, 43.8);
var stops = allStopsRaw.Select(s =>
{
var feedId = s.GtfsId.Split(':')[0];
var name = FeedService.NormalizeStopName(feedId, s.Name);
var code = _feedService.NormalizeStopCode(feedId, s.Code ?? string.Empty);
return new PlannerSearchResult
{
Name = name,
Label = string.IsNullOrWhiteSpace(code) ? name : $"{name} ({code})",
Lat = s.Lat,
Lon = s.Lon,
Layer = "stop",
StopId = s.GtfsId,
StopCode = code
};
}).ToList();
_cache.Set(cacheKey, stops, TimeSpan.FromHours(1));
return stops;
}
}
|