Added Favorites to geocache.db (needs rework)
and more
This commit is contained in:
1 parent
c10d785bfa
commit
e48c22e0f7
5 files changed
+263
-36
No files matched your search
@@ -6,8 +6,19 @@ from geopy.adapters import AioHTTPAdapter
|
||||
from geopy.extra.rate_limiter import AsyncRateLimiter
|
||||
|
||||
logger = logging.getLogger("ios-api")
|
||||
CACHE_LOOKUP_SQL = "SELECT address FROM location_cache WHERE lat_lon = ?"
|
||||
CACHE_UPSERT_SQL = "INSERT OR REPLACE INTO location_cache VALUES (?, ?)"
|
||||
CACHE_LOOKUP_SQL = "SELECT address, favorite FROM location_cache WHERE lat_lon = ?"
|
||||
CACHE_UPSERT_SQL = """
|
||||
INSERT INTO location_cache (lat_lon, address)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(lat_lon) DO UPDATE SET address = excluded.address
|
||||
"""
|
||||
FAVORITE_LOOKUP_SQL = "SELECT favorite FROM location_cache WHERE favorite IS NOT NULL"
|
||||
FAVORITE_UPSERT_SQL = """
|
||||
INSERT INTO location_cache (lat_lon, favorite)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(lat_lon) DO UPDATE SET favorite = excluded.favorite
|
||||
"""
|
||||
FAVORITE_CLEAR_SQL = "UPDATE location_cache SET favorite = NULL WHERE lat_lon = ?"
|
||||
|
||||
|
||||
class AsyncReverseGeocoder:
|
||||
@@ -27,9 +38,15 @@ class AsyncReverseGeocoder:
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS location_cache (
|
||||
lat_lon TEXT PRIMARY KEY,
|
||||
address TEXT
|
||||
address TEXT,
|
||||
favorite TEXT
|
||||
|
||||
)
|
||||
''')
|
||||
cursor.execute("PRAGMA table_info(location_cache)")
|
||||
columns = {row[1] for row in cursor.fetchall()}
|
||||
if "favorite" not in columns:
|
||||
cursor.execute("ALTER TABLE location_cache ADD COLUMN favorite TEXT")
|
||||
conn.commit()
|
||||
|
||||
@staticmethod
|
||||
@@ -40,19 +57,65 @@ class AsyncReverseGeocoder:
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
cursor = conn.execute(CACHE_LOOKUP_SQL, (key,))
|
||||
row = cursor.fetchone()
|
||||
return json.loads(row[0]) if row else None
|
||||
cached = {}
|
||||
if row:
|
||||
cached['address'] = json.loads(row[0]) if row[0] else {}
|
||||
cached['favorite'] = json.loads(row[1]) if row[1] else {}
|
||||
return cached if row else None
|
||||
|
||||
def _store_cached_address(self, key: str, address_data: dict) -> None:
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(CACHE_UPSERT_SQL, (key, json.dumps(address_data)))
|
||||
conn.commit()
|
||||
|
||||
def _read_favorites(self) -> list | None:
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
cursor = conn.execute(FAVORITE_LOOKUP_SQL)
|
||||
rows = cursor.fetchall()
|
||||
favorites = [json.loads(row[0]) for row in rows if row[0]]
|
||||
return favorites if favorites else None
|
||||
|
||||
async def clear_favorite(self, lat: float, lon: float) -> bool:
|
||||
key = self._cache_key(lat, lon)
|
||||
cached = self._read_cached_address(key)
|
||||
if cached and cached.get("favorite"):
|
||||
favorite = cached.get("favorite")
|
||||
name = favorite.get("name") if isinstance(favorite, dict) else key
|
||||
logger.info("Clearing favorite %s", name)
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
cursor = conn.execute(FAVORITE_CLEAR_SQL, (key,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
else:
|
||||
return False
|
||||
|
||||
async def set_favorite(self, lat: float, lon: float, favorite_data: dict) -> bool:
|
||||
key = self._cache_key(lat, lon)
|
||||
name = favorite_data.get("name")
|
||||
if not name:
|
||||
return False
|
||||
logger.info("Setting favorite location %s to location_cache for %s", name, key)
|
||||
try:
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
conn.execute(FAVORITE_UPSERT_SQL, (key, json.dumps(favorite_data)))
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.Error as e:
|
||||
logger.exception("Failed to set favorite location %s to location_cache for %s: %s", name, key, e)
|
||||
return False
|
||||
|
||||
async def get_favorites(self) -> list | None:
|
||||
"""Reverse geocode with SQLite cache."""
|
||||
logger.info("Checking location_cache for favorites")
|
||||
favorites = self._read_favorites()
|
||||
return favorites
|
||||
|
||||
async def get_address(self, lat: float, lon: float) -> dict | None:
|
||||
"""Reverse geocode with SQLite cache."""
|
||||
key = self._cache_key(lat, lon)
|
||||
logger.info("Checking location_cache for %s", key)
|
||||
cached_address = self._read_cached_address(key)
|
||||
if cached_address is not None:
|
||||
logger.info("Found cached address for %s", key)
|
||||
return cached_address
|
||||
|
||||
async with Nominatim(
|
||||
@@ -64,10 +127,11 @@ class AsyncReverseGeocoder:
|
||||
geolocator.reverse, min_delay_seconds=1)
|
||||
location = await reverse(key)
|
||||
if location:
|
||||
response = {}
|
||||
logger.info("Nominatim response: %s", location)
|
||||
address_data = location.raw.get("address", {})
|
||||
self._store_cached_address(key, address_data)
|
||||
return address_data
|
||||
response['address'] = location.raw.get("address", {})
|
||||
self._store_cached_address(key, response['address'])
|
||||
return response
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception("Reverse geocoding failed for key=%s", key)
|
||||
|
||||
@@ -642,10 +642,8 @@ class TunneldRunnerSio:
|
||||
"command": "start",
|
||||
"message": "Simulation started",
|
||||
"data": {
|
||||
|
||||
"simulation_active": self.context.simulation_active,
|
||||
"simulation_queue_state": self.context.simulation_queue_state
|
||||
}
|
||||
"simulation_queue": get_simulation_status(),
|
||||
},
|
||||
}
|
||||
else:
|
||||
data = {
|
||||
@@ -654,9 +652,8 @@ class TunneldRunnerSio:
|
||||
"command": "start",
|
||||
"message": "Simulation already running",
|
||||
"data": {
|
||||
"simulation_active": self.context.simulation_active,
|
||||
"simulation_queue_state": self.context.simulation_queue_state
|
||||
}
|
||||
"simulation_queue": get_simulation_status(),
|
||||
},
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -763,6 +760,7 @@ class TunneldRunnerSio:
|
||||
{
|
||||
"type": "simulation_crash",
|
||||
"udid": self.context.udid,
|
||||
"udid": self.context.udid,
|
||||
"error": traceback.format_exc(),
|
||||
},
|
||||
namespace="/",
|
||||
@@ -885,7 +883,6 @@ class TunneldRunnerSio:
|
||||
"command": "delete",
|
||||
"message": f"Location {loc_id} deleted from the queue",
|
||||
"data": {
|
||||
"simulation_queue": get_simulation_status(),
|
||||
"simulation_queue": get_simulation_status(),
|
||||
"location_item": self.context.simulation_queue_data[loc_id],
|
||||
},
|
||||
@@ -1179,12 +1176,69 @@ class TunneldRunnerSio:
|
||||
else getattr(data, "longitude", 999)
|
||||
)
|
||||
if latitude != 999 and longitude != 999:
|
||||
coords = f"{latitude}, {longitude}"
|
||||
rev_geocode = await self.context.reverse_geocode.get_address(latitude, longitude)
|
||||
return rev_geocode
|
||||
else:
|
||||
return None
|
||||
|
||||
async def get_favorites():
|
||||
favorites = await self.context.reverse_geocode.get_favorites()
|
||||
return favorites
|
||||
|
||||
async def clear_favorite(data):
|
||||
latitude = float(
|
||||
data.get("latitude", 999)
|
||||
if isinstance(data, dict)
|
||||
else getattr(data, "latitude", 999)
|
||||
)
|
||||
longitude = float(
|
||||
data.get("longitude", 999)
|
||||
if isinstance(data, dict)
|
||||
else getattr(data, "longitude", 999)
|
||||
)
|
||||
if latitude != 999 and longitude != 999:
|
||||
clear_status = await self.context.reverse_geocode.clear_favorite(latitude, longitude)
|
||||
if clear_status:
|
||||
return "OK", "Favorite cleared"
|
||||
else:
|
||||
return "ERROR", "Failed to clear favorite"
|
||||
else:
|
||||
return "ERROR", "Invalid latitude and longitude"
|
||||
|
||||
async def set_favorite(data):
|
||||
favorite = (
|
||||
data.get("favorite")
|
||||
if isinstance(data, dict)
|
||||
else getattr(data, "favorite", None)
|
||||
)
|
||||
if favorite is not None:
|
||||
name = (
|
||||
favorite.get("name")
|
||||
if isinstance(favorite, dict)
|
||||
else getattr(favorite, "name", None)
|
||||
)
|
||||
logger.info("Adding favorite: %s", name)
|
||||
latitude = float(
|
||||
favorite.get("latitude", 999)
|
||||
if isinstance(favorite, dict)
|
||||
else getattr(favorite, "latitude", 999)
|
||||
)
|
||||
longitude = float(
|
||||
favorite.get("longitude", 999)
|
||||
if isinstance(favorite, dict)
|
||||
else getattr(favorite, "longitude", 999)
|
||||
)
|
||||
if latitude != 999 and longitude != 999 and favorite:
|
||||
set_status = await self.context.reverse_geocode.set_favorite(latitude, longitude, favorite)
|
||||
if set_status:
|
||||
return "OK", "Favorite added"
|
||||
else:
|
||||
return "ERROR", "Failed to add favorite"
|
||||
else:
|
||||
return "ERROR", "Invalid latitude and longitude"
|
||||
else:
|
||||
return "ERROR", "Invalid favorite data"
|
||||
|
||||
""" FastAPI HTTP Functions"""
|
||||
|
||||
def generate_http_response(
|
||||
@@ -1738,6 +1792,20 @@ class TunneldRunnerSio:
|
||||
}
|
||||
return resp
|
||||
|
||||
case "reset":
|
||||
""" Reset the simulation queue"""
|
||||
reset_queue()
|
||||
resp = {
|
||||
"command": command,
|
||||
"command_class": "simulation_control",
|
||||
"command_status": "OK",
|
||||
"message": "Simulation queue reset",
|
||||
"data": {
|
||||
"simulation_queue": get_simulation_status(),
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "pause":
|
||||
""" Pause the simulation queue"""
|
||||
await pause_simulation_queue()
|
||||
@@ -1751,6 +1819,7 @@ class TunneldRunnerSio:
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "resume":
|
||||
""" Resume the simulation queue"""
|
||||
await resume_simulation_queue()
|
||||
@@ -1764,6 +1833,7 @@ class TunneldRunnerSio:
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "end":
|
||||
""" End the simulation queue"""
|
||||
logger.info(
|
||||
@@ -1779,12 +1849,14 @@ class TunneldRunnerSio:
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "start":
|
||||
""" Start the simulation queue"""
|
||||
logger.info(
|
||||
"Start location simulation request from %s", sid)
|
||||
data = await start_simulation_queue()
|
||||
return data
|
||||
|
||||
case "gps-noise":
|
||||
""" Toggle GPS noise"""
|
||||
before_toggle = self.context.simulation_noise
|
||||
@@ -1952,6 +2024,27 @@ class TunneldRunnerSio:
|
||||
"command_status": "ERROR",
|
||||
"message": f"Error starting tunneld: {e}",
|
||||
}
|
||||
case "restart":
|
||||
"""Restart Tunneld"""
|
||||
logger.info("Restart tunneld request from %s: %s", sid, data)
|
||||
try:
|
||||
self._tunneld_core.clear()
|
||||
await asyncio.sleep(2)
|
||||
self._tunneld_core.start()
|
||||
return {
|
||||
"command_status": "OK",
|
||||
"command_class": "tunneld_control",
|
||||
"command": command,
|
||||
"message": "Tunneld started successfully",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error("Error restarting tunneld: %s", e)
|
||||
return {
|
||||
"command_status": "ERROR",
|
||||
"command_class": "tunneld_control",
|
||||
"command": command,
|
||||
"message": f"Error starting tunneld: {e}",
|
||||
}
|
||||
|
||||
case "start-watcher":
|
||||
""" Start Tunneld Watcher """
|
||||
@@ -2060,6 +2153,76 @@ class TunneldRunnerSio:
|
||||
rev_geocode = await get_reverse_geocode(data)
|
||||
return rev_geocode
|
||||
|
||||
@self.context.sio.event
|
||||
async def favorite_control(sid, data: dict):
|
||||
command = (
|
||||
data.get("command")
|
||||
if isinstance(data, dict)
|
||||
else getattr(data, "command", None)
|
||||
)
|
||||
logger.info(
|
||||
"Favorite Control command: %s requested from %s", command, sid
|
||||
)
|
||||
match command:
|
||||
case "set":
|
||||
""" Add a favorite location to database"""
|
||||
cstat, cmessage = await set_favorite(data)
|
||||
if cstat == "ERROR":
|
||||
logger.error('Favorite set failed: %s', cmessage)
|
||||
resp = {
|
||||
"command": command,
|
||||
"command_class": "favorite_control",
|
||||
"command_status": cstat,
|
||||
"message": cmessage,
|
||||
"data": {
|
||||
"favorites": await get_favorites(),
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "clear":
|
||||
""" Clear a favorite location from database"""
|
||||
cstat, cmessage = await clear_favorite(data)
|
||||
resp = {
|
||||
"command": command,
|
||||
"command_class": "favorite_control",
|
||||
"command_status": cstat,
|
||||
"message": cmessage,
|
||||
"data": {
|
||||
"favorites": await get_favorites(),
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case "get":
|
||||
""" Get favorite locations from database"""
|
||||
favs = await get_favorites()
|
||||
if favs:
|
||||
cstat = "OK"
|
||||
cmessage = "Favorites retrieved successfully"
|
||||
else:
|
||||
cstat = "ERROR"
|
||||
cmessage = "No favorites found"
|
||||
resp = {
|
||||
"command": command,
|
||||
"command_class": "favorite_control",
|
||||
"command_status": cstat,
|
||||
"message": cmessage,
|
||||
"data": {
|
||||
"favorites": favs,
|
||||
}
|
||||
}
|
||||
return resp
|
||||
|
||||
case _:
|
||||
return {
|
||||
"command": command,
|
||||
"command_class": "favorite_control",
|
||||
"command_status": "ERROR",
|
||||
"message": f"Invalid command: {command}",
|
||||
}
|
||||
|
||||
|
||||
|
||||
self._vue_app.include_router(self._app, prefix="/api")
|
||||
self._vue_app.mount(
|
||||
|
||||
Reference in new issue
Block a user