Skip to content

Commit 951c500

Browse files
committed
services: metadata input on zenodo deposit creation
* adds serializers/validation for metadata input * adds unit tests for zenodo serializer * closes #1952 Signed-off-by: Ilias Koutsakis <[email protected]>
1 parent 32f7798 commit 951c500

File tree

7 files changed

+488
-35
lines changed

7 files changed

+488
-35
lines changed

cap/modules/deposit/api.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,15 @@
6161
from cap.modules.repos.tasks import download_repo, download_repo_file
6262
from cap.modules.repos.utils import (create_webhook, disconnect_subscriber,
6363
parse_git_url)
64+
from cap.modules.services.serializers.zenodo import ZenodoUploadSchema
6465
from cap.modules.schemas.resolvers import (resolve_schema_by_url,
6566
schema_name_to_url)
6667
from cap.modules.user.errors import DoesNotExistInLDAP
6768
from cap.modules.user.utils import (get_existing_or_register_role,
6869
get_existing_or_register_user)
6970

7071
from .errors import (DepositValidationError, UpdateDepositPermissionsError,
71-
ReviewError)
72+
ReviewError, InputValidationError)
7273
from .fetchers import cap_deposit_fetcher
7374
from .minters import cap_deposit_minter
7475
from .permissions import (AdminDepositPermission, CloneDepositPermission,
@@ -269,12 +270,22 @@ def upload(self, pid, *args, **kwargs):
269270
'Please connect your Zenodo account '
270271
'before creating a deposit.')
271272

272-
files = data.get('files')
273+
files = data.get('files', [])
273274
bucket = data.get('bucket')
274-
zenodo_data = data.get('zenodo_data', {})
275+
zenodo_data = data.get('zenodo_data')
276+
277+
input = {'files': files, 'bucket': bucket}
278+
if zenodo_data:
279+
input['data'] = zenodo_data
275280

276281
if files and bucket:
277-
zenodo_deposit = create_zenodo_deposit(token, zenodo_data) # noqa
282+
payload, errors = ZenodoUploadSchema().load(input)
283+
if errors:
284+
raise InputValidationError(
285+
'Validation error in Zenodo input data.',
286+
errors=errors)
287+
288+
zenodo_deposit = create_zenodo_deposit(token, payload)
278289
self.setdefault('_zenodo', []).append(zenodo_deposit)
279290
self.commit()
280291

cap/modules/deposit/errors.py

+15
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,21 @@ def __init__(self, description, errors=None, **kwargs):
138138
self.errors = [FieldError(e[0], e[1]) for e in errors.items()]
139139

140140

141+
class InputValidationError(RESTValidationError):
142+
"""Review validation error exception."""
143+
144+
code = 400
145+
146+
description = "Validation error. Try again with valid data"
147+
148+
def __init__(self, description, errors=None, **kwargs):
149+
"""Initialize exception."""
150+
super(InputValidationError, self).__init__(**kwargs)
151+
152+
self.description = description or self.description
153+
self.errors = [FieldError(e[0], e[1]) for e in errors.items()]
154+
155+
141156
class DataValidationError(RESTValidationError):
142157
"""Review validation error exception."""
143158

cap/modules/deposit/tasks.py

-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import requests
2929
from flask import current_app
3030
from celery import shared_task
31-
from invenio_db import db
3231
from invenio_files_rest.models import FileInstance, ObjectVersion
3332

3433

cap/modules/deposit/utils.py

+9-18
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,16 @@
2525

2626
from __future__ import absolute_import, print_function
2727

28+
import json
2829
import requests
2930
from flask import current_app
30-
from flask_login import current_user
3131
from invenio_access.models import Role
3232
from invenio_db import db
3333

3434
from cap.modules.deposit.errors import AuthorizationError, \
3535
DataValidationError, FileUploadError
3636
from cap.modules.records.utils import url_to_api_url
37+
from cap.modules.services.serializers.zenodo import ZenodoDepositSchema
3738

3839

3940
def clean_empty_values(data):
@@ -82,13 +83,16 @@ def add_api_to_links(links):
8283
return response
8384

8485

85-
def create_zenodo_deposit(token, data):
86+
def create_zenodo_deposit(token, data=None):
8687
"""Create a Zenodo deposit using the logged in user's credentials."""
8788
zenodo_url = current_app.config.get("ZENODO_SERVER_URL")
89+
zenodo_data = data.get('data')
90+
upload_data = {'metadata': zenodo_data} if zenodo_data else {}
91+
8892
deposit = requests.post(
8993
url=f'{zenodo_url}/deposit/depositions',
9094
params=dict(access_token=token),
91-
json={'metadata': data},
95+
json=upload_data,
9296
headers={'Content-Type': 'application/json'}
9397
)
9498

@@ -105,18 +109,5 @@ def create_zenodo_deposit(token, data):
105109
raise FileUploadError(
106110
'Something went wrong, Zenodo deposit not created.')
107111

108-
# TODO: fix with serializers
109-
data = deposit.json()
110-
zenodo_deposit = {
111-
'id': data['id'],
112-
'title': data.get('metadata', {}).get('title'),
113-
'creator': current_user.id,
114-
'created': data['created'],
115-
'links': {
116-
'self': data['links']['self'],
117-
'bucket': data['links']['bucket'],
118-
'html': data['links']['html'],
119-
'publish': data['links']['publish'],
120-
}
121-
}
122-
return zenodo_deposit
112+
data = ZenodoDepositSchema().dump(deposit.json()).data
113+
return data
+162
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# This file is part of CERN Analysis Preservation Framework.
4+
# Copyright (C) 2020 CERN.
5+
#
6+
# CERN Analysis Preservation Framework is free software; you can redistribute
7+
# it and/or modify it under the terms of the GNU General Public License as
8+
# published by the Free Software Foundation; either version 2 of the
9+
# License, or (at your option) any later version.
10+
#
11+
# CERN Analysis Preservation Framework is distributed in the hope that it will
12+
# be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14+
# General Public License for more details.
15+
#
16+
# You should have received a copy of the GNU General Public License
17+
# along with CERN Analysis Preservation Framework; if not, write to the
18+
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
19+
# MA 02111-1307, USA.
20+
#
21+
# In applying this license, CERN does not
22+
# waive the privileges and immunities granted to it by virtue of its status
23+
# as an Intergovernmental Organization or submit itself to any jurisdiction.
24+
# or submit itself to any jurisdiction.
25+
26+
"""Zenodo Serializer/Validator."""
27+
28+
import arrow
29+
from flask_login import current_user
30+
from marshmallow import Schema, fields, ValidationError, validate, validates, \
31+
validates_schema
32+
33+
from invenio_files_rest.models import ObjectVersion
34+
35+
DATE_REGEX = r'\d{4}-\d{2}-\d{2}'
36+
DATE_ERROR = 'The date should follow the pattern YYYY-mm-dd.'
37+
CHOICE_ERROR = lambda choices: f'Not a valid choice. Select one of: {choices}' # noqa
38+
39+
UPLOAD_TYPES = [
40+
'publication',
41+
'poster',
42+
'presentation',
43+
'dataset',
44+
'image',
45+
'video',
46+
'software',
47+
'lesson',
48+
'physicalobject',
49+
'other'
50+
]
51+
LICENSES = [
52+
'CC-BY-4.0',
53+
'CC-BY-1.0',
54+
'CC-BY-2.0',
55+
'CC-BY-3.0'
56+
]
57+
ACCESS_RIGHTS = [
58+
'open',
59+
'embargoed',
60+
'restricted',
61+
'closed'
62+
]
63+
64+
65+
class ZenodoCreatorsSchema(Schema):
66+
name = fields.String(required=True)
67+
affiliation = fields.String()
68+
orcid = fields.String()
69+
70+
71+
class ZenodoDepositMetadataSchema(Schema):
72+
title = fields.String(required=True)
73+
description = fields.String(required=True)
74+
version = fields.String()
75+
76+
keywords = fields.List(fields.String())
77+
creators = fields.List(
78+
fields.Nested(ZenodoCreatorsSchema), required=True)
79+
80+
upload_type = fields.String(required=True, validate=validate.OneOf(
81+
UPLOAD_TYPES, error=CHOICE_ERROR(UPLOAD_TYPES)))
82+
license = fields.String(required=True, validate=validate.OneOf(
83+
LICENSES, error=CHOICE_ERROR(LICENSES)))
84+
access_right = fields.String(required=True, validate=validate.OneOf(
85+
ACCESS_RIGHTS, error=CHOICE_ERROR(ACCESS_RIGHTS)))
86+
87+
publication_date = fields.String(
88+
required=True, validate=validate.Regexp(DATE_REGEX, error=DATE_ERROR))
89+
embargo_date = fields.String(
90+
validate=validate.Regexp(DATE_REGEX, error=DATE_ERROR))
91+
access_conditions = fields.String()
92+
93+
@validates('embargo_date')
94+
def validate_embargo_date(self, value):
95+
"""Validate that embargo date is in the future."""
96+
if arrow.get(value).date() <= arrow.utcnow().date():
97+
raise ValidationError(
98+
'Embargo date must be in the future.',
99+
field_names=['embargo_date']
100+
)
101+
102+
@validates_schema()
103+
def validate_license(self, data, **kwargs):
104+
"""Validate license."""
105+
access = data.get('access_right')
106+
if access in ['open', 'embargoed'] and 'license' not in data:
107+
raise ValidationError(
108+
'Required when access right is open or embargoed.',
109+
field_names=['license']
110+
)
111+
if access == 'embargoed' and 'embargo_date' not in data:
112+
raise ValidationError(
113+
'Required when access right is embargoed.',
114+
field_names=['embargo_date']
115+
)
116+
if access == 'restricted' and 'access_conditions' not in data:
117+
raise ValidationError(
118+
'Required when access right is restricted.',
119+
field_names=['access_conditions']
120+
)
121+
122+
123+
class ZenodoUploadSchema(Schema):
124+
files = fields.List(fields.String(), required=True)
125+
data = fields.Nested(ZenodoDepositMetadataSchema, default=dict())
126+
bucket = fields.String(required=True)
127+
128+
@validates_schema()
129+
def validate_files(self, data, **kwargs):
130+
bucket = data['bucket']
131+
files = data['files']
132+
133+
for _file in files:
134+
obj = ObjectVersion.get(bucket, _file)
135+
if not obj:
136+
raise ValidationError(
137+
f'File {_file} not found in bucket.',
138+
field_names=['files']
139+
)
140+
141+
142+
class ZenodoDepositSchema(Schema):
143+
id = fields.Int(dump_only=True)
144+
created = fields.String(dump_only=True)
145+
146+
title = fields.Method('get_title', dump_only=True, allow_none=True)
147+
creator = fields.Method('get_creator', dump_only=True, allow_none=True)
148+
links = fields.Method('get_links', dump_only=True)
149+
150+
def get_creator(self, data):
151+
return current_user.id if current_user else None
152+
153+
def get_title(self, data):
154+
return data.get('metadata', {}).get('title')
155+
156+
def get_links(self, data):
157+
return {
158+
'self': data['links']['self'],
159+
'bucket': data['links']['bucket'],
160+
'html': data['links']['html'],
161+
'publish': data['links']['publish']
162+
}

0 commit comments

Comments
 (0)