fix(map): support share.google domains and address geocoding fallback
- Add share.google and .google TLDs to allowed GOogle Maps domain whitelist - Accept optional fallback_query in resolve_google_maps_coordinates - Build geocoding candidate queries using address_lines and venue name when links lack embedded GPS coordinates - Pass venue location details to coordinate resolver across admin update and preview regeneration routes - Update test suite to verify share.google host validation and fallback parameter propagation
This commit is contained in:
1 parent
c8264b3d76
commit
c44ecfc14b
3 files changed
+54
-27
No files matched your search
@@ -166,7 +166,10 @@ async def update_admin_config(
|
||||
# Condition: Trigger generation ONLY if map_url was changed
|
||||
if current.map_url != update_in.map_url:
|
||||
try:
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(update_in.map_url)
|
||||
fallback = f"{update_in.address_lines}\n{update_in.address_name}"
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(
|
||||
update_in.map_url, fallback_query=fallback
|
||||
)
|
||||
await generate_map_preview_image(lat, lng)
|
||||
update_in.map_preview_url = f"{settings.BASE_PATH}/api/map-preview.png"
|
||||
except ValueError as err:
|
||||
@@ -202,9 +205,9 @@ async def regenerate_map_preview_endpoint(
|
||||
db: DbDep,
|
||||
payload: GenerateMapPreviewRequest | None = None,
|
||||
):
|
||||
current = get_config(db)
|
||||
target_url = payload.map_url.strip() if (payload and payload.map_url) else None
|
||||
if not target_url:
|
||||
current = get_config(db)
|
||||
if not current or not current.map_url:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -213,8 +216,12 @@ async def regenerate_map_preview_endpoint(
|
||||
target_url = current.map_url
|
||||
|
||||
try:
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(target_url)
|
||||
fallback = f"{current.address_lines}\n{current.address_name}" if current else None
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(
|
||||
target_url, fallback_query=fallback
|
||||
)
|
||||
await generate_map_preview_image(lat, lng)
|
||||
|
||||
timestamp = int(datetime.now(UTC).timestamp())
|
||||
return GenerateMapPreviewResponse(
|
||||
map_preview_url=f"{settings.BASE_PATH}/api/map-preview.png?t={timestamp}",
|
||||
|
||||
@@ -21,13 +21,13 @@ GOOGLE_MAPS_DOMAINS = (
|
||||
|
||||
|
||||
def is_google_maps_host(host: str) -> bool:
|
||||
"""Check if the hostname belongs to Google Maps or Goo.gl shortlinks."""
|
||||
"""Check if the hostname belongs to Google Maps, Google share links, or Goo.gl shortlinks."""
|
||||
clean_host = host.lower().strip()
|
||||
if clean_host in ("maps.app.goo.gl", "goo.gl"):
|
||||
if clean_host in ("maps.app.goo.gl", "goo.gl", "share.google"):
|
||||
return True
|
||||
if clean_host.startswith("maps.google."):
|
||||
return True
|
||||
if clean_host == "google.com" or clean_host.endswith(".google.com"):
|
||||
if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"):
|
||||
return True
|
||||
# Regional domains like google.es, google.co, google.com.co
|
||||
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host):
|
||||
@@ -86,7 +86,10 @@ def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
|
||||
return None
|
||||
|
||||
|
||||
async def resolve_google_maps_coordinates(map_url: str) -> tuple[float, float, str]:
|
||||
async def resolve_google_maps_coordinates(
|
||||
map_url: str,
|
||||
fallback_query: str | None = None,
|
||||
) -> tuple[float, float, str]:
|
||||
"""
|
||||
Validate and resolve a Google Maps URL, following redirects if necessary,
|
||||
and return (latitude, longitude, resolved_url).
|
||||
@@ -99,7 +102,7 @@ async def resolve_google_maps_coordinates(map_url: str) -> tuple[float, float, s
|
||||
if direct_coords:
|
||||
return direct_coords[0], direct_coords[1], clean_url
|
||||
|
||||
# Follow HTTP redirects to resolve short links (maps.app.goo.gl, etc.)
|
||||
# Follow HTTP redirects to resolve short links (maps.app.goo.gl, share.google, etc.)
|
||||
resolved_url = clean_url
|
||||
async with httpx.AsyncClient(
|
||||
follow_redirects=True,
|
||||
@@ -133,23 +136,39 @@ async def resolve_google_maps_coordinates(map_url: str) -> tuple[float, float, s
|
||||
place_part = parsed.path.split("/place/")[1].split("/")[0]
|
||||
query_text = unquote(place_part.replace("+", " "))
|
||||
|
||||
if query_text:
|
||||
# Attempt open geocoding with OpenStreetMap Nominatim
|
||||
# Build search candidates for geocoding
|
||||
candidates: list[str] = []
|
||||
clean_fallback = fallback_query.strip() if fallback_query else None
|
||||
|
||||
if query_text and clean_fallback:
|
||||
candidates.append(f"{query_text}, {clean_fallback}")
|
||||
if clean_fallback:
|
||||
for line in clean_fallback.splitlines():
|
||||
line_str = line.strip().strip(",")
|
||||
if line_str and line_str not in candidates:
|
||||
candidates.append(line_str)
|
||||
if clean_fallback not in candidates:
|
||||
candidates.append(clean_fallback)
|
||||
if query_text and query_text not in candidates:
|
||||
candidates.append(query_text)
|
||||
|
||||
if candidates:
|
||||
async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client:
|
||||
try:
|
||||
nom_res = await client.get(
|
||||
"https://nominatim.openstreetmap.org/search",
|
||||
params={"q": query_text, "format": "json", "limit": 1},
|
||||
)
|
||||
if nom_res.status_code == 200:
|
||||
results = nom_res.json()
|
||||
if results and isinstance(results, list) and len(results) > 0:
|
||||
lat = float(results[0]["lat"])
|
||||
lng = float(results[0]["lon"])
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng, resolved_url
|
||||
except Exception:
|
||||
pass
|
||||
for candidate in candidates:
|
||||
try:
|
||||
nom_res = await client.get(
|
||||
"https://nominatim.openstreetmap.org/search",
|
||||
params={"q": candidate, "format": "json", "limit": 1},
|
||||
)
|
||||
if nom_res.status_code == 200:
|
||||
results = nom_res.json()
|
||||
if results and isinstance(results, list) and len(results) > 0:
|
||||
lat = float(results[0]["lat"])
|
||||
lng = float(results[0]["lon"])
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng, resolved_url
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raise ValueError(
|
||||
"No se pudieron extraer las coordenadas de la URL de Google Maps. "
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -15,6 +15,7 @@ ADMIN_HEADERS = {"Remote-User": "kiskaadee"}
|
||||
|
||||
def test_is_google_maps_host():
|
||||
assert is_google_maps_host("maps.app.goo.gl")
|
||||
assert is_google_maps_host("share.google")
|
||||
assert is_google_maps_host("goo.gl")
|
||||
assert is_google_maps_host("maps.google.com")
|
||||
assert is_google_maps_host("google.com")
|
||||
@@ -90,7 +91,7 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
|
||||
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
|
||||
assert data["lat"] == 34.1432
|
||||
assert data["lng"] == -118.2551
|
||||
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2")
|
||||
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY)
|
||||
mock_generate.assert_called_once_with(34.1432, -118.2551)
|
||||
|
||||
|
||||
@@ -120,7 +121,7 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
|
||||
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
|
||||
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551")
|
||||
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY)
|
||||
mock_generate.assert_called_once_with(34.1432, -118.2551)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user