-
Notifications
You must be signed in to change notification settings - Fork 1
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
SFR-2476: Implement DSpace service and update DOAB ingest #531
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ba03da1
implement dspace service and update doab ingest
jackiequach 4c9d776
address comments and update unit tests
jackiequach 90479e5
add integration tests and fix some issues
jackiequach 789f190
refactor while true loop
jackiequach 36a8b13
Merge branch 'main' into SFR-2476/abstract-dspace-integration
jackiequach 032cc1d
clean up integration tests
jackiequach 0cd8bca
updates based on feedback
jackiequach 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 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 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 @@ | ||
from .sources.nypl_bib_service import NYPLBibService | ||
from .sources.publisher_backlist_service import PublisherBacklistService | ||
from .google_drive_service import GoogleDriveService | ||
from .sources.dspace_service import DSpaceService |
This file contains 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,126 @@ | ||
from datetime import datetime, timedelta, timezone | ||
from typing import Optional | ||
import requests | ||
from io import BytesIO | ||
from lxml import etree | ||
from constants.get_constants import get_constants | ||
from logger import create_log | ||
from mappings.base_mapping import MappingError | ||
from mappings.xml import XMLMapping | ||
from .source_service import SourceService | ||
|
||
logger = create_log(__name__) | ||
|
||
|
||
class DSpaceService(SourceService): | ||
ROOT_NAMESPACE = {None: 'http://www.openarchives.org/OAI/2.0/'} | ||
OAI_NAMESPACES = { | ||
'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', | ||
'dc': 'http://purl.org/dc/elements/1.1/', | ||
'datacite': 'https://schema.datacite.org/meta/kernel-4.1/metadata.xsd', | ||
'oapen': 'http://purl.org/dc/elements/1.1/', | ||
'oaire': 'https://raw.githubusercontent.com/rcic/openaire4/master/schemas/4.0/oaire.xsd' | ||
} | ||
|
||
def __init__(self, base_url, source_mapping: type[XMLMapping]): | ||
self.constants = get_constants() | ||
|
||
self.base_url = base_url | ||
self.source_mapping = source_mapping | ||
|
||
def get_records(self, full_import=False, start_timestamp=None, offset: Optional[int]=None, limit: Optional[int]=None): | ||
resumption_token = None | ||
|
||
records_processed = 0 | ||
mapped_records = [] | ||
while resumption_token is not None or records_processed < offset: | ||
oai_file = self.download_records( | ||
full_import, start_timestamp, resumption_token=resumption_token) | ||
|
||
resumption_token = self.get_resumption_token(oai_file) | ||
|
||
if records_processed < offset: | ||
records_processed += 100 | ||
continue | ||
|
||
oaidc_records = etree.parse(oai_file) | ||
|
||
for record in oaidc_records.xpath('//oai_dc:dc', namespaces=self.OAI_NAMESPACES): | ||
if record is None: | ||
continue | ||
|
||
try: | ||
parsed_record = self.parse_record(record) | ||
mapped_records.append(parsed_record) | ||
except Exception as e: | ||
logger.error(f'Error parsing DSpace record {record}') | ||
|
||
records_processed += 1 | ||
|
||
if limit is not None and records_processed >= limit: | ||
return mapped_records | ||
|
||
return mapped_records | ||
|
||
def parse_record(self, record): | ||
try: | ||
record = self.source_mapping(record, self.OAI_NAMESPACES, self.constants) | ||
record.applyMapping() | ||
return record | ||
except MappingError as e: | ||
raise Exception(e.message) | ||
|
||
def get_single_record(self, record_id, source_identifier): | ||
url = f'{self.base_url}verb=GetRecord&metadataPrefix=oai_dc&identifier={source_identifier}:{record_id}' | ||
|
||
response = requests.get(url, timeout=30) | ||
|
||
if response.status_code == 200: | ||
content = BytesIO(response.content) | ||
oaidc_XML = etree.parse(content) | ||
oaidc_record = oaidc_XML.xpath('//oai_dc:dc', namespaces=self.OAI_NAMESPACES)[0] | ||
|
||
try: | ||
parsed_record = self.parse_record(oaidc_record) | ||
return parsed_record | ||
except Exception as e: | ||
logger.error(f'Error parsing DSpace record {oaidc_record}') | ||
|
||
def get_resumption_token(self, oai_file): | ||
try: | ||
oai_XML = etree.parse(oai_file) | ||
return oai_XML.find('.//resumptionToken', namespaces=self.ROOT_NAMESPACE).text | ||
except AttributeError: | ||
return None | ||
|
||
def download_records(self, full_import, start_timestamp, resumption_token=None): | ||
headers = { | ||
# Pass a user-agent header to prevent 403 unauthorized responses from DSpace | ||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" | ||
} | ||
|
||
url_params = 'verb=ListRecords' | ||
if resumption_token: | ||
url_params = f'{url_params}&resumptionToken={resumption_token}' | ||
elif full_import is False: | ||
if not start_timestamp: | ||
start_timestamp = (datetime.now(timezone.utc).replace( | ||
tzinfo=None) - timedelta(hours=24)).strftime('%Y-%m-%d') | ||
url_params = f'{url_params}&metadataPrefix=oai_dc&from={start_timestamp}' | ||
else: | ||
url_params = f'{url_params}&metadataPrefix=oai_dc' | ||
|
||
url = f'{self.base_url}{url_params}' | ||
|
||
response = requests.get(url, stream=True, timeout=30, headers=headers) | ||
|
||
if response.status_code == 200: | ||
content = bytes() | ||
|
||
for chunk in response.iter_content(1024 * 100): | ||
content += chunk | ||
|
||
return BytesIO(content) | ||
|
||
raise Exception( | ||
f'Received {response.status_code} status code from {url}') |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't the result of the else conditional be 0 if the records array is empty?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this should still return 0 since the len of the records array would be 0 if it is empty.