Skip to content

Commit

Permalink
Refactor. Since parse_datetime() is used only on api responses anyway.
Browse files Browse the repository at this point in the history
  • Loading branch information
ping committed Jul 21, 2023
1 parent 9cba8c4 commit 90fd7fb
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 27 deletions.
22 changes: 20 additions & 2 deletions odmpy/libby.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
from urllib import request
from urllib.parse import urljoin

from .utils import parse_datetime

if sys.version_info >= (3, 8):
from typing import TypedDict
Expand Down Expand Up @@ -624,6 +623,25 @@ def is_open_ebook_loan(book: Dict) -> bool:
]
)

@staticmethod
def parse_datetime(value: str) -> datetime: # type: ignore[return]
"""
Parses a datetime string from the API into a datetime.
:param value:
:return:
"""
formats = ("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ")
for i, fmt in enumerate(formats, start=1):
try:
dt = datetime.strptime(value, fmt)
if not dt.tzinfo:
dt = dt.replace(tzinfo=timezone.utc)
return dt
except ValueError:
if i == len(formats):
raise

@staticmethod
def is_renewable(loan: Dict) -> bool:
"""
Expand All @@ -635,7 +653,7 @@ def is_renewable(loan: Dict) -> bool:
if not loan.get("renewableOn"):
raise ValueError("Unable to get renewable date")
# Example: 2023-02-23T07:33:55Z
renewable_on = parse_datetime(loan["renewableOn"])
renewable_on = LibbyClient.parse_datetime(loan["renewableOn"])
return renewable_on <= datetime.utcnow().replace(tzinfo=timezone.utc)

def get_loans(self) -> List[Dict]:
Expand Down
8 changes: 5 additions & 3 deletions odmpy/odm.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
init_session,
extract_authors_from_openbook,
)
from .utils import slugify, plural_or_singular_noun as ps, parse_datetime
from .utils import slugify, plural_or_singular_noun as ps

#
# Orchestrates the interaction between the CLI, APIs and the processing bits
Expand Down Expand Up @@ -1002,7 +1002,7 @@ def run(custom_args: Optional[List[str]] = None, be_quiet: bool = False) -> None
ps(len(libby_loans), "loan"),
)
for index, loan in enumerate(libby_loans, start=1):
expiry_date = parse_datetime(loan["expireDate"])
expiry_date = LibbyClient.parse_datetime(loan["expireDate"])
hold = next(
iter(
[
Expand All @@ -1013,7 +1013,9 @@ def run(custom_args: Optional[List[str]] = None, be_quiet: bool = False) -> None
),
None,
)
hold_date = parse_datetime(hold["placedDate"]) if hold else None
hold_date = (
LibbyClient.parse_datetime(hold["placedDate"]) if hold else None
)

logger.info(
"%s: %-55s %s %-25s \n * %s %s%s",
Expand Down
8 changes: 5 additions & 3 deletions odmpy/processing/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@

from ..constants import PERFORMER_FID, LANGUAGE_FID
from ..errors import OdmpyRuntimeError
from ..libby import USER_AGENT, LibbyFormats
from ..utils import slugify, sanitize_path, is_windows, parse_datetime
from ..libby import USER_AGENT, LibbyFormats, LibbyClient
from ..utils import slugify, sanitize_path, is_windows


#
Expand Down Expand Up @@ -918,7 +918,9 @@ def build_opf_package(
and loan_format == LibbyFormats.MagazineOverDrive
and media_info.get("estimatedReleaseDate")
):
est_release_date = parse_datetime(media_info["estimatedReleaseDate"])
est_release_date = LibbyClient.parse_datetime(
media_info["estimatedReleaseDate"]
)
reading_order = f"{est_release_date:%y%j}" # use release date to construct a pseudo reading order

if reading_order:
Expand Down
19 changes: 0 additions & 19 deletions odmpy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,6 @@
}


def parse_datetime(value: str) -> datetime: # type: ignore[return]
"""
Parses a datetime string from the API into a datetime.
:param value:
:return:
"""
formats = ("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ")
for i, fmt in enumerate(formats, start=1):
try:
dt = datetime.strptime(value, fmt)
if not dt.tzinfo:
dt = dt.replace(tzinfo=timezone.utc)
return dt
except ValueError:
if i == len(formats):
raise


def guess_mimetype(url: str) -> Optional[str]:
"""
Attempt to guess the mimetype for a given url
Expand Down

0 comments on commit 90fd7fb

Please sign in to comment.