id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,500 | config.py | zenodo_zenodo/zenodo/modules/openaire/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configuration for ZenodoOpenAIRE."""
from __future__ import absolute_import, print_function
ZENODO_OPENAIRE_COMMUNITIES = { }
"""OpenAIRE communities resource subtypes configuration."""
| 1,159 | Python | .py | 27 | 41.814815 | 76 | 0.775908 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,501 | tasks.py | zenodo_zenodo/zenodo/modules/openaire/tasks.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Celery tasks for OpenAIRE."""
from __future__ import absolute_import, print_function, unicode_literals
from datetime import datetime
import requests
from celery import shared_task
from flask import current_app
from invenio_cache import current_cache
from invenio_pidstore.models import PersistentIdentifier
from zenodo.modules.records.api import ZenodoRecord
from zenodo.modules.records.serializers import openaire_json_v1
from .errors import OpenAIRERequestError
from .helpers import is_openaire_dataset, is_openaire_other, \
is_openaire_publication, is_openaire_software, openaire_datasource_id, \
openaire_original_id, openaire_type
def _openaire_request_factory(headers=None, auth=None):
"""Request factory for OpenAIRE API."""
ses = requests.Session()
ses.headers.update(headers or {'Content-type': 'application/json',
'Accept': 'application/json'})
if not auth:
username = current_app.config.get('OPENAIRE_API_USERNAME')
password = current_app.config.get('OPENAIRE_API_PASSWORD')
if username and password:
auth = (username, password)
ses.auth = auth
return ses
@shared_task(ignore_result=True, max_retries=6,
default_retry_delay=4 * 60 * 60, rate_limit='100/m')
def openaire_direct_index(record_uuid, retry=True):
"""Send record for direct indexing at OpenAIRE.
:param record_uuid: Record Metadata UUID.
:type record_uuid: str
"""
try:
record = ZenodoRecord.get_record(record_uuid)
# Bail out if not an OpenAIRE record.
if not (is_openaire_publication(record) or
is_openaire_dataset(record) or
is_openaire_software(record) or
is_openaire_other(record)):
return
data = openaire_json_v1.serialize(record.pid, record)
url = '{}/feedObject'.format(
current_app.config['OPENAIRE_API_URL'])
req = _openaire_request_factory()
res = req.post(url, data=data, timeout=10)
if not res.ok:
raise OpenAIRERequestError(res.text)
res_beta = None
if current_app.config['OPENAIRE_API_URL_BETA']:
url_beta = '{}/feedObject'.format(
current_app.config['OPENAIRE_API_URL_BETA'])
res_beta = req.post(url_beta, data=data, timeout=10)
if res_beta and not res_beta.ok:
raise OpenAIRERequestError(res_beta.text)
else:
recid = record.get('recid')
current_cache.delete('openaire_direct_index:{}'.format(recid))
except Exception as exc:
recid = record.get('recid')
current_cache.set('openaire_direct_index:{}'.format(recid),
datetime.now(), timeout=-1)
if retry:
openaire_direct_index.retry(exc=exc)
else:
raise exc
@shared_task(ignore_result=True, max_retries=6,
default_retry_delay=4 * 60 * 60, rate_limit='100/m')
def openaire_delete(record_uuid=None, original_id=None, datasource_id=None):
"""Delete record from OpenAIRE index.
:param record_uuid: Record Metadata UUID.
:type record_uuid: str
:param original_id: OpenAIRE originalId.
:type original_id: str
:param datasource_id: OpenAIRE datasource identifier.
:type datasource_id: str
"""
try:
record = ZenodoRecord.get_record(record_uuid, with_deleted=True)
if record and 'resource_type' not in record:
# record was deleted, find last revision with metadata
record = next(
r for r in reversed(record.revisions)
if 'resource_type' in r
)
if not record:
raise OpenAIRERequestError('Could not resolve record.')
# Resolve originalId and datasource if not already available
if not (original_id and datasource_id):
original_id = openaire_original_id(
record, openaire_type(record))[1]
datasource_id = openaire_datasource_id(record)
params = {'originalId': original_id, 'collectedFromId': datasource_id}
req = _openaire_request_factory()
res = req.delete(current_app.config['OPENAIRE_API_URL'], params=params)
res_beta = None
if current_app.config['OPENAIRE_API_URL_BETA']:
res_beta = req.delete(
current_app.config['OPENAIRE_API_URL_BETA'], params=params)
if not res.ok or (res_beta and not res_beta.ok):
raise OpenAIRERequestError(res.text)
# Remove from failures cache
current_cache.delete(
'openaire_direct_index:{}'.format(record['recid']))
except Exception as exc:
current_cache.set(
'openaire_direct_index:{}'.format(record['recid']),
datetime.now(), timeout=-1)
openaire_delete.retry(exc=exc)
@shared_task
def retry_openaire_failures():
"""Retries failed OpenAIRE indexing/deletion operations."""
cache = current_cache.cache
redis_client = cache._read_clients
failed_recids = redis_client.scan_iter(
match=(cache.key_prefix + 'openaire_direct_index:*'),
count=1000,
)
for key in failed_recids:
recid_value = key.split('openaire_direct_index:')[1]
recid = PersistentIdentifier.query.filter_by(
pid_type='recid', pid_value=recid_value).one_or_none()
record = ZenodoRecord.get_record(recid.object_uuid, with_deleted=True)
if 'resource_type' in record:
openaire_direct_index.delay(str(record.id), retry=False)
else:
openaire_delete.delay(str(record.id))
| 6,646 | Python | .py | 150 | 36.72 | 79 | 0.668521 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,502 | __init__.py | zenodo_zenodo/zenodo/modules/openaire/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo OpenAIRE module."""
from __future__ import absolute_import, print_function
from .proxies import current_openaire
__all__ = (
'current_openaire',
)
| 1,132 | Python | .py | 29 | 37.758621 | 76 | 0.767061 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,503 | schema.py | zenodo_zenodo/zenodo/modules/openaire/schema.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo OpenaAIRE-JSON schema."""
from __future__ import absolute_import, print_function
from flask import current_app
from marshmallow import Schema, fields, missing
from zenodo.modules.records.models import ObjectType
from zenodo.modules.records.serializers.fields import DateString
from .helpers import openaire_datasource_id, openaire_original_id
class RecordSchemaOpenAIREJSON(Schema):
"""Schema for records in OpenAIRE-JSON.
OpenAIRE Schema: https://www.openaire.eu/schema/1.0/oaf-result-1.0.xsd
OpenAIRE Vocabularies: http://api.openaire.eu/vocabularies
"""
originalId = fields.Method('get_original_id', required=True)
title = fields.Str(attribute='metadata.title', required=True)
description = fields.Str(attribute='metadata.description')
url = fields.Method('get_url', required=True)
authors = fields.List(fields.Str(attribute='name'),
attribute='metadata.creators')
type = fields.Method('get_type')
resourceType = fields.Method('get_resource_type', required=True)
language = fields.Str(attribute='metadata.language')
version = fields.Str(attribute='metadata.version')
contexts = fields.Method('get_communities')
licenseCode = fields.Method('get_license_code', required=True)
embargoEndDate = DateString(attribute='metadata.embargo_date')
publisher = fields.Method('get_publisher')
collectedFromId = fields.Method('get_datasource_id', required=True)
hostedById = fields.Method('get_datasource_id')
linksToProjects = fields.Method('get_links_to_projects')
pids = fields.Method('get_pids')
def _openaire_type(self, obj):
return ObjectType.get_by_dict(
obj.get('metadata', {}).get('resource_type')
).get('openaire')
def get_original_id(self, obj):
"""Get Original Id."""
oatype = self._openaire_type(obj)
if oatype:
return openaire_original_id(
obj.get('metadata', {}),
oatype['type']
)[1]
return missing
def get_type(self, obj):
"""Get record type."""
oatype = self._openaire_type(obj)
if oatype:
return oatype['type']
return missing
def get_resource_type(self, obj):
"""Get resource type."""
oatype = self._openaire_type(obj)
if oatype:
return oatype['resourceType']
return missing
def get_datasource_id(self, obj):
"""Get OpenAIRE datasource identifier."""
return openaire_datasource_id(obj.get('metadata')) or missing
def get_communities(self, obj):
"""Get record's communities."""
communities = []
if obj.get('metadata').get('communities'):
for comm in obj.get('metadata').get('communities'):
communities.append("https://zenodo.org/communities/{}".format(comm))
return communities or missing
# Mapped from: http://api.openaire.eu/vocabularies/dnet:access_modes
LICENSE_MAPPING = {
'open': 'OPEN',
'embargoed': 'EMBARGO',
'restricted': 'RESTRICTED',
'closed': 'CLOSED',
}
def get_license_code(self, obj):
"""Get license code."""
metadata = obj.get('metadata')
return self.LICENSE_MAPPING.get(
metadata.get('access_right'), 'UNKNOWN')
def get_links_to_projects(self, obj):
"""Get project/grant links."""
metadata = obj.get('metadata')
grants = metadata.get('grants', [])
links = []
for grant in grants:
eurepo = grant.get('identifiers', {}).get('eurepo', '')
if eurepo:
links.append(u'{eurepo}/{title}/{acronym}'.format(
eurepo=eurepo,
title=grant.get('title', '').replace('/', '%2F'),
acronym=grant.get('acronym', '')))
return links or missing
def get_pids(self, obj):
"""Get record PIDs."""
metadata = obj.get('metadata')
pids = [{'type': 'oai', 'value': metadata['_oai']['id']}]
if 'doi' in metadata:
pids.append({'type': 'doi', 'value': metadata['doi']})
return pids
def get_url(self, obj):
"""Get record URL."""
return current_app.config['ZENODO_RECORDS_UI_LINKS_FORMAT'].format(
recid=obj['metadata']['recid'])
def get_publisher(self, obj):
"""Get publisher."""
m = obj['metadata']
imprint_publisher = m.get('imprint', {}).get('publisher')
if imprint_publisher:
return imprint_publisher
part_publisher = m.get('part_of', {}).get('publisher')
if part_publisher:
return part_publisher
if m.get('doi', '').startswith('10.5281/'):
return 'Zenodo'
return missing
| 5,810 | Python | .py | 136 | 35.338235 | 84 | 0.643945 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,504 | helpers.py | zenodo_zenodo/zenodo/modules/openaire/helpers.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017-2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""OpenAIRE related helpers."""
from __future__ import absolute_import, print_function, unicode_literals
import hashlib
import urllib
from flask import current_app
from zenodo.modules.records.models import ObjectType
from .proxies import current_openaire
class _OAType(object):
"""OpenAIRE types."""
publication = 'publication'
dataset = 'dataset'
software = 'software'
other = 'other'
def is_openaire_publication(record):
"""Determine if record is a publication for OpenAIRE."""
oatype = ObjectType.get_by_dict(record.get('resource_type')).get(
'openaire', {})
if not oatype or oatype['type'] != _OAType.publication:
return False
# Has grants, is part of ecfunded community or is open access.
if record.get('grants') or 'ecfunded' in record.get('communities', []) or \
'open' == record.get('access_right'):
return True
return False
def is_openaire_dataset(record):
"""Determine if record is a dataset for OpenAIRE."""
oatype = ObjectType.get_by_dict(record.get('resource_type')).get(
'openaire', {})
return oatype and oatype['type'] == _OAType.dataset
def is_openaire_software(record):
"""Determine if the record is a software for OpenAIRE."""
oatype = ObjectType.get_by_dict(record.get('resource_type')).get(
'openaire', {})
return oatype and oatype['type'] == _OAType.software
def is_openaire_other(record):
"""Determine if the record has type 'other' for OpenAIRE."""
oatype = ObjectType.get_by_dict(record.get('resource_type')).get(
'openaire', {})
return oatype and oatype['type'] == _OAType.other
def openaire_type(record):
"""Get the OpenAIRE type of a record."""
if is_openaire_publication(record):
return _OAType.publication
elif is_openaire_dataset(record):
return _OAType.dataset
elif is_openaire_software(record):
return _OAType.software
elif is_openaire_other(record):
return _OAType.other
return None
def openaire_id(record):
"""Compute the OpenAIRE identifier."""
return _openaire_id(record, openaire_type(record))
def _openaire_id(record, oatype):
"""Compute the OpenAIRE identifier."""
prefix, identifier = openaire_original_id(record, oatype)
if not identifier or not prefix:
return None
m = hashlib.md5()
m.update(identifier.encode('utf8'))
return '{}::{}'.format(prefix, m.hexdigest())
def openaire_datasource_id(record):
"""Get OpenAIRE datasource identifier."""
return current_app.config['OPENAIRE_ZENODO_IDS'].get(openaire_type(record))
def openaire_original_id(record, oatype):
"""Original original identifier."""
prefix = current_app.config['OPENAIRE_NAMESPACE_PREFIXES'].get(oatype)
value = None
if oatype == _OAType.publication or oatype == _OAType.software or \
oatype == _OAType.other:
value = record.get('_oai', {}).get('id')
elif oatype == _OAType.dataset:
value = record.get('doi')
return prefix, value
def openaire_link(record):
"""Compute an OpenAIRE link."""
oatype = openaire_type(record)
doi = record.get('doi')
if oatype == _OAType.publication:
return '{}/search/publication?pid={}'.format(
current_app.config['OPENAIRE_PORTAL_URL'],
urllib.quote(doi),
)
elif oatype == _OAType.dataset:
return '{}/search/dataset?pid={}'.format(
current_app.config['OPENAIRE_PORTAL_URL'],
urllib.quote(doi),
)
elif oatype == _OAType.software:
return '{}/search/software?pid={}'.format(
current_app.config['OPENAIRE_PORTAL_URL'],
urllib.quote(doi),
)
elif oatype == _OAType.other:
return '{}/search/other?pid={}'.format(
current_app.config['OPENAIRE_PORTAL_URL'],
urllib.quote(doi),
)
return None
def resolve_openaire_communities(communities):
"""Resolve a Zenodo communities list to an OpenAIRE communities set."""
openaire_comms = set()
for comm in communities:
oa_comms = current_openaire.inverse_openaire_community_map.get(comm)
if oa_comms:
for oa_comm in oa_comms:
openaire_comms.add(oa_comm)
return openaire_comms
def openaire_community_identifier(openaire_community):
"""Get OpenAIRE community identifier."""
return u'{0}/{1}'.format(
current_app.config['OPENAIRE_COMMUNITY_IDENTIFIER_PREFIX'],
openaire_community)
| 5,524 | Python | .py | 136 | 35.147059 | 79 | 0.685303 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,505 | proxies.py | zenodo_zenodo/zenodo/modules/openaire/proxies.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Proxy objects for easier access to application objects."""
from flask import current_app
from werkzeug.local import LocalProxy
def _get_current_openaire():
"""Return current state of the OpenAIRE extension."""
return current_app.extensions['zenodo-openaire']
current_openaire = LocalProxy(_get_current_openaire)
| 1,299 | Python | .py | 30 | 41.866667 | 76 | 0.77769 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,506 | views.py | zenodo_zenodo/zenodo/modules/openaire/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Blueprint for OpenAIRE."""
from __future__ import absolute_import, print_function
from flask import Blueprint
from .helpers import openaire_link, openaire_type
blueprint = Blueprint(
'zenodo_openaire',
__name__
)
@blueprint.app_template_filter('openaire_link')
def link(record):
"""Generate an OpenAIRE link."""
return openaire_link(record)
@blueprint.app_template_filter('openaire_type')
def openaire_type_filter(record):
"""Generate an OpenAIRE link."""
return openaire_type(record)
| 1,488 | Python | .py | 39 | 36.307692 | 76 | 0.765278 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,507 | signals.py | zenodo_zenodo/zenodo/modules/communities/signals.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2021 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Receivers for Zenodo Communities."""
from __future__ import absolute_import, print_function
from blinker import Namespace
_signals = Namespace()
record_accepted = _signals.signal('record_accepted')
"""Signal is sent after a record is accepted to a community."""
| 1,237 | Python | .py | 29 | 41.482759 | 76 | 0.773899 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,508 | ext.py | zenodo_zenodo/zenodo/modules/communities/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""ZenodoCommunities module."""
from __future__ import absolute_import, print_function
from invenio_communities.signals import community_created, \
inclusion_request_created
from zenodo.modules.spam.utils import check_and_handle_spam
from . import config
from .receivers import send_inclusion_request_webhook, \
send_record_accepted_webhook
from .signals import record_accepted
class ZenodoCommunities(object):
"""Zenodo communities extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
self.register_signals(app)
app.extensions['zenodo-communities'] = self
@staticmethod
def init_config(app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('ZENODO_COMMUNITIES'):
app.config.setdefault(k, getattr(config, k))
@staticmethod
def register_signals(app):
"""Register Zenodo Deposit signals."""
community_created.connect(
community_spam_checking_receiver, sender=app, weak=False)
inclusion_request_created.connect(
send_inclusion_request_webhook, sender=app, weak=False)
record_accepted.connect(
send_record_accepted_webhook, sender=app, weak=False)
def community_spam_checking_receiver(sender, community):
"""Receiver for spam checking of newly created communities."""
check_and_handle_spam(community=community)
| 2,562 | Python | .py | 61 | 37.245902 | 76 | 0.724678 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,509 | config.py | zenodo_zenodo/zenodo/modules/communities/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015-2021 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configuration for Zenodo Communities."""
from __future__ import absolute_import, print_function
ZENODO_COMMUNITIES_NOTIFY_DISABLED = ['zenodo', ]
"""Communities with disabled email notification on requests."""
ZENODO_COMMUNITIES_AUTO_ENABLED = True
"""Automatically add and request to communities upon publishing."""
ZENODO_COMMUNITIES_AUTO_REQUEST = ['zenodo', ]
"""Communities which are to be auto-requested upon first publishing."""
ZENODO_COMMUNITIES_REQUEST_IF_GRANTS = ['ecfunded', ]
"""Communities which are to be auto-requested if record has grants."""
ZENODO_COMMUNITIES_ADD_IF_GRANTS = []
"""Communities which are to be auto-added if record has grants."""
ZENODO_COMMUNITIES_WEBHOOKS = {}
"""Webhook sending configurations for community inclusion requests.
Example configuration:
.. code-block:: python
ZENODO_COMMUNITIES_WEBHOOKS = {
'astrophysics': {
'example_recipient_id': {
'url': 'https://example.org/webhooks/zenodo',
'headers': {
'X-Custom-Auth': 'foobar',
},
'params': {
'token': 'some-token',
}
},
}
}
"""
| 2,180 | Python | .py | 53 | 36.754717 | 76 | 0.703686 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,510 | tasks.py | zenodo_zenodo/zenodo/modules/communities/tasks.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2021 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Tasks for Zenodo Communities."""
from __future__ import absolute_import, print_function
import uuid
from copy import deepcopy
from datetime import datetime
import requests
from celery import shared_task
from flask import current_app
from invenio_communities.models import Community
from zenodo.modules.records.api import ZenodoRecord
from zenodo.modules.records.serializers import legacyjson_v1
@shared_task(ignore_results=True)
def dispatch_webhook(community_id, record_id, event_type):
"""Build webhook payload and dispatch delivery tasks."""
webhooks_cfg = current_app.config.get('ZENODO_COMMUNITIES_WEBHOOKS', {})
recipients = webhooks_cfg.get(community_id, [])
if not recipients:
return
# TODO: Extract to a utility?
record = ZenodoRecord.get_record(record_id)
community = Community.query.get(community_id)
# TODO: Make configurable
record_payload = legacyjson_v1.transform_record(record.pid, record)
payload = {
"timestamp": datetime.utcnow().isoformat(),
"id": str(uuid.uuid4()),
"event_type": event_type,
"context": {
"community": community.id,
"user": record['owners'][0],
},
"payload": {
"community": {
"id": community.id,
"owner": {
"id": community.id_user,
}
},
"record": record_payload,
},
}
for recipient_id in recipients:
deliver_webhook.delay(payload, community_id, recipient_id)
@shared_task(ignore_result=True, max_retries=3, default_retry_delay=10 * 60)
def deliver_webhook(payload, community_id, recipient_id):
"""Deliver the webhook payload to a recipient."""
try:
webhooks_cfg = current_app.config.get(
'ZENODO_COMMUNITIES_WEBHOOKS', {})
recipient_cfg = deepcopy(webhooks_cfg.get(community_id, {}).get(recipient_id))
if recipient_cfg:
recipient_cfg.setdefault('headers', {})
recipient_cfg['headers'].update({
# TODO: Make configurable
'User-Agent': 'Zenodo v3.0.0',
})
res = requests.post(json=payload, **recipient_cfg)
res.raise_for_status()
except Exception as exc:
deliver_webhook.retry(exc=exc)
| 3,297 | Python | .py | 83 | 33.831325 | 86 | 0.6804 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,511 | api.py | zenodo_zenodo/zenodo/modules/communities/api.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Communities API."""
from __future__ import absolute_import
from flask import after_this_request, request
from flask.globals import current_app
from invenio_communities.errors import InclusionRequestMissingError
from invenio_communities.models import Community, InclusionRequest
from invenio_db import db
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_pidstore.models import PersistentIdentifier
from six import string_types, text_type
from zenodo.modules.records.api import ZenodoRecord
from .signals import record_accepted
class ZenodoCommunity(object):
"""API class for Zenodo Communities."""
def __init__(self, community):
"""Construct the API object.
:param community: Instantiate the API with the community.
Parameter can be either the model instance, or string
(community ID).
:type community: invenio_communities.model.Community or str
"""
if isinstance(community, (text_type, string_types)):
self.community = Community.get(community)
else:
self.community = community
@staticmethod
def get_irs(record, community_id=None, pid=None):
"""Get all inclusion requests for given record and community.
:param record: record for which the inclusion requests are fetched.
This includes all of the record's versions.
:param community_id: Narrow down the query to given community.
Query for all communities if 'None'.
"""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
pv = PIDVersioning(child=pid)
if pv.exists:
sq = pv.children.with_entities(
PersistentIdentifier.object_uuid).subquery()
filter_cond = [
InclusionRequest.id_record.in_(sq),
]
if community_id:
filter_cond.append(
InclusionRequest.id_community == community_id)
q = (db.session.query(InclusionRequest).filter(*filter_cond))
else:
q = InclusionRequest.query.filter_by(id_record=record.id).order_by(
InclusionRequest.id_community)
return q
def get_comm_irs(self, record, pid=None):
"""Inclusion requests for record's versions made to this community.
:rtype: BaseQuery
"""
return ZenodoCommunity.get_irs(
record, community_id=self.community.id, pid=pid)
def has_record(self, record, pid=None, scope='any'):
"""Check if record is in a community.
:type scope: str
:param scope: Can take values 'any', 'all' or 'this'.
* 'all': returns True if all record versions are in the community.
* 'any': returns True if any of the record versions are in the
community.
* 'this': returns if the specified 'record' is in the community.
"""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
pv = PIDVersioning(child=pid)
if scope == 'this':
return self.community.has_record(record)
q = (self.community.has_record(
ZenodoRecord.get_record(p.get_assigned_object()))
for p in pv.children)
if scope == 'all':
return all(q)
if scope == 'any':
return any(q)
def add_record(self, record, pid=None):
"""Add a record and all of its versions to a community."""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
pv = PIDVersioning(child=pid)
for child in pv.children.all():
rec = ZenodoRecord.get_record(
child.get_assigned_object())
if not self.community.has_record(rec):
self.community.add_record(rec)
rec.commit()
def accept_record(self, record, pid=None):
"""Accept the record and all of its versions into the community.
:type record: zenodo.modules.records.api.ZenodoRecord
:param pid: PID of type 'recid'
:type pid: invenio_pidstore.models.PersistentIdentifier
"""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
with db.session.begin_nested():
pending_q = self.get_comm_irs(record, pid=pid)
if not pending_q.count():
raise InclusionRequestMissingError(community=self,
record=record)
pv = PIDVersioning(child=pid)
for child in pv.children.all():
rec = ZenodoRecord.get_record(
child.get_assigned_object())
self.community.add_record(rec)
rec.commit()
if request:
@after_this_request
def send_signals(response):
try:
record_accepted.send(
current_app._get_current_object(),
record_id=rec.id,
community_id=self.community.id,
)
except Exception:
pass
return response
pending_q.delete(synchronize_session=False)
def reject_record(self, record, pid=None):
"""Reject the inclusion request.
:type record: zenodo.modules.records.api.ZenodoRecord
"""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
with db.session.begin_nested():
pending_q = self.get_comm_irs(record, pid=pid)
pending_q.delete(synchronize_session=False)
def remove_record(self, record, pid=None):
"""Remove the record and all of its versions from the community.
:type record: zenodo.modules.records.api.ZenodoRecord
"""
if not pid:
pid = PersistentIdentifier.get('recid', record['recid'])
with db.session.begin_nested():
pv = PIDVersioning(child=pid)
for child in pv.children.all():
rec = ZenodoRecord.get_record(
child.get_assigned_object())
if self.community.has_record(rec):
self.community.remove_record(rec)
rec.commit()
| 7,446 | Python | .py | 166 | 34.168675 | 79 | 0.615968 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,512 | receivers.py | zenodo_zenodo/zenodo/modules/communities/receivers.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2021 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Receivers for Zenodo Communities."""
from __future__ import absolute_import, print_function
from .tasks import dispatch_webhook
def send_inclusion_request_webhook(sender, request=None, **kwargs):
"""Signal receiver to send webhooks after a community inclusion request."""
dispatch_webhook.delay(
community_id=str(request.id_community),
record_id=str(request.id_record),
event_type='community.records.inclusion',
)
def send_record_accepted_webhook(
sender, record_id=None, community_id=None, **kwargs):
"""Signal receiver to send webhooks on a record accepted in a community."""
dispatch_webhook.delay(
community_id=str(community_id),
record_id=str(record_id),
event_type='community.records.addition',
)
| 1,760 | Python | .py | 41 | 39.804878 | 79 | 0.745911 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,513 | __init__.py | zenodo_zenodo/zenodo/modules/communities/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Communities module."""
| 994 | Python | .py | 24 | 40.375 | 76 | 0.770898 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,514 | views.py | zenodo_zenodo/zenodo/modules/communities/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Invenio module that adds support for communities."""
from __future__ import absolute_import, print_function
from flask import Blueprint, abort, current_app, jsonify, request
from flask_login import login_required
from invenio_communities.views.ui import pass_community, permission_required
from invenio_db import db
from invenio_indexer.api import RecordIndexer
from invenio_pidrelations.contrib.versioning import PIDVersioning
from zenodo.modules.communities.api import ZenodoCommunity
from zenodo.modules.deposit.tasks import datacite_register
from zenodo.modules.openaire.tasks import openaire_delete, \
openaire_direct_index
from zenodo.modules.records.resolvers import record_resolver
blueprint = Blueprint(
'zenodo_communities',
__name__,
url_prefix='/communities',
)
@blueprint.route('/<string:community_id>/curaterecord/', methods=['POST'])
@login_required
@pass_community
@permission_required('community-curate')
def curate(community):
"""Index page with uploader and list of existing depositions.
:param community_id: ID of the community to curate.
"""
action = request.json.get('action')
recid = request.json.get('recid')
if not recid:
abort(400)
if action not in ['accept', 'reject', 'remove']:
abort(400)
# Resolve recid to a Record
pid, record = record_resolver.resolve(recid)
# Perform actions
pv = PIDVersioning(child=pid)
if pv.exists:
api = ZenodoCommunity(community)
else:
api = community
if action == "accept":
api.accept_record(record, pid=pid)
elif action == "reject":
api.reject_record(record, pid=pid)
elif action == "remove":
api.remove_record(record, pid=pid)
record_id = record.id
db.session.commit()
RecordIndexer().index_by_id(record_id)
if current_app.config['OPENAIRE_DIRECT_INDEXING_ENABLED']:
if action == 'accept':
openaire_direct_index.delay(record_uuid=str(record_id))
elif action in ('reject', 'remove'):
openaire_delete.delay(record_uuid=str(record_id))
if current_app.config['DEPOSIT_DATACITE_MINTING_ENABLED']:
datacite_register.delay(recid, str(record_id))
return jsonify({'status': 'success'})
| 3,230 | Python | .py | 80 | 36.625 | 76 | 0.73805 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,515 | tasks.py | zenodo_zenodo/zenodo/modules/sipstore/tasks.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Celery tasks for SIPStore."""
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from invenio_db import db
from invenio_sipstore.api import SIP as SIPApi
from invenio_sipstore.archivers import BagItArchiver
from invenio_sipstore.models import SIP
class ArchivingError(Exception):
"""Represents a SIP archiving error that can occur during task."""
@shared_task(ignore_result=True, max_retries=6,
default_retry_delay=4 * 60 * 60)
def archive_sip(sip_uuid):
"""Send the SIP for archiving.
Retries every 4 hours, six times, which should work for up to 24 hours
archiving system downtime.
:param sip_uuid: UUID of the SIP for archiving.
:type sip_uuid: str
"""
try:
sip = SIPApi(SIP.query.get(sip_uuid))
archiver = BagItArchiver(sip)
bagmeta = archiver.get_bagit_metadata(sip)
if bagmeta is None:
raise ArchivingError(
'Bagit metadata does not exist for SIP: {0}.'.format(sip.id))
if sip.archived:
raise ArchivingError(
'SIP was already archived {0}.'.format(sip.id))
archiver.write_all_files()
sip.archived = True
db.session.commit()
except Exception as exc:
# On ArchivingError (see above), do not retry, but re-raise
if not isinstance(exc, ArchivingError):
archive_sip.retry(exc=exc)
raise
| 2,413 | Python | .py | 59 | 36.271186 | 77 | 0.715565 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,516 | utils.py | zenodo_zenodo/zenodo/modules/sipstore/utils.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Utilities for SIPStore module."""
from __future__ import absolute_import, unicode_literals
import arrow
from invenio_sipstore.api import SIP
from invenio_sipstore.archivers.utils import chunks
build_agent_info = SIP._build_agent_info
def generate_bag_path(recid, iso_timestamp):
"""Generates a path for the BagIt.
Splits the recid string into chunks of size 3, e.g.:
generate_bag_path('12345', '2017-09-15T11:44:24.590537+00:00') ==
['123', '45', 'r', '2017-09-15T11:44:24.590537+00:00']
:param recid: recid value
:type recid: str
:param iso_timestamp: ISO-8601 formatted creation date (UTC) of the SIP.
:type iso_timestamp: str
"""
recid_chunks = list(chunks(recid, 3))
return recid_chunks + ['r', iso_timestamp, ]
def archive_directory_builder(sip):
"""Generate a path for BagIt from SIP.
:param sip: SIP which is to be archived
:type SIP: invenio_sipstore.models.SIP
:return: list of str
"""
iso_timestamp = arrow.get(sip.model.created).isoformat()
recid = sip.model.record_sips[0].pid.pid_value
return generate_bag_path(recid, iso_timestamp)
def sipmetadata_name_formatter(sipmetadata):
"""Generator for the archived SIPMetadata filenames."""
return "record-{name}.{format}".format(
name=sipmetadata.type.name,
format=sipmetadata.type.format
)
| 2,339 | Python | .py | 56 | 38.607143 | 76 | 0.734361 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,517 | __init__.py | zenodo_zenodo/zenodo/modules/sipstore/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo SIPStore."""
from __future__ import absolute_import, print_function
| 1,047 | Python | .py | 25 | 40.8 | 76 | 0.771569 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,518 | __init__.py | zenodo_zenodo/zenodo/modules/sipstore/jsonschemas/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo SIPStore JSON schemas."""
from __future__ import absolute_import, print_function
| 1,060 | Python | .py | 25 | 41.32 | 76 | 0.772507 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,519 | ext.py | zenodo_zenodo/zenodo/modules/tokens/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resource access tokens module extension."""
from __future__ import absolute_import, print_function
from . import config
class ResourceAccessTokens(object):
"""Resource access tokens extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
@staticmethod
def init_config(app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('ZENODO_TOKENS_'):
app.config.setdefault(k, getattr(config, k))
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['resource-access-tokens'] = self
| 1,684 | Python | .py | 42 | 36.142857 | 76 | 0.716034 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,520 | errors.py | zenodo_zenodo/zenodo/modules/tokens/errors.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resource access tokens module errors."""
from __future__ import absolute_import, print_function
from invenio_rest.errors import RESTException
class ResourceAccessTokenError(RESTException):
"""Resource access token base error class."""
code = 400
class MissingTokenIDError(ResourceAccessTokenError):
"""Resource access token for missing token ID."""
description = 'Missing "kid" key with personal access token ID in JWT header.'
class InvalidTokenIDError(ResourceAccessTokenError):
"""Resource access token error for invalid token ID."""
description = '"kid" JWT header value not a valid personal access token ID.'
class InvalidTokenError(ResourceAccessTokenError):
"""Resource access token for invalid token."""
description = 'The token is invalid.'
class ExpiredTokenError(InvalidTokenError):
"""Resource access token error for expired token."""
description = 'The token is expired.'
| 1,913 | Python | .py | 41 | 44.243902 | 82 | 0.772384 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,521 | config.py | zenodo_zenodo/zenodo/modules/tokens/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resource access tokens module configuration."""
from __future__ import absolute_import, print_function
from datetime import timedelta
RESOURCE_ACCESS_TOKENS_JWT_LIFETIME = timedelta(minutes=30)
"""Maximum tokens lifetime."""
RESOURCE_ACCESS_TOKENS_WHITELISTED_JWT_ALGORITHMS = ['HS256', 'HS384', 'HS512']
"""Accepted JWT algorithms for the ."""
| 1,320 | Python | .py | 30 | 42.833333 | 79 | 0.774319 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,522 | api.py | zenodo_zenodo/zenodo/modules/tokens/api.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resource access tokens API."""
from __future__ import absolute_import, print_function
from datetime import datetime, timedelta
import jwt
from flask import current_app
from invenio_oauth2server.models import Token
from .errors import ExpiredTokenError, InvalidTokenError, \
InvalidTokenIDError, MissingTokenIDError
from .scopes import tokens_generate_scope
def decode_rat(token, sub_only=True):
"""Decodes a JWT token's payload and signer."""
# Retrieve token ID from "kid"
try:
headers = jwt.get_unverified_header(token)
access_token_id = headers.get('kid')
except jwt.InvalidTokenError:
raise InvalidTokenError()
if not access_token_id:
raise MissingTokenIDError()
if not access_token_id.isdigit():
raise InvalidTokenIDError()
access_token = Token.query.get(int(access_token_id))
if not access_token or tokens_generate_scope.id not in access_token.scopes:
raise InvalidTokenError()
try:
payload = jwt.decode(
token,
key=access_token.access_token,
algorithms=current_app.config.get(
'RESOURCE_ACCESS_TOKENS_WHITELISTED_JWT_ALGORITHMS',
['HS256', 'HS384', 'HS512']),
options={'require_iat': True},
)
token_lifetime = current_app.config.get(
'RESOURCE_ACCESS_TOKENS_JWT_LIFETIME', timedelta(minutes=30))
# Verify that the token is not expired based on its issue time
issued_at = datetime.utcfromtimestamp(payload['iat'])
if (issued_at + token_lifetime) < datetime.utcnow():
raise ExpiredTokenError()
except jwt.InvalidTokenError:
raise InvalidTokenError()
return access_token.user, (payload['sub'] if sub_only else payload)
| 2,760 | Python | .py | 65 | 37.353846 | 79 | 0.716841 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,523 | scopes.py | zenodo_zenodo/zenodo/modules/tokens/scopes.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""OAuth2 tokens scopes."""
from __future__ import absolute_import, print_function
from flask_babelex import lazy_gettext as _
from invenio_oauth2server.models import Scope
tokens_generate_scope = Scope(
id_='generate', group='tokens',
help_text=_('Allow generation of granular access JWT tokens.'),
internal=True,
)
"""Allow generation of granular access JWT tokens."""
| 1,354 | Python | .py | 33 | 39.545455 | 76 | 0.767654 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,524 | __init__.py | zenodo_zenodo/zenodo/modules/tokens/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resource access tokens module."""
from __future__ import absolute_import, print_function
from .api import decode_rat
from .ext import ResourceAccessTokens
__all__ = (
'ResourceAccessTokens',
'decode_rat',
)
| 1,189 | Python | .py | 31 | 36.967742 | 76 | 0.767764 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,525 | ext.py | zenodo_zenodo/zenodo/modules/sitemap/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Sitemap generation for Zenodo."""
from __future__ import absolute_import, print_function
from invenio_cache import current_cache
from . import config
from .generators import generator_fns
class ZenodoSitemap(object):
"""Zenodo sitemap extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
self.app = app
self.init_config(app)
self.generators = [fn for fn in generator_fns]
app.extensions['zenodo-sitemap'] = self
# Keep the currently stored sitemap cache keys for easy clearing
self.cache_keys = set()
def set_cache(self, key, value):
"""Set the sitemap cache."""
current_cache.set(key, value, timeout=-1)
self.cache_keys.add(key)
@staticmethod
def get_cache(key):
"""Get the sitemap cache."""
current_cache.get(key)
def clear_cache(self):
"""Clear the sitemap cache."""
for key in self.cache_keys:
current_cache.delete(key)
self.cache_keys = set()
@staticmethod
def init_config(app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('ZENODO_SITEMAP_'):
app.config.setdefault(k, getattr(config, k))
def _generate_all_urls(self):
"""Run all generators and yield the sitemap JSON entries."""
for generator in self.generators:
for generated in generator():
yield generated
| 2,576 | Python | .py | 66 | 33.469697 | 76 | 0.681217 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,526 | config.py | zenodo_zenodo/zenodo/modules/sitemap/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configuration for Zenodo Sitemap."""
from __future__ import absolute_import, print_function
#: Sitemap links URL scheme
ZENODO_SITEMAP_URL_SCHEME = 'https'
#: Max URLs per sitemap page
ZENODO_SITEMAP_MAX_URL_COUNT = 10000
| 1,196 | Python | .py | 29 | 40.103448 | 76 | 0.773861 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,527 | tasks.py | zenodo_zenodo/zenodo/modules/sitemap/tasks.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Sitemap tasks."""
from __future__ import absolute_import
import itertools
from celery import shared_task
from flask import current_app, render_template, url_for
@shared_task(ignore_results=True)
def update_sitemap_cache(urls=None, max_url_count=None):
"""Update the Sitemap cache."""
# We need request context to properly generate the external link
# using url_for. We fix base_url as we want to simulate a
# request as it looks from an external client, instead of a task.
siteurl = current_app.config['THEME_SITEURL']
with current_app.test_request_context(base_url=siteurl):
max_url_count = max_url_count or \
current_app.config['ZENODO_SITEMAP_MAX_URL_COUNT']
sitemap = current_app.extensions['zenodo-sitemap']
urls = iter(urls or sitemap._generate_all_urls())
url_scheme = current_app.config['ZENODO_SITEMAP_URL_SCHEME']
urls_slice = list(itertools.islice(urls, max_url_count))
page_n = 0
sitemap.clear_cache()
while urls_slice:
page_n += 1
page = render_template('zenodo_sitemap/sitemap.xml',
urlset=filter(None, urls_slice))
sitemap.set_cache('sitemap:' + str(page_n), page)
urls_slice = list(itertools.islice(urls, max_url_count))
urlset = [
{
'loc': url_for('zenodo_sitemap.sitemappage',
page=pn, _external=True,
_scheme=url_scheme)
} for pn in range(1, page_n+1)]
index_page = render_template('zenodo_sitemap/sitemapindex.xml',
urlset=urlset, url_scheme=url_scheme)
sitemap.set_cache('sitemap:0', index_page)
| 2,706 | Python | .py | 59 | 39.576271 | 76 | 0.683352 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,528 | __init__.py | zenodo_zenodo/zenodo/modules/sitemap/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""ZenodoSitemap package."""
from __future__ import absolute_import, print_function
| 1,053 | Python | .py | 25 | 41.04 | 76 | 0.772904 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,529 | views.py | zenodo_zenodo/zenodo/modules/sitemap/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Redirects for legacy URLs."""
from __future__ import absolute_import, print_function, unicode_literals
from flask import Blueprint, abort, current_app
from invenio_cache import current_cache
blueprint = Blueprint(
'zenodo_sitemap',
__name__,
url_prefix='',
template_folder='templates',
static_folder='static',
)
def _get_cached_or_404(page):
data = current_cache.get('sitemap:' + str(page))
if data:
return current_app.response_class(data, mimetype='text/xml')
else:
abort(404)
@blueprint.route('/sitemap.xml', methods=['GET', ])
def sitemapindex():
"""Get the sitemap index."""
return _get_cached_or_404(0)
@blueprint.route('/sitemap<int:page>.xml', methods=['GET', ])
def sitemappage(page):
"""Get the sitemap page."""
return _get_cached_or_404(page)
| 1,796 | Python | .py | 48 | 34.916667 | 76 | 0.733333 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,530 | generators.py | zenodo_zenodo/zenodo/modules/sitemap/generators.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Sitemap generators."""
from __future__ import absolute_import, print_function
import arrow
from flask import current_app, url_for
from invenio_communities.models import Community
from invenio_db import db
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_records.models import RecordMetadata
def _sitemapdtformat(dt):
"""Convert a datetime to a W3 Date and Time format.
Converts the date to a minute-resolution datetime timestamp with a special
UTC designator 'Z'. See more information at
https://www.w3.org/TR/NOTE-datetime.
"""
adt = arrow.Arrow.fromdatetime(dt).to('utc')
return adt.format('YYYY-MM-DDTHH:mm:ss') + 'Z'
def records_generator():
"""Generate the records links."""
q = (db.session.query(PersistentIdentifier, RecordMetadata)
.join(RecordMetadata,
RecordMetadata.id == PersistentIdentifier.object_uuid)
.filter(PersistentIdentifier.status == PIDStatus.REGISTERED,
PersistentIdentifier.pid_type == 'recid'))
scheme = current_app.config['ZENODO_SITEMAP_URL_SCHEME']
for pid, rm in q.yield_per(1000):
yield {
'loc': url_for('invenio_records_ui.recid', pid_value=pid.pid_value,
_external=True, _scheme=scheme),
'lastmod': _sitemapdtformat(rm.updated)
}
def communities_generator():
"""Generate the communities links."""
q = Community.query.filter(Community.deleted_at.is_(None))
scheme = current_app.config['ZENODO_SITEMAP_URL_SCHEME']
for comm in q.yield_per(1000):
for endpoint in 'detail', 'search', 'about':
yield {
'loc': url_for('invenio_communities.{}'.format(endpoint),
community_id=comm.id, _external=True,
_scheme=scheme),
'lastmod': _sitemapdtformat(comm.updated)
}
generator_fns = [
records_generator,
communities_generator,
]
| 2,975 | Python | .py | 69 | 37.42029 | 79 | 0.697546 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,531 | ext.py | zenodo_zenodo/zenodo/modules/theme/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Jinja utilities for Invenio."""
from __future__ import absolute_import, print_function
import base64
import hashlib
from flask import current_app, render_template, request
def too_many_requests(e):
"""Error handler to show a 429.html page in case of a 429 error."""
return render_template(current_app.config['THEME_429_TEMPLATE']), 429
def bad_request(e):
"""Error handler to show a 400.html page in case of a 400 error."""
return render_template(
current_app.config['THEME_400_TEMPLATE'], error=e), 400
def useragent_and_ip_limit_key():
"""Create key for the rate limiting."""
ua_hash = hashlib.sha256(str(request.user_agent).encode('utf8')).digest()
return u'{}:{}'.format(
base64.b64encode(ua_hash).decode('ascii'), request.remote_addr
)
class ZenodoTheme(object):
"""Zenodo theme extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
app.register_error_handler(429, too_many_requests)
app.register_error_handler(400, bad_request)
| 2,144 | Python | .py | 51 | 38.568627 | 77 | 0.723906 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,532 | collect.py | zenodo_zenodo/zenodo/modules/theme/collect.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Flask-Collect filter to remove app.static_folder from source list."""
from __future__ import absolute_import, print_function
from flask import current_app
def collect_staticroot_removal(blueprints):
"""Remove collect's static root folder from list."""
collect_root = current_app.extensions['collect'].static_root
return [bp for bp in blueprints if (
bp.has_static_folder and bp.static_folder != collect_root)]
| 1,405 | Python | .py | 31 | 43.516129 | 76 | 0.765522 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,533 | __init__.py | zenodo_zenodo/zenodo/modules/theme/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo theme."""
from __future__ import absolute_import, print_function
| 1,044 | Python | .py | 25 | 40.68 | 76 | 0.770895 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,534 | views.py | zenodo_zenodo/zenodo/modules/theme/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015-2020 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Theme blueprint in order for template and static files to be loaded."""
from __future__ import absolute_import, print_function
from datetime import datetime, timedelta
import bleach
from flask import Blueprint
from flask_principal import ActionNeed
from invenio_access import Permission
from zenodo.modules.records.serializers.fields.html import ALLOWED_ATTRS, \
ALLOWED_TAGS
blueprint = Blueprint(
'zenodo_theme',
__name__,
template_folder='templates',
static_folder='static',
)
"""Theme blueprint used to define template and static folders."""
@blueprint.app_template_filter('sanitize_html')
def sanitize_html(value):
"""Sanitizes HTML using the bleach library."""
return bleach.clean(
value,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRS,
strip=True,
).strip()
@blueprint.app_template_global()
def current_user_is_admin():
"""Returns ``True`` if current user has the ``admin-access`` permission."""
return Permission(ActionNeed('admin-access')).can()
@blueprint.app_template_test('older_than')
def older_than(dt, **timedelta_kwargs):
"""Check if a date is older than a provided timedelta.
:param dt: The datetime to check.
:param timedelta_kwargs: Passed to ``datetime.timedelta(...)``.
"""
return (datetime.utcnow() - dt) > timedelta(**timedelta_kwargs)
| 2,336 | Python | .py | 59 | 36.813559 | 79 | 0.746908 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,535 | bundles.py | zenodo_zenodo/zenodo/modules/theme/bundles.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""JS/CSS bundles for theme."""
from __future__ import absolute_import, print_function
from flask_assets import Bundle
from invenio_assets import NpmBundle
css = NpmBundle(
Bundle(
'scss/styles.scss',
filters='node-scss, cleancss',
depends=('scss/*.scss', ),
),
Bundle(
'node_modules/angular-loading-bar/build/loading-bar.css',
'node_modules/typeahead.js-bootstrap-css/typeaheadjs.css',
'node_modules/bootstrap-switch/dist/css/bootstrap3'
'/bootstrap-switch.css',
filters='cleancss',
),
output="gen/zenodo.%(version)s.css",
npm={
'bootstrap-sass': '~3.3.5',
'bootstrap-switch': '~3.0.2',
'font-awesome': '~4.4.0',
'typeahead.js-bootstrap-css': '~1.2.1',
}
)
"""Default CSS bundle."""
js = NpmBundle(
Bundle(
'node_modules/almond/almond.js',
'js/modernizr-custom.js',
filters='uglifyjs',
),
Bundle(
'js/zenodo.js',
filters='requirejs',
),
depends=(
'js/zenodo.js',
'js/zenodo/*.js',
'js/zenodo/filters/*.js',
'js/github/*.js',
'node_modules/angular-loading-bar/build/*.js',
'node_modules/typeahead.js/dist/*.js',
'node_modules/invenio-csl-js/dist/*.js',
'node_modules/bootstrap-switch/dist/js/bootstrap-switch.js',
),
filters='jsmin',
output="gen/zenodo.%(version)s.js",
npm={
'almond': '~0.3.1',
'angular': '~1.4.9',
'angular-sanitize': '~1.4.9',
'angular-loading-bar': '~0.9.0',
'bootstrap-switch': '~3.0.2',
'invenio-csl-js': '~0.1.3',
'typeahead.js': '~0.11.1',
}
)
"""Default JavaScript bundle."""
search_js = NpmBundle(
Bundle(
'js/zenodo.search.js',
filters='requirejs',
),
depends=(
'node_modules/invenio-search-js/dist/*.js',
'node_modules/angular-strap/dist/*.js',
'js/invenio_communities/*.js',
'js/invenio_communities/directives/*.js',
),
filters='jsmin',
output="gen/zenodo.search.%(version)s.js",
npm={
'clipboard': '1.5.12',
'invenio-search-js': '~0.2.0',
'angular-strap': '~2.3.9',
}
)
"""Search JavaScript bundle (with communities support)."""
| 3,268 | Python | .py | 102 | 26.77451 | 76 | 0.634695 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,536 | ext.py | zenodo_zenodo/zenodo/modules/frontpage/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""ZenodoFrontpage module."""
from __future__ import absolute_import, print_function
from . import config
class ZenodoFrontpage(object):
"""Zenodo frontpage extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['zenodo-frontpage'] = self
@staticmethod
def init_config(app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('ZENODO_FRONTPAGE'):
app.config.setdefault(k, getattr(config, k))
| 1,653 | Python | .py | 42 | 35.380952 | 76 | 0.714107 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,537 | config.py | zenodo_zenodo/zenodo/modules/frontpage/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configuration for Zenodo Frontpage."""
from __future__ import absolute_import, print_function
ZENODO_FRONTPAGE_BETA_FEATURES = [
'citations'
]
ZENODO_FRONTPAGE_FEATURED_COMMUNITIES_COUNT = 3
"""Number of featured communities to be displayed on frontpage."""
ZENODO_FRONTPAGE_FEATURED_RECORDS = []
"""Record PIDs for featured records on frontpage."""
ZENODO_FRONTPAGE_FEATURED_TITLE = None
"""Featured communities and records title (e.g. 'Astrophysics software')."""
ZENODO_FRONTPAGE_FEATURED_COMMUNITY = None
"""Community used for featured records 'Browse more ...' link."""
| 1,556 | Python | .py | 36 | 41.916667 | 76 | 0.772637 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,538 | api.py | zenodo_zenodo/zenodo/modules/frontpage/api.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Frontpage records."""
from __future__ import absolute_import, print_function
from elasticsearch_dsl.query import Q
from invenio_search.api import RecordsSearch
class FrontpageRecordsSearch(RecordsSearch):
"""Search class for records that goes on the frontpage."""
class Meta:
"""Default index and filter for frontpage search."""
index = 'records'
default_filter = Q(
'query_string',
query=('communities:zenodo '
'AND access_right:open '
'AND relations.version.is_last:true')
)
| 1,556 | Python | .py | 38 | 37.078947 | 76 | 0.726009 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,539 | __init__.py | zenodo_zenodo/zenodo/modules/frontpage/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo frontpage."""
from __future__ import absolute_import, print_function
| 1,048 | Python | .py | 25 | 40.84 | 76 | 0.771792 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,540 | decorators.py | zenodo_zenodo/zenodo/modules/frontpage/decorators.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo frontpage decorators."""
from __future__ import absolute_import, print_function
from functools import wraps
from flask import session
from flask_login import current_user
from invenio_cache import current_cache
def has_flashes_or_authenticated_user():
"""Return True if there are pending flashes or user is authenticated."""
return '_flashes' in session or current_user.is_authenticated
def cached_unless_authenticated_or_flashes(timeout=50, key_prefix='default'):
"""Cache anonymous traffic."""
def caching(f):
@wraps(f)
def wrapper(*args, **kwargs):
cache_fun = current_cache.cached(
timeout=timeout, key_prefix=key_prefix,
unless=has_flashes_or_authenticated_user)
return cache_fun(f)(*args, **kwargs)
return wrapper
return caching
| 1,820 | Python | .py | 43 | 38.813953 | 77 | 0.740531 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,541 | views.py | zenodo_zenodo/zenodo/modules/frontpage/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo frontpage blueprint."""
from __future__ import absolute_import, print_function
import os
from flask import Blueprint, current_app, flash, render_template, request, \
send_from_directory, session
from flask_babelex import lazy_gettext as _
from flask_menu import current_menu
from invenio_communities.models import FeaturedCommunity
from ..records.resolvers import record_resolver
from .api import FrontpageRecordsSearch
from .decorators import cached_unless_authenticated_or_flashes
blueprint = Blueprint(
'zenodo_frontpage',
__name__,
url_prefix='',
template_folder='templates',
)
@blueprint.before_app_first_request
def init_menu():
"""Initialize menu before first request."""
item = current_menu.submenu('main.deposit')
item.register(
'invenio_deposit_ui.index',
_('Upload'),
order=2,
)
item = current_menu.submenu('main.communities')
item.register(
'invenio_communities.index',
_('Communities'),
order=3,
)
@blueprint.route('/')
@cached_unless_authenticated_or_flashes(timeout=600, key_prefix='frontpage')
def index():
"""Frontpage blueprint."""
msg = current_app.config.get('FRONTPAGE_MESSAGE')
if msg:
flash(msg, category=current_app.config.get(
'FRONTPAGE_MESSAGE_CATEGORY', 'info'))
featured_comms_count = current_app.config.get(
'ZENODO_FRONTPAGE_FEATURED_COMMUNITIES_COUNT', 3)
featured_communities = [
fc.community for fc in FeaturedCommunity.query.order_by(
FeaturedCommunity.start_date.desc()).limit(featured_comms_count)
]
featured_recids = current_app.config.get(
'ZENODO_FRONTPAGE_FEATURED_RECORDS', [])
featured_records = [record_resolver.resolve(r) for r in featured_recids]
return render_template(
'zenodo_frontpage/index.html',
records=FrontpageRecordsSearch()[:10].sort('-_created').execute(),
featured_communities=featured_communities,
featured_records=featured_records,
)
@blueprint.route('/favicon.ico')
def favicon():
"""Return the favicon."""
return send_from_directory(
os.path.join(current_app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon'
)
@blueprint.route('/ping', methods=['HEAD', 'GET'])
def ping():
"""Load balancer ping view."""
return 'OK'
| 3,356 | Python | .py | 89 | 33.606742 | 76 | 0.720086 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,542 | models.py | zenodo_zenodo/zenodo/modules/records/models.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Helper models for Zenodo data model."""
from __future__ import absolute_import, print_function, unicode_literals
import json
from datetime import datetime
from os.path import dirname, join
import arrow
from elasticsearch_dsl.utils import AttrDict
from flask import current_app
from flask_babelex import format_date, gettext
from invenio_search import current_search_client
from invenio_search.api import RecordsSearch
from jsonref import JsonRef
from speaklater import make_lazy_gettext
from .utils import is_valid_openaire_type
_ = make_lazy_gettext(lambda: gettext)
class AccessRight(object):
"""Class defining access right status."""
OPEN = 'open'
EMBARGOED = 'embargoed'
RESTRICTED = 'restricted'
CLOSED = 'closed'
_all = (
(OPEN, _('Open Access')),
(EMBARGOED, _('Embargoed Access')),
(RESTRICTED, _('Restricted Access')),
(CLOSED, _('Closed Access')),
)
_icon = {
OPEN: 'fa-unlock',
EMBARGOED: 'fa-ban',
RESTRICTED: 'fa-key',
CLOSED: 'fa-lock',
}
_description = {
OPEN: _('Files are publicly accessible.'),
EMBARGOED: _('Files are currently under embargo but will be publicly '
'accessible after {date}.'),
RESTRICTED: _('You may request access to the files in this upload, '
'provided that you fulfil the conditions below. The '
'decision whether to grant/deny access is solely under '
'the responsibility of the record owner.'),
CLOSED: _('Files are not publicly accessible.'),
}
_category = {
OPEN: 'success',
EMBARGOED: 'warning',
RESTRICTED: 'danger',
CLOSED: 'danger',
}
@staticmethod
def is_embargoed(embargo_date):
"""Test if date is still under embargo."""
return arrow.get(embargo_date).date() > datetime.utcnow().date()
@classmethod
def is_valid(cls, value):
"""Test if access right is valid."""
return bool([key for key, title in cls._all if key == value])
@classmethod
def get(cls, value, embargo_date=None):
"""Get access right."""
if embargo_date is not None and cls.EMBARGOED == value and \
not cls.is_embargoed(embargo_date):
return cls.OPEN
return value
@classmethod
def as_icon(cls, value):
"""Get icon for a specific status."""
return cls._icon[value]
@classmethod
def as_title(cls, value):
"""Get title for a specific status."""
return dict(cls._all)[value]
@classmethod
def as_description(cls, value, embargo_date=None):
"""Get description for a specific status."""
return cls._description[value].format(
date=format_date(embargo_date, 'long'))
@classmethod
def as_category(cls, value, **kwargs):
"""Get title for a specific status."""
cat = cls._category[value]
return kwargs[cat] if cat in kwargs else cat
@classmethod
def as_options(cls):
"""Return list of access rights as options."""
return cls._all
@classmethod
def get_expired_embargos(cls):
"""Get records for which the embargo period have expired."""
endpoint = current_app.config['RECORDS_REST_ENDPOINTS']['recid']
s = RecordsSearch(
using=current_search_client,
index=endpoint['search_index']
).query(
'query_string',
query='access_right:{0} AND embargo_date:{{* TO {1}}}'.format(
cls.EMBARGOED,
# Uses timestamp instead of date on purpose.
datetime.utcnow().isoformat()
),
allow_leading_wildcard=False
).source(False)
return [hit.meta.id for hit in s.scan()]
class ObjectType(object):
"""Class to load object types data."""
index_id = None
index_internal_id = None
types = None
subtypes = None
@classmethod
def _load_data(cls):
"""Load object types for JSON data."""
if cls.index_id is None:
with open(join(dirname(__file__), "data", "objecttypes.json")) \
as fp:
data = json.load(fp)
cls.index_internal_id = {}
cls.index_id = {}
cls.types = set()
cls.subtypes = {}
for objtype in data:
cls.index_internal_id[objtype['internal_id']] = objtype
cls.index_id[objtype['id'][:-1]] = objtype
if '-' in objtype['internal_id']:
type_, subtype = objtype['internal_id'].split('-')
cls.types.add(type_)
if type_ not in cls.subtypes:
cls.subtypes[type_] = set()
cls.subtypes[type_].add(subtype)
else:
cls.types.add(objtype['internal_id'])
@classmethod
def validate_internal_id(cls, id):
"""Check if the provided ID corresponds to the internal ones."""
cls._load_data()
return id in cls.index_internal_id
@classmethod
def _jsonloader(cls, uri, **dummy_kwargs):
"""Local JSON loader for JsonRef."""
cls._load_data()
return cls.index_id[uri]
@classmethod
def get(cls, value):
"""Get object type value."""
cls._load_data()
try:
return JsonRef.replace_refs(
cls.index_internal_id[value],
jsonschema=True,
loader=cls._jsonloader)
except KeyError:
return None
@classmethod
def get_types(cls):
"""Get object type value."""
cls._load_data()
return cls.types
@classmethod
def get_subtypes(cls, type_):
"""Get object type value."""
cls._load_data()
return cls.subtypes[type_]
@classmethod
def get_by_dict(cls, value):
"""Get object type dict with type and subtype key."""
if not value:
return None
if 'subtype' in value:
if isinstance(value, AttrDict):
value = value.to_dict()
internal_id = "{0}-{1}".format(
value.get('type', ''),
value.get('subtype', '')
)
else:
internal_id = value['type']
return cls.get(internal_id)
@classmethod
def get_openaire_subtype(cls, value):
"""Get the OpenAIRE community-specific subtype.
OpenAIRE community-specific subtype requires that the record is
accepted to the relevant community.
:param value: Full 'metadata' dictionary. Higher level metadata is
required since we are fetching both 'resource_type' and
'communities'.
:type value: dict
:returns: Subtype in the form "openaire:<OA-comm-ID>:<OA-subtype-ID>"
or None.
:rtype: str
"""
comms = value.get('communities', [])
oa_type = value['resource_type'].get('openaire_subtype')
if oa_type and is_valid_openaire_type(value['resource_type'], comms):
return 'openaire:' + oa_type
@classmethod
def get_cff_type(cls, value):
"""Get resource type of a CFF type."""
resource_type_obj = cls.index_internal_id
for key in resource_type_obj:
if value == resource_type_obj[key].get('cff'):
return resource_type_obj[key]['internal_id']
return None
| 8,569 | Python | .py | 225 | 29.511111 | 78 | 0.605301 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,543 | indexer.py | zenodo_zenodo/zenodo/modules/records/indexer.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record modification prior to indexing."""
from __future__ import absolute_import, print_function
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_pidrelations.proxies import current_pidrelations
from invenio_pidrelations.serializers.utils import serialize_relations
from invenio_pidstore.models import PersistentIdentifier
from zenodo.modules.records.serializers.pidrelations import \
serialize_related_identifiers
from zenodo.modules.records.utils import build_record_custom_fields
from zenodo.modules.spam.models import SafelistEntry
from zenodo.modules.stats.utils import build_record_stats
def indexer_receiver(sender, json=None, record=None, index=None,
**dummy_kwargs):
"""Connect to before_record_index signal to transform record for ES."""
if not index.startswith('records-') or record.get('$schema') is None:
return
# Remove files from index if record is not open access.
if json['access_right'] != 'open' and '_files' in json:
del json['_files']
else:
# Compute file count and total size
files = json.get('_files', [])
json['filecount'] = len(files)
json['size'] = sum([f.get('size', 0) for f in files])
pid = PersistentIdentifier.query.filter(
PersistentIdentifier.pid_value == str(record['recid']),
PersistentIdentifier.pid_type == 'recid',
PersistentIdentifier.object_uuid == record.id,
).one_or_none()
if pid:
pv = PIDVersioning(child=pid)
if pv.exists:
relations = serialize_relations(pid)
else:
relations = {'version': [{'is_last': True, 'index': 0}, ]}
if relations:
json['relations'] = relations
rels = serialize_related_identifiers(pid)
if rels:
json.setdefault('related_identifiers', []).extend(rels)
for loc in json.get('locations', []):
if loc.get('lat') and loc.get('lon'):
loc['point'] = {'lat': loc['lat'], 'lon': loc['lon']}
# Remove internal data.
if '_internal' in json:
del json['_internal']
json['_stats'] = build_record_stats(record['recid'],
record.get('conceptrecid'))
json['_safelisted'] = SafelistEntry.get_record_status(record)
custom_es_fields = build_record_custom_fields(json)
for es_field, es_value in custom_es_fields.items():
json[es_field] = es_value
| 3,437 | Python | .py | 75 | 40.253333 | 76 | 0.695341 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,544 | ext.py | zenodo_zenodo/zenodo/modules/records/ext.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015-2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Jinja utilities for Invenio."""
from __future__ import absolute_import, print_function
import collections
from invenio_indexer.signals import before_record_index
from invenio_pidrelations.contrib.versioning import versioning_blueprint
from six import itervalues
from werkzeug.utils import cached_property
from zenodo.modules.records.models import ObjectType
from . import config
from .custom_metadata import CustomMetadataAPI
from .indexer import indexer_receiver
from .proxies import current_zenodo_records
from .utils import serialize_record, transform_record
from .views import blueprint, record_jinja_context
class ZenodoRecords(object):
"""Zenodo records extension."""
def __init__(self, app=None):
"""Extension initialization."""
if app:
self.init_app(app)
@cached_property
def resource_types(self):
"""Create an object list with the available resource types."""
resource_list = []
for item in itervalues(ObjectType.index_id):
internal_id = item['internal_id']
parent = item.get('parent')
if parent:
resolved_parent = ObjectType.get(item['internal_id'])['parent']
parent_type_title = resolved_parent['title']['en']
elif item.get('children'):
continue
else:
parent_type_title = ''
resource_list.append({
'type': parent_type_title,
'title': item['title']['en'],
'id': internal_id
})
resource_list.sort(key=lambda x: x['title'])
return resource_list
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
# Register context processors
app.context_processor(record_jinja_context)
app.context_processor(
lambda: dict(current_zenodo_records=current_zenodo_records))
# Register blueprint
app.register_blueprint(blueprint)
# Add global record serializer template filter
app.add_template_filter(serialize_record, 'serialize_record')
app.add_template_filter(transform_record, 'transform_record')
# Register versioning blueprint
app.register_blueprint(versioning_blueprint)
self.custom_metadata = CustomMetadataAPI(
term_types=app.config.get('ZENODO_CUSTOM_METADATA_TERM_TYPES'),
vocabularies=app.config.get('ZENODO_CUSTOM_METADATA_VOCABULARIES'),
)
before_record_index.connect(indexer_receiver, sender=app)
app.extensions['zenodo-records'] = self
@staticmethod
def init_config(app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('ZENODO_'):
app.config.setdefault(k, getattr(config, k))
| 3,829 | Python | .py | 90 | 35.811111 | 79 | 0.688692 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,545 | config.py | zenodo_zenodo/zenodo/modules/records/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configuration for Zenodo Records."""
from __future__ import absolute_import, print_function
import six
from flask_babelex import gettext
from speaklater import make_lazy_gettext
_ = make_lazy_gettext(lambda: gettext)
ZENODO_RECORDS_UI_CITATIONS_ENDPOINT = 'https://zenodo-broker-qa.web.cern.ch/api/relationships'
ZENODO_RECORDS_UI_CITATIONS_ENABLE = False
ZENODO_RELATION_RULES = {
'f1000research': [{
'prefix': '10.12688/f1000research',
'relation': 'isCitedBy',
'scheme': 'doi',
'text': 'Published in',
'image': 'img/f1000research.jpg',
}],
'inspire': [{
'prefix': 'http://inspirehep.net/record/',
'relation': 'isSupplementedBy',
'scheme': 'url',
'text': 'Available in',
'image': 'img/inspirehep.png',
}],
'briefideas': [{
'prefix': 'http://beta.briefideas.org/',
'relation': 'isIdenticalTo',
'scheme': 'url',
'text': 'Published in',
'image': 'img/briefideas.png',
}],
'zenodo': [{
'prefix': 'https://github.com',
'relation': 'isSupplementTo',
'scheme': 'url',
'text': 'Available in',
'image': 'img/github.png',
}, {
'prefix': '10.1109/JBHI',
'relation': 'isCitedBy',
'scheme': 'doi',
'text': 'Published in',
'image': 'img/ieee.jpg',
}],
}
ZENODO_COMMUNITY_BRANDING = [
'biosyslit',
'lory',
]
ZENODO_RELATION_TYPES = [
('isCitedBy', _('Cited by')),
('cites', _('Cites')),
('isSupplementTo', _('Supplement to')),
('isSupplementedBy', _('Supplementary material')),
('references', _('References')),
('isReferencedBy', _('Referenced by')),
('isPublishedIn', _('Published in')),
('isNewVersionOf', _('Previous versions')),
('isPreviousVersionOf', _('New versions')),
('isContinuedBy', _('Continued by')),
('continues', _('Continues')),
('isDescribedBy', _('Described by')),
('describes', _('Describes')),
('isPartOf', _('Part of')),
('hasPart', _('Has part')),
('isReviewedBy', _('Reviewed by')),
('reviews', _('Reviews')),
('isDocumentedBy', _('Documented by')),
('documents', _('Documents')),
('compiles', _('Compiles')),
('isCompiledBy', _('Compiled by')),
('isDerivedFrom', _('Derived from')),
('isSourceOf', _('Source of')),
('requires', _('Requires')),
('isRequiredBy', _('Required by')),
('isObsoletedBy', _('Obsoleted by')),
('obsoletes', _('Obsoletes')),
('isIdenticalTo', _('Identical to')),
]
ZENODO_LOCAL_DOI_PREFIXES = []
ZENODO_DOIID4RECID = {
7468: 7448,
7458: 7457,
7467: 7447,
7466: 7446,
7465: 7464,
7469: 7449,
7487: 7486,
7482: 7481,
7484: 7483,
}
"""Mapping of recids to the id used in generated DOIs.
Wrong DOIs were minted for a short period in 2013 due to mistake in the legacy
system.
"""
ZENODO_CUSTOM_METADATA_TERM_TYPES = {
'keyword': six.string_types,
'text': six.string_types,
'relationship': dict,
}
"""Custom metadata term types mapping."""
ZENODO_CUSTOM_METADATA_VOCABULARIES = {}
"""Custom metadata vocabularies.
..code-block:: python
ZENODO_CUSTOM_METADATA_VOCABULARIES = {
'dwc': {
'@context': 'http://rs.tdwg.org/dwc/terms/',
'attributes': {
'family': {'type': 'keyword', 'label': 'Family'},
'genus': {'type': 'keyword', 'label': 'Genus'},
'behavior': {'type': 'text', 'label': 'Behaviour'}
}
},
'obo': {
'@context': 'http://purl.obolibrary.org/obo/',
'attributes': {
'RO_0002453': {'type': 'relationship', 'label': 'hostOf'},
}
},
},
"""
ZENODO_RECORDS_FUNDER_PROGRAM_MATCHES = {
'10.13039/100010661': ('^H2020$', '^Horizon 2020',),
'10.13039/100011102': ('^FP7$',),
'10.13039/100018693': ('^HE$', '^Horizon Europe',),
}
| 4,957 | Python | .py | 148 | 28.222973 | 95 | 0.608895 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,546 | custom_metadata.py | zenodo_zenodo/zenodo/modules/records/custom_metadata.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Custom metadata utilities."""
from werkzeug.utils import cached_property
from zenodo.modules.utils import obj_or_import_string
class CustomMetadataAPI(object):
"""Custom metadata helper class."""
def __init__(self, term_types=None, vocabularies=None):
"""Initialize custom metadata API object."""
self._term_types = term_types or {}
self._vocabularies = vocabularies or {}
self._validate()
@cached_property
def term_types(self):
"""Get available field types."""
return {k: obj_or_import_string(v)
for k, v in self._term_types.items()}
@cached_property
def vocabularies(self):
"""Get available vocabularies."""
return self._vocabularies
@cached_property
def available_vocabulary_set(self):
"""Get available vocabularies."""
vocabulary = []
for scheme in self.vocabularies:
for value in self.vocabularies[scheme]['attributes']:
vocabulary.append(u'{}:{}'.format(scheme, value))
return set(vocabulary)
@cached_property
def terms(self):
"""Term-to-fieldtype lookup."""
result = {}
for vocab, cfg in self.vocabularies.items():
vocab_url = cfg['@context']
for attr in cfg['attributes']:
term = u'{}:{}'.format(vocab, attr)
term_conf = cfg['attributes'][attr]
result[term] = dict(
term_conf,
url=u'{}{}'.format(vocab_url, attr)
)
return result
def _validate(self):
"""Validates term types, vocabularies and definitions."""
valid_term_types = set(self.term_types.keys())
assert all(
(v['@context'] and v['attributes'] and
set([k['type'] for k in v['attributes'].values()]) <=
valid_term_types)
for k, v in self.vocabularies.items())
| 2,924 | Python | .py | 72 | 33.652778 | 76 | 0.645899 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,547 | tasks.py | zenodo_zenodo/zenodo/modules/records/tasks.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017, 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Celery background tasks."""
from __future__ import absolute_import, print_function
from datetime import datetime
from celery import shared_task
from flask import current_app
from invenio_cache import current_cache
from invenio_db import db
from invenio_indexer.api import RecordIndexer
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.datacite import DataCiteProvider
from invenio_records import Record
from lxml import etree
from zenodo.modules.records.models import AccessRight
from zenodo.modules.records.serializers import datacite_v41
from zenodo.modules.records.utils import find_registered_doi_pids, xsd41
@shared_task(ignore_result=True)
def update_expired_embargos():
"""Release expired embargoes every midnight."""
record_ids = AccessRight.get_expired_embargos()
for record in Record.get_records(record_ids):
record['access_right'] = AccessRight.OPEN
record.commit()
db.session.commit()
indexer = RecordIndexer()
indexer.bulk_index(record_ids)
indexer.process_bulk_queue()
@shared_task(ignore_result=True, rate_limit='1000/h')
def update_datacite_metadata(doi, object_uuid, job_id):
"""Update DataCite metadata of a single PersistentIdentifier.
:param doi: Value of doi PID, with pid_type='doi'. It could be a normal
DOI or a concept DOI.
:type doi: str
:param object_uuid: Record Metadata UUID.
:type object_uuid: str
:param job_id: id of the job to which this task belongs.
:type job_id: str
"""
task_details = current_cache.get('update_datacite:task_details')
if task_details is None or job_id != task_details['job_id']:
return
record = Record.get_record(object_uuid)
dcp = DataCiteProvider.get(doi)
if dcp.pid.status != PIDStatus.REGISTERED:
return
doc = datacite_v41.serialize(dcp.pid, record)
for validator in xsd41():
validator.assertValid(etree.XML(doc.encode('utf8')))
url = None
if doi == record.get('doi'):
url = current_app.config['ZENODO_RECORDS_UI_LINKS_FORMAT'].format(
recid=str(record['recid']))
elif doi == record.get('conceptdoi'):
url = current_app.config['ZENODO_RECORDS_UI_LINKS_FORMAT'].format(
recid=str(record['conceptrecid']))
result = dcp.update(url, doc)
if result is True:
dcp.pid.updated = datetime.utcnow()
db.session.commit()
@shared_task(ignore_result=True)
def schedule_update_datacite_metadata(max_count):
"""Schedule the update of DataCite metadata."""
task_details = current_cache.get('update_datacite:task_details')
if task_details is None or 'from_date' not in task_details or 'until_date' not in task_details:
return
doi_pids = find_registered_doi_pids(task_details['from_date'],
task_details['until_date'],
current_app.config['ZENODO_LOCAL_DOI_PREFIXES'])
dois_count = doi_pids.count()
task_details['left_pids'] = dois_count
task_details['last_update'] = datetime.utcnow()
current_cache.set('update_datacite:task_details', task_details, timeout=-1)
if dois_count == 0:
if 'finish_date' not in task_details:
task_details['finish_date'] = datetime.utcnow()
current_cache.set('update_datacite:task_details', task_details, timeout=-1)
return
scheduled_dois_count = max_count if max_count < dois_count else dois_count
scheduled_dois_pids = doi_pids.limit(scheduled_dois_count)
for doi_pid in scheduled_dois_pids:
update_datacite_metadata.delay(doi_pid.pid_value,
str(doi_pid.object_uuid),
task_details['job_id'])
| 4,766 | Python | .py | 105 | 39.666667 | 99 | 0.706365 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,548 | facets.py | zenodo_zenodo/zenodo/modules/records/facets.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Facets factory for REST API."""
from __future__ import absolute_import, print_function
import re
from decimal import Decimal, InvalidOperation
from elasticsearch_dsl import Q
from invenio_rest.errors import FieldError, RESTValidationError
from zenodo.modules.records import current_custom_metadata
def geo_bounding_box_filter(name, field, type=None):
"""Create a geo bounding box filter.
:param field: Field name.
:param type: Method to use (``memory`` or ``indexed``).
:returns: Function that returns the Geo bounding box query.
"""
def inner(values):
if len(values) != 1:
raise RESTValidationError(
errors=[FieldError(name, 'Only one parameter is allowed.')])
values = [value.strip() for value in values[0].split(',')]
if len(values) != 4:
raise RESTValidationError(
errors=[FieldError(
name,
'Invalid bounds: four comma-separated numbers required. '
'Example: 143.37158,-38.99357,146.90918,-37.35269')])
try:
bottom_left_lon = Decimal(values[0])
bottom_left_lat = Decimal(values[1])
top_right_lon = Decimal(values[2])
top_right_lat = Decimal(values[3])
except InvalidOperation:
raise RESTValidationError(
errors=[FieldError(name, 'Invalid number in bounds.')])
try:
if not (-90 <= bottom_left_lat <= 90) or \
not (-90 <= top_right_lat <= 90):
raise RESTValidationError(
errors=[FieldError(
name, 'Latitude must be between -90 and 90.')])
if not (-180 <= bottom_left_lon <= 180) or \
not (-180 <= top_right_lon <= 180):
raise RESTValidationError(
errors=[FieldError(
name, 'Longitude must be between -180 and 180.')])
if top_right_lat <= bottom_left_lat:
raise RESTValidationError(
errors=[FieldError(
name, 'Top-right latitude must be greater than '
'bottom-left latitude.')])
except InvalidOperation: # comparison with "NaN" raises exception
raise RESTValidationError(
errors=[FieldError(
name, 'Invalid number: "NaN" is not a permitted value.')])
query = {
field: {
'top_right': {
'lat': top_right_lat,
'lon': top_right_lon,
},
'bottom_left': {
'lat': bottom_left_lat,
'lon': bottom_left_lon,
}
}
}
if type:
query['type'] = type
return Q('geo_bounding_box', **query)
return inner
def custom_metadata_filter(field):
"""Custom metadata fields filter.
:param field: Field name.
:returns: Function that returns the custom metadata query.
"""
def inner(values):
terms = current_custom_metadata.terms
available_terms = current_custom_metadata.available_vocabulary_set
conditions = []
for value in values:
# Matches this:
# [vocabulary:term]:[value]
parsed = re.match(
r'^\[(?P<key>[-\w]+\:[-\w]+)\]\:\[(?P<val>.+)\]$', value)
if not parsed:
raise RESTValidationError(
errors=[FieldError(
field, 'The parameter should have the format: '
'custom=[term]:[value].')])
parsed = parsed.groupdict()
search_key = parsed['key']
search_value = parsed['val']
if search_key not in available_terms:
raise RESTValidationError(
errors=[FieldError(
field, u'The "{}" term is not supported.'
.format(search_key))])
custom_fields_mapping = dict(
keyword='custom_keywords',
text='custom_text',
relationship='custom_relationships',
)
term_type = terms[search_key]['type']
es_field = custom_fields_mapping[term_type]
nested_clauses = [
{'term': {'{}.key'.format(es_field): search_key}},
]
if term_type in ('text', 'keyword'):
nested_clauses.append({
'query_string': {
'fields': ['{}.value'.format(es_field)],
'query': search_value,
}
})
elif term_type == 'relationship':
if ':' not in search_value:
raise RESTValidationError(
errors=[
FieldError(field, (
'Relationship terms search values should '
'follow the format "<sub>:<obj>".'))
])
sub, obj = search_value.split(':', 1)
if sub:
nested_clauses.append({'query_string': {
'fields': [es_field + '.subject'], 'query': sub}})
if obj:
nested_clauses.append({'query_string': {
'fields': [es_field + '.object'], 'query': obj}})
conditions.append({
'nested': {
'path': es_field,
'query': {'bool': {'must': nested_clauses}},
}
})
return Q('bool', must=conditions)
return inner
| 6,758 | Python | .py | 158 | 29.841772 | 78 | 0.532391 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,549 | api.py | zenodo_zenodo/zenodo/modules/records/api.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record API."""
from __future__ import absolute_import
from os.path import splitext
from flask import request
from invenio_db import db
from invenio_files_rest.models import ObjectVersion
from invenio_pidstore.models import PersistentIdentifier
from invenio_records.api import Record
from invenio_records_files.api import FileObject, FilesIterator, FilesMixin, \
MissingModelError, _writable
from invenio_records_files.models import RecordsBuckets
from .fetchers import zenodo_record_fetcher
class ZenodoFileObject(FileObject):
"""Zenodo file object."""
def dumps(self):
"""Create a dump."""
super(ZenodoFileObject, self).dumps()
self.data.update({
# Remove dot from extension.
'type': splitext(self.data['key'])[1][1:].lower(),
'file_id': str(self.file_id),
})
return self.data
class ZenodoFilesIterator(FilesIterator):
"""Zenodo files iterator."""
@_writable
def __setitem__(self, key, stream):
"""Add file inside a deposit."""
with db.session.begin_nested():
size = None
if request and request.files and request.files.get('file'):
size = request.files['file'].content_length or None
obj = ObjectVersion.create(
bucket=self.bucket, key=key, stream=stream, size=size)
self.filesmap[key] = self.file_cls(obj, {}).dumps()
self.flush()
class ZenodoFilesMixin(FilesMixin):
"""Metafiles mixin."""
@property
def extra_formats(self):
"""Get extra formats files iterator.
:returns: Files iterator.
"""
if self.model is None:
raise MissingModelError()
extra_formats_bucket = None
records_buckets = RecordsBuckets.query.filter_by(
record_id=self.id)
for record_bucket in records_buckets:
if self['_buckets'].get('extra_formats') == \
str(record_bucket.bucket.id):
extra_formats_bucket = record_bucket.bucket
if not extra_formats_bucket:
return None
else:
return self.files_iter_cls(
self, bucket=extra_formats_bucket, file_cls=self.file_cls)
@extra_formats.setter
def extra_formats(self, data):
"""Set files from data."""
current_files = self.extra_formats
if current_files:
raise RuntimeError('Can not update existing files.')
for key in data:
current_files[key] = data[key]
@property
def files(self):
"""Get files iterator.
:returns: Files iterator.
"""
if self.model is None:
raise MissingModelError()
records_buckets = RecordsBuckets.query.filter_by(
record_id=self.id)
bucket = None
for record_bucket in records_buckets:
if self['_buckets'].get('record') == str(record_bucket.bucket.id):
bucket = record_bucket.bucket
if self['_buckets'].get('deposit') == str(record_bucket.bucket.id):
bucket = record_bucket.bucket
if not bucket:
return None
return self.files_iter_cls(self, bucket=bucket, file_cls=self.file_cls)
class ZenodoRecord(Record, ZenodoFilesMixin):
"""Zenodo Record."""
file_cls = ZenodoFileObject
files_iter_cls = ZenodoFilesIterator
record_fetcher = staticmethod(zenodo_record_fetcher)
@property
def pid(self):
"""Return an instance of record PID."""
pid = self.record_fetcher(self.id, self)
return PersistentIdentifier.get(pid.pid_type, pid.pid_value)
@property
def depid(self):
"""Return depid of the record."""
return PersistentIdentifier.get(
pid_type='depid',
pid_value=self.get('_deposit', {}).get('id')
)
| 4,870 | Python | .py | 123 | 32.308943 | 79 | 0.65727 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,550 | httpretty_mock.py | zenodo_zenodo/zenodo/modules/records/httpretty_mock.py |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Mock HTTPretty.
HTTPretty fix related to SSL bug:
https://github.com/gabrielfalcao/HTTPretty/issues/242
"""
import httpretty
import httpretty.core
from httpretty import HTTPretty as OriginalHTTPretty
try:
from requests.packages.urllib3.contrib.pyopenssl import \
extract_from_urllib3, inject_into_urllib3
pyopenssl_override = True
except:
pyopenssl_override = False
class MyHTTPretty(OriginalHTTPretty):
"""
HTTPretty mock.
pyopenssl monkey-patches the default ssl_wrap_socket() function in the
'requests' library, but this can stop the HTTPretty socket monkey-patching
from working for HTTPS requests.
Our version extends the base HTTPretty enable() and disable()
implementations to undo and redo the pyopenssl monkey-patching,
respectively.
"""
@classmethod
def enable(cls):
"""Enable method mock."""
OriginalHTTPretty.enable()
if pyopenssl_override:
# Take out the pyopenssl version - use the default implementation
extract_from_urllib3()
@classmethod
def disable(cls):
"""Disable method mock."""
OriginalHTTPretty.disable()
if pyopenssl_override:
# Put the pyopenssl version back in place
inject_into_urllib3()
# Substitute in our version
HTTPretty = MyHTTPretty
httpretty.core.httpretty = MyHTTPretty
# May need to set other module-level attributes here, e.g. enable, reset etc,
# depending on your needs
httpretty.httpretty = MyHTTPretty
| 2,498 | Python | .py | 66 | 34.060606 | 78 | 0.74793 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,551 | utils.py | zenodo_zenodo/zenodo/modules/records/utils.py |
# -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017, 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Helper methods for Zenodo records."""
from __future__ import absolute_import, print_function
from os.path import dirname, join
from flask import current_app
from invenio_db import db
from invenio_indexer.utils import schema_to_index
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_records.api import Record
from invenio_search import current_search
from lxml import etree
from sqlalchemy import or_
from werkzeug.utils import import_string
from zenodo.modules.openaire import current_openaire
from zenodo.modules.records import current_custom_metadata
def schema_prefix(schema):
"""Get index prefix for a given schema."""
if not schema:
return None
index, doctype = schema_to_index(
schema, index_names=current_search.mappings.keys())
return index.split('-')[0]
def is_record(record):
"""Determine if a record is a bibliographic record."""
return schema_prefix(record.get('$schema')) == 'records'
def is_deposit(record):
"""Determine if a record is a deposit record."""
return schema_prefix(record.get('$schema')) == 'deposits'
def transform_record(record, pid, serializer, module=None, throws=True,
**kwargs):
"""Transform a record using a serializer."""
if isinstance(record, Record):
try:
module = module or 'zenodo.modules.records.serializers'
serializer = import_string('.'.join((module, serializer)))
return serializer.transform_record(pid, record, **kwargs)
except Exception:
current_app.logger.exception(
u'Record transformation failed {}.'.format(str(record.id)))
if throws:
raise
def serialize_record(record, pid, serializer, module=None, throws=True,
**kwargs):
"""Serialize record according to the passed serializer."""
if isinstance(record, Record):
try:
module = module or 'zenodo.modules.records.serializers'
serializer = import_string('.'.join((module, serializer)))
return serializer.serialize(pid, record, **kwargs)
except Exception:
current_app.logger.exception(
u'Record serialization failed {}.'.format(str(record.id)))
if throws:
raise
def is_doi_locally_managed(doi_value):
"""Determine if a DOI value is locally managed."""
return any(doi_value.startswith(prefix + '/') for prefix in
current_app.config['ZENODO_LOCAL_DOI_PREFIXES'])
def is_valid_openaire_type(resource_type, communities):
"""Check if the OpenAIRE subtype is corresponding with other metadata.
:param resource_type: Dictionary corresponding to 'resource_type'.
:param communities: list of communities identifiers
:returns: True if the 'openaire_subtype' (if it exists) is valid w.r.t.
the `resource_type.type` and the selected communities, False otherwise.
"""
if 'openaire_subtype' not in resource_type:
return True
oa_subtype = resource_type['openaire_subtype']
prefix = oa_subtype.split(':')[0] if ':' in oa_subtype else ''
cfg = current_openaire.openaire_communities
defined_comms = [c for c in cfg.get(prefix, {}).get('communities', [])]
type_ = resource_type['type']
subtypes = cfg.get(prefix, {}).get('types', {}).get(type_, [])
# Check if the OA subtype is defined in config and at least one of its
# corresponding communities is present
is_defined = any(t['id'] == oa_subtype for t in subtypes)
comms_match = len(set(communities) & set(defined_comms))
return is_defined and comms_match
def find_registered_doi_pids(from_date, until_date, prefixes):
"""Find all local DOI's which are in the REGISTERED state."""
query = db.session.query(PersistentIdentifier).filter(
PersistentIdentifier.pid_type == 'doi',
PersistentIdentifier.status == PIDStatus.REGISTERED,
PersistentIdentifier.updated.between(from_date, until_date)
)
query.filter(or_(PersistentIdentifier.pid_value.like(prefix + '/' + '%') for prefix in prefixes))
query.order_by(PersistentIdentifier.updated)
return query
def xsd41():
"""Load DataCite v4.1 full example as an etree."""
from zenodo.modules.records.httpretty_mock import httpretty
# Ensure the schema validator doesn't make any http requests.
with open(join(dirname(__file__), 'data', 'xml.xsd')) as fp:
xmlxsd = fp.read()
httpretty.enable()
httpretty.register_uri(
httpretty.GET,
'https://www.w3.org/2009/01/xml.xsd',
body=xmlxsd)
yield etree.XMLSchema(
file='file://' + join(dirname(__file__), 'data', 'metadata41.xsd')
)
httpretty.disable()
def build_record_custom_fields(record):
"""Build the custom metadata fields for ES indexing."""
valid_terms = current_custom_metadata.terms
es_custom_fields = dict(
custom_keywords=[],
custom_text=[],
custom_relationships=[],
)
custom_fields_mapping = {
'keyword': 'custom_keywords',
'text': 'custom_text',
'relationship': 'custom_relationships',
}
custom_metadata = record.get('custom', {})
for term, value in custom_metadata.items():
term_type = valid_terms.get(term)['type']
es_custom_field = custom_fields_mapping[term_type]
if term_type in ('text', 'keyword'):
es_custom_fields[es_custom_field].append({
'key': term,
'value': value
})
elif term_type == 'relationship':
for rel in value:
es_custom_fields[es_custom_field].append({
'key': term,
'subject': rel['subject'],
'object': rel['object'],
})
return {k: es_custom_fields[k] for k in es_custom_fields
if es_custom_fields[k]}
| 6,941 | Python | .py | 156 | 37.858974 | 101 | 0.674226 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,552 | __init__.py | zenodo_zenodo/zenodo/modules/records/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Data model package."""
from __future__ import absolute_import, print_function
from .proxies import current_custom_metadata, current_zenodo_records
__all__ = (
'current_custom_metadata',
'current_zenodo_records',
)
| 1,196 | Python | .py | 30 | 38.466667 | 76 | 0.766781 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,553 | admin.py | zenodo_zenodo/zenodo/modules/records/admin.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Admin view for updating datacite metadata."""
import uuid
from datetime import datetime
from flask import current_app, flash, redirect, request, url_for
from flask_admin import BaseView, expose
from flask_babelex import lazy_gettext as _
from flask_wtf import FlaskForm
from invenio_cache import current_cache
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired
from zenodo.modules.records.utils import find_registered_doi_pids
class UpdateDataciteForm(FlaskForm):
"""Form for updating datacite metadata."""
from_date = DateField(
_('From'),
description=_('Required.'),
validators=[DataRequired()],
)
until_date = DateField(
_('Until'),
description=_('Required.'),
validators=[DataRequired()],
)
class UpdateDataciteView(BaseView):
"""View for updating datacite metadata."""
@expose('/', methods=('GET', 'POST'))
def update_datacite(self):
"""."""
form = UpdateDataciteForm()
cancel_or_new_task_form = FlaskForm()
is_task_running = False
time = 0
task_details = current_cache.get('update_datacite:task_details')
if task_details:
is_task_running = True
if cancel_or_new_task_form.validate_on_submit():
current_cache.set('update_datacite:task_details', None)
return redirect(url_for('updatedataciteview.update_datacite'))
else:
if form.validate_on_submit():
from_date = request.form['from_date']
until_date = request.form['until_date']
action = request.form['action']
if action == 'SubmitDates':
if from_date > until_date:
flash("Error: the 'From' date should precede the 'Until' date.")
else:
pids_count = find_registered_doi_pids(from_date,
until_date,
current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
task_details = dict(
total_pids=pids_count
)
time = pids_count/current_app.config['DATACITE_UPDATING_RATE_PER_HOUR']
elif action == 'Confirm':
pids_count = find_registered_doi_pids(from_date,
until_date,
current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
task_details = dict(
start_date=datetime.utcnow(),
job_id=str(uuid.uuid4()),
from_date=from_date,
until_date=until_date,
total_pids=pids_count,
left_pids=pids_count,
last_update=datetime.utcnow()
)
current_cache.set('update_datacite:task_details',
task_details, timeout=-1)
return redirect(url_for('updatedataciteview.update_datacite'))
elif action == 'Cancel':
return redirect(url_for('updatedataciteview.update_datacite'))
return self.render('zenodo_records/update_datacite.html',
form=form,
cancel_or_new_task_form=cancel_or_new_task_form,
details=task_details,
is_task_running=is_task_running, time=time)
updatedatacite_adminview = {
'view_class': UpdateDataciteView,
'kwargs': {'name': 'Update Datacite', 'category': 'Records'},
}
| 4,822 | Python | .py | 104 | 33.730769 | 120 | 0.58195 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,554 | fetchers.py | zenodo_zenodo/zenodo/modules/records/fetchers.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""PID Fetchers."""
from __future__ import absolute_import, print_function
from invenio_pidstore.fetchers import FetchedPID
def zenodo_record_fetcher(dummy_record_uuid, data):
"""Fetch a record's identifiers."""
return FetchedPID(
provider=None,
pid_type='recid',
pid_value=str(data['recid']),
)
def zenodo_doi_fetcher(dummy_record_uuid, data):
"""Fetch a record's DOI."""
return FetchedPID(
provider=None,
pid_type='doi',
pid_value=str(data['doi']),
)
| 1,499 | Python | .py | 40 | 34.5 | 76 | 0.731405 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,555 | minters.py | zenodo_zenodo/zenodo/modules/records/minters.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Persistent identifier minters."""
from __future__ import absolute_import, print_function, unicode_literals
import idutils
from flask import current_app
from invenio_db import db
from invenio_oaiserver.minters import oaiid_minter
from invenio_pidstore.errors import PIDValueError
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_pidstore.providers.recordid import RecordIdProvider
from zenodo.modules.deposit.minters import zenodo_concept_recid_minter
def doi_generator(recid, prefix=None):
"""Generate a DOI."""
recid = current_app.config['ZENODO_DOIID4RECID'].get(recid, recid)
return '{prefix}/zenodo.{recid}'.format(
prefix=prefix or current_app.config['PIDSTORE_DATACITE_DOI_PREFIX'],
recid=recid
)
def is_local_doi(doi):
"""Check if DOI is a locally managed DOI."""
prefixes = [
current_app.config['PIDSTORE_DATACITE_DOI_PREFIX']
] + current_app.config['ZENODO_LOCAL_DOI_PREFIXES']
for p in prefixes:
if doi.startswith('{0}/'.format(p)):
return True
return False
def zenodo_record_minter(record_uuid, data):
"""Zenodo record minter.
Mint, or register if previously minted, the Concept RECID and RECID.
Mint the Concept DOI and DOI.
"""
if 'conceptrecid' not in data:
zenodo_concept_recid_minter(record_uuid, data)
if 'recid' in data:
recid = PersistentIdentifier.get('recid', data['recid'])
recid.assign('rec', record_uuid)
recid.register()
else:
recid = RecordIdProvider.create(
object_type='rec', object_uuid=record_uuid).pid
data['recid'] = int(recid.pid_value)
zenodo_doi_minter(record_uuid, data)
oaiid_minter(record_uuid, data)
if 'conceptdoi' not in data:
zenodo_concept_doi_minter(record_uuid, data)
return recid
def zenodo_concept_doi_minter(record_uuid, data):
"""Mint Concept DOI.
.. note::
Only Zenodo DOIs are allowed to have a Concept DOI and in general have
versioning applied.
"""
doi = data.get('doi')
assert 'conceptrecid' in data
# Only mint Concept DOI for Zenodo DOIs
if is_local_doi(doi):
conceptdoi = data.get('conceptdoi')
# Create a DOI if no DOI was found.
if not conceptdoi:
conceptdoi = doi_generator(data['conceptrecid'])
data['conceptdoi'] = conceptdoi
conceptdoi_pid = (PersistentIdentifier.query
.filter_by(pid_type='doi', pid_value=conceptdoi)
.one_or_none())
# Create if not already minted from previous versions
if not conceptdoi_pid:
return PersistentIdentifier.create(
'doi',
conceptdoi,
pid_provider='datacite',
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.RESERVED,
)
else:
# Update to point to latest record
conceptdoi_pid.assign(
object_type='rec',
object_uuid=record_uuid,
overwrite=True,
)
return conceptdoi_pid
def zenodo_doi_minter(record_uuid, data):
"""Mint DOI."""
doi = data.get('doi')
assert 'recid' in data
# Create a DOI if no DOI was found.
if not doi:
doi = doi_generator(data['recid'])
data['doi'] = doi
# Make sure it's a proper DOI
assert idutils.is_doi(doi)
# user-provided DOI (external or Zenodo DOI)
if doi != doi_generator(data['recid']):
if is_local_doi(doi):
# User should not provide a custom Zenodo DOI
# which is not dependent on the recid
raise PIDValueError('doi', doi)
else:
return PersistentIdentifier.create(
'doi',
doi,
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.RESERVED,
)
else: # Zenodo-generated DOI
return PersistentIdentifier.create(
'doi',
doi,
pid_provider='datacite',
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.RESERVED,
)
def zenodo_doi_updater(record_uuid, data):
"""Update the DOI (only external DOIs)."""
assert 'recid' in data
doi = data.get('doi')
assert doi
assert idutils.is_doi(doi)
# If the DOI is the same as an already generated one, do nothing
if doi == doi_generator(data['recid']):
return
if is_local_doi(doi): # Zenodo DOI, but different than recid
# ERROR, user provided a custom ZENODO DOI!
raise PIDValueError('doi', doi)
doi_pid = PersistentIdentifier.get_by_object(
pid_type='doi', object_type='rec', object_uuid=record_uuid)
if doi_pid.pid_value != doi:
with db.session.begin_nested():
db.session.delete(doi_pid)
return PersistentIdentifier.create(
'doi',
doi,
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.RESERVED,
)
| 6,216 | Python | .py | 162 | 30.512346 | 78 | 0.641043 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,556 | query.py | zenodo_zenodo/zenodo/modules/records/query.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Configruation for Zenodo Records search."""
from __future__ import absolute_import, print_function
from elasticsearch_dsl import Q
from flask import current_app, request
from invenio_records_rest.query import es_search_factory as _es_search_factory
def apply_version_filters(search, urlkwargs):
"""Apply record version filters to search."""
if 'all_versions' in request.values:
all_versions = request.values['all_versions']
if str(all_versions).lower() in ("", "1", "true"):
urlkwargs.add('all_versions', "true")
else:
urlkwargs.add('all_versions', str(request.values['all_versions']))
search = search.filter(Q('term', **{'relations.version.is_last': True}))
else:
search = search.filter(Q('term', **{'relations.version.is_last': True}))
return (search, urlkwargs)
def apply_safelist_filter(search, urlkwargs):
"""Apply safelist filter to search."""
safelist_filter_enabled = current_app.config.get(
'ZENODO_RECORDS_SEARCH_SAFELIST', False)
has_query = urlkwargs.get('q')
if safelist_filter_enabled and not has_query:
# Include if safelisted or undetermined (i.e. not indexed yet)
search = search.filter(
Q('term', _safelisted=True) | ~Q('exists', field='_safelisted')
)
return (search, urlkwargs)
def search_factory(self, search, query_parser=None):
"""Search factory."""
search, urlkwargs = _es_search_factory(self, search)
return apply_safelist_filter(*apply_version_filters(search, urlkwargs))
| 2,537 | Python | .py | 55 | 42.054545 | 84 | 0.716539 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,557 | resolvers.py | zenodo_zenodo/zenodo/modules/records/resolvers.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Resolvers for ZenodoRecords."""
from __future__ import absolute_import, print_function
from invenio_pidstore.resolver import Resolver
from .api import ZenodoRecord
record_resolver = Resolver(
pid_type='recid', object_type='rec', getter=ZenodoRecord.get_record
)
"""'recid'-PID resolver for Zenodo Records."""
| 1,292 | Python | .py | 31 | 40.387097 | 76 | 0.775478 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,558 | permissions.py | zenodo_zenodo/zenodo/modules/records/permissions.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Access controls for files on Zenodo."""
from __future__ import absolute_import, print_function
from flask import current_app, request, session
from flask_principal import ActionNeed
from flask_security import current_user
from invenio_access import Permission
from invenio_files_rest.models import Bucket, MultipartObject, ObjectVersion
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_pidstore.models import PersistentIdentifier
from invenio_records.api import Record
from invenio_records_files.api import FileObject
from invenio_records_files.models import RecordsBuckets
from invenio_rest.errors import RESTException
from werkzeug.exceptions import HTTPException
from zenodo_accessrequests.models import SecretLink
from zenodo.modules.tokens import decode_rat
from zenodo.modules.utils import obj_or_import_string
from ..tokens.errors import MissingTokenIDError
from .api import ZenodoRecord
from .models import AccessRight
from .utils import is_deposit, is_record
def get_public_bucket_uuids():
"""Return a list of UUIDs (strings) with publicly accessible buckets."""
buckets = [
'COMMUNITIES_BUCKET_UUID',
'EXPORTER_BUCKET_UUID',
]
return [current_app.config[k] for k in buckets]
def files_permission_factory(obj, action=None):
"""Permission for files are always based on the type of bucket.
1. Community bucket: Read access for everyone
2. Record bucket: Read access only with open and restricted access.
3. Deposit bucket: Read/update with restricted access.
4. Any other bucket is restricted to admins only.
"""
# Extract bucket id
bucket_id = None
if isinstance(obj, Bucket):
bucket_id = str(obj.id)
elif isinstance(obj, ObjectVersion):
bucket_id = str(obj.bucket_id)
elif isinstance(obj, MultipartObject):
bucket_id = str(obj.bucket_id)
elif isinstance(obj, FileObject):
bucket_id = str(obj.bucket_id)
# Retrieve record
if bucket_id is not None:
# Community bucket
if str(bucket_id) in get_public_bucket_uuids():
return PublicBucketPermission(action)
# Record or deposit bucket
rbs = RecordsBuckets.query.filter_by(bucket_id=bucket_id).all()
if len(rbs) >= 2: # Extra formats bucket or bad records-buckets state
# Only admins should access. Users use the ".../formats" endpoints
return Permission(ActionNeed('admin-access'))
rb = next(iter(rbs), None) # Use first bucket
if rb:
record = Record.get_record(rb.record_id)
# "Cache" the file's record in the request context (e.g for stats)
if record and request:
setattr(request, 'current_file_record', record)
# Bail if extra formats bucket
if str(bucket_id) == \
record.get('_buckets', {}).get('extra_formats'):
return Permission(ActionNeed('admin-access'))
if is_record(record):
return RecordFilesPermission.create(record, action)
elif is_deposit(record):
return DepositFilesPermission.create(record, action)
return Permission(ActionNeed('admin-access'))
def record_permission_factory(record=None, action=None):
"""Record permission factory."""
return RecordPermission.create(record, action)
def record_create_permission_factory(record=None):
"""Create permission factory."""
return record_permission_factory(record=record, action='create')
def record_read_permission_factory(record=None):
"""Read permission factory."""
return record_permission_factory(record=record, action='read')
def record_read_files_permission_factory(record=None):
"""Read permission factory."""
return record_permission_factory(record=record, action='read-files')
def record_update_permission_factory(record=None):
"""Update permission factory."""
return record_permission_factory(record=record, action='update')
def record_delete_permission_factory(record=None):
"""Delete permission factory."""
return record_permission_factory(record=record, action='delete')
def deposit_read_permission_factory(record=None):
"""Record permission factory."""
if record and 'deposits' in record['$schema']:
return DepositPermission.create(record=record, action='read')
else:
return RecordPermission.create(record=record, action='read')
def deposit_update_permission_factory(record=None):
"""Deposit update permission factory.
Since Deposit API "actions" (eg. publish, discard, etc) are considered part
of the "update" action, request context (if present) has to be used in
order to figure out if this is an actual "update" or API action.
"""
# TODO: The `need_record_permission` decorator of
# `invenio_deposit.views.rest.DepositActionResource.post` should be
# modified in order to be able to somehow provide a different permission
# factory for the various Deposit API actions and avoid hacking our way
# around to determine if it's an "action" or "update".
if request and request.endpoint == 'invenio_deposit_rest.depid_actions':
action = request.view_args.get('action')
if action in DepositPermission.protected_actions:
return DepositPermission.create(record=record, action=action)
return DepositPermission.create(record=record, action='update')
def deposit_delete_permission_factory(record=None):
"""Record permission factory."""
return DepositPermission.create(record=record, action='delete')
#
# Permission classes
#
class PublicBucketPermission(object):
"""Permission for files in public buckets.
Everyone are allowed to read. Admin can do everything.
"""
def __init__(self, action):
"""Initialize permission."""
self.action = action
def can(self):
"""Check permission."""
if self.action == 'object-read':
return True
else:
return Permission(ActionNeed('admin-access')).can()
class DepositFilesPermission(object):
"""Permission for files in deposit records (read and update access).
Read and update access given to owners and administrators.
"""
update_actions = [
'bucket-read',
'bucket-read-versions',
'bucket-update',
'bucket-listmultiparts',
'object-read',
'object-read-version',
'object-delete',
'object-delete-version',
'multipart-read',
'multipart-delete',
]
rat_read_actions = [
'object-read',
'bucket-read',
]
rat_update_actions = [
]
rat_actions = rat_read_actions + rat_update_actions
def __init__(self, record, func, user=None):
"""Initialize a file permission object."""
self.record = record
self.func = func
self.user = user or current_user
def can(self):
"""Determine access."""
return self.func(self.user, self.record)
@classmethod
def create(cls, record, action):
"""Record and instance."""
rat_token = request.args.get('token')
if rat_token and action in cls.rat_actions:
rat_signer, payload = decode_rat(rat_token)
rat_access = payload.get('access')
if rat_access == 'read' and action in cls.rat_read_actions:
rat_deposit_id = payload.get('deposit_id')
deposit_id = record.get('_deposit', {}).get('id')
if rat_deposit_id == deposit_id:
return cls(record, has_update_permission, user=rat_signer)
if action in cls.update_actions:
return cls(record, has_update_permission)
else:
return cls(record, has_admin_permission)
class RecordFilesPermission(DepositFilesPermission):
"""Permission for files in published records (read only access).
Read access (list and download) granted to:
1. Everyone if record is open access.
2. Owners, token bearers and administrators if embargoed, restricted or
closed access
Read version access granted to:
1. Administrators only.
"""
read_actions = [
'bucket-read',
'object-read',
]
admin_actions = [
'bucket-read',
'bucket-read-versions',
'object-read',
'object-read-version',
]
@classmethod
def create(cls, record, action):
"""Create a record files permission."""
if action in cls.read_actions:
return cls(record, has_read_files_permission)
elif action in cls.admin_actions:
return cls(record, has_admin_permission)
else:
return cls(record, deny)
class RecordPermission(object):
"""Record permission.
- Create action given to any authenticated user.
- Read access given to everyone.
- Update access given to record owners.
- Delete access given to admins only.
"""
create_actions = ['create']
read_actions = ['read']
read_files_actions = ['read-files']
update_actions = ['update']
newversion_actions = ['newversion', 'registerconceptdoi']
protected_actions = newversion_actions
delete_actions = ['delete']
def __init__(self, record, func, user):
"""Initialize a file permission object."""
self.record = record
self.func = func
self.user = user or current_user
def can(self):
"""Determine access."""
return self.func(self.user, self.record)
@classmethod
def create(cls, record, action, user=None):
"""Create a record permission."""
if action in cls.create_actions:
return cls(record, has_create_permission, user)
elif action in cls.read_actions:
return cls(record, allow, user)
elif action in cls.read_files_actions:
return cls(record, has_read_files_permission, user)
elif action in cls.update_actions:
return cls(record, has_update_permission, user)
elif action in (cls.newversion_actions):
return cls(record, has_newversion_permission, user)
elif action in cls.delete_actions:
return cls(record, has_admin_permission, user)
else:
return cls(record, deny, user)
class DepositPermission(RecordPermission):
"""Deposit permission.
- Read action given to record owners.
- Delete action given to record owners (still subject to being unpublished)
"""
@classmethod
def create(cls, record, action, user=None):
"""Create a deposit permission."""
if action in cls.read_actions:
return cls(record, has_update_permission, user)
elif action in cls.delete_actions:
return cls(record, has_update_permission, user)
return super(DepositPermission, cls).create(record, action, user=user)
#
# Utility functions
#
def deny(user, record):
"""Deny access."""
return False
def allow(user, record):
"""Allow access."""
return True
def has_read_files_permission(user, record):
"""Check if user has read access to the record."""
# Allow if record is open access
if AccessRight.get(
record.get('access_right', 'closed'),
record.get('embargo_date')) == AccessRight.OPEN:
return True
# Allow token bearers
token = session.get('accessrequests-secret-token')
if token and SecretLink.validate_token(
token, dict(recid=int(record['recid']))):
return True
# Check for a resource access token
rat_token = request.args.get('token')
if rat_token:
try:
rat_signer, payload = decode_rat(rat_token)
rat_deposit_id = payload.get('deposit_id')
rat_access = payload.get('access')
deposit_id = record.get('_deposit', {}).get('id')
if rat_deposit_id == deposit_id and rat_access == 'read':
return has_update_permission(rat_signer, record)
except MissingTokenIDError:
# The token querystring param is also used for secret link tokens,
# they might be misinterpreted as RAT tokens and validation.
pass
return has_update_permission(user, record)
def has_update_permission(user, record):
"""Check if user has update access to the record."""
# Allow owners
user_id = int(user.get_id()) if user.is_authenticated else None
if user_id in record.get('owners', []):
return True
if user_id in record.get('_deposit', {}).get('owners', []):
return True
return has_admin_permission(user, record)
def has_newversion_permission(user, record):
"""Check if the user has permission to create a newversion for a record."""
# Only the owner of the latest version can create new versions
conceptrecid = record.get('conceptrecid')
if conceptrecid:
conceptrecid = PersistentIdentifier.get('recid', conceptrecid)
pv = PIDVersioning(parent=conceptrecid)
latest_recid = pv.last_child
if latest_recid:
latest_record = ZenodoRecord.get_record(pv.last_child.object_uuid)
return has_update_permission(user, latest_record)
return has_update_permission(user, record)
def has_admin_permission(user, record):
"""Check if user has admin access to record."""
# Allow administrators
if Permission(ActionNeed('admin-access')):
return True
class CreatePermissionException(HTTPException):
"""Exception for users not eligible to create a deposit."""
code = 403
def has_create_permission(user, record):
"""Check if user has permission to create a record."""
# by default any authenticated user can create a deposit
can, error_message = True, ''
permission_func = obj_or_import_string(current_app.config.get(
'ZENODO_DEPOSIT_CREATE_PERMISSION'))
if permission_func and callable(permission_func):
can, error_message = permission_func()
if can or has_admin_permission(user, record):
return True
raise CreatePermissionException(error_message)
| 15,178 | Python | .py | 355 | 35.991549 | 79 | 0.683478 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,559 | proxies.py | zenodo_zenodo/zenodo/modules/records/proxies.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Proxies for Zenodo records module."""
from flask import current_app
from werkzeug.local import LocalProxy
current_zenodo_records = LocalProxy(
lambda: current_app.extensions['zenodo-records'])
current_custom_metadata = LocalProxy(
lambda: current_app.extensions['zenodo-records'].custom_metadata)
| 1,279 | Python | .py | 30 | 41.233333 | 76 | 0.779116 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,560 | views.py | zenodo_zenodo/zenodo/modules/records/views.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Blueprint for Zenodo-Records."""
from __future__ import absolute_import, print_function, unicode_literals
import copy
import json
import re
import urlparse
from datetime import datetime as dt
from operator import itemgetter
import idutils
import six
from flask import Blueprint, abort, current_app, render_template, request
from flask_iiif.restful import IIIFImageAPI
from flask_principal import ActionNeed
from flask_security import current_user
from invenio_access.permissions import Permission
from invenio_communities.models import Community
from invenio_formatter.filters.datetime import from_isodate
from invenio_i18n.ext import current_i18n
from invenio_iiif.previewer import previewable_extensions as thumbnail_exts
from invenio_iiif.utils import iiif_image_key
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_previewer.proxies import current_previewer
from invenio_records_ui.signals import record_viewed
from six.moves.urllib.parse import urlencode, urlunparse
from werkzeug.utils import import_string
from zenodo.modules.communities.api import ZenodoCommunity
from zenodo.modules.deposit.extra_formats import ExtraFormats
from zenodo.modules.deposit.views_rest import pass_extra_formats_mimetype
from zenodo.modules.records.serializers.schemas.common import api_link_for
from zenodo.modules.records.utils import is_doi_locally_managed
from zenodo.modules.stats.utils import get_record_stats
from ..spam.models import SafelistEntry
from ..spam.utils import is_user_safelisted
from .api import ZenodoRecord
from .models import AccessRight, ObjectType
from .permissions import RecordPermission
from .proxies import current_custom_metadata
from .serializers import citeproc_v1
from .serializers.json import ZenodoJSONSerializer
blueprint = Blueprint(
'zenodo_records',
__name__,
template_folder='templates',
static_folder='static',
url_prefix='/search',
)
#
# Access right template filters and tests.
#
@blueprint.app_template_test('accessright')
def is_valid_accessright(value):
"""Test if access right is valid."""
return AccessRight.is_valid(value)
@blueprint.app_template_test('embargoed')
def is_embargoed(embargo_date, accessright=None):
"""Test if date is still embargoed (according to UTC date."""
if accessright is not None and accessright != AccessRight.EMBARGOED:
return False
if embargo_date is not None:
return AccessRight.is_embargoed(embargo_date)
return False
@blueprint.app_template_filter('extra_formats_title')
def extra_formats_title(mimetype):
"""Return a dict of a record's available extra formats and their title."""
return ExtraFormats.mimetype_whitelist.get(mimetype, '')
@blueprint.app_template_test('safelisted_record')
def is_safelisted_record(record):
"""Check if record creators are safelisted."""
return SafelistEntry.get_record_status(record)
@blueprint.app_template_test('safelisted_user')
def is_safelisted_user(user):
"""Check if a user is safelisted."""
return is_user_safelisted(user)
@blueprint.app_template_filter('pidstatus')
def pidstatus_title(pid):
"""Get access right.
Better than comparing record.access_right directly as access_right
may have not yet been updated after the embargo_date has passed.
"""
return PIDStatus(pid.status).title
@blueprint.app_template_filter()
def accessright_get(value, embargo_date=None):
"""Get access right.
Better than comparing record.access_right directly as access_right
may have not yet been updated after the embargo_date has passed.
"""
return AccessRight.get(value, embargo_date)
@blueprint.app_template_filter()
def accessright_category(value, embargo_date=None, **kwargs):
"""Get category for access right."""
return AccessRight.as_category(
AccessRight.get(value, embargo_date=embargo_date), **kwargs
)
@blueprint.app_template_filter()
def make_query(values):
"""Get category for access right."""
parts = []
for k, v in values.items():
parts.append(u'{0}:"{1}"'.format(k, v))
return u' '.join(parts)
@blueprint.app_template_filter()
def accessright_title(value, embargo_date=None):
"""Get category for access right."""
return AccessRight.as_title(
AccessRight.get(value, embargo_date=embargo_date))
@blueprint.app_template_filter()
def accessright_icon(value, embargo_date=None):
"""Get icon for access right."""
return AccessRight.as_icon(AccessRight.get(value, embargo_date))
@blueprint.app_template_filter()
def accessright_description(value, embargo_date=None):
"""Get a description for access right."""
return AccessRight.as_description(
AccessRight.get(value, embargo_date),
from_isodate(embargo_date)
)
@blueprint.app_template_filter()
def has_record_perm(user, record, action):
"""Check if user has a given record permission."""
return RecordPermission.create(record, action, user=user).can()
#
# Related identifiers filters.
#
@blueprint.app_template_filter('zenodo_related_links')
def zenodo_related_links(record, communities):
"""Get logos for related links."""
def apply_rule(item, rule):
r = copy.deepcopy(rule)
r['link'] = idutils.to_url(item['identifier'], item['scheme'], 'https')
return r
def match_rules(item):
rs = []
for c in set(communities):
if c.id in current_app.config['ZENODO_RELATION_RULES']:
rules = current_app.config['ZENODO_RELATION_RULES'][c.id]
for r in rules:
if item['relation'] == r['relation'] and \
item['scheme'] == r['scheme'] and \
item['identifier'].startswith(r['prefix']):
rs.append(r)
return rs
ret = []
for item in record.get('related_identifiers', []):
for r in match_rules(item):
ret.append(apply_rule(item, r))
return ret
#
# Community branding filters
#
@blueprint.app_template_filter('zenodo_community_branding_links')
def zenodo_community_branding_links(record):
"""Get logos for branded communities."""
comms = record.get('communities', [])
branded = current_app.config['ZENODO_COMMUNITY_BRANDING']
ret = []
for comm in comms:
if comm in branded:
comm_model = Community.query.get(comm)
ret.append((comm, comm_model.logo_url))
return ret
#
# Object type template filters and tests.
#
@blueprint.app_template_filter()
def objecttype(value):
"""Get object type."""
return ObjectType.get_by_dict(value)
@blueprint.app_template_filter()
def contributortype_title(value):
"""Get object type."""
return current_app.config.get('DEPOSIT_CONTRIBUTOR_TYPES_LABELS', {}).get(
value, value)
@blueprint.app_template_filter()
def meeting_title(m):
"""Get meeting title."""
acronym = m.get('acronym')
title = m.get('title')
if acronym and title:
return u'{0} ({1})'.format(title, acronym)
else:
return title or acronym
#
# Files related template filters.
#
@blueprint.app_template_filter()
def select_preview_file(files):
"""Get list of files and select one for preview."""
selected = None
try:
for f in sorted(files or [], key=itemgetter('key')):
if f['type'] in current_previewer.previewable_extensions:
if selected is None:
selected = f
elif f['default']:
selected = f
except KeyError:
pass
return selected
#
# Stats filters
#
@blueprint.app_template_filter()
def record_stats(record):
"""Fetch record statistics from Elasticsearch."""
return get_record_stats(record.id, False)
@blueprint.app_template_filter()
def stats_num_format(num):
"""Format a statistics value."""
return '{:,.0f}'.format(num or 0)
#
# Persistent identifiers template filters
#
@blueprint.app_template_test()
def local_doi(value):
"""Test if a DOI is a local DOI."""
prefixes = current_app.config.get('ZENODO_LOCAL_DOI_PREFIXES', [])
return prefixes and any((value.startswith(p + "/") for p in prefixes))
@blueprint.app_template_filter('relation_title')
def relation_title(relation):
"""Map relation type to title."""
return dict(current_app.config['ZENODO_RELATION_TYPES']).get(relation) or \
relation
@blueprint.app_template_filter('citation')
def citation(record, pid, style=None, ln=None):
"""Render citation for record according to style and language."""
locale = ln or current_i18n.language
style = style or 'science'
try:
return citeproc_v1.serialize(pid, record, style=style, locale=locale)
except Exception:
current_app.logger.exception(
'Citation formatting for record {0} failed.'
.format(str(record.id)))
return None
@blueprint.app_template_filter('format_date_range')
def format_date_range(date):
"""."""
if date.get('start') and date.get('end'):
date_start = dt.strptime(date['start'], "%Y-%m-%d")
date_end = dt.strptime(date['end'], "%Y-%m-%d")
if date_start == date_end:
return '{}'.format(date['start'])
else:
return 'From {} to {}'.format(date['start'], date['end'])
elif date.get('end'):
return 'Until {}'.format(date['end'])
elif date.get('start'):
return 'From {}'.format(date['start'])
@blueprint.app_template_filter('pid_url')
def pid_url(identifier, scheme=None, url_scheme='https'):
"""Convert persistent identifier into a link."""
if scheme is None:
try:
scheme = idutils.detect_identifier_schemes(identifier)[0]
except IndexError:
scheme = None
try:
if scheme and identifier:
return idutils.to_url(identifier, scheme, url_scheme=url_scheme)
except Exception:
current_app.logger.warning('URL generation for identifier {0} failed.'
.format(identifier), exc_info=True)
return ''
@blueprint.app_template_filter('doi_locally_managed')
def doi_locally_managed(pid):
"""Determine if DOI is managed locally."""
return is_doi_locally_managed(pid)
@blueprint.app_template_filter()
def pid_from_value(pid_value, pid_type='recid'):
"""Determine if DOI is managed locally."""
try:
return PersistentIdentifier.get(pid_type=pid_type, pid_value=pid_value)
except Exception:
pass
@blueprint.app_template_filter()
def record_from_pid(recid):
"""Get record from PID."""
try:
return ZenodoRecord.get_record(recid.object_uuid)
except Exception:
return {}
def records_ui_export(pid, record, template=None, **kwargs):
"""Record serialization view.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/files/<filename>',
view_imp='zenodo.modules.records.views.records_ui_export',
)
)
"""
formats = current_app.config.get('ZENODO_RECORDS_EXPORTFORMATS')
fmt = request.view_args.get('format')
if formats.get(fmt) is None:
return render_template(
'zenodo_records/records_export_unsupported.html'), 410
else:
serializer = import_string(formats[fmt]['serializer'])
# Pretty print if JSON
if isinstance(serializer, ZenodoJSONSerializer):
json_data = serializer.transform_record(pid, record)
data = json.dumps(json_data, indent=2, separators=(', ', ': '))
else:
data = serializer.serialize(pid, record)
if isinstance(data, six.binary_type):
data = data.decode('utf8')
# emit record_viewed event
record_viewed.send(
current_app._get_current_object(),
pid=pid,
record=record,
)
return render_template(
template, pid=pid, record=record,
data=data, format_code=fmt, format_title=formats[fmt]['title'])
def _can_curate(community, user, record, accepted=False):
"""Determine whether user can curate given community."""
if user.is_anonymous:
return False
if (community.id_user == int(user.get_id())) or \
(accepted and (int(user.get_id()) in record.get('owners', []))):
return True
return False
def community_curation(record, user):
"""Generate a list of pending and accepted communities with permissions.
Return a 4-tuple of lists (in order):
* 'pending' communities, which can be curated by given user
* 'accepted' communities, which can be curated by given user
* All 'pending' communities
* All 'accepted' communities
"""
irs = ZenodoCommunity.get_irs(record).all()
pending = list(set(ir.community for ir in irs))
accepted = [Community.get(c) for c in record.get('communities', [])]
# Additionally filter out community IDs that did not resolve (None)
accepted = [c for c in accepted if c]
# Check for global curation permission (all communities on this record).
global_perm = None
if user.is_anonymous:
global_perm = False
elif Permission(ActionNeed('admin-access')).can():
global_perm = True
if global_perm:
return (pending, accepted, pending, accepted)
else:
return (
[c for c in pending if _can_curate(c, user, record)],
[c for c in accepted
if _can_curate(c, user, record, accepted=True)],
pending,
accepted,
)
def get_reana_badge(record):
"""Get REANA badge information."""
if not current_app.config["ZENODO_REANA_BADGES_ENABLED"]:
return None
try:
p = re.compile("^reana.*\.(yaml|yml)$", re.IGNORECASE)
if record.files:
for file in record.files:
m = p.match(file["key"])
if m:
file_url = api_link_for("object", **(file.dumps()))
reana_url_parts = list(
urlparse.urlparse(
current_app.config["ZENODO_REANA_LAUNCH_URL_BASE"]
)
)
query = dict(urlparse.parse_qsl(reana_url_parts[4]))
query.update({
"url": file_url,
"name": record["title"],
})
reana_url_parts[4] = urlencode(query)
return {
"img_url":
current_app.config["ZENODO_REANA_BADGE_IMG_URL"],
"url": urlunparse(reana_url_parts),
}
for item in record.get("related_identifiers", []):
if item["scheme"] == "url":
reana_hosts = current_app.config["ZENODO_REANA_HOSTS"]
url_parts = urlparse.urlparse(item["identifier"])
if url_parts.netloc in reana_hosts and url_parts.path in [
"/launch",
"/run",
]:
# Add a "name" if not already there
reana_url_parts = list(url_parts)
query = dict(urlparse.parse_qsl(reana_url_parts[4]))
query.setdefault("name", record["title"])
reana_url_parts[4] = urlencode(query)
return {
"img_url":
current_app.config["ZENODO_REANA_BADGE_IMG_URL"],
"url": urlunparse(reana_url_parts),
}
except Exception:
pass
def record_jinja_context():
"""Jinja context processor for records."""
return dict(
community_curation=community_curation,
custom_metadata=current_custom_metadata,
get_reana_badge=get_reana_badge,
)
def record_thumbnail(pid, record, thumbnail_size, **kwargs):
"""Provide easy access to the thumbnail of a record for predefined sizes.
We consider the thumbnail of the record as the first image in the files
iterator or the one set as the default.
"""
if not has_record_perm(current_user, record, 'read-files'):
abort(404)
cached_thumbnails = current_app.config['CACHED_THUMBNAILS']
if thumbnail_size not in cached_thumbnails:
abort(400, 'The selected thumbnail has not been cached')
selected = None
thumbnail_size = cached_thumbnails[thumbnail_size]
for file in record.files:
if file['type'] not in thumbnail_exts:
continue
elif not selected:
selected = file
elif file['default']:
selected = file
break
if selected:
return IIIFImageAPI().get(
version='v2',
uuid=str(iiif_image_key(selected)),
region='full',
size=thumbnail_size,
rotation='0',
quality='default',
image_format=selected['type'])
else:
abort(404, 'This record has no thumbnails')
@pass_extra_formats_mimetype(from_query_string=True, from_accept=True)
def record_extra_formats(pid, record, mimetype=None, **kwargs):
"""Get extra format."""
if mimetype in record.extra_formats:
fileobj = record.extra_formats[mimetype]
return fileobj.obj.send_file(trusted=True, as_attachment=True)
return abort(404, 'No extra format "{}".'.format(mimetype))
| 18,671 | Python | .py | 469 | 32.731343 | 79 | 0.659065 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,561 | __init__.py | zenodo_zenodo/zenodo/modules/records/mappings/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Elasticsearch mappings."""
| 998 | Python | .py | 24 | 40.541667 | 76 | 0.77184 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,562 | __init__.py | zenodo_zenodo/zenodo/modules/records/mappings/v7/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Mappings for ES 7."""
| 255 | Python | .py | 8 | 30.75 | 72 | 0.711382 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,563 | __init__.py | zenodo_zenodo/zenodo/modules/records/jsonschemas/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""JSON schemas for Zenodo."""
from __future__ import absolute_import, print_function
| 1,055 | Python | .py | 25 | 41.12 | 76 | 0.771401 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,564 | dcat.py | zenodo_zenodo/zenodo/modules/records/serializers/dcat.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Datacite to DCAT serializer."""
from __future__ import absolute_import, print_function
import mimetypes
import idutils
from flask import has_request_context
from flask_security import current_user
from invenio_records.api import Record
from lxml import etree as ET
from pkg_resources import resource_stream
from werkzeug.utils import cached_property
from zenodo.modules.records.serializers.schemas.common import ui_link_for
from ..permissions import has_read_files_permission
class DCATSerializer(object):
"""DCAT serializer for records."""
def __init__(self, datacite_serializer):
"""."""
self.datacite_serializer = datacite_serializer
@cached_property
def xslt_transform_func(self):
"""Return the DCAT XSLT transformation function."""
with resource_stream('zenodo.modules.records',
'data/datacite-to-dcat-ap.xsl') as f:
xsl = ET.XML(f.read())
transform = ET.XSLT(xsl)
return transform
def _add_files(self, root, files, record):
"""Add files information via distribution elements."""
ns = root.nsmap
def download_url(file, record):
url = ui_link_for('record_file', id=record['recid'], filename=file['key'])
return None, {'{{{rdf}}}resource'.format(**ns): url}
def media_type(file, _):
return mimetypes.guess_type(file['key'])[0], None
def byte_size(file, _):
return str(file['size']), None
def access_url(_, record):
url = idutils.to_url(record['doi'], 'doi', url_scheme='https')
return None, {'{{{rdf}}}resource'.format(**ns): url}
files_fields = {
'{{{dcat}}}downloadURL': download_url,
'{{{dcat}}}mediaType': media_type,
'{{{dcat}}}byteSize': byte_size,
'{{{dcat}}}accessURL': access_url,
# TODO: there's also "spdx:checksum", but it's not in the W3C spec yet
}
for f in files:
dist_wrapper = ET.SubElement(
root[0], '{{{dcat}}}distribution'.format(**ns))
dist = ET.SubElement(
dist_wrapper, '{{{dcat}}}Distribution'.format(**ns))
for tag, func in files_fields.items():
text_val, attrs_val = func(f, record)
if text_val or attrs_val:
el = ET.SubElement(dist, tag.format(**ns))
if text_val:
el.text = text_val
if attrs_val:
el.attrib.update(attrs_val)
def _etree_tostring(self, root):
return ET.tostring(
root,
pretty_print=True,
xml_declaration=True,
encoding='utf-8',
).decode('utf-8')
def transform_with_xslt(self, pid, record, search_hit=False, **kwargs):
"""Transform record with XSLT."""
files_data = None
if search_hit:
dc_record = self.datacite_serializer.transform_search_hit(
pid, record, **kwargs)
if '_files' in record['_source']:
files_data = record['_source']['_files']
elif '_files' in record:
files_data = record['_files']
else:
dc_record = self.datacite_serializer.transform_record(
pid, record, **kwargs)
# for single-record serialization check file read permissions
if isinstance(record, Record) and '_files' in record:
if not has_request_context() or has_read_files_permission(
current_user, record):
files_data = record['_files']
dc_etree = self.datacite_serializer.schema.dump_etree(dc_record)
dc_namespace = self.datacite_serializer.schema.ns[None]
dc_etree.tag = '{{{0}}}resource'.format(dc_namespace)
dcat_etree = self.xslt_transform_func(dc_etree).getroot()
# Inject files in results (since the XSLT can't do that by default)
if files_data:
self._add_files(
root=dcat_etree,
files=files_data,
record=(record['_source'] if search_hit else record),
)
return dcat_etree
def serialize(self, pid, record, **kwargs):
"""Serialize a single record.
:param pid: Persistent identifier instance.
:param record: Record instance.
"""
return self._etree_tostring(
self.transform_with_xslt(pid, record, **kwargs))
def serialize_search(self, pid_fetcher, search_result, **kwargs):
"""Serialize a search result.
:param pid_fetcher: Persistent identifier fetcher.
:param search_result: Elasticsearch search result.
:param links: Dictionary of links to add to response.
"""
records = []
for hit in search_result['hits']['hits']:
pid = pid_fetcher(hit['_id'], hit['_source'])
dcat_etree = self.transform_with_xslt(
pid, hit, search_hit=True, **kwargs)
records.append(self._etree_tostring(dcat_etree))
return '\n'.join(records)
def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
if isinstance(record["_source"], Record):
return self.transform_with_xslt(pid, record["_source"], search_hit=False)
else:
return self.transform_with_xslt(pid, record, search_hit=True)
| 6,486 | Python | .py | 144 | 35.638889 | 86 | 0.615275 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,565 | dc.py | zenodo_zenodo/zenodo/modules/records/serializers/dc.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""DoJSON based MARCXML serializer for records."""
from __future__ import absolute_import, print_function
from invenio_records_rest.serializers.dc import DublinCoreSerializer
from .pidrelations import preprocess_related_identifiers
class ZenodoDublinCoreSerializer(DublinCoreSerializer):
"""Zenodo Dublin Core serializer for records.
Note: This serializer is not suitable for serializing large number of
records.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Add related identifiers from PID relations."""
result = super(ZenodoDublinCoreSerializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
result = preprocess_related_identifiers(pid, record, result)
return result
| 1,766 | Python | .py | 39 | 42.230769 | 76 | 0.764398 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,566 | pidrelations.py | zenodo_zenodo/zenodo/modules/records/serializers/pidrelations.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public Licnse
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Serializers."""
from __future__ import absolute_import, print_function
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_pidstore.models import PersistentIdentifier
from zenodo.modules.records.api import ZenodoRecord
def serialize_related_identifiers(pid):
"""Serialize PID Versioning relations as related_identifiers metadata."""
pv = PIDVersioning(child=pid)
related_identifiers = []
if pv.exists:
rec = ZenodoRecord.get_record(pid.get_assigned_object())
# External DOI records don't have Concept DOI
if 'conceptdoi' in rec:
ri = {
'scheme': 'doi',
'relation': 'isVersionOf',
'identifier': rec['conceptdoi']
}
related_identifiers.append(ri)
# TODO: We do not serialize previous/next versions to
# related identifiers because of the semantic-versioning cases
# (e.g. GitHub releases of minor versions)
#
# children = pv.children.all()
# idx = children.index(pid)
# left = children[:idx]
# right = children[idx + 1:]
# for p in left:
# rec = ZenodoRecord.get_record(p.get_assigned_object())
# ri = {
# 'scheme': 'doi',
# 'relation': 'isNewVersionOf',
# 'identifier': rec['doi']
# }
# related_identifiers.append(ri)
# for p in right:
# rec = ZenodoRecord.get_record(p.get_assigned_object())
# ri = {
# 'scheme': 'doi',
# 'relation': 'isPreviousVersionOf',
# 'identifier': rec['doi']
# }
# related_identifiers.append(ri)
pv = PIDVersioning(parent=pid)
if pv.exists:
for p in pv.children:
rec = ZenodoRecord.get_record(p.get_assigned_object())
ri = {
'scheme': 'doi',
'relation': 'hasVersion',
'identifier': rec['doi']
}
related_identifiers.append(ri)
return related_identifiers
def preprocess_related_identifiers(pid, record, result):
"""Preprocess related identifiers for record serialization.
Resolves the passed pid to the proper `recid` in order to add related
identifiers from PID relations.
"""
recid_value = record.get('recid')
if pid.pid_type == 'doi' and pid.pid_value == record.get('conceptdoi'):
recid_value = record.get('conceptrecid')
result['metadata']['doi'] = record.get('conceptdoi')
recid = (pid if pid.pid_value == recid_value else
PersistentIdentifier.get(pid_type='recid', pid_value=recid_value))
if recid.pid_value == record.get('conceptrecid'):
pv = PIDVersioning(parent=recid)
else:
pv = PIDVersioning(child=recid)
# Serialize PID versioning as related identifiers
if pv.exists:
rels = serialize_related_identifiers(recid)
if rels:
result['metadata'].setdefault(
'related_identifiers', []).extend(rels)
return result
| 4,107 | Python | .py | 99 | 34.59596 | 79 | 0.641462 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,567 | marc21.py | zenodo_zenodo/zenodo/modules/records/serializers/marc21.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""DoJSON based MARCXML serializer for records."""
from __future__ import absolute_import, print_function
from invenio_marc21.serializers.marcxml import MARCXMLSerializer
from .pidrelations import preprocess_related_identifiers
class ZenodoMARCXMLSerializer(MARCXMLSerializer):
"""Zenodo MARCXML serializer for records.
Note: This serializer is not suitable for serializing large number of
records.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Add related identifiers from PID relations."""
result = super(ZenodoMARCXMLSerializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
result = preprocess_related_identifiers(pid, record, result)
return result
| 1,749 | Python | .py | 39 | 41.794872 | 76 | 0.76322 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,568 | legacyjson.py | zenodo_zenodo/zenodo/modules/records/serializers/legacyjson.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public Licnse
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Serializers."""
from __future__ import absolute_import, print_function
from flask import json
from invenio_records.api import Record
from .json import ZenodoJSONSerializer
class LegacyJSONSerializer(ZenodoJSONSerializer):
"""Legacy JSON Serializer."""
def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None):
"""Serialize as a json array."""
return json.dumps([self.transform_search_hit(
pid_fetcher(hit['_id'], hit['_source']),
hit,
links_factory=item_links_factory,
) for hit in search_result['hits']['hits']])
class DepositLegacyJSONSerializer(LegacyJSONSerializer):
"""Legacy JSON serializer.
Dumps files directly from Bucket instead of relying on record metadata.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Include files for single record retrievals."""
result = super(LegacyJSONSerializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
if isinstance(record, Record):
result['files'] = record.files.dumps()
return result
| 2,170 | Python | .py | 50 | 38.72 | 76 | 0.719772 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,569 | datacite.py | zenodo_zenodo/zenodo/modules/records/serializers/datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016, 2017, 2018 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Marshmallow based DataCite serializer for records."""
from __future__ import absolute_import, print_function
from flask import current_app
from invenio_records_rest.serializers.datacite import DataCite31Serializer, \
DataCite41Serializer
from .pidrelations import preprocess_related_identifiers
from .schemas.common import ui_link_for
class ZenodoDataCite31Serializer(DataCite31Serializer):
"""Marshmallow based DataCite serializer for records.
Note: This serializer is not suitable for serializing large number of
records.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Add related identifiers from PID relations."""
result = super(ZenodoDataCite31Serializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
# Versioning links
result = preprocess_related_identifiers(pid, record, result)
# Alternate identifiers
altidentifiers = result['metadata'].get('alternate_identifiers', [])
altidentifiers.append({
'identifier': ui_link_for('record_html', id=str(record['recid'])),
'scheme': 'url',
})
result['metadata']['alternate_identifiers'] = altidentifiers
return result
class ZenodoDataCite41Serializer(DataCite41Serializer):
"""Marshmallow based DataCite serializer for records.
Note: This serializer is not suitable for serializing large number of
records.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Add related identifiers from PID relations."""
result = super(ZenodoDataCite41Serializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
# Versioning links
result = preprocess_related_identifiers(pid, record, result)
# Alternate identifiers
altidentifiers = result['metadata'].get('alternate_identifiers', [])
altidentifiers.append({
'identifier': ui_link_for('record_html', id=str(record['recid'])),
'scheme': 'url'
})
result['metadata']['alternate_identifiers'] = altidentifiers
return result
| 3,174 | Python | .py | 70 | 40 | 78 | 0.721539 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,570 | __init__.py | zenodo_zenodo/zenodo/modules/records/serializers/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record serialization."""
from __future__ import absolute_import, print_function
from dojson.contrib.to_marc21 import to_marc21
from invenio_records_rest.serializers.citeproc import CiteprocSerializer
from invenio_records_rest.serializers.datacite import OAIDataCiteSerializer
from invenio_records_rest.serializers.response import record_responsify, \
search_responsify
from zenodo.modules.openaire.schema import RecordSchemaOpenAIREJSON
from zenodo.modules.records.serializers.datacite import ZenodoDataCite31Serializer, \
ZenodoDataCite41Serializer
from zenodo.modules.records.serializers.dc import ZenodoDublinCoreSerializer
from zenodo.modules.records.serializers.marc21 import ZenodoMARCXMLSerializer
from .bibtex import BibTeXSerializer
from .dcat import DCATSerializer
from .extra_formats import ExtraFormatsSerializer
from .files import files_responsify
from .geojson import ZenodoGeoJSONSerializer as GeoJSONSerializer
from .json import ZenodoJSONSerializer as JSONSerializer
from .legacyjson import DepositLegacyJSONSerializer, LegacyJSONSerializer
from .schemaorg import ZenodoSchemaOrgSerializer
from .schemas.csl import RecordSchemaCSLJSON
from .schemas.datacite import DataCiteSchemaV1, DataCiteSchemaV4
from .schemas.dc import DublinCoreV1
from .schemas.json import DepositSchemaV1, RecordSchemaV1
from .schemas.legacyjson import DepositFormSchemaV1, FileSchemaV1, \
GitHubRecordSchemaV1, LegacyRecordSchemaV1
from .schemas.marc21 import RecordSchemaMARC21
# Serializers
# ===========
#: Zenodo JSON serializer version 1.0.0
json_v1 = JSONSerializer(RecordSchemaV1, replace_refs=True)
#: Zenodo Deposit JSON serializer version 1.0.0
deposit_json_v1 = JSONSerializer(DepositSchemaV1, replace_refs=True)
#: Zenodo legacy deposit JSON serialzier version 1.0.0
legacyjson_v1 = LegacyJSONSerializer(
LegacyRecordSchemaV1, replace_refs=True)
#: Zenodo legacy deposit JSON serialzier version 1.0.0
githubjson_v1 = LegacyJSONSerializer(
GitHubRecordSchemaV1, replace_refs=True)
#: Deposit form JSON serialzier version 1.0.0
deposit_formjson_v1 = LegacyJSONSerializer(
DepositFormSchemaV1, replace_refs=True)
#: Zenodo legacy deposit JSON serialzier version 1.0.0
deposit_legacyjson_v1 = DepositLegacyJSONSerializer(
LegacyRecordSchemaV1, replace_refs=True)
#: MARCXML serializer version 1.0.0
marcxml_v1 = ZenodoMARCXMLSerializer(
to_marc21, schema_class=RecordSchemaMARC21, replace_refs=True)
#: BibTeX serializer version 1.0.0
bibtex_v1 = BibTeXSerializer()
#: DataCite serializers
datacite_v31 = ZenodoDataCite31Serializer(DataCiteSchemaV1, replace_refs=True)
datacite_v41 = ZenodoDataCite41Serializer(DataCiteSchemaV4, replace_refs=True)
#: DCAT serializer
dcat_v1 = DCATSerializer(datacite_v41)
#: OAI DataCite serializer
oai_datacite = OAIDataCiteSerializer(
serializer=datacite_v31,
datacentre='CERN.ZENODO',
)
#: OAI DataCite 4.1 serializer
oai_datacite_v41 = OAIDataCiteSerializer(
serializer=datacite_v41,
datacentre='CERN.ZENODO',
)
#: Dublin Core serializer
dc_v1 = ZenodoDublinCoreSerializer(DublinCoreV1, replace_refs=True)
#: CSL-JSON serializer
csl_v1 = JSONSerializer(RecordSchemaCSLJSON, replace_refs=True)
#: CSL Citation Formatter serializer
citeproc_v1 = CiteprocSerializer(csl_v1)
#: OpenAIRE JSON serializer
openaire_json_v1 = JSONSerializer(RecordSchemaOpenAIREJSON, replace_refs=True)
#: JSON-LD serializer
schemaorg_jsonld_v1 = ZenodoSchemaOrgSerializer(replace_refs=True)
#: Extra formats serializer
extra_formats_v1 = ExtraFormatsSerializer()
#: GeoJSON serializer
geojson_v1 = GeoJSONSerializer(replace_refs=False)
# Records-REST serializers
# ========================
#: JSON record serializer for individual records.
json_v1_response = record_responsify(json_v1, 'application/json')
#: JSON record legacy serializer for individual records.
legacyjson_v1_response = record_responsify(legacyjson_v1, 'application/json')
#: MARCXML record serializer for individual records.
marcxml_v1_response = record_responsify(marcxml_v1, 'application/marcxml+xml')
#: BibTeX record serializer for individual records.
bibtex_v1_response = record_responsify(bibtex_v1, 'application/x-bibtex')
#: DataCite v3.1 record serializer for individual records.
datacite_v31_response = record_responsify(
datacite_v31, 'application/x-datacite+xml')
#: DataCite v4.1 record serializer for individual records.
datacite_v41_response = record_responsify(
datacite_v41, 'application/x-datacite-v41+xml')
#: DCAT v4.1 record serializer for individual records.
dcat_response = record_responsify(
dcat_v1, 'application/rdf+xml')
#: DublinCore record serializer for individual records.
dc_v1_response = record_responsify(dc_v1, 'application/x-dc+xml')
#: CSL-JSON record serializer for individual records.
csl_v1_response = record_responsify(
csl_v1, 'application/vnd.citationstyles.csl+json')
#: CSL Citation Formatter serializer for individual records.
citeproc_v1_response = record_responsify(citeproc_v1, 'text/x-bibliography')
#: OpenAIRE JSON serializer for individual records.
openaire_json_v1_response = record_responsify(openaire_json_v1,
'application/x-openaire+json')
schemaorg_jsonld_v1_response = record_responsify(schemaorg_jsonld_v1,
'application/ld+json')
#: JSON record serializer for search results.
json_v1_search = search_responsify(json_v1, 'application/json')
#: JSON record legacy serializer for search results.
legacyjson_v1_search = search_responsify(legacyjson_v1, 'application/json')
#: MARCXML record serializer for search records.
marcxml_v1_search = search_responsify(marcxml_v1, 'application/marcxml+xml')
#: BibTeX serializer for search records.
bibtex_v1_search = search_responsify(bibtex_v1, 'application/x-bibtex')
#: DataCite v3.1 record serializer for search records.
datacite_v31_search = search_responsify(
datacite_v31, 'application/x-datacite+xml')
#: DublinCore record serializer for search records.
dc_v1_search = search_responsify(dc_v1, 'application/x-dc+xml')
schemaorg_jsonld_v1_search = record_responsify(
schemaorg_jsonld_v1, 'application/ld+json')
#: GeoJSON record serializer for search records.
geojson_v1_response = record_responsify(geojson_v1, 'application/vnd.geo+json')
# Deposit serializers
# ===================
#: JSON record legacy serializer for individual deposits.
deposit_legacyjson_v1_response = record_responsify(
deposit_legacyjson_v1, 'application/json')
#: JSON record legacy serializer for deposit search results.
deposit_legacyjson_v1_search = search_responsify(
deposit_legacyjson_v1, 'application/json')
#: JSON files legacy serializer for deposit files.
deposit_legacyjson_v1_files_response = files_responsify(
FileSchemaV1, 'application/json')
#: JSON record serializer for individual records.
deposit_json_v1_response = record_responsify(
deposit_json_v1, 'application/json')
#: JSON record serializer for search results.
deposit_json_v1_search = search_responsify(
deposit_json_v1, 'application/json')
# OAI-PMH record serializers.
# ===========================
#: OAI-PMH MARC21 record serializer.
oaipmh_marc21_v1 = marcxml_v1.serialize_oaipmh
#: OAI-PMH DataCite record serializer.
oaipmh_datacite_v41 = datacite_v41.serialize_oaipmh
#: OAI-PMH DataCite record serializer.
oaipmh_datacite_v31 = datacite_v31.serialize_oaipmh
#: OAI-PMH DCAT record serializer.
oaipmh_dcat_v1 = dcat_v1.serialize_oaipmh
#: OAI-PMH OAI DataCite record serializer.
oaipmh_oai_datacite = oai_datacite.serialize_oaipmh
#: OAI-PMH OAI DataCite 4.1 record serializer.
oaipmh_oai_datacite_v41 = oai_datacite_v41.serialize_oaipmh
#: OAI-PMH OAI Dublin Core record serializer.
oaipmh_oai_dc = dc_v1.serialize_oaipmh
| 8,745 | Python | .py | 183 | 45.704918 | 85 | 0.7971 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,571 | geojson.py | zenodo_zenodo/zenodo/modules/records/serializers/geojson.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo schema.org serializer."""
from __future__ import absolute_import, print_function
from zenodo.modules.records.models import ObjectType
from zenodo.modules.records.serializers.schemas.geojson import \
FeatureCollection
from .json import ZenodoJSONSerializer
class ZenodoGeoJSONSerializer(ZenodoJSONSerializer):
"""Zenodo GeoJSON serializer."""
def dump(self, obj, context=None):
"""Serialize object with schema."""
return FeatureCollection(context=context).dump(obj).data
| 1,482 | Python | .py | 34 | 41.558824 | 76 | 0.776544 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,572 | schemaorg.py | zenodo_zenodo/zenodo/modules/records/serializers/schemaorg.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo schema.org serializer."""
from __future__ import absolute_import, print_function
from zenodo.modules.records.models import ObjectType
from zenodo.modules.records.serializers.schemas import schemaorg as schemas
from .json import ZenodoJSONSerializer
class ZenodoSchemaOrgSerializer(ZenodoJSONSerializer):
"""Zenodo schema.org serializer.
Serializes the record using the appropriate marshmallow schema based on
its schema.org type.
"""
@classmethod
def _get_schema_class(self, obj):
data = obj['metadata']
obj_type = ObjectType.get_by_dict(data['resource_type'])
return getattr(schemas, obj_type['schema.org'][19:])
def dump(self, obj, context=None):
"""Serialize object with schema."""
# Resolve string "https://schema.org/ScholarlyArticle"
# to schemas.ScholarlyArticle class (etc.)
schema_cls = self._get_schema_class(obj)
return schema_cls(context=context).dump(obj).data
| 1,952 | Python | .py | 44 | 41.068182 | 76 | 0.749342 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,573 | extra_formats.py | zenodo_zenodo/zenodo/modules/records/serializers/extra_formats.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2019 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Extra Formats serializer."""
from __future__ import absolute_import, print_function
from flask import request
from zenodo.modules.deposit.extra_formats import ExtraFormats
class ExtraFormatsSerializer(object):
"""Extra Formats serializer.
Serializes the extra formats types.
"""
def serialize(self, pid, record, links_factory=None):
"""Include files for single record retrievals."""
mimetype = request and request.args.get('mimetype')
if not mimetype:
return 'Extra format MIMEType not specified.'
if mimetype not in ExtraFormats.mimetype_whitelist:
return ('"{}" is not an acceptable extra format MIMEType.'
.format(mimetype))
if mimetype in record.extra_formats:
fileobj = record.extra_formats[mimetype]
try: # if an exception occurs, just let it be raised/logged
fp = fileobj.obj.file.storage().open('rb')
result = fp.read()
finally:
fp.close()
return result
return 'No extra formats available for this MIMEType.'
| 2,100 | Python | .py | 48 | 38.333333 | 76 | 0.705969 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,574 | bibtex.py | zenodo_zenodo/zenodo/modules/records/serializers/bibtex.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo. If not, see <http://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.
"""BibTeX serializer for records."""
from __future__ import absolute_import, print_function, unicode_literals
import textwrap
import six
from dateutil.parser import parse as iso2dt
from flask import current_app
from slugify import slugify
class BibTeXSerializer(object):
"""BibTeX serializer for records."""
# pylint: disable=W0613
def serialize(self, pid, record, links_factory=None):
"""Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
return Bibtex(record=record).format()
# pylint: disable=W0613
def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None):
"""Serialize a search result.
:param pid_fetcher: Persistent identifier fetcher.
:param search_result: Elasticsearch search result.
:param links: Dictionary of links to add to response.
"""
records = []
for hit in search_result['hits']['hits']:
records.append(Bibtex(record=hit['_source']).format())
return "\n".join(records)
class MissingRequiredFieldError(Exception):
"""Base class for exceptions in this module.
The exception should be raised when the specific,
required field doesn't exist in the record.
"""
def _init_(self, field):
self.field = field
def _str_(self):
return "Missing field: " + self.field
class Bibtex(object):
"""BibTeX formatter."""
def __init__(self, record):
"""Initialize BibTEX formatter with the specific record."""
self.record = record
def format(self):
"""Return BibTeX export for single record."""
formats = {
'dataset': self._format_dataset,
'image': self._format_misc,
'poster': self._format_misc,
'presentation': self._format_misc,
'publication': self._format_publication,
'software': self._format_software,
'video': self._format_misc,
'default': self._format_misc,
}
t = self._get_entry_type()
if t in formats:
return formats[t]()
else:
return formats['default']()
def _format_publication(self):
formats = {
'book': [self._format_book,
self._format_booklet,
self._format_misc],
'section': [self._format_misc],
'conferencepaper': [self._format_inproceedings,
self._format_proceedings,
self._format_misc],
'article': [self._format_article,
self._format_misc],
'patent': self._format_misc,
'preprint': [self._format_unpublished,
self._format_misc],
'report': [self._format_misc],
'thesis': [self._format_thesis,
self._format_misc],
'technicalnote': [self._format_manual,
self._format_misc],
'workingpaper': [self._format_unpublished,
self._format_misc],
'other': [self._format_misc],
'default': self._format_misc,
}
subtype = self._get_entry_subtype()
if subtype in formats:
for f in formats[subtype]:
try:
out = f()
except MissingRequiredFieldError:
continue
else:
return out
else:
return formats['default']()
def _format_entry(self, name, req, opt, ign):
out = "@" + name + "{"
out += self._get_citation_key() + ",\n"
out += self._clean_input(self._fetch_fields(req, opt, ign))
out += "}"
return out
def _clean_input(self, input):
unsupported_chars = ['&', '%', '$', '_', '#']
chars = list(input)
for index, char in enumerate(chars):
if char in unsupported_chars:
chars[index] = "\\" + chars[index]
return ''.join(chars)
def _format_article(self):
"""Format article entry type.
An article from a journal or magazine.
"""
name = "article"
req_fields = ['author', 'title', 'journal', 'year']
opt_fields = ['volume', 'number', 'pages', 'month', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_book(self):
"""Format book entry type.
A book with an explicit publisher.
"""
name = "book"
req_fields = ['author', 'title', 'publisher', 'year']
opt_fields = ['volume', 'address', 'month', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_booklet(self):
"""Format article entry type.
A work that is printed and bound, but without a named publisher
or sponsoring institution.
"""
name = "booklet"
req_fields = ['title']
opt_fields = ['author', 'address', 'month', 'year', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_proceedings(self):
"""Format article entry type.
The proceedings of a conference.
"""
name = "proceedings"
req_fields = ['title', 'year']
opt_fields = ['publisher', 'address', 'month', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_inproceedings(self):
"""Format article entry type.
An article in the proceedings of a conference.
"""
name = "inproceedings"
req_fields = ['author', 'title', 'booktitle', 'year']
opt_fields = ['pages', 'publisher', 'address', 'month', 'note', 'venue']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_unpublished(self):
"""Format article entry type.
A document with an author and title, but not formally published.
"""
name = "unpublished"
req_fields = ['author', 'title', 'note']
opt_fields = ['month', 'year']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_manual(self):
"""Format article entry type.
Technical documentation.
"""
name = "manual"
req_fields = ['title']
opt_fields = ['author', 'address', 'month', 'year', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_thesis(self):
"""Format article entry type.
An article from a journal or magazine.
"""
name = "phdthesis"
req_fields = ['author', 'title', 'school', 'year']
opt_fields = ['address', 'month', 'note']
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_misc(self):
"""Format misc entry type.
For use when nothing else fits.
"""
name = "misc"
req_fields = []
opt_fields = [
'author', 'title', 'month', 'year', 'note', 'publisher', 'version'
]
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_software(self):
"""Format software entry type."""
name = 'software'
req_fields = []
opt_fields = [
'author', 'title', 'month', 'year', 'note', 'publisher', 'version'
]
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _format_dataset(self):
"""Format dataset entry type."""
name = 'dataset'
req_fields = []
opt_fields = [
'author', 'title', 'month', 'year', 'note', 'publisher', 'version'
]
ign_fields = ['doi', 'url']
return self._format_entry(name, req_fields,
opt_fields, ign_fields)
def _fetch_fields(self, req_fields, opt_fields=None, ign_fields=None):
opt_fields = opt_fields or []
ign_fields = ign_fields or []
fields = {
'address': self._get_address,
'author': self._get_author,
'booktitle': self._get_booktitle,
'journal': self._get_journal,
'month': self._get_month,
'note': self._get_note,
'number': self._get_number,
'pages': self._get_pages,
'publisher': self._get_publisher,
'school': self._get_school,
'title': self._get_title,
'url': self._get_url,
'venue': self._get_venue,
'volume': self._get_volume,
'year': self._get_year,
'doi': self._get_doi,
'version': self._get_version
}
out = ""
for field in req_fields:
value = fields[field]()
if value:
out += self._format_output_row(field, value)
else:
raise MissingRequiredFieldError(field)
for field in opt_fields:
value = fields[field]()
if value:
out += self._format_output_row(field, value)
for field in ign_fields:
value = fields[field]()
if value:
out += self._format_output_row(field, value)
return out
def _format_output_row(self, field, value):
out = ""
if isinstance(value, six.string_types):
value = value.strip()
if field == "author":
if len(value) == 1:
out += u" {0:<12} = {{{1}}},\n".format(field, value[0])
else:
out += u" {0:<12} = {{{1} and\n".format(field, value[0])
if len(value) > 1:
for line in value[1:-1]:
out += u" {0:<16} {1:<} and\n".format("", line)
out += u" {0:<16} {1:<}}},\n".format("", value[-1])
elif len(value) > 50:
wrapped = textwrap.wrap(value, 50)
out += u" {0:<12} = {{{{{1} \n".format(field, wrapped[0])
for line in wrapped[1:-1]:
out += u" {0:<17} {1:<}\n".format("", line)
out += u" {0:<17} {1:<}}}}},\n".format("", wrapped[-1])
elif field == "month":
out += u" {0:<12} = {1},\n".format(field, value)
elif field == "url":
out += u" {0:<12} = {{{1}}}\n".format(field, value)
else:
if(self._is_number(value)):
out += u" {0:<12} = {1},\n".format(field, value)
else:
out += u" {0:<12} = {{{1}}},\n".format(field, value)
return out
def _is_number(self, s):
try:
int(s)
return True
except (ValueError, TypeError):
return False
def _get_entry_type(self):
"""Return entry type."""
if 'resource_type' in self.record:
if 'type' in self.record['resource_type']:
return self.record['resource_type']['type']
return 'default'
def _get_entry_subtype(self):
"""Return entry subtype."""
if 'resource_type' in self.record:
if 'subtype' in self.record['resource_type']:
return self.record['resource_type']['subtype']
return 'default'
def _get_citation_key(self):
"""Return citation key."""
if "recid" in self.record:
authors = self.record.get("creators", None)
if authors:
first_author = authors[0]
name = first_author.get(
"familyname",
first_author.get("name")
)
pubdate = self.record.get('publication_date', None)
if pubdate:
year = "{}_{}".format(iso2dt(pubdate).year,
self.record['recid'])
else:
year = self.record['recid']
return "{0}_{1}".format(slugify(name, separator="_",
max_length=40),
year)
else:
return six.text_type(self.record['recid'])
else:
raise MissingRequiredFieldError("citation key")
def _get_doi(self):
"""Return doi."""
if "doi" in self.record:
return self.record['doi']
else:
return None
def _get_author(self):
"""Return list of name(s) of the author(s)."""
result = []
if "creators" in self.record:
for author in self.record['creators']:
result.append(author["name"])
return result
else:
return result
def _get_title(self):
"""Return work's title."""
if "title" in self.record:
return self.record['title'].strip()
else:
return ""
def _get_month(self):
"""Return the month in which the work was published."""
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
if "publication_date" in self.record:
return months[iso2dt(self.record["publication_date"]).month - 1]
else:
return ""
def _get_year(self):
"""Return the year of publication."""
if "publication_date" in self.record:
return six.text_type(iso2dt(self.record["publication_date"]).year)
else:
return ""
def _get_note(self):
"""Return any additional information that can help the reader."""
if "notes" in self.record:
return self.record["notes"]
else:
return ""
def _get_address(self):
"""Return publisher's address."""
if "imprint" in self.record and\
"place" in self.record["imprint"]:
return self.record["imprint"]["place"]
else:
return ""
def _get_booktitle(self):
"""Return the title of the book, part of which is being cited."""
if "part_of" in self.record and\
"title" in self.record["part_of"]:
return self.record["part_of"]["title"]
else:
return ""
def _get_journal(self):
"""Return the journal or magazine the work was published in."""
if "journal" in self.record and\
"title" in self.record["journal"]:
return self.record["journal"]["title"]
else:
return ""
def _get_number(self):
"""Return the (issue) number of a journal, magazine, or tech-report."""
if "journal" in self.record and\
"issue" in self.record["journal"]:
return self.record["journal"]["issue"]
else:
return ""
def _get_pages(self):
"""Return page numbers, separated by commas or double-hyphens."""
if "journal" in self.record and\
"pages" in self.record["journal"]:
return self.record["journal"]["pages"]
elif "part_of" in self.record and\
"pages" in self.record["part_of"]:
return self.record["part_of"]["pages"]
else:
return ""
def _get_publisher(self):
"""Return the publisher's name."""
if "imprint" in self.record and\
"publisher" in self.record["imprint"]:
return self.record["imprint"]["publisher"]
elif "part_of" in self.record and\
"publisher" in self.record["part_of"]:
return self.record["part_of"]["publisher"]
else:
return current_app.config.get("THEME_SITENAME", "")
def _get_school(self):
"""Return the school where the thesis was written."""
return self.record.get("thesis", {}).get("university", "")
def _get_url(self):
"""Return the WWW address."""
return "https://doi.org/%s" % self.record['doi'] \
if "doi" in self.record else ""
def _get_venue(self):
"""Return conference's venue."""
if "meeting" in self.record and\
"place" in self.record["meeting"]:
return self.record["meeting"]["place"]
else:
return ""
def _get_volume(self):
"""Return the volume of a journal or multi-volume book."""
return self.record.get("journal", {}).get("volume", "")
def _get_version(self):
"""Return the version of a record."""
return self.record.get('version', "")
| 18,437 | Python | .py | 459 | 28.980392 | 80 | 0.530542 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,575 | files.py | zenodo_zenodo/zenodo/modules/records/serializers/files.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Serializers."""
from __future__ import absolute_import, print_function
from flask import current_app, json
from invenio_files_rest.models import ObjectVersion
from invenio_records_files.api import FilesIterator
from zenodo.modules.records.api import ZenodoFileObject
def files_responsify(schema_class, mimetype):
"""Create a deposit files JSON serializer.
:param schema_class: Marshmallow schema class.
:param mimetype: MIME type of response.
"""
def view(obj=None, pid=None, record=None, status=None):
schema = schema_class(
context={'pid': pid},
many=isinstance(obj, FilesIterator)
)
if isinstance(obj, ObjectVersion):
obj = ZenodoFileObject(obj, {})
return current_app.response_class(
json.dumps(schema.dump(obj.dumps()).data),
mimetype=mimetype,
status=status
)
return view
| 1,907 | Python | .py | 47 | 36.468085 | 76 | 0.72973 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,576 | json.py | zenodo_zenodo/zenodo/modules/records/serializers/json.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016-2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo Serializers."""
from __future__ import absolute_import, print_function
import json
from flask import has_request_context
from flask_security import current_user
from invenio_communities.models import Community
from invenio_pidrelations.contrib.versioning import PIDVersioning
from invenio_records.api import Record
from invenio_records_rest.serializers.json import JSONSerializer
from zenodo.modules.records.serializers.pidrelations import \
serialize_related_identifiers
from ..permissions import has_read_files_permission
class ZenodoJSONSerializer(JSONSerializer):
"""Zenodo JSON serializer.
Adds or removes files from depending on access rights and provides a
context to the request serializer.
"""
def preprocess_record(self, pid, record, links_factory=None):
"""Include files for single record retrievals."""
result = super(ZenodoJSONSerializer, self).preprocess_record(
pid, record, links_factory=links_factory
)
# Add/remove files depending on access right.
if isinstance(record, Record) and '_files' in record:
if not has_request_context() or has_read_files_permission(
current_user, record):
result['files'] = record['_files']
else:
result['metadata'].pop('_buckets', None)
# Serialize PID versioning as related identifiers
pv = PIDVersioning(child=pid)
if pv.exists:
rels = serialize_related_identifiers(pid)
if rels:
result['metadata'].setdefault(
'related_identifiers', []).extend(rels)
return result
def preprocess_search_hit(self, pid, record_hit, links_factory=None,
**kwargs):
"""Prepare a record hit from Elasticsearch for serialization."""
result = super(ZenodoJSONSerializer, self).preprocess_search_hit(
pid, record_hit, links_factory=links_factory, **kwargs
)
# Add files if in search hit (only public files exists in index)
if '_files' in record_hit['_source']:
result['files'] = record_hit['_source']['_files']
elif '_files' in record_hit:
result['files'] = record_hit['_files']
else:
# delete the bucket if no files
result['metadata'].pop('_buckets', None)
return result
def dump(self, obj, context=None):
"""Serialize object with schema."""
return self.schema_class(context=context).dump(obj).data
def transform_record(self, pid, record, links_factory=None):
"""Transform record into an intermediate representation."""
return self.dump(
self.preprocess_record(pid, record, links_factory=links_factory),
context={'pid': pid}
)
def transform_search_hit(self, pid, record_hit, links_factory=None):
"""Transform search result hit into an intermediate representation."""
return self.dump(
self.preprocess_search_hit(
pid, record_hit, links_factory=links_factory),
context={'pid': pid}
)
def serialize_exporter(self, pid, record):
"""Serialize a single record for the exporter."""
return json.dumps(
self.transform_search_hit(pid, record)
).encode('utf8') + b'\n'
def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None, **kwargs):
"""Serialize Zenodo search results and aggregations."""
aggregations = search_result.get('aggregations', dict())
if 'communities' in aggregations:
self.enrich_community_aggs(aggregations)
return super(ZenodoJSONSerializer, self).serialize_search(
pid_fetcher, search_result, links=links,
item_links_factory=item_links_factory,
**kwargs
)
def enrich_community_aggs(self, aggregations):
"""Enriches community aggregations with additional information."""
comm_aggs = aggregations['communities']['buckets']
keys = []
for bucket in comm_aggs:
keys.append(bucket['key'])
comms = Community.query.filter(Community.id.in_(keys)).all()
for comm in comms:
for bucket in comm_aggs:
if bucket['key'] == comm.id:
bucket['title'] = comm.title
| 5,427 | Python | .py | 118 | 37.966102 | 78 | 0.665281 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,577 | datetime.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/datetime.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Date string field."""
from __future__ import absolute_import, print_function
import arrow
from arrow.parser import ParserError
from marshmallow import fields, missing
class DateString(fields.Date):
"""ISO8601-formatted date string."""
def _serialize(self, value, attr, obj):
"""Serialize an ISO8601-formatted date."""
try:
return super(DateString, self)._serialize(
arrow.get(value).date(), attr, obj)
except ParserError:
return missing
def _deserialize(self, value, attr, data):
"""Deserialize an ISO8601-formatted date."""
return super(DateString, self)._deserialize(
value, attr, data).isoformat()
| 1,682 | Python | .py | 41 | 37.317073 | 76 | 0.72705 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,578 | sanitizedunicode.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/sanitizedunicode.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Sanitized Unicode string field."""
from __future__ import absolute_import, print_function
from ftfy import fix_text
from .trimmedstring import TrimmedString
class SanitizedUnicode(TrimmedString):
"""String field that sanitizes and fixes problematic unicode characters."""
UNWANTED_CHARACTERS = {
# Zero-width space
u'\u200b',
}
def is_valid_xml_char(self, char):
"""Check if a character is valid based on the XML specification."""
codepoint = ord(char)
return (0x20 <= codepoint <= 0xD7FF or
codepoint in (0x9, 0xA, 0xD) or
0xE000 <= codepoint <= 0xFFFD or
0x10000 <= codepoint <= 0x10FFFF)
def _deserialize(self, value, attr, data):
"""Deserialize sanitized string value."""
value = super(SanitizedUnicode, self)._deserialize(value, attr, data)
value = fix_text(value)
# NOTE: This `join` might be inefficient... There's a solution with a
# large compiled regex lying around, but needs a lot of tweaking.
value = ''.join(filter(self.is_valid_xml_char, value))
for char in self.UNWANTED_CHARACTERS:
value = value.replace(char, '')
return value
| 2,208 | Python | .py | 50 | 39.28 | 79 | 0.703445 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,579 | __init__.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Custom marshmallow fields."""
from __future__ import absolute_import, print_function
from .datetime import DateString
from .doi import DOI, DOILink
from .html import SanitizedHTML
from .persistentid import PersistentId
from .sanitizedunicode import SanitizedUnicode
from .sanitizedurl import SanitizedUrl
from .trimmedstring import TrimmedString
__all__ = (
'DateString',
'DOI',
'DOILink',
'PersistentId',
'SanitizedHTML',
'SanitizedUnicode',
'SanitizedUrl',
'TrimmedString',
)
| 1,484 | Python | .py | 42 | 33.47619 | 76 | 0.77121 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,580 | html.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/html.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""HTML sanitized string field."""
from __future__ import absolute_import, print_function
import bleach
from .sanitizedunicode import SanitizedUnicode
ALLOWED_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'br',
'code',
'caption',
'div',
'em',
'i',
'li',
'ol',
'p',
'pre',
'span',
'strike',
'strong',
'sub',
'sup',
'table',
'tbody',
'thead',
'th',
'td',
'tr',
'u',
'ul',
]
ALLOWED_ATTRS = {
'*': ['class'],
'a': ['href', 'title', 'name', 'rel'],
'table': ['title', 'align', 'summary'],
'caption': ['class'],
'thead': ['title', 'align'],
'tbody': ['title', 'align'],
'th': ['title', 'scope'],
'td': ['title'],
'tr': ['title'],
'abbr': ['title'],
'acronym': ['title'],
}
class SanitizedHTML(SanitizedUnicode):
"""String field which strips sanitizes HTML using the bleach library."""
def __init__(self, tags=None, attrs=None, *args, **kwargs):
"""Initialize field."""
super(SanitizedHTML, self).__init__(*args, **kwargs)
self.tags = tags or ALLOWED_TAGS
self.attrs = attrs or ALLOWED_ATTRS
def _deserialize(self, value, attr, data):
"""Deserialize string by sanitizing HTML."""
value = super(SanitizedHTML, self)._deserialize(value, attr, data)
return bleach.clean(
value,
tags=self.tags,
attributes=self.attrs,
strip=True,
).strip()
| 2,822 | Python | .py | 86 | 24.627907 | 76 | 0.556493 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,581 | persistentid.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/persistentid.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Persistent identifier field."""
from __future__ import absolute_import, print_function
import idutils
from flask_babelex import lazy_gettext as _
from marshmallow import missing
from .sanitizedunicode import SanitizedUnicode
class PersistentId(SanitizedUnicode):
"""Special DOI field."""
default_error_messages = {
'invalid_scheme': 'Not a valid {scheme} identifier.',
# TODO: Translation on format strings sounds tricky...
# 'invalid_scheme': _('Not a valid {scheme} identifier.'),
'invalid_pid': _('Not a valid persistent identifier.'),
}
def __init__(self, scheme=None, normalize=True, *args, **kwargs):
"""Initialize field."""
super(PersistentId, self).__init__(*args, **kwargs)
self.scheme = scheme
self.normalize = normalize
def _serialize(self, value, attr, obj):
"""Serialize persistent identifier value."""
if not value:
return missing
return value
def _deserialize(self, value, attr, data):
"""Deserialize persistent identifier value."""
value = super(PersistentId, self)._deserialize(value, attr, data)
value = value.strip()
schemes = idutils.detect_identifier_schemes(value)
if self.scheme and self.scheme.lower() not in schemes:
self.fail('invalid_scheme', scheme=self.scheme)
if not schemes:
self.fail('invalid_pid')
return idutils.normalize_pid(value, schemes[0]) \
if self.normalize else value
| 2,507 | Python | .py | 58 | 38.310345 | 76 | 0.703035 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,582 | sanitizedurl.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/sanitizedurl.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Sanitized Unicode string field."""
from __future__ import absolute_import, print_function
from marshmallow import fields
from .sanitizedunicode import SanitizedUnicode
class SanitizedUrl(SanitizedUnicode, fields.Url):
"""SanitizedString-based URL field."""
def _deserialize(self, value, attr, data):
"""Deserialize sanitized URL value."""
# Apply SanitizedUnicode first
value = SanitizedUnicode._deserialize(self, value, attr, data)
return fields.Url._deserialize(self, value, attr, data)
| 1,506 | Python | .py | 34 | 41.911765 | 76 | 0.761775 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,583 | trimmedstring.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/trimmedstring.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Trimmed string field."""
from __future__ import absolute_import, print_function
from marshmallow import fields
class TrimmedString(fields.String):
"""String field which strips whitespace the ends of the string."""
def _deserialize(self, value, attr, data):
"""Deserialize DOI value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip()
| 1,382 | Python | .py | 32 | 41 | 76 | 0.755208 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,584 | doi.py | zenodo_zenodo/zenodo/modules/records/serializers/fields/doi.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""DOI field."""
from __future__ import absolute_import, print_function
import idutils
from flask_babelex import lazy_gettext as _
from marshmallow import fields
from .sanitizedunicode import SanitizedUnicode
class DOI(SanitizedUnicode):
"""Special DOI field."""
default_error_messages = {
'invalid_doi': _(
'The provided DOI is invalid - it should look similar '
' to \'10.1234/foo.bar\'.'),
'managed_prefix': (
'The prefix {prefix} is administrated locally.'),
'banned_prefix': (
'The prefix {prefix} is invalid.'
),
'test_prefix': _(
'The prefix 10.5072 is invalid. The '
'prefix is only used for testing purposes, and no DOIs with '
'this prefix are attached to any meaningful content.'
),
'required_doi': _(
'The DOI cannot be changed.'
),
}
def __init__(self, required_doi=None, allowed_dois=None,
managed_prefixes=None, banned_prefixes=None, *args, **kwargs):
"""Initialize field."""
super(DOI, self).__init__(*args, **kwargs)
self.required_doi = required_doi
self.allowed_dois = allowed_dois
self.managed_prefixes = managed_prefixes or []
self.banned_prefixes = banned_prefixes or ['10.5072']
def _deserialize(self, value, attr, data):
"""Deserialize DOI value."""
value = super(DOI, self)._deserialize(value, attr, data)
value = value.strip()
if value == '' and not (
self.required or self.context.get('doi_required')):
return value
if not idutils.is_doi(value):
self.fail('invalid_doi')
return idutils.normalize_doi(value)
def _validate(self, value):
"""Validate DOI value."""
super(DOI, self)._validate(value)
required_doi = self.context.get(
'required_doi', self.required_doi)
allowed_dois = self.context.get(
'allowed_dois', self.allowed_dois)
managed_prefixes = self.context.get(
'managed_prefixes', self.managed_prefixes)
banned_prefixes = self.context.get(
'banned_prefixes', self.banned_prefixes)
# First check for required DOI.
if required_doi:
if value == required_doi:
return
self.fail('required_doi')
# Check if DOI is in allowed list.
if allowed_dois:
if value in allowed_dois:
return
prefix = value.split('/')[0]
# Check for managed prefix
if managed_prefixes and prefix in managed_prefixes:
self.fail('managed_prefix', prefix=prefix)
# Check for banned prefixes
if banned_prefixes and prefix in banned_prefixes:
self.fail(
'test_prefix' if prefix == '10.5072' else 'banned_prefix',
prefix=prefix
)
class DOILink(fields.Field):
"""DOI link field."""
def _serialize(self, value, attr, obj):
if value is None:
return None
return idutils.to_url(value, 'doi', 'https')
| 4,148 | Python | .py | 103 | 32.543689 | 79 | 0.632415 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,585 | dc.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/dc.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record serialization."""
from __future__ import absolute_import, print_function
import lxml.html
from marshmallow import Schema, fields, missing
from ...models import ObjectType
from .common import ui_link_for
class DublinCoreV1(Schema):
"""Schema for records v1 in JSON."""
identifiers = fields.Method('get_identifiers')
titles = fields.Function(lambda o: [o['metadata'].get('title', u'')])
creators = fields.Method('get_creators')
relations = fields.Method('get_relations')
rights = fields.Method('get_rights')
dates = fields.Method('get_dates')
subjects = fields.Method('get_subjects')
descriptions = fields.Method('get_descriptions')
publishers = fields.Method('get_publishers')
contributors = fields.Method('get_contributors')
types = fields.Method('get_types')
sources = fields.Method('get_sources')
languages = fields.Function(lambda o: [o['metadata'].get('language', u'')])
coverage = fields.Method('get_locations')
def get_identifiers(self, obj):
"""Get identifiers."""
items = []
items.append(u'https://zenodo.org/record/{0}'.format(
obj['metadata']['recid']))
items.append(obj['metadata'].get('doi', u''))
oai = obj['metadata'].get('_oai', {}).get('id')
if oai:
items.append(oai)
return items
def get_creators(self, obj):
"""Get creators."""
return [c['name'] for c in obj['metadata'].get('creators', [])]
def get_relations(self, obj):
"""Get creators."""
rels = []
# Grants
for g in obj['metadata'].get('grants', []):
eurepo_id = g.get('identifiers', {}).get('eurepo')
if eurepo_id:
rels.append(eurepo_id)
# Alternate identifiers
for a in obj['metadata'].get('alternate_identifiers', []):
rels.append(
u'info:eu-repo/semantics/altIdentifier/{0}/{1}'.format(
a['scheme'],
a['identifier']))
# Related identifiers
for a in obj['metadata'].get('related_identifiers', []):
rels.append(
u'{0}:{1}'.format(
a['scheme'],
a['identifier']))
# Zenodo community identifiers
for comm in obj['metadata'].get('communities', []):
rels.append(u'url:{}'.format(ui_link_for('community', id=comm)))
return rels
def get_rights(self, obj):
"""Get rights."""
rights = [
u'info:eu-repo/semantics/{}Access'.format(
obj['metadata']['access_right'])]
license_url = obj['metadata'].get('license', {}).get('url')
if license_url:
rights.append(license_url)
return rights
def get_dates(self, obj):
"""Get dates."""
dates = [obj['metadata']['publication_date']]
if obj['metadata']['access_right'] == u'embargoed':
dates.append(
u'info:eu-repo/date/embargoEnd/{0}'.format(
obj['metadata']['embargo_date']))
for interval in obj['metadata'].get('dates', []):
start = interval.get('start') or ''
end = interval.get('end') or ''
if start != '' and end != '' and start == end:
dates.append(start)
else:
dates.append(start + '/' + end)
return dates
def get_descriptions(self, obj):
"""Get descriptions."""
descriptions = []
if obj['metadata'].get('description', '').strip():
descriptions.append(
lxml.html.document_fromstring(obj['metadata']['description'])
.text_content().replace(u"\xa0", u" "))
if obj['metadata'].get('notes', '').strip():
descriptions.append(
lxml.html.document_fromstring(obj['metadata']['notes'])
.text_content().replace(u"\xa0", u" "))
if obj['metadata'].get('method', '').strip():
descriptions.append(
lxml.html.document_fromstring(obj['metadata']['method'])
.text_content().replace(u"\xa0", u" "))
return descriptions
def get_subjects(self, obj):
"""Get subjects."""
metadata = obj['metadata']
subjects = []
subjects.extend(metadata.get('keywords', []))
subjects.extend((s['term'] for s in metadata.get('subjects', [])
if s.get('term')))
return subjects
def get_publishers(self, obj):
"""Get publishers."""
imprint = obj['metadata'].get('imprint', {}).get('publisher')
if imprint:
return [imprint]
part = obj['metadata'].get('part_of', {}).get('publisher')
if part:
return [part]
return []
def get_contributors(self, obj):
"""Get contributors."""
return [c['name'] for c in obj['metadata'].get('contributors', [])]
def get_types(self, obj):
"""Get types."""
t = ObjectType.get_by_dict(obj['metadata']['resource_type'])
types = [t['eurepo'], t['internal_id']]
oa_type = ObjectType.get_openaire_subtype(obj['metadata'])
if oa_type:
types.append(oa_type)
return types
def get_sources(self, obj):
"""Get sources."""
items = []
# Journal
journal = obj['metadata'].get('journal')
if journal is not None:
vol = journal.get('volume')
issue = journal.get('issue')
if vol and issue:
vol = u'{0}({1})'.format(vol, issue)
if vol is None:
vol = issue
y = journal.get('year')
parts = [
journal.get('title'),
vol,
journal.get('pages'),
u'({0})'.format(y) if y else None,
]
items.append(u' '.join([x for x in parts if x]))
# Meetings
m = obj['metadata'].get('meetings', {})
if m:
parts = [
m.get('acronym'),
m.get('title'),
m.get('place'),
m.get('dates'),
]
items.append(', '.join([x for x in parts if x]))
return items
def get_locations(self, obj):
"""Get locations."""
locations = []
for location in obj['metadata'].get('locations', []):
if location.get('lat') and location.get('lon'):
locations.append(
u'name={place}; east={lon}; north={lat}'.format(**location)
)
return locations or missing
| 7,667 | Python | .py | 190 | 30.836842 | 79 | 0.562567 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,586 | pidrelations.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/pidrelations.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""PID Version relation schemas."""
from invenio_pidrelations.serializers.schemas import RelationSchema
from marshmallow import fields
class VersionRelation(RelationSchema):
"""PID version relation schema."""
count = fields.Method('dump_count')
last_child = fields.Method('dump_last_child')
draft_child_deposit = fields.Method('dump_draft_child_deposit')
def dump_count(self, obj):
"""Dump the number of children."""
return obj.children.count()
def dump_last_child(self, obj):
"""Dump the last child."""
if obj.is_ordered:
return self._dump_relative(obj.last_child)
def dump_draft_child_deposit(self, obj):
"""Dump the deposit of the draft child."""
if obj.draft_child_deposit:
return self._dump_relative(obj.draft_child_deposit)
class Meta:
"""Meta fields of the schema."""
fields = ('parent', 'is_last', 'index', 'last_child', 'count',
'draft_child_deposit')
| 1,981 | Python | .py | 46 | 38.826087 | 76 | 0.714137 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,587 | marc21.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/marc21.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""MARCXML translation index."""
from __future__ import absolute_import, print_function, unicode_literals
from dateutil.parser import parse
from flask import current_app
from marshmallow import Schema, fields, missing, post_dump
class RecordSchemaMARC21(Schema):
"""Schema for records in MARC."""
control_number = fields.Function(
lambda o: str(o['metadata'].get('recid')))
date_and_time_of_latest_transaction = fields.Function(
lambda obj: parse(obj['updated']).strftime("%Y%m%d%H%M%S.0"))
information_relating_to_copyright_status = fields.Function(
lambda o: dict(copyright_status=o['metadata']['access_right']))
index_term_uncontrolled = fields.Function(
lambda o: [
dict(uncontrolled_term=kw)
for kw in o['metadata'].get('keywords', [])
]
)
subject_added_entry_topical_term = fields.Method(
'get_subject_added_entry_topical_term')
terms_governing_use_and_reproduction_note = fields.Function(
lambda o: dict(
uniform_resource_identifier=o[
'metadata'].get('license', {}).get('url'),
terms_governing_use_and_reproduction=o[
'metadata'].get('license', {}).get('title')
))
title_statement = fields.Function(
lambda o: dict(title=o['metadata'].get('title')))
general_note = fields.Function(
lambda o: dict(general_note=o['metadata'].get('notes')))
information_relating_to_copyright_status = fields.Function(
lambda o: dict(copyright_status=o['metadata'].get('access_right')))
publication_distribution_imprint = fields.Method(
'get_publication_distribution_imprint')
funding_information_note = fields.Function(
lambda o: [dict(
text_of_note=v.get('title'),
grant_number=v.get('code')
) for v in o['metadata'].get('grants', [])])
other_standard_identifier = fields.Method('get_other_standard_identifier')
added_entry_meeting_name = fields.Method('get_added_entry_meeting_name')
main_entry_personal_name = fields.Method('get_main_entry_personal_name')
added_entry_personal_name = fields.Method('get_added_entry_personal_name')
summary = fields.Function(
lambda o: dict(summary=o['metadata'].get('description')))
host_item_entry = fields.Method('get_host_item_entry')
dissertation_note = fields.Function(
lambda o: dict(name_of_granting_institution=o[
'metadata'].get('thesis', {}).get('university')))
language_code = fields.Function(
lambda o: dict(language_code_of_text_sound_track_or_separate_title=\
o['metadata'].get('language')))
# Custom
# ======
resource_type = fields.Raw(attribute='metadata.resource_type')
communities = fields.Raw(attribute='metadata.communities')
references = fields.Raw(attribute='metadata.references')
embargo_date = fields.Raw(attribute='metadata.embargo_date')
journal = fields.Raw(attribute='metadata.journal')
_oai = fields.Raw(attribute='metadata._oai')
_files = fields.Method('get_files')
leader = fields.Method('get_leader')
conference_url = fields.Raw(attribute='metadata.meeting.url')
def get_leader(self, o):
"""Return the leader information."""
rt = o['metadata']['resource_type']['type']
rec_types = {
'image': 'two-dimensional_nonprojectable_graphic',
'video': 'projected_medium',
'dataset': 'computer_file',
'software': 'computer_file',
}
type_of_record = rec_types[rt] if rt in rec_types \
else 'language_material'
res = {
'record_length': '00000',
'record_status': 'new',
'type_of_record': type_of_record,
'bibliographic_level': 'monograph_item',
'type_of_control': 'no_specified_type',
'character_coding_scheme': 'marc-8',
'indicator_count': 2,
'subfield_code_count': 2,
'base_address_of_data': '00000',
'encoding_level': 'unknown',
'descriptive_cataloging_form': 'unknown',
'multipart_resource_record_level':
'not_specified_or_not_applicable',
'length_of_the_length_of_field_portion': 4,
'length_of_the_starting_character_position_portion': 5,
'length_of_the_implementation_defined_portion': 0,
'undefined': 0,
}
return res
def get_files(self, o):
"""Get the files provided the record is open access."""
if o['metadata']['access_right'] != 'open':
return missing
res = []
for f in o['metadata'].get('_files', []):
res.append(dict(
uri=u'https://zenodo.org/record/{0}/files/{1}'.format(
o['metadata'].get('recid', ''), f['key']),
size=f['size'],
checksum=f['checksum'],
type=f['type'],
))
return res or missing
def get_host_item_entry(self, o):
"""Get host items."""
res = []
for v in o['metadata'].get('related_identifiers', []):
res.append(dict(
main_entry_heading=v.get('identifier'),
relationship_information=v.get('relation'),
note=v.get('scheme'),
))
imprint = o['metadata'].get('imprint', {})
part_of = o['metadata'].get('part_of', {})
if part_of and imprint:
res.append(dict(
main_entry_heading=imprint.get('place'),
edition=imprint.get('publisher'),
title=part_of.get('title'),
related_parts=part_of.get('pages'),
international_standard_book_number=imprint.get('isbn'),
))
return res or missing
def get_publication_distribution_imprint(self, o):
"""Get publication date and imprint."""
res = []
pubdate = o['metadata'].get('publication_date')
if pubdate:
res.append(dict(date_of_publication_distribution=pubdate))
imprint = o['metadata'].get('imprint')
part_of = o['metadata'].get('part_of')
if not part_of and imprint:
res.append(dict(
place_of_publication_distribution=imprint.get('place'),
name_of_publisher_distributor=imprint.get('publisher'),
date_of_publication_distribution=pubdate,
))
return res or missing
def get_subject_added_entry_topical_term(self, o):
"""Get licenses and subjects."""
res = []
license = o['metadata'].get('license', {}).get('id')
if license:
res.append(dict(
topical_term_or_geographic_name_entry_element='cc-by',
source_of_heading_or_term='opendefinition.org',
level_of_subject='Primary',
thesaurus='Source specified in subfield $2',
))
def _subject(term, id_, scheme):
return dict(
topical_term_or_geographic_name_entry_element=term,
authority_record_control_number_or_standard_number=(
'({0}){1}'.format(scheme, id_)),
level_of_subject='Primary',
)
for s in o['metadata'].get('subjects', []):
res.append(_subject(
s.get('term'), s.get('identifier'), s.get('scheme'), ))
return res or missing
def get_other_standard_identifier(self, o):
"""Get other standard identifiers."""
res = []
def stdid(pid, scheme, q=None):
return dict(
standard_number_or_code=pid,
source_of_number_or_code=scheme,
qualifying_information=q,
)
m = o['metadata']
if m.get('doi'):
res.append(stdid(m['doi'], 'doi'))
for id_ in m.get('alternate_identifiers', []):
res.append(stdid(
id_.get('identifier'),
id_.get('scheme'),
q='alternateidentifier'
))
return res or missing
def _get_personal_name(self, v, relator_code=None):
ids = []
for scheme in ['gnd', 'orcid', ]:
if v.get(scheme):
ids.append((scheme, v[scheme]))
return dict(
personal_name=v.get('name'),
affiliation=v.get('affiliation'),
authority_record_control_number_or_standard_number=[
"({0}){1}".format(scheme, identifier)
for (scheme, identifier) in ids
],
relator_code=[relator_code] if relator_code else []
)
def get_main_entry_personal_name(self, o):
"""Get main_entry_personal_name."""
creators = o['metadata'].get('creators', [])
if len(creators) > 0:
v = creators[0]
return self._get_personal_name(v)
def get_added_entry_personal_name(self, o):
"""Get added_entry_personal_name."""
items = []
creators = o['metadata'].get('creators', [])
if len(creators) > 1:
for c in creators[1:]:
items.append(self._get_personal_name(c))
contributors = o['metadata'].get('contributors', [])
for c in contributors:
items.append(self._get_personal_name(
c, relator_code=self._map_contributortype(c.get('type'))))
supervisors = o['metadata'].get('thesis', {}).get('supervisors', [])
for s in supervisors:
items.append(self._get_personal_name(s, relator_code='ths'))
return items
def _map_contributortype(self, type_):
return current_app.config['DEPOSIT_CONTRIBUTOR_DATACITE2MARC'][type_]
def get_added_entry_meeting_name(self, o):
"""Get added_entry_meeting_name."""
v = o['metadata'].get('meeting', {})
return [dict(
meeting_name_or_jurisdiction_name_as_entry_element=v.get('title'),
location_of_meeting=v.get('place'),
date_of_meeting=v.get('dates'),
miscellaneous_information=v.get('acronym'),
number_of_part_section_meeting=v.get('session'),
name_of_part_section_of_a_work=v.get('session_part'),
)]
@post_dump(pass_many=True)
def remove_empty_fields(self, data, many):
"""Dump + Remove empty fields."""
_filter_empty(data)
return data
def _is_non_empty(value):
"""Conditional for regarding a value as 'non-empty'.
This enhances the default "bool" return value with some exceptions:
- number 0 resolves as True - non-empty.
"""
if isinstance(value, int):
return True # All integers are non-empty values
else:
return bool(value)
def _filter_empty(record):
"""Filter empty fields."""
if isinstance(record, dict):
for k in list(record.keys()):
if _is_non_empty(record[k]):
_filter_empty(record[k])
if not _is_non_empty(record[k]):
del record[k]
elif isinstance(record, list) or isinstance(record, tuple):
for (k, v) in list(enumerate(record)):
if _is_non_empty(v):
_filter_empty(record[k])
if not _is_non_empty(v):
del record[k]
| 12,434 | Python | .py | 285 | 33.761404 | 78 | 0.593362 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,588 | legacyjson.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/legacyjson.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo legacy JSON schema."""
from __future__ import absolute_import, print_function, unicode_literals
import six
from flask import current_app, url_for
from flask_babelex import lazy_gettext as _
from invenio_communities.models import Community
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from marshmallow import Schema, ValidationError, fields, missing, post_dump, \
post_load, pre_dump, pre_load, validate, validates, validates_schema
from werkzeug.routing import BuildError
from zenodo.modules.records.models import AccessRight, ObjectType
from zenodo.modules.records.utils import is_valid_openaire_type
from ...minters import doi_generator
from ..fields import DOILink, SanitizedUnicode, SanitizedUrl
from . import common
class FileSchemaV1(Schema):
"""Schema for files depositions."""
id = fields.String(attribute='file_id', dump_only=True)
filename = SanitizedUnicode(attribute='key', dump_only=True)
filesize = fields.Integer(attribute='size', dump_only=True)
checksum = fields.Method('dump_checksum', dump_only=True)
links = fields.Method('dump_links', dump_only=True)
def dump_checksum(self, obj):
"""Dump checksum."""
checksum = obj.get('checksum')
if not checksum:
return missing
algo, hashval = checksum.split(':')
if algo != 'md5':
return missing
return hashval
def dump_links(self, obj):
"""Dump links."""
links = {
'download': common.api_link_for(
'object',
bucket=obj.get('bucket'),
key=obj.get('key'),
),
'self': common.api_link_for(
'deposit_file',
id=self.context['pid'].pid_value,
file_id=obj.get('file_id'),
),
}
if not links:
return missing
return links
class LegacyMetadataSchemaV1(common.CommonMetadataSchemaV1):
"""Legacy JSON metadata."""
upload_type = fields.String(
attribute='resource_type.type',
required=True,
validate=validate.OneOf(choices=ObjectType.get_types()),
)
publication_type = fields.Method(
'dump_publication_type',
attribute='resource_type.subtype',
validate=validate.OneOf(
choices=ObjectType.get_subtypes('publication')),
)
image_type = fields.Method(
'dump_image_type',
attribute='resource_type.subtype',
validate=validate.OneOf(choices=ObjectType.get_subtypes('image')),
)
openaire_type = fields.Method(
'dump_openaire_type',
attribute='resource_type.openaire_subtype'
)
license = fields.Method('dump_license', 'load_license')
communities = fields.Method('dump_communities', 'load_communities')
grants = fields.Method('dump_grants', 'load_grants')
prereserve_doi = fields.Method('dump_prereservedoi', 'load_prereservedoi')
journal_title = SanitizedUnicode(attribute='journal.title')
journal_volume = SanitizedUnicode(attribute='journal.volume')
journal_issue = SanitizedUnicode(attribute='journal.issue')
journal_pages = SanitizedUnicode(attribute='journal.pages')
conference_title = SanitizedUnicode(attribute='meeting.title')
conference_acronym = SanitizedUnicode(attribute='meeting.acronym')
conference_dates = SanitizedUnicode(attribute='meeting.dates')
conference_place = SanitizedUnicode(attribute='meeting.place')
conference_url = SanitizedUrl(attribute='meeting.url')
conference_session = SanitizedUnicode(attribute='meeting.session')
conference_session_part = SanitizedUnicode(
attribute='meeting.session_part')
imprint_isbn = SanitizedUnicode(attribute='imprint.isbn')
imprint_place = SanitizedUnicode(attribute='imprint.place')
imprint_publisher = SanitizedUnicode(attribute='imprint.publisher')
partof_pages = SanitizedUnicode(attribute='part_of.pages')
partof_title = SanitizedUnicode(attribute='part_of.title')
thesis_university = SanitizedUnicode(attribute='thesis.university')
thesis_supervisors = fields.Nested(
common.PersonSchemaV1, many=True, attribute='thesis.supervisors')
def _dump_subtype(self, obj, type_):
"""Get subtype."""
if obj.get('resource_type', {}).get('type') == type_:
return obj.get('resource_type', {}).get('subtype', missing)
return missing
def dump_publication_type(self, obj):
"""Get publication type."""
return self._dump_subtype(obj, 'publication')
def dump_image_type(self, obj):
"""Get publication type."""
return self._dump_subtype(obj, 'image')
def dump_openaire_type(self, obj):
"""Get OpenAIRE type."""
return obj.get('resource_type', {}).get('openaire_subtype', missing)
def dump_license(self, obj):
"""Dump license."""
return obj.get('license', {}).get('id', missing)
def load_license(self, data):
"""Load license."""
if isinstance(data, six.string_types):
license = data
elif isinstance(data, dict):
license = data['id']
else:
raise ValidationError(_('License must be a string or dictionary.'))
return {'$ref': 'https://dx.zenodo.org/licenses/{0}'.format(license)}
def dump_grants(self, obj):
"""Get grants."""
res = []
for g in obj.get('grants', []):
if g.get('program', {}) == 'FP7' and \
g.get('funder', {}).get('doi') == '10.13039/501100000780':
res.append(dict(id=g['code']))
else:
res.append(dict(id=g['internal_id']))
return res or missing
def load_grants(self, data):
"""Load grants."""
if not isinstance(data, list):
raise ValidationError(_('Not a list.'))
result = set()
errors = set()
for g in data:
if not isinstance(g, dict):
raise ValidationError(_('Element not an object.'))
g = g.get('id')
if not g:
continue
# FP7 project grant
if not str(g).startswith('10.13039/'):
g = '10.13039/501100000780::{0}'.format(g)
# Check that the PID exists
grant_pid = PersistentIdentifier.query.filter_by(
pid_type='grant', pid_value=g).one_or_none()
if not grant_pid or grant_pid.status != PIDStatus.REGISTERED:
errors.add(g)
continue
result.add(g)
if errors:
raise ValidationError(
'Invalid grant ID(s): {0}'.format(', '.join(errors)),
field_names='grants')
return [{'$ref': 'https://dx.zenodo.org/grants/{0}'.format(grant_id)}
for grant_id in result] or missing
def dump_communities(self, obj):
"""Dump communities type."""
return [dict(identifier=x) for x in obj.get('communities', [])] \
or missing
def load_communities(self, data):
"""Load communities type."""
if not isinstance(data, list):
raise ValidationError(_('Not a list.'))
invalid_format_comms = [
c for c in data if not (isinstance(c, dict) and 'identifier' in c)]
if invalid_format_comms:
raise ValidationError(
'Invalid community format: {}.'.format(invalid_format_comms),
field_names='communities')
comm_ids = list(sorted([
x['identifier'] for x in data if x.get('identifier')
]))
errors = {c for c in comm_ids if not Community.get(c)}
if errors:
raise ValidationError(
'Invalid communities: {0}'.format(', '.join(errors)),
field_names='communities')
return comm_ids or missing
def dump_prereservedoi(self, obj):
"""Dump pre-reserved DOI."""
recid = obj.get('recid')
if recid:
prefix = None
if not current_app:
prefix = '10.5072' # Test prefix
return dict(
recid=recid,
doi=doi_generator(recid, prefix=prefix),
)
return missing
def load_prereservedoi(self, obj):
"""Load pre-reserved DOI.
The value is not important as we do not store it. Since the deposit and
record id are now the same
"""
return missing
@pre_dump()
def predump_related_identifiers(self, data):
"""Split related/alternate identifiers.
This ensures that we can just use the base schemas definitions of
related/alternate identifies.
"""
relids = data.pop('related_identifiers', [])
alids = data.pop('alternate_identifiers', [])
for a in alids:
a['relation'] = 'isAlternateIdentifier'
if relids or alids:
data['related_identifiers'] = relids + alids
return data
@pre_load()
def preload_related_identifiers(self, data):
"""Split related/alternate identifiers.
This ensures that we can just use the base schemas definitions of
related/alternate identifies for loading.
"""
# Legacy API does not accept alternate_identifiers, so force delete it.
data.pop('alternate_identifiers', None)
for r in data.pop('related_identifiers', []):
# Problem that API accepted one relation while documentation
# presented a different relation.
if r.get('relation') in [
'isAlternativeIdentifier', 'isAlternateIdentifier']:
k = 'alternate_identifiers'
r.pop('relation')
else:
k = 'related_identifiers'
data.setdefault(k, [])
data[k].append(r)
@pre_load()
def preload_resource_type(self, data):
"""Prepare data for easier deserialization."""
if data.get('upload_type') != 'publication':
data.pop('publication_type', None)
if data.get('upload_type') != 'image':
data.pop('image_type', None)
@pre_load()
def preload_license(self, data):
"""Default license."""
acc = data.get('access_right', AccessRight.OPEN)
if acc in [AccessRight.OPEN, AccessRight.EMBARGOED]:
if 'license' not in data:
if data.get('upload_type') == 'dataset':
data['license'] = 'CC0-1.0'
else:
data['license'] = 'CC-BY-4.0'
@post_load()
def merge_keys(self, data):
"""Merge dot keys."""
prefixes = [
'resource_type',
'journal',
'meeting',
'imprint',
'part_of',
'thesis',
]
for p in prefixes:
for k in list(data.keys()):
if k.startswith('{0}.'.format(p)):
key, subkey = k.split('.')
if key not in data:
data[key] = dict()
data[key][subkey] = data.pop(k)
# Pre-reserve DOI is implemented differently now.
data.pop('prereserve_doi', None)
@validates('communities')
def validate_communities(self, values):
"""Validate communities."""
for v in values:
if not isinstance(v, six.string_types):
raise ValidationError(
_('Invalid community identifier.'),
field_names=['communities']
)
@validates_schema
def validate_data(self, obj):
"""Validate resource type."""
type_ = obj.get('resource_type', {}).get('type')
if type_ in ['publication', 'image']:
type_dict = {
'type': type_,
'subtype': obj.get('resource_type', {}).get('subtype')
}
field_names = ['{0}_type'.format(type_)]
else:
type_dict = {'type': type_}
field_names = ['upload_type']
if ObjectType.get_by_dict(type_dict) is None:
raise ValidationError(
_('Invalid upload, publication or image type.'),
field_names=field_names,
)
if not is_valid_openaire_type(obj.get('resource_type', {}),
obj.get('communities', [])):
raise ValidationError(
_('Invalid OpenAIRE subtype.'),
field_names=['openaire_subtype'],
)
class LegacyRecordSchemaV1(common.CommonRecordSchemaV1):
"""Legacy JSON schema (used by deposit)."""
doi_url = DOILink(attribute='metadata.doi', dump_only=True)
files = fields.List(
fields.Nested(FileSchemaV1), dump_only=True)
metadata = fields.Nested(LegacyMetadataSchemaV1)
modified = fields.Str(attribute='updated', dump_only=True)
owner = fields.Method('dump_owners', dump_only=True)
record_id = fields.Integer(attribute='metadata.recid', dump_only=True)
record_url = fields.String(dump_only=True)
state = fields.Method('dump_state', dump_only=True)
submitted = fields.Function(
lambda o: o['metadata'].get(
'_deposit', {}).get('pid') is not None,
dump_only=True
)
title = SanitizedUnicode(
attribute='metadata.title', default='', dump_only=True)
def dump_state(self, o):
"""Get state of deposit."""
if o['metadata'].get('_deposit', {}).get('status', 'draft') == 'draft':
if o['metadata'].get('_deposit', {}).get('pid', {}):
return 'inprogress'
else:
return 'unsubmitted'
return 'done'
def dump_owners(self, obj):
"""Get owners."""
if '_deposit' in obj['metadata']:
try:
return obj['metadata']['_deposit'].get('owners', [])[0]
except IndexError:
return None
elif 'owners' in obj['metadata']:
return obj['metadata']['owners'][0]
return None
class DepositFormSchemaV1(LegacyRecordSchemaV1):
"""Schema for deposit form JSON."""
@post_dump()
def remove_envelope(self, data):
"""Remove envelope."""
if 'metadata' in data:
data = data['metadata']
return data
class GitHubRecordSchemaV1(DepositFormSchemaV1):
"""JSON which can be added to the .zenodo.json file in a repository."""
@post_dump()
def remove_envelope(self, data):
"""Remove envelope."""
data = super(GitHubRecordSchemaV1, self).remove_envelope(data)
for k in ['doi', 'prereserve_doi']:
if k in data:
del data[k]
return data
| 15,808 | Python | .py | 378 | 32.375661 | 79 | 0.603098 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,589 | datacite.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016-2018 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record serialization."""
from __future__ import absolute_import, print_function, unicode_literals
import json
import re
import arrow
import pycountry
from flask import current_app
from marshmallow import Schema, fields, missing, post_dump
from ...models import ObjectType
from ...utils import is_doi_locally_managed
from .common import ui_link_for
class PersonSchema(Schema):
"""Creator/contributor common schema."""
affiliation = fields.Str()
nameIdentifier = fields.Method('get_nameidentifier')
def get_nameidentifier(self, obj):
"""Get name identifier."""
if obj.get('orcid'):
return {
"nameIdentifier": obj.get('orcid'),
"nameIdentifierScheme": "ORCID",
"schemeURI": "http://orcid.org/"
}
if obj.get('gnd'):
return {
"nameIdentifier": obj.get('gnd'),
"nameIdentifierScheme": "GND",
}
return {}
class CreatorSchema(PersonSchema):
"""Creator schema."""
creatorName = fields.Str(attribute='name')
class ContributorSchema(PersonSchema):
"""Contributor schema."""
contributorName = fields.Str(attribute='name')
contributorType = fields.Str(attribute='type')
class TitleSchema(Schema):
"""Title schema."""
title = fields.Str()
class DateSchema(Schema):
"""Date schema."""
VALID_DATE_TYPES = {
'Accepted',
'Available',
'Copyrighted',
'Collected',
'Created',
'Issued',
'Submitted',
'Updated',
'Valid',
}
date = fields.Str(attribute='date')
dateType = fields.Str(attribute='type')
class AlternateIdentifierSchema(Schema):
"""Alternate identifiers schema."""
alternateIdentifier = fields.Str(attribute='identifier')
alternateIdentifierType = fields.Str(attribute='scheme')
class RelatedIdentifierSchema(Schema):
"""Alternate identifiers schema."""
relatedIdentifier = fields.Str(attribute='identifier')
relatedIdentifierType = fields.Method('get_type')
relationType = fields.Function(
lambda o: o['relation'][0].upper() + o['relation'][1:])
resourceTypeGeneral = fields.Method(
'get_resource_type', attribute='resource_type')
def get_type(self, obj):
"""Get type."""
if obj['scheme'] == 'handle':
return 'Handle'
elif obj['scheme'] == 'ads':
return 'bibcode'
elif obj['scheme'] == 'arxiv':
return 'arXiv'
else:
return obj['scheme'].upper()
def get_resource_type(self, obj):
"""Resource type."""
resource_type = obj.get('resource_type')
if resource_type:
t = ObjectType.get_by_dict(resource_type)
return t['datacite']['general']
else:
return missing
class DataCiteSchema(Schema):
"""Base class for schemas."""
DATE_SCHEMA = DateSchema
identifier = fields.Method('get_identifier', attribute='metadata.doi')
titles = fields.List(fields.Nested(TitleSchema), attribute='metadata')
publisher = fields.Constant('Zenodo')
publicationYear = fields.Function(
lambda o: str(arrow.get(o['metadata']['publication_date']).year))
subjects = fields.Method('get_subjects')
dates = fields.Method('get_dates')
language = fields.Method('get_language')
geoLocations = fields.Method('get_locations')
version = fields.Str(attribute='metadata.version')
resourceType = fields.Method('get_type')
alternateIdentifiers = fields.List(
fields.Nested(AlternateIdentifierSchema),
attribute='metadata.alternate_identifiers',
)
relatedIdentifiers = fields.Method('get_related_identifiers')
rightsList = fields.Method('get_rights')
descriptions = fields.Method('get_descriptions')
@post_dump
def cleanup(self, data):
"""Clean the data."""
# Remove the language if Alpha-2 code was not found
if 'language' in data and data['language'] is None:
del data['language']
return data
def get_identifier(self, obj):
"""Get record main identifier."""
doi = obj['metadata'].get('doi', '')
if is_doi_locally_managed(doi):
return {
'identifier': doi,
'identifierType': 'DOI'
}
else:
recid = obj.get('metadata', {}).get('recid', '')
return {
'identifier': ui_link_for('record_html', id=recid),
'identifierType': 'URL',
}
def get_language(self, obj):
"""Export language to the Alpha-2 code (if available)."""
lang = obj['metadata'].get('language', None)
if lang:
lang_res = pycountry.languages.get(alpha_3=lang)
if not lang_res or not hasattr(lang_res, 'alpha_2'):
return None
return lang_res.alpha_2
return None
def get_descriptions(self, obj):
"""Get descriptions."""
items = []
desc = obj['metadata']['description']
max_descr_size = current_app.config.get(
'DATACITE_MAX_DESCRIPTION_SIZE', 20000)
if desc:
items.append({
'description': desc[:max_descr_size],
'descriptionType': 'Abstract'
})
notes = obj['metadata'].get('notes')
if notes:
items.append({
'description': notes[:max_descr_size],
'descriptionType': 'Other'
})
refs = obj['metadata'].get('references')
if refs:
items.append({
'description': json.dumps({
'references': [
r['raw_reference'] for r in refs
if 'raw_reference' in r]
})[:max_descr_size],
'descriptionType': 'Other'
})
method = obj['metadata'].get('method')
if method:
items.append({
'description': method[:max_descr_size],
'descriptionType': 'Methods'
})
return items
def get_rights(self, obj):
"""Get rights."""
items = []
# license
license_url = obj['metadata'].get('license', {}).get('url')
license_text = obj['metadata'].get('license', {}).get('title')
if license_url and license_text:
items.append({
'rightsURI': license_url,
'rights': license_text,
})
# info:eu-repo
items.append({
'rightsURI': 'info:eu-repo/semantics/{}Access'.format(
obj['metadata']['access_right']),
'rights': '{0} access'.format(
obj['metadata']['access_right']).title()
})
return items
def get_type(self, obj):
"""Resource type."""
t = ObjectType.get_by_dict(obj['metadata']['resource_type'])
type_ = {
'resourceTypeGeneral': t['datacite']['general'],
'resourceType': t['datacite'].get('type'),
}
oa_type = ObjectType.get_openaire_subtype(obj['metadata'])
# NOTE: This overwrites the resourceType if the configuration
# of the OpenAIRE subtypes overlaps with regular subtypes.
if oa_type:
type_['resourceType'] = oa_type
return type_
def get_related_identifiers(self, obj):
"""Related identifiers."""
accepted_types = [
'doi', 'ark', 'ean13', 'eissn', 'handle', 'isbn', 'issn', 'istc',
'lissn', 'lsid', 'purl', 'upc', 'url', 'urn', 'ads', 'arxiv',
'bibcode',
]
s = RelatedIdentifierSchema()
items = []
for r in obj['metadata'].get('related_identifiers', []):
if r['scheme'] in accepted_types:
items.append(s.dump(r).data)
doi = obj['metadata'].get('doi', '')
if not is_doi_locally_managed(doi):
items.append(s.dump({
'identifier': doi,
'scheme': 'doi',
'relation': 'IsIdenticalTo',
}).data)
# Zenodo community identifiers
for comm in obj['metadata'].get('communities', []):
items.append(s.dump({
'identifier': ui_link_for('community', id=comm),
'scheme': 'url',
'relation': 'IsPartOf',
}).data)
return items
def get_subjects(self, obj):
"""Get subjects."""
items = []
for s in obj['metadata'].get('keywords', []):
items.append({'subject': s})
for s in obj['metadata'].get('subjects', []):
items.append({
'subject': s['identifier'],
'subjectScheme': s['scheme'],
})
return items
def get_dates(self, obj):
"""Get dates from record."""
schema_cls = self.DATE_SCHEMA
schema = schema_cls()
dates = []
if obj['metadata']['access_right'] == 'embargoed' and \
obj['metadata'].get('embargo_date'):
dates.append(schema.dump(dict(
date=obj['metadata']['embargo_date'],
type='Available')).data)
dates.append(schema.dump(dict(
date=obj['metadata']['publication_date'],
type='Accepted')).data)
else:
dates.append(schema.dump(dict(
date=obj['metadata']['publication_date'],
type='Issued')).data)
for interval in obj['metadata'].get('dates', []):
date_type = interval.get('type')
if date_type in schema.VALID_DATE_TYPES:
start = interval.get('start') or ''
end = interval.get('end') or ''
if start != '' and end != '' and start == end:
dates.append(schema.dump(dict(
date=start,
type=date_type,
info=interval.get('description', missing))).data)
else:
dates.append(schema.dump(dict(
date=start + '/' + end,
type=date_type,
info=interval.get('description', missing))).data)
return dates
class DataCiteSchemaV1(DataCiteSchema):
"""Schema for records v1 in JSON."""
creators = fields.List(
fields.Nested(CreatorSchema),
attribute='metadata.creators')
contributors = fields.Method('get_contributors')
def get_contributors(self, obj):
"""Get contributors."""
def inject_type(c):
c['type'] = 'Supervisor'
return c
# Contributors and supervisors
s = ContributorSchema()
contributors = obj['metadata'].get('contributors', [])
contributors.extend([
inject_type(c) for c in
obj['metadata'].get('thesis_supervisors', [])
])
items = []
for c in contributors:
items.append(s.dump(c).data)
# Grants
s = ContributorSchema()
for g in obj['metadata'].get('grants', []):
funder = g.get('funder', {}).get('name')
eurepo = g.get('identifiers', {}).get('eurepo')
if funder and eurepo:
items.append({
'contributorName': funder,
'contributorType': 'Funder',
'nameIdentifier': {
'nameIdentifier': eurepo,
'nameIdentifierScheme': 'info',
},
})
return items
def get_locations(self, obj):
"""Get locations."""
locations = []
for l in obj['metadata'].get('locations', []):
location = {'geoLocationPlace': l['place']}
if l.get('lat') and l.get('lon'):
location['geoLocationPoint'] = '{} {}'\
.format(l['lat'], l['lon'])
locations.append(location)
return locations or missing
def get_related_identifiers(self, obj):
"""Related identifiers."""
items = super(DataCiteSchemaV1, self).get_related_identifiers(obj)
for item in items:
if item['relationType'] and item['relationType'] == 'IsVersionOf':
item['relationType'] = 'IsPartOf'
if item['relationType'] and item['relationType'] == 'HasVersion':
item['relationType'] = 'HasPart'
return items
class PersonSchemav4(Schema):
"""Creator/contributor common schema for v4."""
affiliations = fields.List(
fields.Str(),
attribute='affiliation')
nameIdentifiers = fields.Method('get_nameidentifiers')
familyName = fields.Method('get_familyname')
givenName = fields.Method('get_givennames')
def get_familyname(self, obj):
"""Get family name."""
name = obj.get('name')
if name:
names = name.split(',')
if len(names) == 2:
return names.pop(0).strip()
return ''
def get_givennames(self, obj):
"""Get given name."""
name = obj.get('name')
if name:
names = name.split(',')
if len(names) == 2:
return names.pop(1).strip()
return ''
def get_nameidentifiers(self, obj):
"""Get name identifier."""
name_identifiers = []
if obj.get('orcid'):
name_identifiers.append({
"nameIdentifier": obj.get('orcid'),
"nameIdentifierScheme": "ORCID",
"schemeURI": "http://orcid.org/"
})
if obj.get('gnd'):
name_identifiers.append({
"nameIdentifier": obj.get('gnd'),
"nameIdentifierScheme": "GND",
})
return name_identifiers
class CreatorSchemav4(PersonSchemav4):
"""Creator schema for v4."""
creatorName = fields.Str(attribute='name')
class ContributorSchemav4(PersonSchemav4):
"""Contributor schema for v4."""
contributorName = fields.Str(attribute='name')
contributorType = fields.Str(attribute='type')
class DateSchemaV4(DateSchema):
"""Date schema for v4."""
VALID_DATE_TYPES = {
'Accepted',
'Available',
'Copyrighted',
'Collected',
'Created',
'Issued',
'Submitted',
'Updated',
'Valid',
'Withdrawn',
'Other',
}
dateInformation = fields.Str(attribute='info')
class DataCiteSchemaV4(DataCiteSchema):
"""Schema for records v4 in JSON."""
DATE_SCHEMA = DateSchemaV4
creators = fields.List(
fields.Nested(CreatorSchemav4),
attribute='metadata.creators')
contributors = fields.Method('get_contributors')
fundingReferences = fields.Method('get_fundingreferences')
def get_contributors(self, obj):
"""Get contributors."""
def inject_type(c):
c['type'] = 'Supervisor'
return c
# Contributors and supervisors
s = ContributorSchemav4()
contributors = obj['metadata'].get('contributors', [])
contributors.extend([
inject_type(c) for c in
obj['metadata'].get('thesis', {}).get('supervisors', [])
])
items = []
for c in contributors:
items.append(s.dump(c).data)
return items
def get_fundingreferences(self, obj):
"""Get funding references."""
items = []
for g in obj['metadata'].get('grants', []):
funder_name = g.get('funder', {}).get('name')
funder_identifier = g.get('funder', {}).get('doi')
award_program = g.get('program')
if award_program:
funder_program_matches = current_app.config.get(
'ZENODO_RECORDS_FUNDER_PROGRAM_MATCHES', {})
for funder_id, regexes in funder_program_matches.items():
if any(re.match(r, award_program) for r in regexes):
funder_identifier = funder_id
award_number = g.get('code')
award_title = g.get('title')
eurepo = g.get('identifiers', {}).get('eurepo')
if funder_name and eurepo:
items.append({
'funderName': funder_name,
'funderIdentifier': {
'funderIdentifier': funder_identifier,
'funderIdentifierType': 'Crossref Funder ID',
},
'awardNumber': {
'awardNumber': award_number,
'awardURI': eurepo
},
'awardTitle': award_title
})
return items
def get_locations(self, obj):
"""Get locations."""
locations = []
for l in obj['metadata'].get('locations', []):
location = {'geoLocationPlace': l['place']}
if l.get('lat') and l.get('lon'):
location['geoLocationPoint'] = {
'pointLongitude': l['lon'],
'pointLatitude': l['lat']
}
locations.append(location)
return locations or missing
| 18,409 | Python | .py | 478 | 28.069038 | 78 | 0.556883 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,590 | __init__.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Record serialization."""
from __future__ import absolute_import, print_function
| 1,052 | Python | .py | 25 | 41 | 76 | 0.772683 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,591 | geojson.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/geojson.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo schema.org marshmallow schema."""
from __future__ import absolute_import, print_function, unicode_literals
from marshmallow import Schema, fields, missing
class Feature(Schema):
"""Schema for Feature."""
type_ = fields.Constant('Feature', dump_to='type')
geometry = fields.Method('get_locations')
properties = fields.Method('get_name')
def get_locations(self, obj):
"""Get locations of the record."""
if obj.get('lat') and obj.get('lon'):
return {
"type": "Point",
"coordinates": [obj['lon'], obj['lat']]
}
else:
return missing
def get_name(self, obj):
"""Get name of the record."""
return {"name": obj['place']}
class FeatureCollection(Schema):
"""Schema for FeatureCollection."""
features = fields.Method('get_locations')
type_ = fields.Constant('FeatureCollection', dump_to='type')
def get_locations(self, obj):
"""Get locations."""
s = Feature()
items = []
for l in obj['metadata'].get('locations', []):
if l.get('lat') and l.get('lon'):
items.append(s.dump({
'lat': l['lat'], 'lon': l['lon'], 'place': l['place']
}).data)
return items
| 2,283 | Python | .py | 57 | 34.385965 | 76 | 0.654611 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,592 | schemaorg.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/schemaorg.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo schema.org marshmallow schema."""
from __future__ import absolute_import, print_function, unicode_literals
import idutils
import pycountry
from flask import current_app, request
from invenio_iiif.previewer import previewable_extensions as thumbnail_exts
from invenio_iiif.utils import ui_iiif_image_url
from marshmallow import Schema, fields, missing, pre_dump
from ...models import ObjectType
from ..fields import DateString, SanitizedHTML, SanitizedUnicode
from .common import api_link_for, ui_link_for
def _serialize_identifiers(ids, relations=None):
"""Serialize related and alternate identifiers to URLs.
:param ids: List of related_identifier or alternate_identifier objects.
:param relations: if not None, will only select IDs of specific relation
:returns: List of identifiers in schema.org format.
:rtype dict:
"""
relations = relations or []
ids = [{'@type': ObjectType.get_by_dict(i['resource_type'])['schema.org'][19:] if 'resource_type' in i else 'CreativeWork',
'@id': idutils.to_url(i['identifier'], i['scheme'], 'https')}
for i in ids if (not relations or i['relation'] in relations) and 'scheme' in i]
return [id_ for id_ in ids if id_['@id']]
def _serialize_subjects(ids):
"""Serialize subjects to URLs."""
return [{'@type': 'CreativeWork',
'@id': idutils.to_url(i['identifier'], i['scheme'], 'https')}
for i in ids if 'scheme' in i]
def format_files_rest_link(bucket, key, scheme='https'):
"""Format Files REST URL."""
return current_app.config['FILES_REST_ENDPOINT'].format(
scheme=scheme, host=request.host, bucket=bucket, key=key)
class Person(Schema):
"""Person schema (schema.org/Person)."""
id_ = fields.Method('get_id', dump_to='@id')
type_ = fields.Constant('Person', dump_to='@type')
name = SanitizedUnicode()
affiliation = SanitizedUnicode()
def get_id(self, obj):
"""Get URL for the person's ORCID or GND."""
orcid = obj.get('orcid')
gnd = obj.get('gnd')
if orcid:
return idutils.to_url(orcid, 'orcid', 'https')
if gnd:
return idutils.to_url(gnd, 'gnd', 'https')
return missing
class Language(Schema):
"""Language schema (schema.org/Language)."""
type_ = fields.Constant('Language', dump_to="@type")
name = fields.Method('get_name')
alternateName = fields.Method('get_alternate_name')
def get_name(self, obj):
"""Get the language human-readable name."""
lang = pycountry.languages.get(alpha_3=obj)
if lang:
return lang.name
def get_alternate_name(self, obj):
"""Get the language code."""
return obj
class Place(Schema):
"""Marshmallow schema for schema.org/Place."""
type_ = fields.Constant('Place', dump_to='@type')
geo = fields.Method('get_geo')
name = SanitizedUnicode(attribute='place')
def get_geo(self, obj):
"""Generate geo field."""
if obj.get('lat') and obj.get('lon'):
return {
'@type': 'GeoCoordinates',
'latitude': obj['lat'],
'longitude': obj['lon']
}
else:
return missing
class MeetingEvent(Schema):
"""Schema for Meeting event."""
type_ = fields.Constant('Event', dump_to='@type')
name = fields.Str(attribute='title')
alternateName = fields.Str(attribute='acronym')
location = fields.Str(attribute='place')
url = fields.Str()
class CreativeWork(Schema):
"""Schema for schema.org/CreativeWork type."""
CONTEXT = "https://schema.org/"
identifier = fields.Method('get_doi', dump_to='identifier')
id_ = fields.Method('get_doi', dump_to='@id')
# NOTE: use `__class__`?
type_ = fields.Method('get_type', dump_to='@type')
url = fields.Method('get_url')
name = SanitizedUnicode(attribute='metadata.title')
description = SanitizedHTML(attribute='metadata.description')
context = fields.Method('get_context', dump_to='@context')
keywords = fields.List(SanitizedUnicode(), attribute='metadata.keywords')
spatial = fields.Nested(Place, many=True, attribute='metadata.locations')
# TODO: What date?
# dateCreated
# dateModified
datePublished = DateString(attribute='metadata.publication_date')
temporal = fields.Method('get_dates')
# NOTE: could also be "author"
creator = fields.Nested(Person, many=True, attribute='metadata.creators')
version = SanitizedUnicode(attribute='metadata.version')
inLanguage = fields.Nested(Language, attribute='metadata.language')
license = SanitizedUnicode(attribute='metadata.license.url')
citation = fields.Method('get_citation')
isPartOf = fields.Method('get_is_part_of')
hasPart = fields.Method('get_has_part')
sameAs = fields.Method('get_sameAs')
# NOTE: reverse of subjectOf
about = fields.Method('get_subjects')
contributor = fields.Nested(
Person, many=True, attribute='metadata.contributors')
workFeatured = fields.Nested(MeetingEvent, attribute='metadata.meeting')
# NOTE: editor from "contributors"?
# editor
# NOTE: Zenodo or similar?
# provider
# publisher
# NOTE: "grants" or aggregation of "funders"? Could go in "sponsor" as well
# Relevant codemeta issue: https://github.com/codemeta/codemeta/issues/160
# funder
# NOTE: Zenodo communities?
# sourceOrganization
def get_dates(self, obj):
"""Get dates of the record."""
dates = []
for interval in obj['metadata'].get('dates', []):
start = interval.get('start') or '..'
end = interval.get('end') or '..'
if start != '..' and end != '..' and start == end:
dates.append(start)
else:
dates.append(start + '/' + end)
return dates or missing
def get_context(self, obj):
"""Returns the value for '@context' value."""
return self.CONTEXT
def get_doi(self, obj):
"""Get DOI of the record."""
data = obj['metadata']
return idutils.to_url(data['doi'], 'doi', 'https') \
if data.get('doi') \
else missing
def get_type(self, obj):
"""Get schema.org type of the record."""
data = obj['metadata']
obj_type = ObjectType.get_by_dict(data['resource_type'])
return (obj_type['schema.org'][len(self.CONTEXT):]
if obj_type else missing)
def get_url(self, obj):
"""Get Zenodo URL of the record."""
recid = obj.get('metadata', {}).get('recid')
return ui_link_for('record_html', id=recid) if recid else missing
def get_citation(self, obj):
"""Get citations of the record."""
relids = obj.get('metadata', {}).get('related_identifiers', [])
ids = _serialize_identifiers(relids, {'cites', 'references'})
return ids or missing
def get_is_part_of(self, obj):
"""Get records that this record is part of."""
relids = obj.get('metadata', {}).get('related_identifiers', [])
ids = _serialize_identifiers(relids, {'isPartOf'})
return ids or missing
def get_has_part(self, obj):
"""Get parts of the record."""
relids = obj.get('metadata', {}).get('related_identifiers', [])
ids = _serialize_identifiers(relids, {'hasPart'})
return ids or missing
def get_sameAs(self, obj):
"""Get identical identifiers of the record."""
relids = obj.get('metadata', {}).get('related_identifiers', [])
ids = [i['@id']
for i in _serialize_identifiers(relids, {'isIdenticalTo'})]
relids = obj.get('metadata', {}).get('alternate_identifiers', [])
ids += [i['@id'] for i in _serialize_identifiers(relids)]
return ids or missing
def get_subjects(self, obj):
"""Get subjects of the record."""
subjects = obj.get('metadata', {}).get('subjects', [])
return _serialize_subjects(subjects) or missing
class Distribution(Schema):
"""Marshmallow schema for schema.org/Distribution."""
type_ = fields.Constant('DataDownload', dump_to='@type')
encodingFormat = SanitizedUnicode(attribute='type')
contentUrl = fields.Method('get_content_url')
def get_content_url(self, obj):
"""Get URL of the file."""
return format_files_rest_link(bucket=obj['bucket'], key=obj['key'])
class Dataset(CreativeWork):
"""Marshmallow schema for schema.org/Dataset."""
distribution = fields.Nested(
Distribution, many=True, attribute='metadata._files')
measurementTechnique = SanitizedUnicode(attribute='metadata.method')
@pre_dump
def hide_closed_files(self, obj):
"""Hide the _files if the record is not Open Access."""
m = obj['metadata']
if m['access_right'] != 'open' and '_files' in m:
del obj['metadata']['_files']
class ScholarlyArticle(CreativeWork):
"""Marshmallow schema for schema.org/ScholarlyArticle."""
# TODO: Investigate if this should be the same as title
headline = SanitizedUnicode(attribute='metadata.title')
image = fields.Constant(
'https://zenodo.org/static/img/logos/zenodo-gradient-round.svg')
class ImageObject(CreativeWork):
"""Marshmallow schema for schema.org/ImageObject."""
# The first image file of the record
contentUrl = fields.Method('get_content_url')
# The thumb250 URL of the record
thumbnailUrl = fields.Method('get_thumbnail_url')
def get_content_url(self, obj):
"""Dump contentUrl."""
files = obj.get('metadata', {}).get('_files', [])
for f in files:
if f.get('type') in thumbnail_exts:
return api_link_for('object', **f)
return missing
def get_thumbnail_url(self, obj):
"""Dump thumbnailUrl."""
files = obj.get('metadata', {}).get('_files', [])
for f in files:
if f.get('type') in thumbnail_exts:
return ui_link_for(
'thumbnail',
path=ui_iiif_image_url(
f,
size='{},'.format(250),
image_format='png' if f['type'] == 'png' else 'jpg',
)
)
return missing
class Collection(CreativeWork):
"""Marshmallow schema for schema.org/Collection."""
pass
class Book(CreativeWork):
"""Marshmallow schema for schema.org/Book."""
pass
class PresentationDigitalDocument(CreativeWork):
"""Marshmallow schema for schema.org/PresentationDigitalDocument."""
pass
class MediaObject(CreativeWork):
"""Marshmallow schema for schema.org/MediaObject."""
pass
class SoftwareSourceCode(CreativeWork):
"""Marshmallow schema for schema.org/SoftwareSourceCode."""
# TODO: Include GitHub url if it's there...
# related_identifiers.
codeRepository = fields.Method('get_code_repository_url')
def get_code_repository_url(self, obj):
"""Get URL of the record's code repository."""
relids = obj.get('metadata', {}).get('related_identifiers', [])
def is_github_url(id):
return (id['relation'] == 'isSupplementTo' and
id['scheme'] == 'url' and
id['identifier'].startswith('https://github.com'))
# TODO: Strip 'tree/v1.0'?
return next(
(i['identifier'] for i in relids if is_github_url(i)), missing)
class Photograph(CreativeWork):
"""Marshmallow schema for schema.org/Photograph."""
pass
| 12,659 | Python | .py | 286 | 37.13986 | 127 | 0.644108 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,593 | csl.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/csl.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo CSL-JSON schema."""
from __future__ import absolute_import, print_function
import re
from invenio_formatter.filters.datetime import from_isodate
from marshmallow import Schema, fields, missing
from zenodo.modules.records.models import ObjectType
class AuthorSchema(Schema):
"""Schema for an author."""
family = fields.Method('get_family_name')
given = fields.Method('get_given_names')
def get_family_name(self, obj):
"""Get family name."""
if {'familyname', 'givennames'} <= set(obj):
return obj.get('familyname')
else:
return obj['name']
def get_given_names(self, obj):
"""Get given names."""
if {'familyname', 'givennames'} <= set(obj):
return obj.get('givennames')
return missing
class RecordSchemaCSLJSON(Schema):
"""Schema for records in CSL-JSON."""
id = fields.Str(attribute='pid.pid_value')
type = fields.Method('get_type')
title = fields.Str(attribute='metadata.title')
abstract = fields.Str(attribute='metadata.description')
author = fields.List(fields.Nested(AuthorSchema),
attribute='metadata.creators')
issued = fields.Method('get_issue_date')
language = fields.Str(attribute='metadata.language')
version = fields.Str(attribute='metadata.version')
note = fields.Str(attribute='metadata.notes')
DOI = fields.Str(attribute='metadata.doi')
ISBN = fields.Str(attribute='metadata.imprint.isbn')
ISSN = fields.Method('get_issn')
container_title = fields.Method('get_container_title')
page = fields.Method('get_pages')
volume = fields.Str(attribute='metadata.journal.volume')
issue = fields.Str(attribute='metadata.journal.issue')
publisher = fields.Method('get_publisher')
publisher_place = fields.Str(attribute='metadata.imprint.place')
event = fields.Method('get_event')
event_place = fields.Str(
attribute='metadata.meeting.place', dump_to='event-place')
# TODO: check if possible to dump in EDTF format
# event_date = fields.Str(
# attribute='metadata.meeting.dates', dump_to='event-date')
def get_event(self, obj):
"""Get event/meeting title and acronym."""
m = obj['metadata']
meeting = m.get('meeting', {})
if meeting:
title = meeting.get('title')
acronym = meeting.get('acronym')
if title and acronym:
return u'{} ({})'.format(title, acronym)
elif title or acronym:
return title or acronym
return missing
def get_journal_or_part_of(self, obj, key):
"""Get journal or part of."""
m = obj['metadata']
journal = m.get('journal', {}).get(key)
part_of = m.get('part_of', {}).get(key)
return journal or part_of or missing
def get_container_title(self, obj):
"""Get container title."""
return self.get_journal_or_part_of(obj, 'title')
def get_pages(self, obj):
"""Get pages."""
# Remove multiple dashes between page numbers (eg. 12--15)
pages = self.get_journal_or_part_of(obj, 'pages')
pages = re.sub('-+', '-', pages) if pages else pages
return pages
def get_publisher(self, obj):
"""Get publisher."""
m = obj['metadata']
publisher = m.get('imprint', {}).get('publisher')
if publisher:
return publisher
if m.get('doi', '').startswith('10.5281/'):
return 'Zenodo'
return missing
def get_type(self, obj):
"""Get record CSL type."""
metadata = obj['metadata']
obj_type = ObjectType.get_by_dict(metadata.get('resource_type'))
return obj_type.get('csl', 'article') if obj_type else 'article'
def get_issn(self, obj):
"""Get the record's ISSN."""
for id in obj['metadata'].get('alternate_identifiers', []):
if id['scheme'] == 'issn':
return id['identifier']
return missing
def get_issue_date(self, obj):
"""Get a date in list format."""
d = from_isodate(obj['metadata'].get('publication_date'))
return {'date-parts': [[d.year, d.month, d.day]]} if d else missing
| 5,237 | Python | .py | 122 | 36.278689 | 76 | 0.649302 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,594 | common.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/common.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016, 2017 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Definition of fields which are common between JSON and Legacy JSON."""
from __future__ import absolute_import, print_function, unicode_literals
import arrow
import idutils
import jsonref
import pycountry
from flask import current_app, has_request_context
from flask_babelex import lazy_gettext as _
from invenio_iiif.previewer import previewable_extensions as thumbnail_exts
from invenio_iiif.utils import ui_iiif_image_url
from invenio_pidrelations.serializers.utils import serialize_relations
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier
from invenio_records.api import Record
from marshmallow import Schema, ValidationError, fields, missing, post_dump, \
post_load, pre_dump, pre_load, validate, validates, validates_schema
from marshmallow.fields import DateTime
from six import string_types
from six.moves.urllib.parse import quote
from werkzeug.routing import BuildError
from zenodo.modules.records import current_custom_metadata
from zenodo.modules.records.config import ZENODO_RELATION_TYPES
from zenodo.modules.records.models import AccessRight, ObjectType
from ...utils import is_deposit, is_record
from ..fields import DOI as DOIField
from ..fields import DateString, PersistentId, SanitizedHTML, SanitizedUnicode
def clean_empty(data, keys):
"""Clean empty values."""
for k in keys:
if k in data and not data[k]:
del data[k]
return data
URLS = {
'badge': '{base}/badge/doi/{doi}.svg',
'bucket': '{base}/files/{bucket}',
'funder': '{base}/funders/{id}',
'grant': '{base}/grants/{id}',
'object': '{base}/files/{bucket}/{key}',
'deposit_html': '{base}/deposit/{id}',
'deposit_file': '{base}/deposit/depositions/{id}/files/{file_id}',
'deposit': '{base}/deposit/depositions/{id}',
'record_html': '{base}/record/{id}',
'record_file': '{base}/record/{id}/files/{filename}',
'record': '{base}/records/{id}',
'thumbnail': '{base}{path}',
'thumbs': '{base}/record/{id}/thumb{size}',
'community': '{base}/communities/{id}',
}
def link_for(base, tpl, **kwargs):
"""Create a link using specific template."""
tpl = URLS.get(tpl)
for k in ['key', ]:
if k in kwargs:
kwargs[k] = quote(kwargs[k].encode('utf8'))
return tpl.format(base=base, **kwargs)
def api_link_for(tpl, **kwargs):
"""Create an API link using specific template."""
is_api_app = 'invenio-deposit-rest' in current_app.extensions
base = '{}/api'
if current_app.testing and is_api_app:
base = '{}'
return link_for(
base.format(current_app.config['THEME_SITEURL']), tpl, **kwargs)
def ui_link_for(tpl, **kwargs):
"""Create an UI link using specific template."""
return link_for(current_app.config['THEME_SITEURL'], tpl, **kwargs)
class StrictKeysMixin(object):
"""Ensure only defined keys exists in data."""
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
if not isinstance(original_data, list):
items = [original_data]
else:
items = original_data
for original_data in items:
for key in original_data:
if key not in self.fields:
raise ValidationError(
'Unknown field name.'.format(key),
field_names=[key],
)
class RefResolverMixin(object):
"""Mixin for helping to validate if a JSONRef resolves."""
def validate_jsonref(self, value):
"""Validate that a JSONRef resolves.
Test is skipped if not explicitly requested and you are in an
application context.
"""
if not self.context.get('replace_refs') or not current_app:
return True
if not(isinstance(value, dict) and '$ref' in value):
return True
try:
Record(value).replace_refs().dumps()
return True
except jsonref.JsonRefError:
return False
class PersonSchemaV1(Schema, StrictKeysMixin):
"""Schema for a person."""
name = SanitizedUnicode(required=True)
affiliation = SanitizedUnicode()
gnd = PersistentId(scheme='GND')
orcid = PersistentId(scheme='ORCID')
@post_dump(pass_many=False)
@post_load(pass_many=False)
def clean(self, data):
"""Clean empty values."""
return clean_empty(data, ['orcid', 'gnd', 'affiliation'])
@post_load(pass_many=False)
def remove_gnd_prefix(self, data):
"""Remove GND prefix (which idutils normalization adds)."""
gnd = data.get('gnd')
if gnd and gnd.startswith('gnd:'):
data['gnd'] = gnd[len('gnd:'):]
@validates_schema
def validate_data(self, data):
"""Validate schema."""
name = data.get('name')
if not name:
raise ValidationError(
_('Name is required.'),
field_names=['name']
)
class ContributorSchemaV1(PersonSchemaV1):
"""Schema for a contributor."""
type = fields.Str(required=True)
@validates('type')
def validate_type(self, value):
"""Validate the type."""
if value not in \
current_app.config['DEPOSIT_CONTRIBUTOR_DATACITE2MARC']:
raise ValidationError(
_('Invalid contributor type.'),
field_names=['type']
)
class IdentifierSchemaV1(Schema, StrictKeysMixin):
"""Schema for a identifiers.
During deserialization the schema takes care of detecting the identifier
scheme if not specified, as well as validating and normalizing the
persistent identifier value.
"""
identifier = PersistentId(required=True)
scheme = fields.Str()
@pre_load()
def detect_scheme(self, data):
"""Load scheme."""
id_ = data.get('identifier')
scheme = data.get('scheme')
if not scheme and id_:
scheme = idutils.detect_identifier_schemes(id_)
if scheme:
data['scheme'] = scheme[0]
return data
@post_load()
def normalize_identifier(self, data):
"""Normalize identifier."""
data['identifier'] = idutils.normalize_pid(
data['identifier'], data['scheme'])
@validates_schema
def validate_data(self, data):
"""Validate identifier and scheme."""
id_ = data.get('identifier')
scheme = data.get('scheme')
if not id_:
raise ValidationError(
'Identifier is required.',
field_names=['identifier']
)
schemes = idutils.detect_identifier_schemes(id_)
if not schemes:
raise ValidationError(
'Not a valid persistent identifier.',
field_names=['identifier']
)
if scheme not in schemes:
raise ValidationError(
'Not a valid {0} identifier.'.format(scheme),
field_names=['identifier']
)
class ResourceTypeMixin(object):
"""Schema for resource type."""
resource_type = fields.Method('dump_resource_type', 'load_resource_type')
def load_resource_type(self, data):
"""Split the resource type and into separate keys."""
if not isinstance(data, string_types):
raise ValidationError(
'Not a string.', field_names=['resource_type'])
if not ObjectType.validate_internal_id(data):
raise ValidationError(
'Not a valid type.', field_names=['resource_type'])
serialized_object = {}
split_data = data.split('-')
if len(split_data) == 2:
serialized_object['type'], serialized_object['subtype'] = \
split_data
else:
serialized_object['type'] = split_data[0]
return serialized_object
def dump_resource_type(self, data):
"""Dump resource type metadata."""
resource_type = data.get('resource_type')
if resource_type:
if resource_type.get('subtype'):
return resource_type['type'] + '-' + resource_type['subtype']
else:
return resource_type['type']
else:
return missing
class AlternateIdentifierSchemaV1(IdentifierSchemaV1, ResourceTypeMixin):
"""Schema for an alternate identifier."""
class RelatedIdentifierSchemaV1(IdentifierSchemaV1, ResourceTypeMixin):
"""Schema for a related identifier."""
relation = fields.Str(
required=True,
validate=validate.OneOf(
choices=[x[0] for x in ZENODO_RELATION_TYPES],
)
)
class SubjectSchemaV1(IdentifierSchemaV1):
"""Schema for a subject."""
term = SanitizedUnicode()
class DateSchemaV1(Schema):
"""Schema for date intervals."""
start = DateString()
end = DateString()
type = fields.Str(required=True)
description = fields.Str()
class LocationSchemaV1(Schema):
"""Schema for geographical locations."""
lat = fields.Float()
lon = fields.Float()
place = SanitizedUnicode(required=True)
description = SanitizedUnicode()
@validates('lat')
def validate_latitude(self, value):
"""Validate that location exists."""
if not (-90 <= value <= 90):
raise ValidationError(
_('Latitude must be between -90 and 90.')
)
@validates('lon')
def validate_longitude(self, value):
"""Validate that location exists."""
if not (-180 <= value <= 180):
raise ValidationError(
_('Longitude must be between -180 and 180.')
)
class CommonMetadataSchemaV1(Schema, StrictKeysMixin, RefResolverMixin):
"""Common metadata schema."""
doi = DOIField(missing='')
publication_date = DateString(required=True)
title = SanitizedUnicode(required=True, validate=validate.Length(min=3))
creators = fields.Nested(
PersonSchemaV1, many=True, validate=validate.Length(min=1))
dates = fields.List(
fields.Nested(DateSchemaV1), validate=validate.Length(min=1))
description = SanitizedHTML(
required=True, validate=validate.Length(min=3))
keywords = fields.List(SanitizedUnicode())
locations = fields.List(
fields.Nested(LocationSchemaV1), validate=validate.Length(min=1))
notes = SanitizedHTML()
version = SanitizedUnicode()
language = SanitizedUnicode()
access_right = fields.Str(validate=validate.OneOf(
choices=[
AccessRight.OPEN,
AccessRight.EMBARGOED,
AccessRight.RESTRICTED,
AccessRight.CLOSED,
],
))
embargo_date = DateString()
access_conditions = SanitizedHTML()
subjects = fields.Nested(SubjectSchemaV1, many=True)
contributors = fields.List(fields.Nested(ContributorSchemaV1))
references = fields.List(SanitizedUnicode(attribute='raw_reference'))
related_identifiers = fields.Nested(
RelatedIdentifierSchemaV1, many=True)
alternate_identifiers = fields.Nested(
AlternateIdentifierSchemaV1, many=True)
method = SanitizedUnicode()
@validates('locations')
def validate_locations(self, value):
"""Validate that there should be both latitude and longitude."""
for location in value:
if (location.get('lon') and not location.get('lat')) or \
(location.get('lat') and not location.get('lon')):
raise ValidationError(
_('There should be both latitude and longitude.'),
field_names=['locations'])
@validates('language')
def validate_language(self, value):
"""Validate that language is ISO 639-3 value."""
if not pycountry.languages.get(alpha_3=value):
raise ValidationError(
_('Language must be a lower-cased 3-letter ISO 639-3 string.'),
field_name=['language']
)
@validates('dates')
def validate_dates(self, value):
"""Validate that start date is before the corresponding end date."""
for interval in value:
start = arrow.get(interval.get('start'), 'YYYY-MM-DD').date() \
if interval.get('start') else None
end = arrow.get(interval.get('end'), 'YYYY-MM-DD').date() \
if interval.get('end') else None
if not start and not end:
raise ValidationError(
_('There must be at least one date.'),
field_names=['dates']
)
if start and end and start > end:
raise ValidationError(
_('"start" date must be before "end" date.'),
field_names=['dates']
)
@validates('embargo_date')
def validate_embargo_date(self, value):
"""Validate that embargo date is in the future."""
if arrow.get(value).date() <= arrow.utcnow().date():
raise ValidationError(
_('Embargo date must be in the future.'),
field_names=['embargo_date']
)
@validates('license')
def validate_license_ref(self, value):
"""Validate if license resolves."""
if not self.validate_jsonref(value):
raise ValidationError(
_('Invalid choice.'),
field_names=['license'],
)
@validates('grants')
def validate_grants_ref(self, values):
"""Validate if license resolves."""
for v in values:
if not self.validate_jsonref(v):
raise ValidationError(
_('Invalid grant.'),
field_names=['grants'],
)
@validates('doi')
def validate_doi(self, value):
"""Validate if doi exists."""
if value and has_request_context():
required_doi = self.context.get('required_doi')
if value == required_doi:
return
err = ValidationError(_('DOI already exists in Zenodo.'),
field_names=['doi'])
try:
doi_pid = PersistentIdentifier.get('doi', value)
except PIDDoesNotExistError:
return
# If the DOI exists, check if it's been assigned to this record
# by fetching the recid and comparing both PIDs record UUID
try:
# If the deposit has not been created yet, raise
if not self.context.get('recid'):
raise err
recid_pid = PersistentIdentifier.get(
'recid', self.context['recid'])
except PIDDoesNotExistError:
# There's no way to verify if this DOI belongs to this record
raise err
doi_uuid = doi_pid.get_assigned_object()
recid_uuid = recid_pid.get_assigned_object()
if doi_uuid and doi_uuid == recid_uuid:
return
else: # DOI exists and belongs to a different record
raise err
@validates_schema()
def validate_license(self, data):
"""Validate license."""
acc = data.get('access_right')
if acc in [AccessRight.OPEN, AccessRight.EMBARGOED] and \
'license' not in data:
raise ValidationError(
_('Required when access right is open or embargoed.'),
field_names=['license']
)
if acc == AccessRight.EMBARGOED and 'embargo_date' not in data:
raise ValidationError(
_('Required when access right is embargoed.'),
field_names=['embargo_date']
)
if acc == AccessRight.RESTRICTED and 'access_conditions' not in data:
raise ValidationError(
_('Required when access right is restricted.'),
field_names=['access_conditions']
)
custom = fields.Method('dump_custom', 'load_custom')
def load_custom(self, obj):
"""Validate the custom metadata according to config."""
if not obj:
return missing
if not isinstance(obj, dict):
raise ValidationError('Not an object.', field_names=['custom'])
valid_vocabulary = current_custom_metadata.available_vocabulary_set
term_types = current_custom_metadata.term_types
valid_terms = current_custom_metadata.terms
for term, values in obj.items():
if term not in valid_vocabulary:
raise ValidationError(
u'Zenodo does not support "{0}" as a custom metadata term.'
.format(term),
field_names=['custom'])
# Validate term type
term_type = term_types[valid_terms[term]['type']]
if not isinstance(values, list):
raise ValidationError(
u'Term "{0}" should be of type array.'
.format(term),
field_names=['custom'])
if len(values) == 0:
raise ValidationError(
u'No values were provided for term "{0}".'
.format(term),
field_names=['custom'])
for value in values:
if not isinstance(value, term_type):
raise ValidationError(
u'Invalid type for term "{0}", should be "{1}".'
.format(term, valid_terms[term]['type']),
field_names=['custom'])
return obj
def dump_custom(self, data):
"""Dump custom metadata."""
return data.get('custom', missing)
@pre_load()
def preload_accessrights(self, data):
"""Remove invalid access rights combinations."""
# Default value
if 'access_right' not in data:
data['access_right'] = AccessRight.OPEN
# Pop values which should not be set for a given access right.
if data.get('access_right') not in [
AccessRight.OPEN, AccessRight.EMBARGOED]:
data.pop('license', None)
if data.get('access_right') != AccessRight.RESTRICTED:
data.pop('access_conditions', None)
if data.get('access_right') != AccessRight.EMBARGOED:
data.pop('embargo_date', None)
@pre_load()
def preload_publicationdate(self, data):
"""Default publication date."""
if 'publication_date' not in data:
data['publication_date'] = arrow.utcnow().date().isoformat()
@post_load()
def postload_keywords_filter(self, data):
"""Filter empty keywords."""
if 'keywords' in data:
data['keywords'] = [
kw for kw in data['keywords'] if kw.strip()
]
@post_load()
def postload_references(self, data):
"""Filter empty references and wrap them."""
if 'references' in data:
data['references'] = [
{'raw_reference': ref}
for ref in data['references'] if ref.strip()
]
class CommonRecordSchemaV1(Schema, StrictKeysMixin):
"""Common record schema."""
id = fields.Integer(attribute='pid.pid_value', dump_only=True)
conceptrecid = SanitizedUnicode(
attribute='metadata.conceptrecid', dump_only=True)
doi = SanitizedUnicode(attribute='metadata.doi', dump_only=True)
conceptdoi = SanitizedUnicode(
attribute='metadata.conceptdoi', dump_only=True)
links = fields.Method('dump_links', dump_only=True)
created = fields.Str(dump_only=True)
@pre_dump()
def predump_relations(self, obj):
"""Add relations to the schema context."""
m = obj.get('metadata', {})
if 'relations' not in m:
pid = self.context['pid']
# For deposits serialize the record's relations
if is_deposit(m):
pid = PersistentIdentifier.get('recid', m['recid'])
m['relations'] = serialize_relations(pid)
# Remove some non-public fields
if is_record(m):
version_info = m['relations'].get('version', [])
if version_info:
version_info[0].pop('draft_child_deposit', None)
def dump_links(self, obj):
"""Dump links."""
links = obj.get('links', {})
if current_app:
links.update(self._dump_common_links(obj))
try:
m = obj.get('metadata', {})
if is_deposit(m):
links.update(self._dump_deposit_links(obj))
else:
links.update(self._dump_record_links(obj))
except BuildError:
pass
return links
def _thumbnail_url(self, fileobj, thumbnail_size):
"""Create the thumbnail URL for an image."""
return link_for(
current_app.config.get('THEME_SITEURL'),
'thumbnail',
path=ui_iiif_image_url(
fileobj,
size='{},'.format(thumbnail_size),
image_format='png' if fileobj['type'] == 'png' else 'jpg',
)
)
def _thumbnail_urls(self, recid):
"""Create the thumbnail URL for an image."""
thumbnail_urls = {}
cached_sizes = current_app.config.get('CACHED_THUMBNAILS')
for size in cached_sizes:
thumbnail_urls[size] = link_for(
current_app.config.get('THEME_SITEURL'),
'thumbs',
id=recid,
size=size
)
return thumbnail_urls
def _dump_common_links(self, obj):
"""Dump common links for deposits and records."""
links = {}
m = obj.get('metadata', {})
doi = m.get('doi')
if doi:
links['badge'] = ui_link_for('badge', doi=quote(doi))
links['doi'] = idutils.to_url(doi, 'doi', 'https')
conceptdoi = m.get('conceptdoi')
if conceptdoi:
links['conceptbadge'] = ui_link_for('badge', doi=quote(conceptdoi))
links['conceptdoi'] = idutils.to_url(conceptdoi, 'doi', 'https')
files = m.get('_files', [])
for f in files:
if f.get('type') in thumbnail_exts:
try:
# First previewable image is used for preview.
links['thumbs'] = self._thumbnail_urls(m.get('recid'))
links['thumb250'] = self._thumbnail_url(f, 250)
except RuntimeError:
pass
break
return links
def _dump_record_links(self, obj):
"""Dump record-only links."""
links = {}
m = obj.get('metadata')
bucket_id = m.get('_buckets', {}).get('record')
recid = m.get('recid')
if bucket_id:
links['bucket'] = api_link_for('bucket', bucket=bucket_id)
links['html'] = ui_link_for('record_html', id=recid)
# Generate relation links
links.update(self._dump_relation_links(m))
return links
def _dump_deposit_links(self, obj):
"""Dump deposit-only links."""
links = {}
m = obj.get('metadata')
bucket_id = m.get('_buckets', {}).get('deposit')
recid = m.get('recid')
is_published = 'pid' in m.get('_deposit', {})
if bucket_id:
links['bucket'] = api_link_for('bucket', bucket=bucket_id)
# Record links
if is_published:
links['record'] = api_link_for('record', id=recid)
links['record_html'] = ui_link_for('record_html', id=recid)
# Generate relation links
links.update(self._dump_relation_links(m))
return links
def _dump_relation_links(self, metadata):
"""Dump PID relation links."""
links = {}
relations = metadata.get('relations')
if relations:
version_info = next(iter(relations.get('version', [])), None)
if version_info:
last_child = version_info.get('last_child')
if last_child:
links['latest'] = api_link_for(
'record', id=last_child['pid_value'])
links['latest_html'] = ui_link_for(
'record_html', id=last_child['pid_value'])
if is_deposit(metadata):
draft_child_depid = version_info.get('draft_child_deposit')
if draft_child_depid:
links['latest_draft'] = api_link_for(
'deposit', id=draft_child_depid['pid_value'])
links['latest_draft_html'] = ui_link_for(
'deposit_html', id=draft_child_depid['pid_value'])
return links
@post_load(pass_many=False)
def remove_envelope(self, data):
"""Post process data."""
# Remove envelope
if 'metadata' in data:
data = data['metadata']
# Record schema.
data['$schema'] = \
'https://zenodo.org/schemas/deposits/records/record-v1.0.0.json'
return data
| 26,340 | Python | .py | 632 | 31.632911 | 79 | 0.593036 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,595 | json.py | zenodo_zenodo/zenodo/modules/records/serializers/schemas/json.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Zenodo JSON schema."""
from __future__ import absolute_import, print_function, unicode_literals
from flask_babelex import lazy_gettext as _
from invenio_pidrelations.serializers.utils import serialize_relations
from invenio_pidstore.models import PersistentIdentifier
from marshmallow import Schema, ValidationError, fields, missing, \
validates_schema
from werkzeug.routing import BuildError
from zenodo.modules.records.utils import is_deposit
from zenodo.modules.stats.utils import get_record_stats
from ...models import AccessRight, ObjectType
from . import common
class StrictKeysSchema(Schema):
"""Ensure only valid keys exists."""
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
"""Check for unknown keys."""
for key in original_data:
if key not in self.fields:
raise ValidationError('Unknown field name {}'.format(key))
class ResourceTypeSchema(StrictKeysSchema):
"""Resource type schema."""
type = fields.Str(
required=True,
error_messages=dict(
required=_('Type must be specified.')
),
)
subtype = fields.Str()
openaire_subtype = fields.Str()
title = fields.Method('get_title', dump_only=True)
def get_title(self, obj):
"""Get title."""
obj = ObjectType.get_by_dict(obj)
return obj['title']['en'] if obj else missing
@validates_schema
def validate_data(self, data):
"""Validate resource type."""
obj = ObjectType.get_by_dict(data)
if obj is None:
raise ValidationError(_('Invalid resource type.'))
def dump_openaire_type(self, obj):
"""Get OpenAIRE subtype."""
acc = obj.get('access_right')
if acc:
return AccessRight.as_category(acc)
return missing
class JournalSchemaV1(StrictKeysSchema):
"""Schema for a journal."""
issue = fields.Str()
pages = fields.Str()
title = fields.Str()
volume = fields.Str()
year = fields.Str()
class MeetingSchemaV1(StrictKeysSchema):
"""Schema for a meeting."""
title = fields.Str()
acronym = fields.Str()
dates = fields.Str()
place = fields.Str()
url = fields.Str()
session = fields.Str()
session_part = fields.Str()
class ImprintSchemaV1(StrictKeysSchema):
"""Schema for imprint."""
publisher = fields.Str()
place = fields.Str()
isbn = fields.Str()
class PartOfSchemaV1(StrictKeysSchema):
"""Schema for imprint."""
pages = fields.Str()
title = fields.Str()
class ThesisSchemaV1(StrictKeysSchema):
"""Schema for thesis."""
university = fields.Str()
supervisors = fields.Nested(common.PersonSchemaV1, many=True)
class FunderSchemaV1(StrictKeysSchema):
"""Schema for a funder."""
doi = fields.Str()
name = fields.Str(dump_only=True)
acronyms = fields.List(fields.Str(), dump_only=True)
links = fields.Method('get_funder_url', dump_only=True)
def get_funder_url(self, obj):
"""Get grant url."""
return dict(self=common.api_link_for('funder', id=obj['doi']))
class GrantSchemaV1(StrictKeysSchema):
"""Schema for a grant."""
title = fields.Str(dump_only=True)
code = fields.Str()
program = fields.Str(dump_only=True)
acronym = fields.Str(dump_only=True)
funder = fields.Nested(FunderSchemaV1)
links = fields.Method('get_grant_url', dump_only=True)
def get_grant_url(self, obj):
"""Get grant url."""
return dict(self=common.api_link_for('grant', id=obj['internal_id']))
class CommunitiesSchemaV1(StrictKeysSchema):
"""Schema for communities."""
id = fields.Function(lambda x: x)
class ActionSchemaV1(StrictKeysSchema):
"""Schema for a actions."""
prereserve_doi = fields.Str(load_only=True)
class FilesSchema(Schema):
"""Files metadata schema."""
type = fields.String()
checksum = fields.String()
size = fields.Integer()
bucket = fields.String()
key = fields.String()
links = fields.Method('get_links')
def get_links(self, obj):
"""Get links."""
return {
'self': common.api_link_for(
'object', bucket=obj['bucket'], key=obj['key'])
}
class OwnerSchema(StrictKeysSchema):
"""Schema for owners.
Allows us to later introduce more properties for an owner.
"""
id = fields.Function(lambda x: x)
class LicenseSchemaV1(StrictKeysSchema):
"""Schema for license.
Allows us to later introduce more properties for an owner.
"""
id = fields.Str(attribute='id')
class MetadataSchemaV1(common.CommonMetadataSchemaV1):
"""Schema for a record."""
resource_type = fields.Nested(ResourceTypeSchema)
access_right_category = fields.Method(
'dump_access_right_category', dump_only=True)
license = fields.Nested(LicenseSchemaV1)
communities = fields.Nested(CommunitiesSchemaV1, many=True)
grants = fields.Nested(GrantSchemaV1, many=True)
journal = fields.Nested(JournalSchemaV1)
meeting = fields.Nested(MeetingSchemaV1)
imprint = fields.Nested(ImprintSchemaV1)
part_of = fields.Nested(PartOfSchemaV1)
thesis = fields.Nested(ThesisSchemaV1)
relations = fields.Method('dump_relations')
def dump_access_right_category(self, obj):
"""Get access right category."""
acc = obj.get('access_right')
if acc:
return AccessRight.as_category(acc)
return missing
def dump_relations(self, obj):
"""Dump the relations to a dictionary."""
if 'relations' in obj:
return obj['relations']
if is_deposit(obj):
pid = self.context['pid']
return serialize_relations(pid)
else:
pid = self.context['pid']
return serialize_relations(pid)
class RecordSchemaV1(common.CommonRecordSchemaV1):
"""Schema for records v1 in JSON."""
files = fields.Nested(
FilesSchema, many=True, dump_only=True, attribute='files')
metadata = fields.Nested(MetadataSchemaV1)
owners = fields.List(
fields.Integer, attribute='metadata.owners', dump_only=True)
revision = fields.Integer(dump_only=True)
updated = fields.Str(dump_only=True)
stats = fields.Method('dump_stats')
def dump_stats(self, obj):
"""Dump the stats to a dictionary."""
if '_stats' in obj.get('metadata', {}):
return obj['metadata'].get('_stats', {})
else:
pid = self.context.get('pid')
if isinstance(pid, PersistentIdentifier):
return get_record_stats(pid.object_uuid, False)
else:
return None
class DepositSchemaV1(RecordSchemaV1):
"""Deposit schema.
Same as the Record schema except for some few extra additions.
"""
files = None
owners = fields.Nested(
OwnerSchema, dump_only=True, attribute='metadata._deposit.owners',
many=True)
status = fields.Str(dump_only=True, attribute='metadata._deposit.status')
recid = fields.Str(dump_only=True, attribute='metadata.recid')
| 8,136 | Python | .py | 209 | 33.043062 | 77 | 0.680962 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,596 | rules.py | zenodo_zenodo/zenodo/modules/records/serializers/to_marc21/rules.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""MARC21 rules."""
from __future__ import absolute_import, print_function, unicode_literals
from dojson import utils
from dojson.contrib.to_marc21 import to_marc21
@to_marc21.over('980', '^(resource_type|communities)$')
@utils.for_each_value
@utils.filter_values
def reverse_resource_type(dummy_self, key, value):
"""Reverse - Resource Type."""
if key == 'resource_type':
return {
'a': value.get('type'),
'b': value.get('subtype'),
'$ind1': '_',
'$ind2': '_',
}
elif key == 'communities':
return {
'a': 'user-{0}'.format(value),
'$ind1': '_',
'$ind2': '_',
}
@to_marc21.over('999', '^references$')
@utils.reverse_for_each_value
@utils.filter_values
def reverse_references(dummy_self, dummy_key, value):
"""Reverse - References - raw reference."""
return {
'x': value.get('raw_reference'),
'$ind1': 'C',
'$ind2': '5',
}
@to_marc21.over('942', '^embargo_date$')
@utils.filter_values
def reverse_embargo_date(dummy_self, dummy_key, value):
"""Reverse - embargo date."""
return {
'a': value,
'$ind1': '_',
'$ind2': '_',
}
@to_marc21.over('909', '^(_oai|journal)$')
@utils.filter_values
def reverse_oai(dummy_self, key, value):
"""Reverse - OAI/Journal."""
if key == '_oai':
return {
'o': value.get('id'),
'p': utils.reverse_force_list(value.get('sets')),
'$ind1': 'C',
'$ind2': 'O',
}
elif key == 'journal':
return {
'n': value.get('issue'),
'c': value.get('pages'),
'v': value.get('volume'),
'p': value.get('title'),
'y': value.get('year'),
'$ind1': 'C',
'$ind2': '4',
}
return
@to_marc21.over('856', '^conference_url$')
@utils.filter_values
def reverse_conference_url(dummy_self, key, value):
"""Reverse - Meeting."""
return {
'y': 'Conference website',
'u': value,
'$ind1': '4',
'$ind2': '_',
}
@to_marc21.over('856', '^_files$')
@utils.reverse_for_each_value
@utils.filter_values
def reverse_files(dummy_self, key, value):
"""Reverse - Files."""
return {
's': str(value['size']),
'u': value['uri'],
'z': value['checksum'],
'$ind1': '4',
'$ind2': '_',
}
@to_marc21.over('041', '^language$')
@utils.filter_values
def reverse_language(dummy_self, dummy_key, value):
"""Reverse - language code."""
return {
'a': value,
'$ind1': '_',
'$ind2': '_',
}
| 3,642 | Python | .py | 117 | 25.606838 | 76 | 0.590935 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,597 | __init__.py | zenodo_zenodo/zenodo/modules/records/serializers/to_marc21/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""MARC21 rules."""
from __future__ import absolute_import, print_function
| 1,044 | Python | .py | 25 | 40.68 | 76 | 0.770895 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,598 | model.py | zenodo_zenodo/zenodo/modules/records/serializers/to_marc21/model.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""MARC21 model."""
from __future__ import absolute_import, print_function
from dojson.contrib.to_marc21.model import Underdo
from dojson.overdo import Index
class ZenodoUnderdo(Underdo):
"""Temporary fix for dojson branch size problem."""
def build(self):
"""."""
self._collect_entry_points()
self.index = Index(self.rules, branch_size=98)
to_marc21 = ZenodoUnderdo(entry_point_group='dojson.contrib.to_marc21')
| 1,420 | Python | .py | 34 | 39.588235 | 76 | 0.756894 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,599 | models.py | zenodo_zenodo/zenodo/modules/spam/models.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2022 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Spam models."""
from datetime import datetime
from invenio_accounts.models import User
from invenio_db import db
from sqlalchemy.dialects import mysql
class SafelistEntry(db.Model):
"""Defines a message to show to users."""
__tablename__ = "safelist_entries"
__versioned__ = {"versioning": False}
user_id = db.Column(
db.Integer,
db.ForeignKey(User.id, ondelete='RESTRICT'),
primary_key=True,
nullable=False
)
"""The safelisted user."""
notes = db.Column(
db.Text,
nullable=True
)
"""Notes about the safelisting."""
created = db.Column(
db.DateTime().with_variant(mysql.DATETIME(fsp=6), "mysql"),
default=datetime.utcnow,
nullable=False,
)
user = db.relationship(User, backref='safelist')
@classmethod
def create(cls, user_id, notes=None):
"""Create a safelist entry."""
try:
entry = cls(user_id=user_id, notes=notes)
db.session.add(entry)
except Exception:
entry = None
return entry
@classmethod
def get_by_user_id(cls, user_id):
"""Get entry by user_id."""
try:
entry = cls.query.filter(cls.user_id == user_id).first()
except Exception:
entry = None
return entry
@classmethod
def remove_by_user_id(cls, user_id):
"""Delete entry by user_id."""
try:
entry = cls.query.filter(cls.user_id == user_id).first()
db.session.delete(entry)
except Exception:
pass
@classmethod
def get_record_status(cls, record):
"""Get entry by user_id."""
for owner_id in record.get("owners", []):
if cls.get_by_user_id(owner_id):
return True
return False
| 2,807 | Python | .py | 82 | 28.304878 | 76 | 0.654485 | zenodo/zenodo | 906 | 241 | 543 | GPL-2.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |