Skip to content

Fix ONVIF camera connection issues by disabling aiohttp auto-decompression #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 29 additions & 41 deletions onvif/zeep_aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@
from zeep.transports import Transport
from zeep.utils import get_version
from zeep.wsdl.utils import etree_to_string
from multidict import CIMultiDict
import httpx
from aiohttp import ClientResponse, ClientSession, hdrs
from aiohttp import ClientResponse, ClientSession
from requests import Response
from requests.structures import CaseInsensitiveDict

Expand Down Expand Up @@ -66,23 +65,14 @@ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
async def aclose(self) -> None:
"""Close the transport session."""

def _filter_headers(self, headers: CIMultiDict[str]) -> list[tuple[str, str]]:
"""Filter out Content-Encoding header.

Since aiohttp has already decompressed the content, we need to
remove the Content-Encoding header to prevent zeep from trying
to decompress it again, which would cause a zlib error.
"""
return [(k, v) for k, v in headers.items() if k != hdrs.CONTENT_ENCODING]

def _aiohttp_to_httpx_response(
self, aiohttp_response: ClientResponse, content: bytes
) -> httpx.Response:
"""Convert aiohttp ClientResponse to httpx Response."""
# Create httpx Response with the content
httpx_response = httpx.Response(
status_code=aiohttp_response.status,
headers=httpx.Headers(self._filter_headers(aiohttp_response.headers)),
headers=httpx.Headers(aiohttp_response.headers),
content=content,
request=httpx.Request(
method=aiohttp_response.method,
Expand Down Expand Up @@ -115,9 +105,7 @@ def _aiohttp_to_requests_response(
new._content = content
new.status_code = aiohttp_response.status
# Use dict comprehension for requests.Response headers
new.headers = CaseInsensitiveDict(
self._filter_headers(aiohttp_response.headers)
)
new.headers = CaseInsensitiveDict(aiohttp_response.headers)
# Convert aiohttp cookies to requests format
if aiohttp_response.cookies:
for name, cookie in aiohttp_response.cookies.items():
Expand Down Expand Up @@ -148,24 +136,24 @@ async def _post_internal(
data = message

try:
response = await self.session.post(
async with self.session.post(
address,
data=data,
headers=headers,
proxy=self.proxy,
timeout=self._client_timeout,
)

# Read the content to log it before checking status
content = await response.read()
_LOGGER.debug(
"HTTP Response from %s (status: %d):\n%s",
address,
response.status,
content,
)
auto_decompress=False, # Let zeep handle decompression
) as response:
# Read the content to log it before checking status
content = await response.read()
_LOGGER.debug(
"HTTP Response from %s (status: %d):\n%s",
address,
response.status,
content,
)

return response, content
return response, content
except RuntimeError as exc:
# Handle RuntimeError which may occur if the session is closed
raise RuntimeError(f"Failed to post to {address}: {exc}") from exc
Expand Down Expand Up @@ -234,26 +222,26 @@ async def get(
headers.setdefault("User-Agent", f"Zeep/{get_version()}")

try:
response = await self.session.get(
async with self.session.get(
address,
params=params,
headers=headers,
proxy=self.proxy,
timeout=self._client_timeout,
)

# Read content and log before checking status
content = await response.read()

_LOGGER.debug(
"HTTP Response from %s (status: %d):\n%s",
address,
response.status,
content,
)
auto_decompress=False, # Let zeep handle decompression
) as response:
# Read content and log before checking status
content = await response.read()

_LOGGER.debug(
"HTTP Response from %s (status: %d):\n%s",
address,
response.status,
content,
)

# Convert directly to requests.Response
return self._aiohttp_to_requests_response(response, content)
# Convert directly to requests.Response
return self._aiohttp_to_requests_response(response, content)
except RuntimeError as exc:
# Handle RuntimeError which may occur if the session is closed
raise RuntimeError(f"Failed to get from {address}: {exc}") from exc
Expand Down
Loading