Looking good. Db querying works
This commit is contained in:
@@ -7,18 +7,31 @@ handshaking functionality with configurable supported actions and capabilities.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import difflib
|
||||
import json
|
||||
import inspect
|
||||
import re
|
||||
from typing import Dict, List, Optional, Any, Union, Tuple, Type
|
||||
from xml.etree import ElementTree as ET
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum, IntEnum
|
||||
|
||||
from .generated.alpinebits import OtaPingRq, OtaPingRs, WarningStatus
|
||||
from .generated.alpinebits import OtaPingRq, OtaPingRs, WarningStatus, OtaReadRq
|
||||
from xsdata_pydantic.bindings import XmlSerializer
|
||||
from xsdata.formats.dataclass.serializers.config import SerializerConfig
|
||||
from abc import ABC, abstractmethod
|
||||
from xsdata_pydantic.bindings import XmlParser
|
||||
import logging
|
||||
from .db import Reservation, Customer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
class HttpStatusCode(IntEnum):
|
||||
@@ -122,7 +135,7 @@ class AlpineBitsAction(ABC):
|
||||
) # list of versions in case action supports multiple versions
|
||||
|
||||
async def handle(
|
||||
self, action: str, request_xml: str, version: Version
|
||||
self, action: str, request_xml: str, version: Version, dbsession=None, server_capabilities=None, username=None, password=None, config: Dict = None
|
||||
) -> AlpineBitsResponse:
|
||||
"""
|
||||
Handle the incoming request XML and return response XML.
|
||||
@@ -251,12 +264,13 @@ class ServerCapabilities:
|
||||
class PingAction(AlpineBitsAction):
|
||||
"""Implementation for OTA_Ping action (handshaking)."""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, config: Dict = None):
|
||||
self.name = AlpineBitsActionName.OTA_PING
|
||||
self.version = [
|
||||
Version.V2024_10,
|
||||
Version.V2022_10,
|
||||
] # Supports multiple versions
|
||||
self.config = config
|
||||
|
||||
async def handle(
|
||||
self,
|
||||
@@ -291,6 +305,8 @@ class PingAction(AlpineBitsAction):
|
||||
|
||||
# compare echo data with capabilities, create a dictionary containing the matching capabilities
|
||||
capabilities_dict = server_capabilities.get_capabilities_dict()
|
||||
|
||||
_LOGGER.info(f"Capabilities Dict: {capabilities_dict}")
|
||||
matching_capabilities = {"versions": []}
|
||||
|
||||
# Iterate through client's requested versions
|
||||
@@ -339,10 +355,12 @@ class PingAction(AlpineBitsAction):
|
||||
|
||||
warning_response = OtaPingRs.Warnings(warning=[warning])
|
||||
|
||||
all_capabilities = server_capabilities.get_capabilities_json()
|
||||
|
||||
response_ota_ping = OtaPingRs(
|
||||
version="7.000",
|
||||
warnings=warning_response,
|
||||
echo_data=capabilities_json,
|
||||
echo_data=all_capabilities,
|
||||
success="",
|
||||
)
|
||||
|
||||
@@ -357,51 +375,164 @@ class PingAction(AlpineBitsAction):
|
||||
)
|
||||
|
||||
return AlpineBitsResponse(response_xml, HttpStatusCode.OK)
|
||||
def strip_control_chars(s):
|
||||
# Remove all control characters (ASCII < 32 and DEL)
|
||||
return re.sub(r'[\x00-\x1F\x7F]', '', s)
|
||||
|
||||
def validate_hotel_authentication(username: str, password: str, hotelid: str, config: Dict) -> bool:
|
||||
""" Validate hotel authentication based on username, password, and hotel ID.
|
||||
|
||||
Example config
|
||||
alpine_bits_auth:
|
||||
- hotel_id: "123"
|
||||
hotel_name: "Frangart Inn"
|
||||
username: "alice"
|
||||
password: !secret ALICE_PASSWORD
|
||||
"""
|
||||
|
||||
if not config or "alpine_bits_auth" not in config:
|
||||
return False
|
||||
auth_list = config["alpine_bits_auth"]
|
||||
for auth in auth_list:
|
||||
if (
|
||||
auth.get("hotel_id") == hotelid
|
||||
and auth.get("username") == username
|
||||
and auth.get("password") == password
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
# look for hotelid in config
|
||||
|
||||
|
||||
|
||||
|
||||
class ReadAction(AlpineBitsAction):
|
||||
"""Implementation for OTA_Read action."""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, config: Dict = None):
|
||||
self.name = AlpineBitsActionName.OTA_READ
|
||||
self.version = [Version.V2024_10, Version.V2022_10]
|
||||
self.config = config
|
||||
|
||||
async def handle(
|
||||
self, action: str, request_xml: str, version: Version
|
||||
self, action: str, request_xml: str, version: Version, dbsession=None, username=None, password=None
|
||||
) -> AlpineBitsResponse:
|
||||
"""Handle read requests."""
|
||||
response_xml = f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<OTA_ReadRS xmlns="http://www.opentravel.org/OTA/2003/05" Version="8.000">
|
||||
<Success/>
|
||||
<Data>Read operation successful for {version.value}</Data>
|
||||
</OTA_ReadRS>"""
|
||||
return AlpineBitsResponse(response_xml, HttpStatusCode.OK)
|
||||
|
||||
clean_action = strip_control_chars(str(action)).strip()
|
||||
clean_expected = strip_control_chars(self.name.value[1]).strip()
|
||||
|
||||
if clean_action != clean_expected:
|
||||
|
||||
return AlpineBitsResponse(
|
||||
f"Error: Invalid action {action}, expected {self.name.value[1]}", HttpStatusCode.BAD_REQUEST
|
||||
)
|
||||
|
||||
if dbsession is None:
|
||||
return AlpineBitsResponse(
|
||||
"Error: Something went wrong", HttpStatusCode.INTERNAL_SERVER_ERROR
|
||||
)
|
||||
|
||||
read_request = XmlParser().from_string(request_xml, OtaReadRq)
|
||||
|
||||
hotel_read_request = read_request.read_requests.hotel_read_request
|
||||
|
||||
hotelid = hotel_read_request.hotel_code
|
||||
hotelname = hotel_read_request.hotel_name
|
||||
|
||||
if hotelname is None:
|
||||
hotelname = "unknown"
|
||||
|
||||
if username is None or password is None or hotelid is None:
|
||||
return AlpineBitsResponse(
|
||||
f"Error: Unauthorized Read Request for this specific hotel {hotelname}. Check credentials", HttpStatusCode.UNAUTHORIZED
|
||||
)
|
||||
|
||||
if not validate_hotel_authentication(username, password, hotelid, self.config):
|
||||
return AlpineBitsResponse(
|
||||
f"Error: Unauthorized Read Request for this specific hotel {hotelname}. Check credentials", HttpStatusCode.UNAUTHORIZED
|
||||
)
|
||||
|
||||
start_date = None
|
||||
|
||||
if hotel_read_request.selection_criteria is not None:
|
||||
start_date = datetime.fromisoformat(hotel_read_request.selection_criteria.start)
|
||||
|
||||
|
||||
class HotelAvailNotifAction(AlpineBitsAction):
|
||||
"""Implementation for Hotel Availability Notification action with supports."""
|
||||
|
||||
def __init__(self):
|
||||
self.name = AlpineBitsActionName.OTA_HOTEL_AVAIL_NOTIF
|
||||
self.version = Version.V2022_10
|
||||
self.supports = [
|
||||
"OTA_HotelAvailNotif_accept_rooms",
|
||||
"OTA_HotelAvailNotif_accept_categories",
|
||||
"OTA_HotelAvailNotif_accept_deltas",
|
||||
"OTA_HotelAvailNotif_accept_BookingThreshold",
|
||||
]
|
||||
# query all reservations for this hotel from the database, where start_date is greater than or equal to the given start_date
|
||||
|
||||
async def handle(
|
||||
self, action: str, request_xml: str, version: Version
|
||||
) -> AlpineBitsResponse:
|
||||
"""Handle hotel availability notifications."""
|
||||
stmt = (
|
||||
select(Reservation, Customer)
|
||||
.join(Customer, Reservation.customer_id == Customer.id)
|
||||
.filter(Reservation.hotel_code == hotelid)
|
||||
)
|
||||
if start_date:
|
||||
stmt = stmt.filter(Reservation.start_date >= start_date)
|
||||
|
||||
result = await dbsession.execute(stmt)
|
||||
reservation_customer_pairs: list[tuple[Reservation, Customer]] = result.all() # List of (Reservation, Customer) tuples
|
||||
|
||||
_LOGGER.info(f"Querying reservations and customers for hotel {hotelid} from database")
|
||||
for reservation, customer in reservation_customer_pairs:
|
||||
_LOGGER.info(f"Reservation: {reservation.id}, Customer: {customer.given_name}")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# For demonstration, just echo back a simple XML response
|
||||
response_xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<OTA_HotelAvailNotifRS xmlns="http://www.opentravel.org/OTA/2003/05" Version="8.000">
|
||||
<Success/>
|
||||
</OTA_HotelAvailNotifRS>"""
|
||||
<OTA_ReadRS xmlns="http://www.opentravel.org/OTA/2003/
|
||||
05" Version="8.000">
|
||||
<Success/>
|
||||
</OTA_ReadRS>"""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return AlpineBitsResponse(response_xml, HttpStatusCode.OK)
|
||||
|
||||
|
||||
# class HotelAvailNotifAction(AlpineBitsAction):
|
||||
# """Implementation for Hotel Availability Notification action with supports."""
|
||||
|
||||
# def __init__(self):
|
||||
# self.name = AlpineBitsActionName.OTA_HOTEL_AVAIL_NOTIF
|
||||
# self.version = Version.V2022_10
|
||||
# self.supports = [
|
||||
# "OTA_HotelAvailNotif_accept_rooms",
|
||||
# "OTA_HotelAvailNotif_accept_categories",
|
||||
# "OTA_HotelAvailNotif_accept_deltas",
|
||||
# "OTA_HotelAvailNotif_accept_BookingThreshold",
|
||||
# ]
|
||||
|
||||
# async def handle(
|
||||
# self, action: str, request_xml: str, version: Version
|
||||
# ) -> AlpineBitsResponse:
|
||||
# """Handle hotel availability notifications."""
|
||||
# response_xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
# <OTA_HotelAvailNotifRS xmlns="http://www.opentravel.org/OTA/2003/05" Version="8.000">
|
||||
# <Success/>
|
||||
# </OTA_HotelAvailNotifRS>"""
|
||||
# return AlpineBitsResponse(response_xml, HttpStatusCode.OK)
|
||||
|
||||
|
||||
class GuestRequestsAction(AlpineBitsAction):
|
||||
"""Unimplemented action - will not appear in capabilities."""
|
||||
|
||||
@@ -421,15 +552,17 @@ class AlpineBitsServer:
|
||||
their capabilities, and can respond to handshake requests with its capabilities.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, config: Dict = None):
|
||||
self.capabilities = ServerCapabilities()
|
||||
self._action_instances = {}
|
||||
self.config = config
|
||||
self._initialize_action_instances()
|
||||
|
||||
|
||||
def _initialize_action_instances(self):
|
||||
"""Initialize instances of all discovered action classes."""
|
||||
for capability_name, action_class in self.capabilities.action_registry.items():
|
||||
self._action_instances[capability_name] = action_class()
|
||||
self._action_instances[capability_name] = action_class(config=self.config)
|
||||
|
||||
def get_capabilities(self) -> Dict:
|
||||
"""Get server capabilities."""
|
||||
@@ -440,7 +573,7 @@ class AlpineBitsServer:
|
||||
return self.capabilities.get_capabilities_json()
|
||||
|
||||
async def handle_request(
|
||||
self, request_action_name: str, request_xml: str, version: str = "2024-10"
|
||||
self, request_action_name: str, request_xml: str, version: str = "2024-10", dbsession=None, username=None, password=None
|
||||
) -> AlpineBitsResponse:
|
||||
"""
|
||||
Handle an incoming AlpineBits request by routing to appropriate action handler.
|
||||
@@ -495,7 +628,7 @@ class AlpineBitsServer:
|
||||
)
|
||||
else:
|
||||
return await action_instance.handle(
|
||||
request_action_name, request_xml, version_enum
|
||||
request_action_name, request_xml, version_enum, dbsession=dbsession, username=username, password=password
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error handling request {request_action_name}: {str(e)}")
|
||||
|
||||
Reference in New Issue
Block a user