-
Notifications
You must be signed in to change notification settings - Fork 16
Improve handling of overflowing timestamps #83
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2b998d1
Improve handling of overflowing timestamps
bdraco 3f9a93a
Update onvif/types.py
bdraco 31f2b52
fixes
bdraco e691e9d
Merge remote-tracking branch 'origin/invalid_datetime' into invalid_d…
bdraco e8e23b5
coverage
bdraco e22637b
coverage
bdraco 7f6afd0
coverage
bdraco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,90 @@ | ||
"""ONVIF types.""" | ||
|
||
from datetime import datetime, timedelta, time | ||
import ciso8601 | ||
from zeep.xsd.types.builtins import DateTime, treat_whitespace | ||
from zeep.xsd.types.builtins import DateTime, treat_whitespace, Time | ||
import isodate | ||
|
||
|
||
def _try_parse_datetime(value: str) -> datetime | None: | ||
try: | ||
return ciso8601.parse_datetime(value) | ||
except ValueError: | ||
pass | ||
|
||
try: | ||
return isodate.parse_datetime(value) | ||
except ValueError: | ||
pass | ||
|
||
return None | ||
|
||
|
||
def _try_fix_time_overflow(time: str) -> tuple[str, dict[str, int]]: | ||
offset: dict[str, int] = {} | ||
hour = int(time[0:2]) | ||
if hour > 23: | ||
offset["hours"] = hour - 23 | ||
hour = 23 | ||
minute = int(time[3:5]) | ||
if minute > 59: | ||
offset["minutes"] = minute - 59 | ||
minute = 59 | ||
second = int(time[6:8]) | ||
if second > 59: | ||
offset["seconds"] = second - 59 | ||
second = 59 | ||
time_trailer = time[8:] | ||
return f"{hour:02d}:{minute:02d}:{second:02d}{time_trailer}", offset | ||
|
||
|
||
# see https://github.com/mvantellingen/python-zeep/pull/1370 | ||
class FastDateTime(DateTime): | ||
"""Fast DateTime that supports timestamps with - instead of T.""" | ||
|
||
@treat_whitespace("collapse") | ||
def pythonvalue(self, value): | ||
def pythonvalue(self, value: str) -> datetime: | ||
"""Convert the xml value into a python value.""" | ||
if len(value) > 10 and value[10] == "-": # 2010-01-01-00:00:00... | ||
value[10] = "T" | ||
if len(value) > 10 and value[11] == "-": # 2023-05-15T-07:10:32Z... | ||
value = value[:11] + value[12:] | ||
# Determine based on the length of the value if it only contains a date | ||
# lazy hack ;-) | ||
if len(value) == 10: | ||
value += "T00:00:00" | ||
elif (len(value) == 19 or len(value) == 26) and value[10] == " ": | ||
value = "T".join(value.split(" ")) | ||
|
||
if dt := _try_parse_datetime(value): | ||
return dt | ||
|
||
# Some cameras overflow the hours/minutes/seconds | ||
# For example, 2024-08-17T00:61:16Z so we need | ||
# to fix the overflow | ||
date, _, time = value.partition("T") | ||
fixed_time, offset = _try_fix_time_overflow(time) | ||
if dt := _try_parse_datetime(f"{date}T{fixed_time}"): | ||
return dt + timedelta(**offset) | ||
|
||
return ciso8601.parse_datetime(value) | ||
|
||
|
||
class ForgivingTime(Time): | ||
"""ForgivingTime.""" | ||
|
||
@treat_whitespace("collapse") | ||
def pythonvalue(self, value: str) -> time: | ||
try: | ||
return ciso8601.parse_datetime(value) | ||
return isodate.parse_time(value) | ||
except ValueError: | ||
pass | ||
|
||
return super().pythonvalue(value) | ||
# Some cameras overflow the hours/minutes/seconds | ||
# For example, 2024-08-17T00:61:16Z so we need | ||
# to fix the overflow | ||
fixed_time, offset = _try_fix_time_overflow(value) | ||
try: | ||
return isodate.parse_time(fixed_time) + timedelta(**offset) | ||
except ValueError: | ||
return isodate.parse_time(value) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
[tool.black] | ||
target-version = ["py36", "py37", "py38"] | ||
exclude = 'generated' | ||
[tool.pytest.ini_options] | ||
pythonpath = ["onvif"] | ||
log_cli="true" | ||
log_level="NOTSET" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from __future__ import annotations | ||
|
||
import os | ||
|
||
import pytest | ||
from zeep.loader import parse_xml | ||
import datetime | ||
from onvif.client import ONVIFCamera | ||
from onvif.settings import DEFAULT_SETTINGS | ||
from onvif.transport import ASYNC_TRANSPORT | ||
|
||
INVALID_TERM_TIME = b'<?xml version="1.0" encoding="UTF-8"?>\r\n<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:tev="http://www.onvif.org/ver10/events/wsdl" xmlns:wsnt="http://docs.oasis-open.org/wsn/b-2" xmlns:wsa5="http://www.w3.org/2005/08/addressing" xmlns:chan="http://schemas.microsoft.com/ws/2005/02/duplex" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:tt="http://www.onvif.org/ver10/schema" xmlns:tns1="http://www.onvif.org/ver10/topics">\r\n<SOAP-ENV:Header>\r\n<wsa5:Action>http://www.onvif.org/ver10/events/wsdl/PullPointSubscription/PullMessagesResponse</wsa5:Action>\r\n</SOAP-ENV:Header>\r\n<SOAP-ENV:Body>\r\n<tev:PullMessagesResponse>\r\n<tev:CurrentTime>2024-08-17T00:56:16Z</tev:CurrentTime>\r\n<tev:TerminationTime>2024-08-17T00:61:16Z</tev:TerminationTime>\r\n</tev:PullMessagesResponse>\r\n</SOAP-ENV:Body>\r\n</SOAP-ENV:Envelope>\r\n' | ||
_WSDL_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "onvif", "wsdl") | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_parse_invalid_time(caplog: pytest.LogCaptureFixture) -> None: | ||
device = ONVIFCamera("127.0.0.1", 80, "user", "pass", wsdl_dir=_WSDL_PATH) | ||
device.xaddrs = { | ||
"http://www.onvif.org/ver10/events/wsdl": "http://192.168.210.102:6688/onvif/event_service" | ||
} | ||
# Create subscription manager | ||
subscription = await device.create_notification_service() | ||
operation = subscription.document.bindings[subscription.binding_name].get( | ||
"Subscribe" | ||
) | ||
envelope = parse_xml( | ||
INVALID_TERM_TIME, # type: ignore[arg-type] | ||
ASYNC_TRANSPORT, | ||
settings=DEFAULT_SETTINGS, | ||
) | ||
result = operation.process_reply(envelope) | ||
assert result.CurrentTime == datetime.datetime( | ||
2024, 8, 17, 0, 56, 16, tzinfo=datetime.timezone.utc | ||
) | ||
assert result.TerminationTime == datetime.datetime( | ||
2024, 8, 17, 1, 1, 16, tzinfo=datetime.timezone.utc | ||
) | ||
assert "ValueError" not in caplog.text |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.