Skip to content

Commit

Permalink
fix: use dateparser to parse dates
Browse files Browse the repository at this point in the history
  • Loading branch information
firstof9 committed Feb 12, 2024
1 parent ce2870d commit f5992b5
Show file tree
Hide file tree
Showing 14 changed files with 26 additions and 48 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pytest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ jobs:
strategy:
matrix:
python-version:
- "3.9"
- "3.10"
- "3.11"
- "3.12"

steps:
- uses: actions/checkout@v2
Expand Down
1 change: 1 addition & 0 deletions custom_components/mail_and_packages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Mail and Packages Integration."""

import asyncio
import logging
from datetime import timedelta
Expand Down
1 change: 1 addition & 0 deletions custom_components/mail_and_packages/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Binary sensors for Mail and Packages."""

import logging
import os

Expand Down
1 change: 1 addition & 0 deletions custom_components/mail_and_packages/camera.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Camera that loads a picture from a local file."""

from __future__ import annotations

import logging
Expand Down
1 change: 1 addition & 0 deletions custom_components/mail_and_packages/const.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Constants for Mail and Packages."""

from __future__ import annotations

from typing import Final
Expand Down
1 change: 1 addition & 0 deletions custom_components/mail_and_packages/diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Provide diagnostics for Mail and Packages."""

from __future__ import annotations

import logging
Expand Down
38 changes: 4 additions & 34 deletions custom_components/mail_and_packages/helpers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Helper functions for Mail and Packages."""

from __future__ import annotations

import base64
import datetime
import email
import hashlib
import imaplib
import locale
import logging
import os
import quopri
Expand All @@ -19,6 +19,7 @@
from typing import Any, List, Optional, Type, Union

import aiohttp
import dateparser
from bs4 import BeautifulSoup
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
Expand Down Expand Up @@ -46,7 +47,6 @@
AMAZON_HUB_SUBJECT,
AMAZON_HUB_SUBJECT_SEARCH,
AMAZON_IMG_PATTERN,
AMAZON_LANGS,
AMAZON_ORDER,
AMAZON_PACKAGES,
AMAZON_PATTERN,
Expand Down Expand Up @@ -1290,36 +1290,6 @@ def amazon_date_format(arrive_date: str, lang: str) -> tuple:
return (arrive_date, "%A, %B %d")


def amazon_date_lang(arrive_date: str) -> datetime.datetime | None:
"""Return the datetime for the date based on language."""
time_format = None
new_arrive_date = None
dateobj = None

for lang in AMAZON_LANGS:
try:
locale.setlocale(locale.LC_TIME, lang)
except Exception as err:
_LOGGER.debug("Locale error: %s (%s)", err, lang)
continue

_LOGGER.debug("Arrive Date: %s", arrive_date)
new_arrive_date, time_format = amazon_date_format(arrive_date, lang)

try:
dateobj = datetime.datetime.strptime(new_arrive_date, time_format)
_LOGGER.debug("Valid date format found.")
break
except ValueError as err:
_LOGGER.debug(
"Invalid date format found for language %s. (%s)",
lang,
err,
)
continue
return dateobj


def get_items(
account: Type[imaplib.IMAP4_SSL],
param: str = None,
Expand Down Expand Up @@ -1425,8 +1395,8 @@ def get_items(
arrive_date = arrive_date[0:3]
arrive_date = " ".join(arrive_date).strip()

# Loop through all the langs for date format
dateobj = amazon_date_lang(arrive_date)
# Get the date object
dateobj = dateparser.parse(arrive_date)

if (
dateobj is not None
Expand Down
3 changes: 2 additions & 1 deletion custom_components/mail_and_packages/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"integration_type": "service",
"requirements": [
"beautifulsoup4",
"Pillow>=9.0"
"Pillow>=9.0",
"dateparser"
],
"iot_class": "cloud_polling",
"version": "0.0.0-dev"
Expand Down
3 changes: 2 additions & 1 deletion custom_components/mail_and_packages/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
https://blog.kalavala.net/usps/homeassistant/mqtt/2018/01/12/usps.html
Configuration code contribution from @firstof9 https://github.com/firstof9/
"""

import datetime
import logging
from datetime import timezone
Expand All @@ -15,10 +16,10 @@
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import (
AMAZON_DELIVERED,
AMAZON_EXCEPTION,
AMAZON_EXCEPTION_ORDER,
AMAZON_ORDER,
AMAZON_DELIVERED,
ATTR_IMAGE,
ATTR_IMAGE_NAME,
ATTR_IMAGE_PATH,
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Pillow>=9.0
beautifulsoup4
beautifulsoup4
dateparser
1 change: 1 addition & 0 deletions requirements_test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ pytest-asyncio==0.20.2
pytest-cov==3.0.0
pytest-homeassistant-custom-component
homeassistant
freezegun
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[mypy]
python_version = 3.8
python_version = 3.12
show_error_codes = true
ignore_errors = true
follow_imports = silent
Expand Down
11 changes: 5 additions & 6 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for helpers module."""
import datetime
import errno
from freezegun import freeze_time
from datetime import date, timezone
from unittest import mock
from unittest.mock import call, mock_open, patch
Expand Down Expand Up @@ -792,13 +793,11 @@ async def test_royal_out_for_delivery(hass, mock_imap_royal_out_for_delivery):
assert result["tracking"] == ["MA038501234GB"]


@freeze_time("2020-09-11")
@pytest.mark.asyncio
async def test_amazon_shipped_count(hass, mock_imap_amazon_shipped):
with patch("datetime.date") as mock_date:
mock_date.today.return_value = date(2020, 9, 11)

result = get_items(mock_imap_amazon_shipped, "count")
assert result == 1
result = get_items(mock_imap_amazon_shipped, "count")
assert result == 1


@pytest.mark.asyncio
Expand Down Expand Up @@ -1185,4 +1184,4 @@ async def test_email_search_none(mock_imap_search_error_none, caplog):
async def test_amazon_shipped_fwd(hass, mock_imap_amazon_fwd, caplog):
result = get_items(mock_imap_amazon_fwd, "order")
assert result == ["123-1234567-1234567"]
assert "Arrive Date: Tuesday, January 11" in caplog.text
assert "First pass: Tuesday, January 11" in caplog.text
4 changes: 2 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ ignore_basepython_conflict = True

[gh-actions]
python =
3.9: py39
3.10: py310, lint, mypy
3.11: py311
3.10: py312, lint, mypy

[testenv]
pip_version = pip>=21.0,<22.1
Expand Down

0 comments on commit f5992b5

Please sign in to comment.