2021-03-08 16:49:10 +00:00
|
|
|
""" functionality outline for a book data connector """
|
2023-07-28 15:43:32 +00:00
|
|
|
from __future__ import annotations
|
2020-03-07 20:22:28 +00:00
|
|
|
from abc import ABC, abstractmethod
|
2023-07-28 15:43:32 +00:00
|
|
|
from typing import Optional, TypedDict, Any, Callable, Union, Iterator
|
2023-02-02 20:02:57 +00:00
|
|
|
from urllib.parse import quote_plus
|
2024-03-02 23:59:17 +00:00
|
|
|
|
|
|
|
# pylint: disable-next=deprecated-module
|
2024-03-03 01:31:16 +00:00
|
|
|
import imghdr # Deprecated in 3.11 for removal in 3.13; no good alternative yet
|
2020-12-30 17:14:07 +00:00
|
|
|
import logging
|
2022-05-30 17:15:22 +00:00
|
|
|
import re
|
2023-04-04 16:01:53 +00:00
|
|
|
import asyncio
|
2023-04-04 16:46:32 +00:00
|
|
|
import requests
|
|
|
|
from requests.exceptions import RequestException
|
|
|
|
import aiohttp
|
2020-03-07 20:22:28 +00:00
|
|
|
|
2022-02-02 05:18:25 +00:00
|
|
|
from django.core.files.base import ContentFile
|
2020-05-10 19:56:59 +00:00
|
|
|
from django.db import transaction
|
|
|
|
|
2020-12-30 11:35:11 +00:00
|
|
|
from bookwyrm import activitypub, models, settings
|
2023-04-04 16:46:32 +00:00
|
|
|
from bookwyrm.settings import USER_AGENT
|
2022-05-30 17:15:22 +00:00
|
|
|
from .connector_manager import load_more_data, ConnectorException, raise_not_valid_url
|
2021-09-29 19:21:19 +00:00
|
|
|
from .format_mappings import format_mappings
|
2023-07-28 15:43:32 +00:00
|
|
|
from ..book_search import SearchResult
|
2020-03-07 20:22:28 +00:00
|
|
|
|
2020-12-30 17:14:07 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2021-03-08 16:49:10 +00:00
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
JsonDict = dict[str, Any]
|
|
|
|
|
2021-03-08 16:49:10 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
class ConnectorResults(TypedDict):
|
|
|
|
"""TypedDict for results returned by connector"""
|
|
|
|
|
|
|
|
connector: AbstractMinimalConnector
|
2023-07-28 18:54:03 +00:00
|
|
|
results: list[SearchResult]
|
2023-07-28 15:43:32 +00:00
|
|
|
|
|
|
|
|
2020-11-29 02:56:28 +00:00
|
|
|
class AbstractMinimalConnector(ABC):
|
2021-04-26 16:15:42 +00:00
|
|
|
"""just the bare bones, for other bookwyrm instances"""
|
2021-03-08 16:49:10 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def __init__(self, identifier: str):
|
2020-03-07 20:22:28 +00:00
|
|
|
# load connector settings
|
2020-03-27 23:36:52 +00:00
|
|
|
info = models.Connector.objects.get(identifier=identifier)
|
2020-03-28 23:01:02 +00:00
|
|
|
self.connector = info
|
2020-03-07 20:22:28 +00:00
|
|
|
|
2020-05-10 23:41:24 +00:00
|
|
|
# the things in the connector model to copy over
|
2023-07-28 15:43:32 +00:00
|
|
|
self.base_url = info.base_url
|
|
|
|
self.books_url = info.books_url
|
|
|
|
self.covers_url = info.covers_url
|
|
|
|
self.search_url = info.search_url
|
|
|
|
self.isbn_search_url = info.isbn_search_url
|
|
|
|
self.name = info.name
|
|
|
|
self.identifier = info.identifier
|
|
|
|
|
|
|
|
def get_search_url(self, query: str) -> str:
|
2022-05-30 17:34:03 +00:00
|
|
|
"""format the query url"""
|
2022-05-30 17:15:22 +00:00
|
|
|
# Check if the query resembles an ISBN
|
2022-05-30 17:34:03 +00:00
|
|
|
if maybe_isbn(query) and self.isbn_search_url and self.isbn_search_url != "":
|
2022-08-28 01:05:40 +00:00
|
|
|
# Up-case the ISBN string to ensure any 'X' check-digit is correct
|
|
|
|
# If the ISBN has only 9 characters, prepend missing zero
|
2022-08-28 07:30:46 +00:00
|
|
|
normalized_query = query.strip().upper().rjust(10, "0")
|
2022-08-28 07:28:00 +00:00
|
|
|
return f"{self.isbn_search_url}{normalized_query}"
|
2022-05-30 17:15:22 +00:00
|
|
|
# NOTE: previously, we tried searching isbn and if that produces no results,
|
|
|
|
# searched as free text. This, instead, only searches isbn if it's isbn-y
|
2023-02-02 20:02:57 +00:00
|
|
|
return f"{self.search_url}{quote_plus(query)}"
|
2022-05-30 17:15:22 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def process_search_response(
|
|
|
|
self, query: str, data: Any, min_confidence: float
|
|
|
|
) -> list[SearchResult]:
|
2023-04-04 15:13:11 +00:00
|
|
|
"""Format the search results based on the format of the query"""
|
2022-05-30 17:34:03 +00:00
|
|
|
if maybe_isbn(query):
|
2022-05-30 23:42:37 +00:00
|
|
|
return list(self.parse_isbn_search_data(data))[:10]
|
|
|
|
return list(self.parse_search_data(data, min_confidence))[:10]
|
2021-04-07 01:00:54 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
async def get_results(
|
|
|
|
self,
|
|
|
|
session: aiohttp.ClientSession,
|
|
|
|
url: str,
|
|
|
|
min_confidence: float,
|
|
|
|
query: str,
|
|
|
|
) -> Optional[ConnectorResults]:
|
2023-04-04 16:01:53 +00:00
|
|
|
"""try this specific connector"""
|
|
|
|
# pylint: disable=line-too-long
|
|
|
|
headers = {
|
|
|
|
"Accept": (
|
|
|
|
'application/json, application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"; charset=utf-8'
|
|
|
|
),
|
|
|
|
"User-Agent": USER_AGENT,
|
|
|
|
}
|
|
|
|
params = {"min_confidence": min_confidence}
|
|
|
|
try:
|
|
|
|
async with session.get(url, headers=headers, params=params) as response:
|
|
|
|
if not response.ok:
|
|
|
|
logger.info("Unable to connect to %s: %s", url, response.reason)
|
2023-07-28 15:43:32 +00:00
|
|
|
return None
|
2023-04-04 16:46:32 +00:00
|
|
|
|
2023-04-04 16:01:53 +00:00
|
|
|
try:
|
|
|
|
raw_data = await response.json()
|
|
|
|
except aiohttp.client_exceptions.ContentTypeError as err:
|
|
|
|
logger.exception(err)
|
2023-07-28 15:43:32 +00:00
|
|
|
return None
|
2023-04-04 16:46:32 +00:00
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
return ConnectorResults(
|
|
|
|
connector=self,
|
|
|
|
results=self.process_search_response(
|
2023-04-04 16:01:53 +00:00
|
|
|
query, raw_data, min_confidence
|
|
|
|
),
|
2023-07-28 18:54:03 +00:00
|
|
|
)
|
2023-04-04 16:01:53 +00:00
|
|
|
except asyncio.TimeoutError:
|
|
|
|
logger.info("Connection timed out for url: %s", url)
|
|
|
|
except aiohttp.ClientError as err:
|
|
|
|
logger.info(err)
|
2023-07-28 15:43:32 +00:00
|
|
|
return None
|
2023-04-04 16:01:53 +00:00
|
|
|
|
2020-11-29 02:56:28 +00:00
|
|
|
@abstractmethod
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_or_create_book(self, remote_id: str) -> Optional[models.Book]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""pull up a book record by whatever means possible"""
|
2020-11-29 02:56:28 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
2023-07-28 15:43:32 +00:00
|
|
|
def parse_search_data(
|
|
|
|
self, data: Any, min_confidence: float
|
|
|
|
) -> Iterator[SearchResult]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""turn the result json from a search into a list"""
|
2020-11-29 02:56:28 +00:00
|
|
|
|
2021-03-01 20:09:21 +00:00
|
|
|
@abstractmethod
|
2023-07-28 15:43:32 +00:00
|
|
|
def parse_isbn_search_data(self, data: Any) -> Iterator[SearchResult]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""turn the result json from a search into a list"""
|
2021-03-01 20:09:21 +00:00
|
|
|
|
2020-11-29 02:56:28 +00:00
|
|
|
|
|
|
|
class AbstractConnector(AbstractMinimalConnector):
|
2021-04-26 16:15:42 +00:00
|
|
|
"""generic book data connector"""
|
2021-03-08 16:49:10 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
generated_remote_link_field = ""
|
|
|
|
|
|
|
|
def __init__(self, identifier: str):
|
2020-11-29 02:56:28 +00:00
|
|
|
super().__init__(identifier)
|
|
|
|
# fields we want to look for in book data to copy over
|
|
|
|
# title we handle separately.
|
2023-07-28 15:43:32 +00:00
|
|
|
self.book_mappings: list[Mapping] = []
|
|
|
|
self.author_mappings: list[Mapping] = []
|
2020-11-29 02:56:28 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_or_create_book(self, remote_id: str) -> Optional[models.Book]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""translate arbitrary json into an Activitypub dataclass"""
|
2020-12-19 22:56:03 +00:00
|
|
|
# first, check if we have the origin_id saved
|
2021-03-08 16:49:10 +00:00
|
|
|
existing = models.Edition.find_existing_by_remote_id(
|
|
|
|
remote_id
|
|
|
|
) or models.Work.find_existing_by_remote_id(remote_id)
|
2020-12-19 22:56:03 +00:00
|
|
|
if existing:
|
2023-07-28 15:43:32 +00:00
|
|
|
if hasattr(existing, "default_edition") and isinstance(
|
|
|
|
existing.default_edition, models.Edition
|
|
|
|
):
|
2021-04-28 22:19:24 +00:00
|
|
|
return existing.default_edition
|
2020-12-19 22:56:03 +00:00
|
|
|
return existing
|
|
|
|
|
2021-12-05 20:37:19 +00:00
|
|
|
# load the json data from the remote data source
|
2021-04-06 19:29:06 +00:00
|
|
|
data = self.get_book_data(remote_id)
|
2020-05-10 19:56:59 +00:00
|
|
|
if self.is_work_data(data):
|
|
|
|
try:
|
2020-12-19 22:56:03 +00:00
|
|
|
edition_data = self.get_edition_from_work_data(data)
|
2021-02-10 20:00:16 +00:00
|
|
|
except (KeyError, ConnectorException):
|
2020-05-10 19:56:59 +00:00
|
|
|
# hack: re-use the work data as the edition data
|
|
|
|
# this is why remote ids aren't necessarily unique
|
2020-12-20 00:14:05 +00:00
|
|
|
edition_data = data
|
2021-04-30 22:48:52 +00:00
|
|
|
work_data = data
|
2020-05-10 19:56:59 +00:00
|
|
|
else:
|
2020-12-20 00:14:05 +00:00
|
|
|
edition_data = data
|
2021-04-28 23:33:40 +00:00
|
|
|
try:
|
|
|
|
work_data = self.get_work_from_edition_data(data)
|
2021-06-18 21:12:56 +00:00
|
|
|
except (KeyError, ConnectorException) as err:
|
2022-03-11 22:31:04 +00:00
|
|
|
logger.info(err)
|
2021-04-30 22:48:52 +00:00
|
|
|
work_data = data
|
2021-04-28 23:33:40 +00:00
|
|
|
|
|
|
|
if not work_data or not edition_data:
|
2021-09-18 18:32:00 +00:00
|
|
|
raise ConnectorException(f"Unable to load book data: {remote_id}")
|
2020-10-29 00:16:16 +00:00
|
|
|
|
2021-01-02 15:45:45 +00:00
|
|
|
with transaction.atomic():
|
2021-04-28 23:33:40 +00:00
|
|
|
# create activitypub object
|
2021-04-30 22:48:52 +00:00
|
|
|
work_activity = activitypub.Work(
|
|
|
|
**dict_from_mappings(work_data, self.book_mappings)
|
|
|
|
)
|
2021-04-28 23:33:40 +00:00
|
|
|
# this will dedupe automatically
|
2021-08-17 17:08:07 +00:00
|
|
|
work = work_activity.to_model(model=models.Work, overwrite=False)
|
2023-07-28 15:43:32 +00:00
|
|
|
if not work:
|
|
|
|
return None
|
|
|
|
|
2021-04-30 22:48:52 +00:00
|
|
|
for author in self.get_authors_from_data(work_data):
|
2021-01-02 15:45:45 +00:00
|
|
|
work.authors.add(author)
|
|
|
|
|
|
|
|
edition = self.create_edition_from_data(work, edition_data)
|
|
|
|
load_more_data.delay(self.connector.id, work.id)
|
|
|
|
return edition
|
2020-05-08 23:56:49 +00:00
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
def get_book_data(self, remote_id: str) -> JsonDict: # pylint: disable=no-self-use
|
2021-04-26 21:43:29 +00:00
|
|
|
"""this allows connectors to override the default behavior"""
|
2021-04-06 19:29:06 +00:00
|
|
|
return get_data(remote_id)
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def create_edition_from_data(
|
|
|
|
self,
|
|
|
|
work: models.Work,
|
2023-07-28 18:54:03 +00:00
|
|
|
edition_data: Union[str, JsonDict],
|
2023-07-28 15:43:32 +00:00
|
|
|
instance: Optional[models.Edition] = None,
|
|
|
|
) -> Optional[models.Edition]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""if we already have the work, we're ready"""
|
2023-07-28 15:43:32 +00:00
|
|
|
if isinstance(edition_data, str):
|
|
|
|
# We don't expect a string here
|
|
|
|
return None
|
|
|
|
|
2020-12-20 00:14:05 +00:00
|
|
|
mapped_data = dict_from_mappings(edition_data, self.book_mappings)
|
2021-03-08 16:49:10 +00:00
|
|
|
mapped_data["work"] = work.remote_id
|
2020-12-20 00:14:05 +00:00
|
|
|
edition_activity = activitypub.Edition(**mapped_data)
|
2021-12-05 20:37:19 +00:00
|
|
|
edition = edition_activity.to_model(
|
|
|
|
model=models.Edition, overwrite=False, instance=instance
|
|
|
|
)
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
if not edition:
|
|
|
|
return None
|
|
|
|
|
2021-12-05 20:37:19 +00:00
|
|
|
# if we're updating an existing instance, we don't need to load authors
|
|
|
|
if instance:
|
|
|
|
return edition
|
|
|
|
|
|
|
|
if not edition.connector:
|
|
|
|
edition.connector = self.connector
|
|
|
|
edition.save(broadcast=False, update_fields=["connector"])
|
2020-05-09 19:09:40 +00:00
|
|
|
|
2020-12-20 00:14:05 +00:00
|
|
|
for author in self.get_authors_from_data(edition_data):
|
2020-12-19 22:56:03 +00:00
|
|
|
edition.authors.add(author)
|
2021-12-05 20:37:19 +00:00
|
|
|
# use the authors from the work if none are found for the edition
|
2020-12-20 00:14:05 +00:00
|
|
|
if not edition.authors.exists() and work.authors.exists():
|
2020-12-21 19:47:47 +00:00
|
|
|
edition.authors.set(work.authors.all())
|
2020-05-08 23:56:49 +00:00
|
|
|
|
2020-12-19 22:56:03 +00:00
|
|
|
return edition
|
2020-05-10 19:56:59 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_or_create_author(
|
|
|
|
self, remote_id: str, instance: Optional[models.Author] = None
|
|
|
|
) -> Optional[models.Author]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""load that author"""
|
2021-12-05 21:24:40 +00:00
|
|
|
if not instance:
|
|
|
|
existing = models.Author.find_existing_by_remote_id(remote_id)
|
|
|
|
if existing:
|
|
|
|
return existing
|
2020-12-19 23:20:31 +00:00
|
|
|
|
2021-04-06 19:29:06 +00:00
|
|
|
data = self.get_book_data(remote_id)
|
2020-12-19 23:20:31 +00:00
|
|
|
|
2020-12-20 00:14:05 +00:00
|
|
|
mapped_data = dict_from_mappings(data, self.author_mappings)
|
2021-04-07 15:59:33 +00:00
|
|
|
try:
|
|
|
|
activity = activitypub.Author(**mapped_data)
|
|
|
|
except activitypub.ActivitySerializerError:
|
|
|
|
return None
|
|
|
|
|
2020-12-19 23:20:31 +00:00
|
|
|
# this will dedupe
|
2021-12-05 20:37:19 +00:00
|
|
|
return activity.to_model(
|
|
|
|
model=models.Author, overwrite=False, instance=instance
|
|
|
|
)
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_remote_id_from_model(self, obj: models.BookDataModel) -> Optional[str]:
|
2021-12-05 21:38:15 +00:00
|
|
|
"""given the data stored, how can we look this up"""
|
2023-07-28 15:43:32 +00:00
|
|
|
remote_id: Optional[str] = getattr(obj, self.generated_remote_link_field)
|
|
|
|
return remote_id
|
2021-12-05 21:38:15 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def update_author_from_remote(self, obj: models.Author) -> Optional[models.Author]:
|
2021-12-05 20:37:19 +00:00
|
|
|
"""load the remote data from this connector and add it to an existing author"""
|
2021-12-05 21:38:15 +00:00
|
|
|
remote_id = self.get_remote_id_from_model(obj)
|
2023-07-28 15:43:32 +00:00
|
|
|
if not remote_id:
|
|
|
|
return None
|
2021-12-05 20:37:19 +00:00
|
|
|
return self.get_or_create_author(remote_id, instance=obj)
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def update_book_from_remote(self, obj: models.Edition) -> Optional[models.Edition]:
|
2021-12-05 20:37:19 +00:00
|
|
|
"""load the remote data from this connector and add it to an existing book"""
|
2021-12-05 21:38:15 +00:00
|
|
|
remote_id = self.get_remote_id_from_model(obj)
|
2023-07-28 15:43:32 +00:00
|
|
|
if not remote_id:
|
|
|
|
return None
|
2021-12-05 20:37:19 +00:00
|
|
|
data = self.get_book_data(remote_id)
|
|
|
|
return self.create_edition_from_data(obj.parent_work, data, instance=obj)
|
2020-10-31 00:04:10 +00:00
|
|
|
|
2020-05-10 19:56:59 +00:00
|
|
|
@abstractmethod
|
2023-07-28 18:54:03 +00:00
|
|
|
def is_work_data(self, data: JsonDict) -> bool:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""differentiate works and editions"""
|
2020-05-10 19:56:59 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
2023-07-28 18:54:03 +00:00
|
|
|
def get_edition_from_work_data(self, data: JsonDict) -> JsonDict:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""every work needs at least one edition"""
|
2020-05-10 19:56:59 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
2023-07-28 18:54:03 +00:00
|
|
|
def get_work_from_edition_data(self, data: JsonDict) -> JsonDict:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""every edition needs a work"""
|
2020-05-09 19:53:55 +00:00
|
|
|
|
2020-05-09 19:09:40 +00:00
|
|
|
@abstractmethod
|
2023-07-28 18:54:03 +00:00
|
|
|
def get_authors_from_data(self, data: JsonDict) -> Iterator[models.Author]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""load author data"""
|
2020-05-09 19:09:40 +00:00
|
|
|
|
2020-04-02 05:11:31 +00:00
|
|
|
@abstractmethod
|
2023-07-28 15:43:32 +00:00
|
|
|
def expand_book_data(self, book: models.Book) -> None:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""get more info on a book"""
|
2020-04-02 05:11:31 +00:00
|
|
|
|
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
def dict_from_mappings(data: JsonDict, mappings: list[Mapping]) -> JsonDict:
|
2021-03-08 16:49:10 +00:00
|
|
|
"""create a dict in Activitypub format, using mappings supplies by
|
|
|
|
the subclass"""
|
2023-07-28 18:54:03 +00:00
|
|
|
result: JsonDict = {}
|
2020-12-19 23:20:31 +00:00
|
|
|
for mapping in mappings:
|
2021-04-30 19:50:35 +00:00
|
|
|
# sometimes there are multiple mappings for one field, don't
|
|
|
|
# overwrite earlier writes in that case
|
|
|
|
if mapping.local_field in result and result[mapping.local_field]:
|
|
|
|
continue
|
2020-12-19 23:20:31 +00:00
|
|
|
result[mapping.local_field] = mapping.get_value(data)
|
|
|
|
return result
|
2020-03-30 00:40:51 +00:00
|
|
|
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_data(
|
|
|
|
url: str,
|
|
|
|
params: Optional[dict[str, str]] = None,
|
|
|
|
timeout: int = settings.QUERY_TIMEOUT,
|
2023-07-28 18:54:03 +00:00
|
|
|
) -> JsonDict:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""wrapper for request.get"""
|
2021-04-10 18:38:57 +00:00
|
|
|
# check if the url is blocked
|
2022-02-03 23:11:01 +00:00
|
|
|
raise_not_valid_url(url)
|
|
|
|
|
2020-10-29 21:29:31 +00:00
|
|
|
try:
|
|
|
|
resp = requests.get(
|
|
|
|
url,
|
2021-03-13 16:52:36 +00:00
|
|
|
params=params,
|
2021-10-26 21:37:43 +00:00
|
|
|
headers={ # pylint: disable=line-too-long
|
|
|
|
"Accept": (
|
2021-12-14 21:47:09 +00:00
|
|
|
'application/json, application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"; charset=utf-8'
|
2021-10-26 21:37:43 +00:00
|
|
|
),
|
2021-03-08 16:49:10 +00:00
|
|
|
"User-Agent": settings.USER_AGENT,
|
2020-10-29 21:29:31 +00:00
|
|
|
},
|
2021-06-17 19:34:54 +00:00
|
|
|
timeout=timeout,
|
2020-10-29 21:29:31 +00:00
|
|
|
)
|
2021-06-20 16:23:57 +00:00
|
|
|
except RequestException as err:
|
2022-03-11 22:31:04 +00:00
|
|
|
logger.info(err)
|
2021-12-14 21:47:09 +00:00
|
|
|
raise ConnectorException(err)
|
2021-02-10 19:56:08 +00:00
|
|
|
|
2020-05-09 19:39:58 +00:00
|
|
|
if not resp.ok:
|
2023-01-20 08:55:38 +00:00
|
|
|
if resp.status_code == 401:
|
|
|
|
# this is probably an AUTHORIZED_FETCH issue
|
|
|
|
resp.raise_for_status()
|
|
|
|
else:
|
|
|
|
raise ConnectorException()
|
2020-12-03 21:42:02 +00:00
|
|
|
try:
|
|
|
|
data = resp.json()
|
2021-06-18 21:12:56 +00:00
|
|
|
except ValueError as err:
|
2022-03-11 22:31:04 +00:00
|
|
|
logger.info(err)
|
2021-12-14 21:47:09 +00:00
|
|
|
raise ConnectorException(err)
|
2020-12-03 21:42:02 +00:00
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
if not isinstance(data, dict):
|
|
|
|
raise ConnectorException("Unexpected data format")
|
|
|
|
|
|
|
|
return data
|
2020-05-09 19:39:58 +00:00
|
|
|
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def get_image(
|
|
|
|
url: str, timeout: int = 10
|
|
|
|
) -> Union[tuple[ContentFile[bytes], str], tuple[None, None]]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""wrapper for requesting an image"""
|
2022-02-03 23:11:01 +00:00
|
|
|
raise_not_valid_url(url)
|
2020-11-29 17:40:15 +00:00
|
|
|
try:
|
2020-12-30 11:35:11 +00:00
|
|
|
resp = requests.get(
|
|
|
|
url,
|
|
|
|
headers={
|
2021-03-08 16:49:10 +00:00
|
|
|
"User-Agent": settings.USER_AGENT,
|
2020-12-30 11:35:11 +00:00
|
|
|
},
|
2021-06-17 19:34:54 +00:00
|
|
|
timeout=timeout,
|
2020-12-30 11:35:11 +00:00
|
|
|
)
|
2021-06-20 16:23:57 +00:00
|
|
|
except RequestException as err:
|
2022-03-11 22:31:04 +00:00
|
|
|
logger.info(err)
|
2022-02-02 15:09:35 +00:00
|
|
|
return None, None
|
2022-02-02 05:18:25 +00:00
|
|
|
|
2020-11-29 17:40:15 +00:00
|
|
|
if not resp.ok:
|
2022-02-02 15:09:35 +00:00
|
|
|
return None, None
|
2022-02-02 05:18:25 +00:00
|
|
|
|
|
|
|
image_content = ContentFile(resp.content)
|
|
|
|
extension = imghdr.what(None, image_content.read())
|
|
|
|
if not extension:
|
2022-03-11 22:31:04 +00:00
|
|
|
logger.info("File requested was not an image: %s", url)
|
2022-02-02 15:09:35 +00:00
|
|
|
return None, None
|
2022-02-02 05:18:25 +00:00
|
|
|
|
|
|
|
return image_content, extension
|
2020-11-29 17:40:15 +00:00
|
|
|
|
|
|
|
|
2020-09-21 17:25:26 +00:00
|
|
|
class Mapping:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""associate a local database field with a field in an external dataset"""
|
2021-03-08 16:49:10 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
local_field: str,
|
|
|
|
remote_field: Optional[str] = None,
|
2023-07-28 18:54:03 +00:00
|
|
|
formatter: Optional[Callable[[Any], Any]] = None,
|
2023-07-28 15:43:32 +00:00
|
|
|
):
|
2021-04-07 00:46:06 +00:00
|
|
|
noop = lambda x: x
|
2020-05-10 23:41:24 +00:00
|
|
|
|
|
|
|
self.local_field = local_field
|
|
|
|
self.remote_field = remote_field or local_field
|
|
|
|
self.formatter = formatter or noop
|
2020-12-19 22:56:03 +00:00
|
|
|
|
2023-07-28 18:54:03 +00:00
|
|
|
def get_value(self, data: JsonDict) -> Optional[Any]:
|
2021-04-26 16:15:42 +00:00
|
|
|
"""pull a field from incoming json and return the formatted version"""
|
2020-12-19 22:56:03 +00:00
|
|
|
value = data.get(self.remote_field)
|
2020-12-20 00:14:05 +00:00
|
|
|
if not value:
|
|
|
|
return None
|
|
|
|
try:
|
2021-04-07 00:46:06 +00:00
|
|
|
return self.formatter(value)
|
2021-03-08 16:49:10 +00:00
|
|
|
except: # pylint: disable=bare-except
|
2020-12-20 00:14:05 +00:00
|
|
|
return None
|
2021-09-29 19:21:19 +00:00
|
|
|
|
2021-09-29 19:38:31 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def infer_physical_format(format_text: str) -> Optional[str]:
|
2021-09-29 19:38:31 +00:00
|
|
|
"""try to figure out what the standardized format is from the free value"""
|
2021-09-29 19:21:19 +00:00
|
|
|
format_text = format_text.lower()
|
|
|
|
if format_text in format_mappings:
|
|
|
|
# try a direct match
|
|
|
|
return format_mappings[format_text]
|
2021-09-29 19:42:28 +00:00
|
|
|
# failing that, try substring
|
|
|
|
matches = [v for k, v in format_mappings.items() if k in format_text]
|
|
|
|
if not matches:
|
|
|
|
return None
|
|
|
|
return matches[0]
|
2021-09-29 19:29:17 +00:00
|
|
|
|
2021-09-29 19:38:31 +00:00
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def unique_physical_format(format_text: str) -> Optional[str]:
|
2023-04-04 15:13:06 +00:00
|
|
|
"""only store the format if it isn't directly in the format mappings"""
|
2021-09-29 19:29:17 +00:00
|
|
|
format_text = format_text.lower()
|
|
|
|
if format_text in format_mappings:
|
|
|
|
# try a direct match, so saving this would be redundant
|
|
|
|
return None
|
|
|
|
return format_text
|
2022-05-30 17:34:03 +00:00
|
|
|
|
|
|
|
|
2023-07-28 15:43:32 +00:00
|
|
|
def maybe_isbn(query: str) -> bool:
|
2022-05-30 17:34:03 +00:00
|
|
|
"""check if a query looks like an isbn"""
|
|
|
|
isbn = re.sub(r"[\W_]", "", query) # removes filler characters
|
2022-08-28 01:05:40 +00:00
|
|
|
# ISBNs must be numeric except an ISBN10 checkdigit can be 'X'
|
2022-08-30 10:00:09 +00:00
|
|
|
if not isbn.upper().rstrip("X").isnumeric():
|
2022-08-28 01:05:40 +00:00
|
|
|
return False
|
2022-08-28 07:30:46 +00:00
|
|
|
return len(isbn) in [
|
|
|
|
9,
|
|
|
|
10,
|
|
|
|
13,
|
2022-08-30 10:00:09 +00:00
|
|
|
] # ISBN10 or ISBN13, or maybe ISBN10 missing a leading zero
|