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,400
test_spam_utils.py
zenodo_zenodo/tests/unit/spam/test_spam_utils.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. """Test utils.""" import os import tempfile import pytest from zenodo.modules.spam.proxies import current_domain_forbiddenlist, \ current_domain_safelist def test_forbidden_list_search(app): assert not current_domain_forbiddenlist.matches("test.com") assert not current_domain_forbiddenlist.matches("other.ch") assert current_domain_forbiddenlist.matches("testing.com") assert current_domain_forbiddenlist.matches("some.other.ch") def test_safelist_search(app): assert not current_domain_safelist.matches("test.com") assert not current_domain_safelist.matches("other.ch") assert current_domain_safelist.matches("safedomain.org") assert current_domain_safelist.matches("safe.domain.org")
1,698
Python
.py
39
41.410256
76
0.778922
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,401
stats_helpers.py
zenodo_zenodo/tests/unit/stats/stats_helpers.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 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. """Statistics testing helpers.""" from collections import defaultdict from contextlib import contextmanager from copy import deepcopy from datetime import datetime, timedelta from types import MethodType from flask import current_app from invenio_db import db from invenio_files_rest.models import Bucket from invenio_files_rest.signals import file_downloaded from invenio_indexer.api import RecordIndexer from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.models import PersistentIdentifier from invenio_records_files.models import RecordsBuckets from invenio_records_ui.signals import record_viewed from invenio_search import current_search from invenio_stats import current_stats from invenio_stats.tasks import aggregate_events, process_events from mock import patch from six import BytesIO from zenodo.modules.records.api import ZenodoRecord from zenodo.modules.stats.tasks import update_record_statistics def mock_date(*date_parts): """Mocked 'datetime.utcnow()'.""" class MockDate(datetime): """datetime.datetime mock.""" @classmethod def utcnow(cls): """Override to return 'current_date'.""" return cls(*date_parts) return MockDate def _create_records(base_metadata, total, versions, files): records = [] cur_recid_val = 1 for _ in range(total): conceptrecid_val = cur_recid_val conceptrecid = PersistentIdentifier.create( 'recid', str(conceptrecid_val), status='R') db.session.commit() versioning = PIDVersioning(parent=conceptrecid) for ver_idx in range(versions): recid_val = conceptrecid_val + ver_idx + 1 data = deepcopy(base_metadata) data.update({ 'conceptrecid': str(conceptrecid_val), 'conceptdoi': '10.1234/{}'.format(recid_val), 'recid': recid_val, 'doi': '10.1234/{}'.format(recid_val), }) record = ZenodoRecord.create(data) bucket = Bucket.create() record['_buckets'] = {'record': str(bucket.id)} record.commit() RecordsBuckets.create(bucket=bucket, record=record.model) recid = PersistentIdentifier.create( pid_type='recid', pid_value=record['recid'], object_type='rec', object_uuid=record.id, status='R') versioning.insert_child(recid) file_objects = [] for f in range(files): filename = 'Test{0}_v{1}.pdf'.format(f, ver_idx) record.files[filename] = BytesIO(b'1234567890') # 10 bytes record.files[filename]['type'] = 'pdf' file_objects.append(record.files[filename].obj) record.commit() db.session.commit() records.append((recid, record, file_objects)) cur_recid_val += versions + 1 return records def _gen_date_range(start, end, interval): assert isinstance(interval, timedelta) cur_date = start while cur_date < end: yield cur_date cur_date += interval def create_stats_fixtures(metadata, n_records, n_versions, n_files, event_data, start_date, end_date, interval, do_process_events=True, do_aggregate_events=True, do_update_record_statistics=True): """Generate configurable statistics fixtures. :param dict metadata: Base metadata for the created records. :param int n_records: Number of records that will be created. :param int n_versions: Number of versions for each record. :param int n_files: Number of files for each record version. :param dict event_data: Base event metadata (e.g. user, user agent, etc). :param datetime start_date: Start date for the generated events. :param datetime end_date: End date for the generated events. :param timedelta interval: Interval between each group of events. :param bool do_process_events: ``True`` will run the ``process_events`` task. :param bool do_aggregate_events: ``True`` will run the ``aggregate_events`` task. :param bool do_update_record_statistics: ``True`` will run the ``update_record_statistics`` task. """ records = _create_records( metadata, total=n_records, versions=n_versions, files=n_files) @contextmanager def _patch_stats_publish(): original_publish = current_stats.publish event_batches = defaultdict(list) def _patched_publish(self, event_type, events): events[0].update(event_data) event_batches[event_type].append(events[0]) current_stats.publish = MethodType(_patched_publish, current_stats) yield current_stats.publish = original_publish for event_type, events in event_batches.items(): current_stats.publish(event_type, events) with _patch_stats_publish(): for ts in _gen_date_range(start_date, end_date, interval): event_data['timestamp'] = ts.isoformat() for recid, record, file_objects in records: with current_app.test_request_context(): record_viewed.send(current_app._get_current_object(), pid=recid, record=record) for obj in file_objects: file_downloaded.send( current_app._get_current_object(), obj=obj, record=record) if do_process_events: process_events(['record-view', 'file-download']) current_search.flush_and_refresh(index='events-stats-*') if do_aggregate_events: with patch('invenio_stats.aggregations.datetime', mock_date(*end_date.timetuple()[:3])): aggregate_events( ['record-view-agg', 'record-view-all-versions-agg', 'record-download-agg', 'record-download-all-versions-agg']) current_search.flush_and_refresh(index='stats-*') if do_update_record_statistics: update_record_statistics(start_date=start_date.isoformat(), end_date=end_date.isoformat()) RecordIndexer().process_bulk_queue() current_search.flush_and_refresh(index='records') return records
7,300
Python
.py
157
37.923567
79
0.660674
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,402
test_stats_aggs.py
zenodo_zenodo/tests/unit/stats/test_stats_aggs.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 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. """Unit tests statistics aggregations.""" from datetime import datetime, timedelta from elasticsearch_dsl import Search from elasticsearch_dsl.query import Ids from invenio_search.proxies import current_search_client from invenio_search.utils import build_alias_name from stats_helpers import create_stats_fixtures def test_basic_stats(app, db, es, locations, event_queues, minimal_record): """Test basic statistics results.""" search = Search(using=es) records = create_stats_fixtures( # (10 * 2) -> 20 records and (10 * 2 * 3) -> 60 files metadata=minimal_record, n_records=10, n_versions=2, n_files=3, event_data={'user_id': '1'}, # 4 event timestamps start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30)) # Events indices prefix = app.config['SEARCH_INDEX_PREFIX'] # 2 versions * 10 records * 3 files * 4 events -> 240 assert search.index(prefix + 'events-stats-file-download').count() == 240 # 2 versions * 10 records * 4 events -> 80 assert search.index(prefix + 'events-stats-record-view').count() == 80 # Aggregations indices # (2 versions + 1 concept) * 10 records -> 30 documents + 2 bookmarks # 30d assert search.index(prefix + 'stats-file-download').count() == 30 # 30d assert search.index(prefix + 'stats-record-view').count() == 30 # 2bm + 2bm assert search.index(prefix + 'stats-bookmarks').count() == 4 # Records index for _, record, _ in records: doc = \ current_search_client.get( index=build_alias_name('records'), id=str(record.id), params={'_source_includes': '_stats'} ) assert doc['_source']['_stats'] == { # 4 view events 'views': 4.0, 'version_views': 8.0, # 4 view events over 2 different hours 'unique_views': 2.0, 'version_unique_views': 2.0, # 4 download events * 3 files 'downloads': 12.0, 'version_downloads': 24.0, # 4 download events * 3 files over 2 different hours 'unique_downloads': 2.0, 'version_unique_downloads': 2.0, # 4 download events * 3 files * 10 bytes 'volume': 120.0, 'version_volume': 240.0, } def test_large_stats(app, db, es, locations, event_queues, minimal_record): """Test a larger number of events, aggregations, and results.""" search = Search(using=es) records = create_stats_fixtures( # (3 * 4) -> 12 records and (3 * 4 * 2) -> 24 files metadata=minimal_record, n_records=3, n_versions=4, n_files=2, event_data={'user_id': '1'}, # (31 + 30) * 2 -> 122 event timestamps (61 days and 2 events/day) start_date=datetime(2018, 3, 1), end_date=datetime(2018, 5, 1), interval=timedelta(hours=12)) # Events indices prefix = app.config['SEARCH_INDEX_PREFIX'] # 4 versions * 3 records * 2 files * 122 events -> 2928 assert search.index(prefix + 'events-stats-file-download').count() == 2928 # 4 versions * 3 records * 122 events -> 1464 assert search.index(prefix + 'events-stats-record-view').count() == 1464 # Aggregations indices # (4 versions + 1 concept) * 3 records -> 15 documents + 2 bookmarks q = search.index(prefix + 'stats-file-download') assert q.count() == 915 # 61 days * 15 records q = search.index(prefix + 'stats-record-view') assert q.count() == 915 # 61 days * 15 records # Records index for _, record, _ in records: doc = \ current_search_client.get( index=build_alias_name('records'), id=str(record.id), params={'_source_includes': '_stats'} ) assert doc['_source']['_stats'] == { # 4 view events 'views': 122.0, 'version_views': 488.0, # 4 view events over 2 different hours 'unique_views': 122.0, 'version_unique_views': 122.0, # 4 download events * 3 files 'downloads': 244.0, 'version_downloads': 976.0, # 4 download events * 3 files over 2 different hours 'unique_downloads': 122.0, 'version_unique_downloads': 122.0, # 4 download events * 3 files * 10 bytes 'volume': 2440.0, 'version_volume': 9760.0, }
5,346
Python
.py
116
38.913793
78
0.631619
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,403
test_stats_exporters.py
zenodo_zenodo/tests/unit/stats/test_stats_exporters.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 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. """Unit tests for statistics exporters.""" from datetime import datetime, timedelta import pytest from invenio_cache import current_cache from mock import mock from stats_helpers import create_stats_fixtures from zenodo.modules.stats.exporters import PiwikExporter, \ PiwikExportRequestError class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code self.ok = status_code == 200 def json(self): return self.json_data def mocked_requests_success(*args, **kwargs): json = {'status': 'success', 'invalid': 0} return MockResponse(json, 200) def mocked_requests_invalid(*args, **kwargs): json = {'status': 'success', 'invalid': 1} return MockResponse(json, 200) def mocked_requests_fail(*args, **kwargs): return MockResponse({}, 500) @mock.patch('zenodo.modules.stats.exporters.requests.post', side_effect=mocked_requests_success) def test_piwik_exporter(app, db, es, locations, event_queues, full_record): records = create_stats_fixtures( metadata=full_record, n_records=1, n_versions=1, n_files=1, event_data={'user_id': '1', 'country': 'CH'}, # 4 event timestamps start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30), do_process_events=True, do_aggregate_events=False, do_update_record_statistics=False ) current_cache.delete('piwik_export:bookmark') bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None start_date = datetime(2018, 1, 1, 12) end_date = datetime(2018, 1, 1, 14) PiwikExporter().run(start_date=start_date, end_date=end_date) bookmark = current_cache.get('piwik_export:bookmark') assert bookmark == u'2018-01-01T14:00:00' PiwikExporter().run() bookmark = current_cache.get('piwik_export:bookmark') assert bookmark == u'2018-01-01T14:30:00' @mock.patch('zenodo.modules.stats.exporters.requests.post', side_effect=mocked_requests_invalid) def test_piwik_exporter_invalid_request(app, db, es, locations, event_queues, full_record): records = create_stats_fixtures( metadata=full_record, n_records=1, n_versions=1, n_files=1, event_data={'user_id': '1', 'country': 'CH'}, # 4 event timestamps start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30), do_process_events=True) current_cache.delete('piwik_export:bookmark') bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None start_date = datetime(2018, 1, 1, 12) end_date = datetime(2018, 1, 1, 14) PiwikExporter().run(start_date=start_date, end_date=end_date) bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None @mock.patch('zenodo.modules.stats.exporters.requests.post', side_effect=mocked_requests_fail) def test_piwik_exporter_request_fail(app, db, es, locations, event_queues, full_record): records = create_stats_fixtures( metadata=full_record, n_records=1, n_versions=1, n_files=1, event_data={'user_id': '1', 'country': 'CH'}, # 4 event timestamps start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30), do_process_events=True) current_cache.delete('piwik_export:bookmark') bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None start_date = datetime(2018, 1, 1, 12) end_date = datetime(2018, 1, 1, 14) with pytest.raises(PiwikExportRequestError): PiwikExporter().run(start_date=start_date, end_date=end_date) bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None def test_piwik_exporter_no_bookmark(app, db, es, locations, event_queues, full_record): records = create_stats_fixtures( metadata=full_record, n_records=1, n_versions=1, n_files=1, event_data={'user_id': '1', 'country': 'CH'}, # 4 event timestamps start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30), do_process_events=True) current_cache.delete('piwik_export:bookmark') bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None with mock.patch('zenodo.modules.stats.exporters.requests.post') as mocked: PiwikExporter().run() mocked.assert_not_called() bookmark = current_cache.get('piwik_export:bookmark') assert bookmark is None
5,720
Python
.py
128
38.53125
78
0.685129
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,404
test_stats_tasks.py
zenodo_zenodo/tests/unit/stats/test_stats_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 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. """Unit tests for statistics tasks.""" from datetime import datetime, timedelta from flask import url_for from invenio_indexer.api import RecordIndexer from invenio_search import current_search from invenio_stats.tasks import aggregate_events, process_events from stats_helpers import create_stats_fixtures from zenodo.modules.stats.tasks import update_record_statistics from zenodo.modules.stats.utils import get_record_stats def test_update_record_statistics(app, db, es, locations, event_queues, minimal_record): """Test record statistics update task.""" records = create_stats_fixtures( metadata=minimal_record, n_records=1, n_versions=5, n_files=3, event_data={'user_id': '1'}, # 4 event timestamps (half-hours between 13:00-15:00) start_date=datetime(2018, 1, 1, 13), end_date=datetime(2018, 1, 1, 15), interval=timedelta(minutes=30), # This also runs the task we want to test and indexes records. do_update_record_statistics=True) expected_stats = { 'views': 4.0, 'version_views': 20.0, 'unique_views': 2.0, 'version_unique_views': 2.0, 'downloads': 12.0, 'version_downloads': 60.0, 'unique_downloads': 2.0, 'version_unique_downloads': 2.0, 'volume': 120.0, 'version_volume': 600.0, } # Check current stats for all records for recid, _, _ in records: stats = get_record_stats(recid.object_uuid) assert stats == expected_stats # Perform a view and all-files download today on the first version recid_v1, record_v1, file_objects_v1 = records[0] with app.test_client() as client: for f in file_objects_v1: file_url = url_for('invenio_records_ui.recid_files', pid_value=recid_v1.pid_value, filename=f.key) assert client.get(file_url).status_code == 200 record_url = url_for( 'invenio_records_ui.recid', pid_value=recid_v1.pid_value) assert client.get(record_url).status_code == 200 process_events(['record-view', 'file-download']) current_search.flush_and_refresh(index='events-stats-*') aggregate_events( ['record-view-agg', 'record-view-all-versions-agg', 'record-download-agg', 'record-download-all-versions-agg']) current_search.flush_and_refresh(index='stats-*') update_record_statistics() RecordIndexer().process_bulk_queue() current_search.flush_and_refresh(index='records') # Check current stats for all records stats = get_record_stats(recid_v1.object_uuid) assert stats == { 'views': 5.0, 'version_views': 21.0, 'unique_views': 3.0, 'version_unique_views': 3.0, 'downloads': 15.0, 'version_downloads': 63.0, 'unique_downloads': 3.0, 'version_unique_downloads': 3.0, 'volume': 150.0, 'version_volume': 630.0, } # Other versions will have only their `version_*` statistics updated expected_stats['version_views'] += 1 expected_stats['version_unique_views'] += 1 expected_stats['version_downloads'] += 3 expected_stats['version_unique_downloads'] += 1 expected_stats['version_volume'] += 30 for recid, _, _ in records[1:]: stats = get_record_stats(recid.object_uuid) assert stats == expected_stats
4,324
Python
.py
100
37.06
77
0.674501
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,405
test_stats_cli.py
zenodo_zenodo/tests/unit/stats/test_stats_cli.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 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. """Unit tests CLI commands for statistics.""" from click.testing import CliRunner from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.api import Record from zenodo.modules.stats.cli import import_events def test_record_view_import(app, db, es, event_queues, full_record, script_info, tmpdir): """Test record page view event import.""" full_record['conceptrecid'] = '12344' full_record['conceptdoi'] = '10.1234/foo.concept' r = Record.create(full_record) PersistentIdentifier.create( 'recid', '12345', object_type='rec', object_uuid=r.id, status=PIDStatus.REGISTERED) db.session.commit() csv_file = tmpdir.join('record-views.csv') csv_file.write( ',userAgent,ipAddress,url,serverTimePretty,timestamp,referrer\n' ',foo,137.138.36.206,https://zenodo.org/record/12345,,1367928000,\n') runner = CliRunner() res = runner.invoke( import_events, ['record-view', csv_file.dirname], obj=script_info) assert res.exit_code == 0 events = list(event_queues['stats-record-view'].consume()) assert len(events) == 1 assert events[0] == { 'pid_type': 'recid', 'pid_value': '12345', 'communities': ['zenodo'], 'owners': [1], 'conceptdoi': '10.1234/foo.concept', 'conceptrecid': '12344', 'doi': '10.1234/foo.bar', 'ip_address': '137.138.36.206', 'recid': '12345', 'record_id': str(r.id), 'referrer': '', 'resource_type': {'subtype': 'book', 'type': 'publication'}, 'access_right': 'open', 'timestamp': '2013-05-07T12:00:00', 'user_agent': 'foo', 'user_id': None, }
2,644
Python
.py
64
36.1875
77
0.67535
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,406
test_stats_rest_views.py
zenodo_zenodo/tests/unit/stats/test_stats_rest_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 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. """Unit tests for stats rest views.""" import json from helpers import login_user_via_session def test_queries_permission_factory(app, db, es, event_queues, users, record_with_files_creation, api_client): """Test queries permission factory.""" recid, record, _ = record_with_files_creation record['conceptdoi'] = '10.1234/foo.concept' record['conceptrecid'] = 'foo.concept' record.commit() db.session.commit() headers = [('Content-Type', 'application/json'), ('Accept', 'application/json')] sample_histogram_query_data = { "mystat": { "stat": "record-download", "params": { "file_key": "Test.pdf", "recid": recid.pid_value } } } query_url = '/stats' login_user_via_session(api_client, email=users[0]['email']) res = api_client.post(query_url, headers=headers, data=json.dumps(sample_histogram_query_data)) assert res.status_code == 403 login_user_via_session(api_client, email=users[2]['email']) res = api_client.post(query_url, headers=headers, data=json.dumps(sample_histogram_query_data)) assert res.status_code == 200
2,179
Python
.py
52
35.923077
77
0.670127
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,407
test_event_emitters.py
zenodo_zenodo/tests/unit/stats/test_event_emitters.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 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. """Unit tests statistics for record views.""" from elasticsearch_dsl import Search from flask import url_for from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.api import Record from invenio_search import current_search from invenio_stats.tasks import process_events def test_record_page(app, db, es, event_queues, full_record): """Test record page views.""" full_record['conceptdoi'] = '10.1234/foo.concept' full_record['conceptrecid'] = 'foo.concept' r = Record.create(full_record) PersistentIdentifier.create( 'recid', '12345', object_type='rec', object_uuid=r.id, status=PIDStatus.REGISTERED) db.session.commit() with app.test_client() as client: record_url = url_for('invenio_records_ui.recid', pid_value='12345') assert client.get(record_url).status_code == 200 process_events(['record-view']) current_search.flush_and_refresh(index='events-stats-record-view') prefix = app.config['SEARCH_INDEX_PREFIX'] search = Search(using=es, index=prefix+'events-stats-record-view') assert search.count() == 1 doc = search.execute()[0] assert doc['doi'] == '10.1234/foo.bar' assert doc['conceptdoi'] == '10.1234/foo.concept' assert doc['recid'] == '12345' assert doc['conceptrecid'] == 'foo.concept' assert doc['resource_type'] == {'type': 'publication', 'subtype': 'book'} assert doc['access_right'] == 'open' assert doc['communities'] == ['zenodo'] assert doc['owners'] == [1] def test_file_download(app, db, es, event_queues, record_with_files_creation): """Test file download views.""" recid, record, _ = record_with_files_creation record['conceptdoi'] = '10.1234/foo.concept' record['conceptrecid'] = 'foo.concept' record.commit() db.session.commit() with app.test_client() as client: file_url = url_for( 'invenio_records_ui.recid_files', pid_value=recid.pid_value, filename='Test.pdf', ) assert client.get(file_url).status_code == 200 process_events(['file-download']) current_search.flush_and_refresh(index='events-stats-file-download') prefix = app.config['SEARCH_INDEX_PREFIX'] search = Search(using=es, index=prefix+'events-stats-file-download') assert search.count() == 1 doc = search.execute()[0] assert doc['doi'] == '10.1234/foo.bar' assert doc['conceptdoi'] == '10.1234/foo.concept' assert doc['recid'] == '12345' assert doc['conceptrecid'] == 'foo.concept' assert doc['resource_type'] == {'type': 'publication', 'subtype': 'book'} assert doc['access_right'] == 'open' assert doc['communities'] == ['zenodo'] assert doc['owners'] == [1]
3,654
Python
.py
82
40.243902
78
0.696067
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,408
test_rest_views.py
zenodo_zenodo/tests/unit/rest/test_rest_views.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 REST root view.""" from __future__ import absolute_import, print_function import json from datetime import datetime, timedelta from flask import render_template_string, url_for from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.api import Record from zenodo.modules.records.views import zenodo_related_links def test_is_valid_access_right(app): """Test template test.""" assert render_template_string("{{ 'open' is accessright }}") == "True" assert render_template_string("{{ 'invalid' is accessright }}") == "False" def test_is_embargoed(app): """Test template test.""" today = datetime.utcnow().date() assert render_template_string( "{{ dt is embargoed }}", dt=today) == "False" assert render_template_string( "{{ dt is embargoed }}", dt=today+timedelta(days=1)) == "True" assert render_template_string( "{{ dt is embargoed(accessright='open') }}", dt=today+timedelta(days=1)) == "False" assert render_template_string( "{{ dt is embargoed(accessright='embargoed') }}", dt=today+timedelta(days=1)) == "True" assert render_template_string( "{{ dt is embargoed(accessright='embargoed') }}", dt=None) == "False" def test_accessright_category(app): """Test template filter.""" assert render_template_string( "{{ 'open'|accessright_category }}") == "success" def test_accessright_title(app): """Test template filter.""" assert render_template_string( "{{ 'open'|accessright_title }}") == "Open Access" def test_objecttype(app): """Test template filter.""" assert render_template_string( r"{% set t = upload_type|objecttype %}{{ t.title.en }}", upload_type=dict(type="publication", subtype="book")) == "Book" assert render_template_string( r"{% set t = upload_type|objecttype %}{{ t.title.en }}", upload_type=dict(type="publication")) == "Publication" assert render_template_string( r"{% set t = upload_type|objecttype %}{{ t }}", upload_type="") == "None" def test_local_doi(app): """Test template test.""" orig = app.config['ZENODO_LOCAL_DOI_PREFIXES'] app.config['ZENODO_LOCAL_DOI_PREFIXES'] = ['10.123', '10.5281'] assert render_template_string( "{{ '10.123/foo' is local_doi }}") == "True" assert render_template_string( "{{ '10.1234/foo' is local_doi }}") == "False" assert render_template_string( "{{ '10.5281/foo' is local_doi }}") == "True" app.config['ZENODO_LOCAL_DOI_PREFIXES'] = orig def test_relation_title(app): """Test relation title.""" assert render_template_string( "{{ 'isCitedBy'|relation_title }}") == "Cited by" assert render_template_string( "{{ 'nonExistingRelation'|relation_title }}") == "nonExistingRelation" def test_relation_logo(app): """Test relation logo.""" no_relations = {} assert zenodo_related_links(no_relations, []) == [] class MockCommunity(object): id = 'zenodo' github_relation = { 'communities': [ 'zenodo', ], 'related_identifiers': [ { 'scheme': 'url', 'relation': 'isSupplementTo', 'identifier': 'https://github.com/' 'TaghiAliyev/BBiCat/tree/v1.0.4-alpha', } ], } assert zenodo_related_links(github_relation, [MockCommunity]) == [ { 'image': 'img/github.png', 'link': 'https://github.com/TaghiAliyev/BBiCat/tree/v1.0.4-alpha', 'prefix': 'https://github.com', 'relation': 'isSupplementTo', 'scheme': 'url', 'text': 'Available in' } ] def test_pid_url(app): """Test pid_url.""" assert render_template_string( "{{ '10.123/foo'|pid_url }}") == "https://doi.org/10.123/foo" assert render_template_string( "{{ 'asfasdf'|pid_url }}") == "" assert render_template_string( "{{ 'arXiv:1512.01558'|pid_url(scheme='arxiv', url_scheme='http') }}" ) == "http://arxiv.org/abs/arXiv:1512.01558" assert render_template_string( "{{ 'arXiv:1512.01558'|pid_url(scheme='arxiv') }}") \ == "https://arxiv.org/abs/arXiv:1512.01558" def test_records_ui_export(app, db, full_record): """Test export pages.""" r = Record.create(full_record) PersistentIdentifier.create( 'recid', '12345', object_type='rec', object_uuid=r.id, status=PIDStatus.REGISTERED) db.session.commit() formats = app.config['ZENODO_RECORDS_EXPORTFORMATS'] with app.test_client() as client: for f, val in formats.items(): res = client.get(url_for( 'invenio_records_ui.recid_export', pid_value='12345', format=f)) assert res.status_code == 410 if val is None else 200 def test_citation_formatter_styles_get(api, api_client, db): """Test get CSL styles.""" with api.test_request_context(): style_url = url_for('invenio_csl_rest.styles') res = api_client.get(style_url) styles = json.loads(res.get_data(as_text=True)) assert res.status_code == 200 assert 'apa' in styles assert 'American Psychological Association' in styles['apa'] def test_index(api, api_client): """Test root endpoint.""" with api.test_request_context(): index_url = url_for('zenodo_rest.index') res = api_client.get(index_url) assert res.status_code == 200 data = json.loads(res.get_data(as_text=True)) assert 'links' in data
6,618
Python
.py
159
35.440252
78
0.640778
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,409
test_utils.py
zenodo_zenodo/tests/unit/jsonschemas/test_utils.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 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. """Unit tests Zenodo JSON schemas utils.""" from __future__ import absolute_import, print_function from zenodo.modules.jsonschemas.utils import merge_dicts def test_merge_dicts(): """Test jsonschema merging util.""" a1 = { 'd': { 'k1': 1, 'k2': 'v2', 'd2': { 'k3': 'v3', }, }, 'l': [1, 2, 3, ], } b1 = { 'd': { 'k1': 10, # Updated value in nested 'k2': 'v2', 'k3': 'v3', # New key in nested 'd2': { 'k4': 'v4', }, }, 'l': [4, 5, 6, ], # Updated list 'v': 'value', # New key at root } exp1 = { 'd': { 'k1': 10, 'k2': 'v2', 'k3': 'v3', 'd2': { 'k3': 'v3', 'k4': 'v4', }, }, 'l': [4, 5, 6, ], 'v': 'value', } ab1 = merge_dicts(a1, b1) assert ab1 == exp1
1,915
Python
.py
63
23.650794
77
0.551463
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,410
test_jsonschemas_compilers.py
zenodo_zenodo/tests/unit/jsonschemas/test_jsonschemas_compilers.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 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. """Unit tests Zenodo JSON schemas.""" from __future__ import absolute_import, print_function from zenodo.modules.jsonschemas.compilers import compile_deposit_jsonschema, \ compile_record_jsonschema from zenodo.modules.jsonschemas.utils import resolve_schema_path def test_compile_schemas(app): """Test record jsonschema compilation. NOTE: Failure of this test most likely means that the 'compiled' jsonschemas have been edited manually and are divergent from the 'source' jsonschemas. """ config_vars = [ app.config['ZENODO_JSONSCHEMAS_RECORD_SCHEMA'], app.config['ZENODO_JSONSCHEMAS_DEPOSIT_SCHEMA'], ] compile_funcs = [ compile_record_jsonschema, compile_deposit_jsonschema, ] for config_var, compile_func in zip(config_vars, compile_funcs): src, dst = config_var compiled_schema = compile_func(src) repo_schema = resolve_schema_path(dst) assert compiled_schema == repo_schema
1,891
Python
.py
45
38.488889
78
0.744565
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,411
test_fixtures_cli.py
zenodo_zenodo/tests/unit/fixtures/test_fixtures_cli.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. """Zenodo fixtures CLI test cases.""" from __future__ import absolute_import, print_function from click.testing import CliRunner from invenio_records.models import RecordMetadata from zenodo.modules.fixtures.cli import loadfp6grants_cli, loadfunders_cli def test_loadfunders_and_fp6grants(script_info, db): """Test loading of funders fixture and FP6 grants.""" assert not RecordMetadata.query.count() runner = CliRunner() res = runner.invoke(loadfunders_cli, [], obj=script_info) assert res.exit_code == 0 # We support 14 funders, but 4 parent funders are also required to properly # index the funder records. assert RecordMetadata.query.count() == 18 res = runner.invoke(loadfp6grants_cli, [], obj=script_info) assert res.exit_code == 0 assert RecordMetadata.query.count() == 20 # + 2 FP6 grants
1,822
Python
.py
40
43.275
79
0.759437
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,412
conftest.py
zenodo_zenodo/tests/e2e/conftest.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. """Pytest configuration. Before running any of the tests you must have initialized the assets using the ``script scripts/setup-assets.sh``. """ from __future__ import absolute_import, print_function import os import pytest from elasticsearch.exceptions import RequestError from invenio_db import db as db_ from invenio_search import current_search, current_search_client from selenium import webdriver from sqlalchemy_utils.functions import create_database, database_exists from zenodo.config import APP_DEFAULT_SECURE_HEADERS from zenodo.factory import create_app @pytest.yield_fixture(scope='session', autouse=True) def base_app(request): """Flask application fixture.""" # Disable HTTPS APP_DEFAULT_SECURE_HEADERS['force_https'] = False APP_DEFAULT_SECURE_HEADERS['session_cookie_secure'] = False app = create_app( # CELERY_ALWAYS_EAGER=True, # CELERY_CACHE_BACKEND="memory", # CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, # CELERY_RESULT_BACKEND="cache", APP_DEFAULT_SECURE_HEADERS=APP_DEFAULT_SECURE_HEADERS, DEBUG_TB_ENABLED=False, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME", MAIL_SUPPRESS_SEND=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, ) with app.app_context(): yield app @pytest.yield_fixture(scope='session') def es(base_app): """Provide elasticsearch access.""" try: list(current_search.create()) except RequestError: list(current_search.delete()) list(current_search.create()) current_search_client.indices.refresh() yield current_search_client list(current_search.delete(ignore=[404])) @pytest.yield_fixture(scope='session') def db(base_app): """Setup database.""" if not database_exists(str(db_.engine.url)): create_database(str(db_.engine.url)) db_.create_all() yield db_ db_.session.remove() db_.drop_all() @pytest.yield_fixture(scope='session', autouse=True) def app(base_app, es, db): """Application with ES and DB.""" yield base_app def pytest_generate_tests(metafunc): """Override pytest's default test collection function. For each test in this directory which uses the `env_browser` fixture, the given test is called once for each value found in the `E2E_WEBDRIVER_BROWSERS` environment variable. """ if 'env_browser' in metafunc.fixturenames: # In Python 2.7 the fallback kwarg of os.environ.get is `failobj`, # in 3.x it's `default`. browsers = os.environ.get('E2E_WEBDRIVER_BROWSERS', 'Firefox').split() metafunc.parametrize('env_browser', browsers, indirect=True) @pytest.yield_fixture() def env_browser(request): """Fixture for a webdriver instance of the browser.""" if request.param is None: request.param = "Firefox" # Create instance of webdriver.`request.param`() browser = getattr(webdriver, request.param)() yield browser # Quit the webdriver instance browser.quit()
4,120
Python
.py
105
34.67619
76
0.717865
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,413
test_frontpage.py
zenodo_zenodo/tests/e2e/test_frontpage.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. """E2E integration tests.""" from __future__ import absolute_import, print_function from flask import url_for def test_frontpage(live_server, env_browser): """Test retrieval of frontpage.""" env_browser.get( url_for('zenodo_frontpage.index', _external=True))
1,247
Python
.py
30
39.866667
76
0.762376
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,414
loggedin.py
zenodo_zenodo/benchmarks/loggedin.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. """Logged-in benchmarks.""" from __future__ import absolute_import, print_function from anonymous import AnonymousWebsiteTasks from locust import HttpLocust class LoggedInWebsiteTasks(AnonymousWebsiteTasks): """Benchmark logged-in user.""" def on_start(self): """Load user on start.""" with self.client.post('https://sandbox.zenodo.org/login/', { 'email': 'test@zenodo.org', 'password': '123456', }) as response: if response.status_code != 200: response.failure('wrong login') class WebsiteUser(HttpLocust): """Locust.""" task_set = LoggedInWebsiteTasks min_wait = 5000 max_wait = 15000
1,759
Python
.py
43
35.139535
76
0.684827
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,415
anonymous.py
zenodo_zenodo/benchmarks/anonymous.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. """Anonymous benchmarks.""" from __future__ import absolute_import, print_function from locust import HttpLocust, TaskSet, task class AnonymousWebsiteTasks(TaskSet): """Benchmark anonymous user.""" @task def download(self): """Task download.""" self.client.get( 'https://sandbox.zenodo.org/record/16464/files/' 'FWF_JournalPublicationCosts_2013__incl._licenses.xlsx') @task def static(self): """Task static file.""" self.client.get( 'https://sandbox.zenodo.org/static/gen/zenodo.21142a66.css') @task def sandbox(self): """Task home page.""" self.client.get("https://sandbox.zenodo.org/") class WebsiteUser(HttpLocust): """Locust.""" task_set = AnonymousWebsiteTasks min_wait = 5000 max_wait = 15000
1,805
Python
.py
48
33.708333
76
0.715349
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,416
celery.py
zenodo_zenodo/zenodo/celery.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 celery application object.""" from __future__ import absolute_import, print_function from invenio_app.celery import celery __all__ = ('celery', )
1,127
Python
.py
27
40.592593
76
0.769161
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,417
config.py
zenodo_zenodo/zenodo/config.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2015, 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. """Zenodo default application configuration. You can customize these configuration variables on your instance by either setting environment variables prefixed with ``APP_``, e.g. .. code-block:: console export APP_SUPPORT_EMAIL=info@example.org or provide an instance configuration file (Python syntax): .. code-block:: python # ${VIRTUAL_ENV}/var/instance/invenio.cfg SUPPORT_EMAIL = "info@example.org" Configuration variables ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import absolute_import, print_function, unicode_literals import os from datetime import timedelta from functools import partial import jsonref from celery.schedules import crontab from flask_principal import ActionNeed from invenio_access.permissions import Permission from invenio_app.config import APP_DEFAULT_SECURE_HEADERS from invenio_deposit.config import DEPOSIT_REST_DEFAULT_SORT, \ DEPOSIT_REST_FACETS, DEPOSIT_REST_SORT_OPTIONS from invenio_deposit.scopes import write_scope from invenio_deposit.utils import check_oauth2_scope from invenio_github.config import GITHUB_REMOTE_APP from invenio_github.errors import CustomGitHubMetadataError from invenio_oauthclient.contrib.orcid import REMOTE_APP as ORCID_REMOTE_APP from invenio_openaire.config import OPENAIRE_REST_DEFAULT_SORT, \ OPENAIRE_REST_ENDPOINTS, OPENAIRE_REST_FACETS, \ OPENAIRE_REST_SORT_OPTIONS from invenio_opendefinition.config import OPENDEFINITION_REST_ENDPOINTS from invenio_pidrelations.config import RelationType from invenio_records_rest.facets import range_filter, terms_filter from invenio_records_rest.sorter import geolocation_sort from invenio_records_rest.utils import allow_all from invenio_stats.aggregations import StatAggregator from invenio_stats.processors import EventsIndexer from invenio_stats.queries import ESTermsQuery from zenodo_accessrequests.config import ACCESSREQUESTS_RECORDS_UI_ENDPOINTS from zenodo.modules.deposit.utils import is_user_verified from zenodo.modules.github.schemas import CitationMetadataSchema from zenodo.modules.records.facets import custom_metadata_filter, \ geo_bounding_box_filter from zenodo.modules.records.permissions import deposit_delete_permission_factory, \ deposit_read_permission_factory, deposit_update_permission_factory, \ record_create_permission_factory from zenodo.modules.stats import current_stats_search_client from zenodo.modules.theme.ext import useragent_and_ip_limit_key from zenodo.modules.metrics.config import ZENODO_METRICS_CACHE_UPDATE_INTERVAL def _(x): """Identity function for string extraction.""" return x #: System sender email address ZENODO_SYSTEM_SENDER_EMAIL = 'system@zenodo.org' #: Email address of admins ZENODO_ADMIN_EMAIL = 'admin@zenodo.org' #: Email address for support. SUPPORT_EMAIL = "info@zenodo.org" MAIL_SUPPRESS_SEND = True # Application # =========== #: Disable Content Security Policy headers. APP_DEFAULT_SECURE_HEADERS['content_security_policy'] = {} # NOTE: These should be set explicitly inside ``invenio.cfg`` for development, # if one wants to run without ``FLASK_DEBUG`` enabled. # APP_DEFAULT_SECURE_HEADERS['force_https'] = False # APP_DEFAULT_SECURE_HEADERS['session_cookie_secure'] = False # DataCite # ======== #: DOI prefixes considered as local prefixes. ZENODO_LOCAL_DOI_PREFIXES = ["10.5072", "10.5281"] #: DataCite API - URL endpoint. PIDSTORE_DATACITE_URL = "https://mds.datacite.org" #: DataCite API - Disable test mode (we however use the test prefix). PIDSTORE_DATACITE_TESTMODE = False #: DataCite API - Prefix for minting DOIs in (10.5072 is a test prefix). PIDSTORE_DATACITE_DOI_PREFIX = "10.5072" #: DataCite MDS username. PIDSTORE_DATACITE_USERNAME = "CERN.ZENODO" #: DataCite MDS password. PIDSTORE_DATACITE_PASSWORD = "CHANGE_ME" #: DataCite updating rate. DATACITE_UPDATING_RATE_PER_HOUR = 1000 #: DataCite max description length DATACITE_MAX_DESCRIPTION_SIZE = 20000 #: Zenodo PID relations PIDRELATIONS_RELATION_TYPES = [ RelationType(0, 'version', 'Version', 'invenio_pidrelations.contrib.versioning:PIDVersioning', 'zenodo.modules.records.serializers.schemas.pidrelations:' 'VersionRelation'), RelationType(1, 'record_draft', 'Record Draft', 'invenio_pidrelations.contrib.records:RecordDraft', None), ] #: Enable the DataCite minding of DOIs after Deposit publishing DEPOSIT_DATACITE_MINTING_ENABLED = False # Debug # ===== #: Do not allow DebugToolbar to redirects redirects. DEBUG_TB_INTERCEPT_REDIRECTS = False # Assets # ====== #: Switch of assets debug. ASSETS_DEBUG = False #: Switch of automatic building. ASSETS_AUTO_BUILD = False #: Remove app.static_folder from source list of static folders. COLLECT_FILTER = 'zenodo.modules.theme.collect:collect_staticroot_removal' # Language # ======== #: Default language. BABEL_DEFAULT_LANGUAGE = 'en' #: Default timezone. BABEL_DEFAULT_TIMEZONE = 'Europe/Zurich' #: Other supported languages. I18N_LANGUAGES = [] # Celery # ====== #: Default broker (RabbitMQ on locahost). CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672//" #: Default Celery result backend. CELERY_RESULT_BACKEND = "redis://localhost:6379/1" #: Accepted content types for Celery. CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] #: Custom task routing CELERY_TASK_ROUTES = { # Low 'invenio_files_rest.tasks.verify_checksum': {'queue': 'low'}, 'invenio_github.tasks.sync_account': {'queue': 'low'}, 'zenodo.modules.sipstore.tasks.archive_sip': {'queue': 'low'}, 'zenodo.modules.spam.tasks.reindex_user_records': {'queue': 'low'}, 'zenodo.modules.spam.tasks.delete_spam_user': {'queue': 'low'}, 'zenodo.modules.spam.tasks.delete_record': {'queue': 'low'}, 'invenio_openaire.tasks.register_grant': {'queue': 'low'}, # Indexer 'invenio_indexer.tasks.process_bulk_queue': {'queue': 'celery-indexer'} } #: Beat schedule CELERY_BEAT_SCHEDULE = { 'embargo-updater': { 'task': 'zenodo.modules.records.tasks.update_expired_embargos', 'schedule': crontab(minute=2, hour=0), }, 'indexer': { 'task': 'invenio_indexer.tasks.process_bulk_queue', 'schedule': timedelta(minutes=5), 'kwargs': { 'es_bulk_kwargs': {'raise_on_error': False}, }, }, 'openaire-updater': { 'task': 'zenodo.modules.utils.tasks.update_search_pattern_sets', 'schedule': timedelta(hours=12), }, 'cleanup-indexed-deposits': { 'task': 'zenodo.modules.deposit.tasks.cleanup_indexed_deposits', 'schedule': timedelta(hours=2), }, 'session-cleaner': { 'task': 'invenio_accounts.tasks.clean_session_table', 'schedule': timedelta(hours=24), }, 'file-checks': { 'task': 'invenio_files_rest.tasks.schedule_checksum_verification', 'schedule': timedelta(hours=1), 'kwargs': { 'batch_interval': {'hours': 1}, 'frequency': {'days': 14}, 'max_count': 0, # Query taking into account only files with URI prefixes defined by # the FILES_REST_CHECKSUM_VERIFICATION_URI_PREFIXES config variable 'files_query': 'zenodo.modules.utils.files.checksum_verification_files_query', }, }, 'hard-file-checks': { 'task': 'invenio_files_rest.tasks.schedule_checksum_verification', 'schedule': timedelta(hours=1), 'kwargs': { 'batch_interval': {'hours': 1}, # Manually check and calculate checksums of files biannually 'frequency': {'days': 180}, # Split batches based on total files size 'max_size': 0, # Query taking into account only files with URI prefixes defined by # the FILES_REST_CHECKSUM_VERIFICATION_URI_PREFIXES config variable 'files_query': 'zenodo.modules.utils.files.checksum_verification_files_query', # Actual checksum calculation, instead of relying on a EOS query 'checksum_kwargs': {'use_default_impl': True}, }, }, 'sitemap-updater': { 'task': 'zenodo.modules.sitemap.tasks.update_sitemap_cache', 'schedule': timedelta(hours=24) }, 'file-integrity-report': { 'task': 'zenodo.modules.utils.tasks.file_integrity_report', 'schedule': crontab(minute=0, hour=7), # Every day at 07:00 UTC }, 'datacite-metadata-updater': { 'task': ( 'zenodo.modules.records.tasks.schedule_update_datacite_metadata'), 'schedule': timedelta(hours=1), 'kwargs': { 'max_count': DATACITE_UPDATING_RATE_PER_HOUR, } }, 'export': { 'task': 'zenodo.modules.exporter.tasks.export_job', 'schedule': crontab(minute=0, hour=4, day_of_month=1), 'kwargs': { 'job_id': 'records', } }, # Stats 'stats-process-events': { 'task': 'invenio_stats.tasks.process_events', 'schedule': timedelta(minutes=30), 'args': [('record-view', 'file-download')], }, 'stats-aggregate-events': { 'task': 'invenio_stats.tasks.aggregate_events', 'schedule': timedelta(hours=3), 'args': [( 'record-view-agg', 'record-view-all-versions-agg', 'record-download-agg', 'record-download-all-versions-agg', )], }, 'stats-update-record-statistics': { 'task': 'zenodo.modules.stats.tasks.update_record_statistics', 'schedule': crontab(minute=0, hour=1), # Every day at 01:00 UTC }, 'stats-export': { 'task': 'zenodo.modules.stats.tasks.export_stats', 'schedule': crontab(minute=0, hour=4), 'kwargs': { 'retry': True, } }, 'github-tokens-refresh': { 'task': 'invenio_github.tasks.refresh_accounts', 'schedule': crontab(minute=0, hour=3), }, 'openaire-failures-retry': { 'task': 'zenodo.modules.openaire.tasks.retry_openaire_failures', 'schedule': crontab(minute=0, hour=9), # Every day at 09:00 UTC }, 'metrics-calculate': { 'task': 'zenodo.modules.metrics.tasks.calculate_metrics', 'kwargs': { "metric_id": "openaire-nexus", }, 'schedule': ZENODO_METRICS_CACHE_UPDATE_INTERVAL, }, } # Cache # ========= #: Cache key prefix CACHE_KEY_PREFIX = "cache::" #: Host CACHE_REDIS_HOST = "localhost" #: Port CACHE_REDIS_PORT = 6379 #: DB CACHE_REDIS_DB = 0 #: URL of Redis db. CACHE_REDIS_URL = "redis://{0}:{1}/{2}".format( CACHE_REDIS_HOST, CACHE_REDIS_PORT, CACHE_REDIS_DB) #: Default cache type. CACHE_TYPE = "redis" #: Default cache URL for sessions. ACCOUNTS_SESSION_REDIS_URL = "redis://localhost:6379/2" #: Cache for storing access restrictions ACCESS_CACHE = 'invenio_cache:current_cache' #: Disable JSON Web Tokens ACCOUNTS_JWT_ENABLE = False # CSL Citation Formatter # ====================== #: Styles Endpoint for CSL CSL_STYLES_API_ENDPOINT = '/api/csl/styles' #: Records Endpoint for CSL CSL_RECORDS_API_ENDPOINT = '/api/records/' #: Template directory for CSL CSL_JSTEMPLATE_DIR = 'node_modules/invenio-csl-js/dist/templates/' #: Template for CSL citation result CSL_JSTEMPLATE_CITEPROC = 'templates/invenio_csl/citeproc.html' #: Template for CSL citation list item CSL_JSTEMPLATE_LIST_ITEM = 'templates/invenio_csl/item.html' #: Template for CSL error CSL_JSTEMPLATE_ERROR = os.path.join(CSL_JSTEMPLATE_DIR, 'error.html') #: Template for CSL loading CSL_JSTEMPLATE_LOADING = os.path.join(CSL_JSTEMPLATE_DIR, 'loading.html') #: Template for CSL typeahead CSL_JSTEMPLATE_TYPEAHEAD = os.path.join(CSL_JSTEMPLATE_DIR, 'typeahead.html') # Formatter # ========= #: List of allowed titles in badges. FORMATTER_BADGES_ALLOWED_TITLES = ['DOI', 'doi'] #: Mapping of titles. FORMATTER_BADGES_TITLE_MAPPING = {'doi': 'DOI'} # Frontpage # ========= #: Frontpage endpoint. FRONTPAGE_ENDPOINT = "zenodo_frontpage.index" # Logging # ======= #: Celery sentry logging LOGGING_SENTRY_CELERY = True # GitHub # ====== #: Repositories list template. GITHUB_TEMPLATE_INDEX = 'zenodo_github/settings/index.html' #: Repository detail view template. GITHUB_TEMPLATE_VIEW = 'zenodo_github/settings/view.html' #: Record serializer to use for serialize record metadata GITHUB_RECORD_SERIALIZER = 'zenodo.modules.records.serializers.githubjson_v1' #: Time period after which a GitHub account sync should be initiated. GITHUB_REFRESH_TIMEDELTA = timedelta(hours=3) #: GitHub webhook url override GITHUB_WEBHOOK_RECEIVER_URL = \ 'http://localhost:5000' \ '/api/hooks/receivers/github/events/?access_token={token}' #: Set Zenodo deposit class GITHUB_RELEASE_CLASS = 'zenodo.modules.github.api:ZenodoGitHubRelease' #: Set Zenodo deposit class GITHUB_DEPOSIT_CLASS = 'zenodo.modules.deposit.api:ZenodoDeposit' #: GitHub PID fetcher GITHUB_PID_FETCHER = 'zenodo_doi_fetcher' #: GitHub metadata file GITHUB_METADATA_FILE = '.zenodo.json' #: GitHub citation file GITHUB_CITATION_FILE = 'CITATION.cff' #: Github Citation Metadata Schema GITHUB_CITATION_METADATA_SCHEMA = partial( CitationMetadataSchema, context={'replace_refs': True}) #: GitHub error handlers GITHUB_ERROR_HANDLERS = [ ( 'zenodo.modules.deposit.errors.VersioningFilesError', 'zenodo.modules.github.error_handlers.versioning_files_error' ), ( 'github3.exceptions.AuthenticationFailed', 'zenodo.modules.github.error_handlers.authentification_failed' ), ( 'zenodo.modules.deposit.errors.MarshmallowErrors', 'zenodo.modules.github.error_handlers.marshmallow_error' ), ( CustomGitHubMetadataError, 'zenodo.modules.github.error_handlers.invalid_json_error' ), ( jsonref.JsonRefError, 'zenodo.modules.github.error_handlers.invalid_ref_error' ), ( Exception, 'zenodo.modules.github.error_handlers.default_error' ), ] # ( # 'invenio_github.errors.RepositoryAccessError', # 'zenodo.modules.github.error_handlers.repository_access_error' # ), # ( # 'sqlalchemy.lib.sqlalchemy.orm.exc.StaleDataError', # 'zenodo.modules.github.error_handlers.stale_data_error' # ), # ( # 'sqlalchemy.lib.sqlalchemy.exc.InvalidRequestError', # 'zenodo.modules.github.error_handlers.invalid_request_error' # ), # ( # 'elasticsearch.exceptions.ConnectionError', # 'zenodo.modules.github.error_handlers.connection_error' # ), # ( # 'elasticsearch.exceptions.ClientError', # 'zenodo.modules.github.error_handlers.client_error' # ), # ( # 'sqlalchemy.lib.sqlalchemy.exc.IntegrityError', # 'zenodo.modules.github.error_handlers.integrity_error' # ), # ( # 'ForbiddenError', # 'zenodo.modules.github.error_handlers.forbidden_error' # ), # ( # 'ServerError', # 'zenodo.modules.github.error_handlers.server_error' # ) #: SIPStore SIPSTORE_GITHUB_AGENT_JSONSCHEMA = 'sipstore/agent-githubclient-v1.0.0.json' #: Set OAuth client application config. SIPSTORE_ARCHIVER_DIRECTORY_BUILDER = \ 'zenodo.modules.sipstore.utils.archive_directory_builder' #: Set the builder for archived SIPs directory structure SIPSTORE_ARCHIVER_LOCATION_NAME = 'archive' #: Set the name of the Location object holding the archive URI SIPSTORE_ARCHIVER_METADATA_TYPES = ['json', 'marcxml'] #: Set the names of SIPMetadataType(s), which are to be archived. SIPSTORE_ARCHIVER_SIPFILE_NAME_FORMATTER = \ 'invenio_sipstore.archivers.utils.secure_sipfile_name_formatter' #: Set the SIPFile name formatter to write secure filenames SIPSTORE_ARCHIVER_SIPMETADATA_NAME_FORMATTER = \ 'zenodo.modules.sipstore.utils.sipmetadata_name_formatter' #: Set the SIPMetadata name formatter: "record-{json/marcxml}.{json/xml}" SIPSTORE_BAGIT_TAGS = [ ('Source-Organization', 'European Organization for Nuclear Research'), ('Organization-Address', 'CERN, CH-1211 Geneva 23, Switzerland'), ('Bagging-Date', None), # Autogenerated ('Payload-Oxum', None), # Autogenerated ('External-Identifier', None), # Autogenerated ('External-Description', ("BagIt archive of Zenodo record. " "Description of the payload structure and data interpretation " "available at https://doi.org/10.5281/zenodo.841781")), ] SIPSTORE_ARCHIVER_WRITING_ENABLED = False #: Flag controlling whether writing files to disk should be enabled GITHUB_REMOTE_APP.update(dict( description='Software collaboration platform, with one-click ' 'software preservation in Zenodo.', )) GITHUB_REMOTE_APP['params']['request_token_params']['scope'] = \ 'user:email,admin:repo_hook,read:org' #: Definition of OAuth client applications. OAUTHCLIENT_REMOTE_APPS = dict( github=GITHUB_REMOTE_APP, orcid=ORCID_REMOTE_APP, ) #: Change default template for oauth sign up. OAUTHCLIENT_SIGNUP_TEMPLATE = 'zenodo_theme/security/oauth_register_user.html' #: Stop oauthclient from taking over template. OAUTHCLIENT_TEMPLATE_KEY = None #: Credentials for GitHub (must be changed to work). GITHUB_APP_CREDENTIALS = dict( consumer_key="CHANGE_ME", consumer_secret="CHANGE_ME", ) #: Credentials for ORCID (must be changed to work). ORCID_APP_CREDENTIALS = dict( consumer_key="CHANGE_ME", consumer_secret="CHANGE_ME", ) # OpenAIRE # ======== #: Hostname for JSON Schemas in OpenAIRE. OPENAIRE_SCHEMAS_HOST = 'zenodo.org' #: Hostname for OpenAIRE's grant resolver. OPENAIRE_JSONRESOLVER_GRANTS_HOST = 'dx.zenodo.org' #: OpenAIRE data source IDs for Zenodo. OPENAIRE_ZENODO_IDS = { 'publication': 'opendoar____::2659', 'dataset': 'opendoar____::2659', 'software': 'opendoar____::2659', 'other': 'opendoar____::2659' } #: OpenAIRE ID namespace prefixes for Zenodo. OPENAIRE_NAMESPACE_PREFIXES = { 'publication': 'od______2659', 'dataset': 'od______2659', 'software': 'od______2659', 'other': 'od______2659' } #: OpenAIRE API endpoint. OPENAIRE_API_URL = 'http://dev.openaire.research-infrastructures.eu/is/mvc/api/results' OPENAIRE_API_URL_BETA = None #: OpenAIRE API endpoint username. OPENAIRE_API_USERNAME = None #: OpenAIRE API endpoint password. OPENAIRE_API_PASSWORD = None #: URL to OpenAIRE portal. OPENAIRE_PORTAL_URL = 'https://explore.openaire.eu' #: OpenAIRE community identifier prefix. OPENAIRE_COMMUNITY_IDENTIFIER_PREFIX = 'https://openaire.eu/communities' #: Enable sending published records for direct indexing at OpenAIRE. OPENAIRE_DIRECT_INDEXING_ENABLED = False # OpenDefinition # ============== #: Hostname for JSON Schemas in OpenAIRE. OPENDEFINITION_SCHEMAS_HOST = 'zenodo.org' #: Hostname for OpenAIRE's grant resolver. OPENDEFINITION_JSONRESOLVER_HOST = 'dx.zenodo.org' # JSON Schemas # ============ #: Hostname for JSON Schemas. JSONSCHEMAS_HOST = 'zenodo.org' # Deposit # ======= #: PID minter used during record creation. DEPOSIT_PID_MINTER = 'zenodo_record_minter' _PID = 'pid(depid,record_class="zenodo.modules.deposit.api:ZenodoDeposit")' #: Template for deposit list view. DEPOSIT_SEARCH_API = '/api/deposit/depositions' #: Mimetype for deposit search. DEPOSIT_SEARCH_MIMETYPE = 'application/vnd.zenodo.v1+json' #: Template for deposit list view. DEPOSIT_UI_INDEX_TEMPLATE = 'zenodo_deposit/index.html' #: Template to use for UI. DEPOSIT_UI_NEW_TEMPLATE = 'zenodo_deposit/edit.html' #: Template for <invenio-records-form> DEPOSIT_UI_JSTEMPLATE_FORM = 'templates/zenodo_deposit/form.html' #: Template for <invenio-records-actions> DEPOSIT_UI_JSTEMPLATE_ACTIONS = 'templates/zenodo_deposit/actions.html' #: Template for <invenio-files-upload-zone> DEPOSIT_UI_JSTEMPLATE_UPLOADZONE = 'templates/zenodo_deposit/upload.html' #: Template for <invenio-files-list> DEPOSIT_UI_JSTEMPLATE_FILESLIST = 'templates/zenodo_deposit/list.html' #: Endpoint for deposit. DEPOSIT_UI_ENDPOINT = '{scheme}://{host}/deposit/{pid_value}' #: Template path for angular form elements. DEPOSIT_FORM_TEMPLATES_BASE = 'templates/zenodo_deposit' #: Specific templates for the various deposit form elements. DEPOSIT_FORM_TEMPLATES = { 'actions': 'actions.html', 'array': 'array.html', 'button': 'button.html', 'checkbox': 'checkbox.html', 'ckeditor': 'ckeditor.html', 'default': 'default.html', 'fieldset': 'fieldset.html', 'radios_inline': 'radios_inline.html', 'radios': 'radios.html', 'select': 'select.html', 'strapselect': 'strapselect.html', 'textarea': 'textarea.html', 'uiselect': 'uiselect.html', 'grantselect': 'grantselect.html', } #: Allow list of contributor types. DEPOSIT_CONTRIBUTOR_TYPES = [ dict(label='Contact person', marc='prc', datacite='ContactPerson'), dict(label='Data collector', marc='col', datacite='DataCollector'), dict(label='Data curator', marc='cur', datacite='DataCurator'), dict(label='Data manager', marc='dtm', datacite='DataManager'), dict(label='Distributor', marc='dst', datacite='Distributor'), dict(label='Editor', marc='edt', datacite='Editor'), dict(label='Hosting institution', marc='his', datacite='HostingInstitution'), dict(label='Other', marc='oth', datacite='Other'), dict(label='Producer', marc='pro', datacite='Producer'), dict(label='Project leader', marc='pdr', datacite='ProjectLeader'), dict(label='Project manager', marc='rth', datacite='ProjectManager'), dict(label='Project member', marc='rtm', datacite='ProjectMember'), dict(label='Registration agency', marc='cor', datacite='RegistrationAgency'), dict(label='Registration authority', marc='cor', datacite='RegistrationAuthority'), dict(label='Related person', marc='oth', datacite='RelatedPerson'), dict(label='Research group', marc='rtm', datacite='ResearchGroup'), dict(label='Researcher', marc='res', datacite='Researcher'), dict(label='Rights holder', marc='cph', datacite='RightsHolder'), dict(label='Sponsor', marc='spn', datacite='Sponsor'), dict(label='Supervisor', marc='dgs', datacite='Supervisor'), dict(label='Work package leader', marc='led', datacite='WorkPackageLeader'), ] DEPOSIT_CONTRIBUTOR_MARC2DATACITE = { x['marc']: x['datacite'] for x in DEPOSIT_CONTRIBUTOR_TYPES } DEPOSIT_CONTRIBUTOR_DATACITE2MARC = { x['datacite']: x['marc'] for x in DEPOSIT_CONTRIBUTOR_TYPES } DEPOSIT_CONTRIBUTOR_TYPES_LABELS = { x['datacite']: x['label'] for x in DEPOSIT_CONTRIBUTOR_TYPES } #: Default JSON Schema for deposit. DEPOSIT_DEFAULT_JSONSCHEMA = 'deposits/records/record-v1.0.0.json' #: Angular Schema Form for deposit. DEPOSIT_DEFAULT_SCHEMAFORM = 'json/zenodo_deposit/deposit_form.json' #: JSON Schema for deposit Angular Schema Form. DEPOSIT_FORM_JSONSCHEMA = 'deposits/records/legacyrecord.json' #: Template for deposit records API. DEPOSIT_RECORDS_API = '/api/deposit/depositions/{pid_value}' #: Alerts shown when actions are completed on deposit. DEPOSIT_UI_RESPONSE_MESSAGES = dict( self=dict( message="Saved successfully." ), delete=dict( message="Deleted successfully." ), discard=dict( message="Changes discarded successfully." ), publish=dict( message="Published successfully." ), ) #: REST API configuration. DEPOSIT_REST_ENDPOINTS = dict( depid=dict( pid_type='depid', pid_minter='zenodo_deposit_minter', pid_fetcher='zenodo_deposit_fetcher', record_class='zenodo.modules.deposit.api:ZenodoDeposit', record_loaders={ 'application/json': ( 'zenodo.modules.deposit.loaders:legacyjson_v1'), # 'application/vnd.zenodo.v1+json': ( # 'zenodo.modules.deposit.loaders:deposit_json_v1'), }, record_serializers={ 'application/json': ( 'zenodo.modules.records.serializers' ':deposit_legacyjson_v1_response'), 'application/vnd.zenodo.v1+json': ( 'zenodo.modules.records.serializers:deposit_json_v1_response'), }, search_class='invenio_deposit.search:DepositSearch', search_factory_imp='zenodo.modules.deposit.query.search_factory', search_serializers={ 'application/json': ( 'zenodo.modules.records.serializers' ':deposit_legacyjson_v1_search'), 'application/vnd.zenodo.v1+json': ( 'zenodo.modules.records.serializers:deposit_json_v1_search'), }, files_serializers={ 'application/json': ( 'zenodo.modules.records.serializers' ':deposit_legacyjson_v1_files_response'), }, list_route='/deposit/depositions', item_route='/deposit/depositions/<{0}:pid_value>'.format(_PID), file_list_route=( '/deposit/depositions/<{0}:pid_value>/files'.format(_PID)), file_item_route=( '/deposit/depositions/<{0}:pid_value>/files/<file_key:key>'.format( _PID)), default_media_type='application/json', links_factory_imp='zenodo.modules.deposit.links:links_factory', create_permission_factory_imp=check_oauth2_scope( lambda record: record_create_permission_factory( record=record).can(), write_scope.id), read_permission_factory_imp=deposit_read_permission_factory, update_permission_factory_imp=check_oauth2_scope( lambda record: deposit_update_permission_factory( record=record).can(), write_scope.id), delete_permission_factory_imp=check_oauth2_scope( lambda record: deposit_delete_permission_factory( record=record).can(), write_scope.id), max_result_window=10000, ), ) #: Deposit UI endpoints DEPOSIT_RECORDS_UI_ENDPOINTS = { 'depid': { 'pid_type': 'depid', 'route': '/deposit/<pid_value>', 'template': 'zenodo_deposit/edit.html', 'record_class': 'zenodo.modules.deposit.api:ZenodoDeposit', 'view_imp': 'zenodo.modules.deposit.views.default_view_method', }, } #: Endpoint for uploading files. DEPOSIT_FILES_API = u'/api/files' #: Size after which files are chunked when uploaded DEPOSIT_FILEUPLOAD_CHUNKSIZE = 15 * 1024 * 1024 # 15 MiB #: Maximum upload file size via application/mulitpart-formdata MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 100 MiB # SIPStore # ======== #: Default JSON schema for the SIP agent SIPSTORE_DEFAULT_AGENT_JSONSCHEMA = 'sipstore/agent-webclient-v1.0.0.json' # Default SIP agent factory SIPSTORE_AGENT_FACTORY = 'zenodo.modules.sipstore.utils:build_agent_info' #: Enable the agent JSON schema SIPSTORE_AGENT_JSONSCHEMA_ENABLED = True #: Max length of SIPFile.filepath SIPSTORE_FILEPATH_MAX_LEN = 1000 # Records # ======= #: Standard record removal reasons. ZENODO_REMOVAL_REASONS = [ ('', ''), ('spam', 'Spam record, removed by Zenodo staff.'), ('uploader', 'Record removed on request by uploader.'), ('takedown', 'Record removed on request by third-party.'), ] ZENODO_REANA_HOSTS = ["reana.cern.ch", "reana-qa.cern.ch", "reana-dev.cern.ch"] ZENODO_REANA_LAUNCH_URL_BASE = "https://reana.cern.ch/launch" ZENODO_REANA_BADGE_IMG_URL = "https://www.reana.io/static/img/badges/launch-on-reana.svg" ZENODO_REANA_BADGES_ENABLED = True #: Mapping of old export formats to new content type. ZENODO_RECORDS_EXPORTFORMATS = { 'dcite': dict( title='DataCite XML', serializer='zenodo.modules.records.serializers.datacite_v41', ), 'dcite3': dict( title='DataCite XML', serializer='zenodo.modules.records.serializers.datacite_v31', ), 'dcite4': dict( title='DataCite XML', serializer='zenodo.modules.records.serializers.datacite_v41', ), 'hm': dict( title='MARC21 XML', serializer='zenodo.modules.records.serializers.marcxml_v1', ), 'hx': dict( title='BibTeX', serializer='zenodo.modules.records.serializers.bibtex_v1', ), 'xd': dict( title='Dublin Core', serializer='zenodo.modules.records.serializers.dc_v1', ), 'xm': dict( title='MARC21 XML', serializer='zenodo.modules.records.serializers.marcxml_v1', ), 'json': dict( title='JSON', serializer='zenodo.modules.records.serializers.json_v1', ), 'schemaorg_jsonld': dict( title='JSON-LD (schema.org)', serializer='zenodo.modules.records.serializers.schemaorg_jsonld_v1', ), 'csl': dict( title='Citation Style Language JSON', serializer='zenodo.modules.records.serializers.csl_v1', ), 'cp': dict( title='Citation', serializer='zenodo.modules.records.serializers.citeproc_v1', ), # Generic serializer 'ef': dict( title='Formats', serializer='zenodo.modules.records.serializers.extra_formats_v1', ), 'geojson': dict( title='GeoJSON', serializer='zenodo.modules.records.serializers.geojson_v1', ), 'dcat': dict( title='DCAT', serializer='zenodo.modules.records.serializers.dcat_v1', ), # Unsupported formats. 'xe': None, 'xn': None, 'xw': None, } #: Endpoints for displaying records. RECORDS_UI_ENDPOINTS = dict( recid=dict( pid_type='recid', route='/record/<pid_value>', template='zenodo_records/record_detail.html', record_class='zenodo.modules.records.api:ZenodoRecord', ), recid_export=dict( pid_type='recid', route='/record/<pid_value>/export/<any({0}):format>'.format(", ".join( list(ZENODO_RECORDS_EXPORTFORMATS.keys()))), template='zenodo_records/record_export.html', view_imp='zenodo.modules.records.views.records_ui_export', record_class='zenodo.modules.records.api:ZenodoRecord', ), recid_preview=dict( pid_type='recid', route='/record/<pid_value>/preview/<path:filename>', view_imp='invenio_previewer.views.preview', record_class='zenodo.modules.records.api:ZenodoRecord', ), recid_thumbnail=dict( pid_type='recid', route='/record/<pid_value>/thumb<thumbnail_size>', view_imp='zenodo.modules.records.views.record_thumbnail', record_class='zenodo.modules.records.api:ZenodoRecord', ), recid_files=dict( pid_type='recid', route='/record/<pid_value>/files/<path:filename>', view_imp='invenio_records_files.utils.file_download_ui', record_class='zenodo.modules.records.api:ZenodoRecord', ), recid_extra_formats=dict( pid_type='recid', route='/record/<pid_value>/formats', view_imp='zenodo.modules.records.views.record_extra_formats', record_class='zenodo.modules.records.api:ZenodoRecord', ), ) RECORDS_UI_ENDPOINTS.update(ACCESSREQUESTS_RECORDS_UI_ENDPOINTS) #: Endpoint for record ui. RECORDS_UI_ENDPOINT = '{scheme}://{host}/record/{pid_value}' #: Permission factory for records-ui and deposit-ui RECORDS_UI_DEFAULT_PERMISSION_FACTORY = \ "zenodo.modules.records.permissions:deposit_read_permission_factory" #: Default tombstone template. RECORDS_UI_TOMBSTONE_TEMPLATE = "zenodo_records/tombstone.html" ZENODO_RECORDS_UI_LINKS_FORMAT = "https://zenodo.org/record/{recid}" #: Files REST permission factory FILES_REST_PERMISSION_FACTORY = \ 'zenodo.modules.records.permissions:files_permission_factory' #: Max object key length FILES_REST_OBJECT_KEY_MAX_LEN = 1000 #: Max URI length FILES_REST_FILE_URI_MAX_LEN = 1000 #: URI prefixes of files their checksums should be verified FILES_REST_CHECKSUM_VERIFICATION_URI_PREFIXES = [ # 'root://eospublic' ] #: URL template for generating URLs outside the application/request context FILES_REST_ENDPOINT = '{scheme}://{host}/api/files/{bucket}/{key}' #: Records REST API endpoints. RECORDS_API = '/api/records/{pid_value}' RECORDS_REST_ENDPOINTS = dict( recid=dict( pid_type='recid', pid_minter='zenodo_record_minter', pid_fetcher='zenodo_record_fetcher', list_route='/records/', item_route='/records/<{0}:pid_value>'.format( 'pid(recid,record_class="zenodo.modules.records.api:ZenodoRecord")' ), search_index='records', record_class='zenodo.modules.records.api:ZenodoRecord', search_type=['record-v1.0.0'], search_factory_imp='zenodo.modules.records.query.search_factory', record_serializers={ 'application/json': ( 'zenodo.modules.records.serializers.legacyjson_v1_response'), 'application/vnd.zenodo.v1+json': ( 'zenodo.modules.records.serializers.json_v1_response'), 'application/ld+json': ( 'zenodo.modules.records.serializers.schemaorg_jsonld_v1_response'), 'application/marcxml+xml': ( 'zenodo.modules.records.serializers.marcxml_v1_response'), 'application/x-bibtex': ( 'zenodo.modules.records.serializers.bibtex_v1_response'), 'application/x-datacite+xml': ( 'zenodo.modules.records.serializers.datacite_v31_response'), 'application/x-datacite-v41+xml': ( 'zenodo.modules.records.serializers.datacite_v41_response'), 'application/x-dc+xml': ( 'zenodo.modules.records.serializers.dc_v1_response'), 'application/vnd.citationstyles.csl+json': ( 'zenodo.modules.records.serializers.csl_v1_response'), 'application/dcat+xml': ( 'zenodo.modules.records.serializers.dcat_response'), 'text/x-bibliography': ( 'zenodo.modules.records.serializers.citeproc_v1_response'), 'application/vnd.geo+json': ( 'zenodo.modules.records.serializers.geojson_v1_response'), }, search_serializers={ 'application/json': ( 'zenodo.modules.records.serializers:legacyjson_v1_search'), 'application/vnd.zenodo.v1+json': ( 'zenodo.modules.records.serializers:json_v1_search'), 'application/marcxml+xml': ( 'zenodo.modules.records.serializers.marcxml_v1_search'), 'application/x-bibtex': ( 'zenodo.modules.records.serializers:bibtex_v1_search'), 'application/x-datacite+xml': ( 'zenodo.modules.records.serializers.datacite_v31_search'), 'application/x-dc+xml': ( 'zenodo.modules.records.serializers.dc_v1_search'), }, default_media_type='application/vnd.zenodo.v1+json', read_permission_factory_imp=allow_all, ), ) # Add record serializer aliases for use with the "?format=<mimetype>" parameter RECORDS_REST_ENDPOINTS['recid']['record_serializers_aliases'] = { s: s for s in RECORDS_REST_ENDPOINTS['recid']['record_serializers'] } # Default OpenAIRE API endpoints. RECORDS_REST_ENDPOINTS.update(OPENAIRE_REST_ENDPOINTS) # Add fuzzy matching for licenses OPENDEFINITION_REST_ENDPOINTS['od_lic']['suggesters']['text']['completion']['fuzzy'] = True RECORDS_REST_ENDPOINTS.update(OPENDEFINITION_REST_ENDPOINTS) #: Sort options records REST API. RECORDS_REST_SORT_OPTIONS = dict( records=dict( bestmatch=dict( fields=['-_score'], title='Best match', default_order='asc', order=1, ), mostviewed=dict( fields=['-_stats.version_views'], title='Most viewed', default_order='asc', order=1, ), mostrecent=dict( fields=['-_created'], title='Most recent', default_order='asc', order=2, ), publication_date=dict( fields=['publication_date'], title='Publication date', default_order='desc', order=3, ), conference_session=dict( fields=['meeting.session', '-meeting.session_part'], title='Conference session', default_order='desc', order=4, ), journal=dict( fields=[ 'journal.year', 'journal.volume', 'journal.issue', 'journal.pages', ], title='Journal', default_order='desc', order=6, ), distance=dict( title='Distance', fields=[geolocation_sort('location.point', 'center', 'km')], default_order='asc', display=False, order=2, ), version=dict( # TODO: There are a lot of implications when sorting record results # by versions and using the `_score`... Maybe there's some # elaborate ES syntax/API (eg. `constant_score`) to get a better # version-friendly sorted result. fields=['conceptrecid', 'relations.version.index'], title='Version', default_order='desc', order=7, ) ) ) def safelist_sort(_): """Always show safelisted records first.""" return {'_safelisted': {'order': 'desc'}} # Apply safelist sorting to all record sorting options for k in RECORDS_REST_SORT_OPTIONS['records']: # NOTE: We insert in the beginning RECORDS_REST_SORT_OPTIONS['records'][k]['fields'].insert(0, safelist_sort) DEPOSIT_REST_SORT_OPTIONS['deposits'].update( dict( distance=dict( title=_('Distance'), fields=[geolocation_sort('location.point', 'center', 'km')], default_order='asc', display=False, order=2, ), version=dict( # FIXME: No `_score` in deposit search response... fields=['conceptrecid', 'relations.version.index'], title='Version', default_order='desc', order=7, ) ) ) RECORDS_REST_SORT_OPTIONS.update(OPENAIRE_REST_SORT_OPTIONS) RECORDS_REST_SORT_OPTIONS.update(DEPOSIT_REST_SORT_OPTIONS) #: Default sort for records REST API. RECORDS_REST_DEFAULT_SORT = dict( records=dict(query='bestmatch', noquery='mostrecent'), ) RECORDS_REST_DEFAULT_SORT.update(OPENAIRE_REST_DEFAULT_SORT) RECORDS_REST_DEFAULT_SORT.update(DEPOSIT_REST_DEFAULT_SORT) #: Defined facets for records REST API. RECORDS_REST_FACETS = dict( records=dict( default_aggs=['access_right', 'type', 'file_type', 'keywords'], aggs=dict( type=dict( terms=dict(field='resource_type.type'), aggs=dict( subtype=dict( terms=dict(size=20, field='resource_type.subtype'), ) ) ), access_right=dict( terms=dict(field='access_right'), ), file_type=dict( terms=dict(field='filetype'), ), keywords=dict( terms=dict(field='keywords'), ), communities=dict( terms=dict(field='communities'), ), related_identifiers_type=dict( terms=dict(field='related.resource_type.type'), aggs=dict( related_identifiers_subtype=dict( terms=dict(field='related.resource_type.subtype'), ) ) ), publication_date=dict( date_histogram=dict( field='publication_date', interval='1y', format='yyyy' ) ), ), filters=dict( communities=terms_filter('communities'), custom=custom_metadata_filter('custom'), provisional_communities=terms_filter('provisional_communities'), bounds=geo_bounding_box_filter( 'bounds', 'locations.point', type='indexed'), publication_date=range_filter( field='publication_date', format='yyyy' ), ), post_filters=dict( access_right=terms_filter('access_right'), file_type=terms_filter('filetype'), keywords=terms_filter('keywords'), subtype=terms_filter('resource_type.subtype'), type=terms_filter('resource_type.type'), related_identifiers_type=terms_filter( 'related.resource_type.type'), related_identifiers_subtype=terms_filter( 'related.resource_type.subtype'), ) ) ) #: Update deposit facets as well DEPOSIT_REST_FACETS['deposits'].setdefault('filters', {}) DEPOSIT_REST_FACETS['deposits']['filters'].update(dict( communities=terms_filter('communities'), custom=custom_metadata_filter('custom'), provisional_communities=terms_filter('provisional_communities'), locations=geo_bounding_box_filter( 'locations', 'locations.point', type='indexed'), )) # TODO: Remove `grants` aggregations until # https://github.com/zenodo/zenodo/issues/1909 is fixed OPENAIRE_REST_FACETS.pop('grants', None) RECORDS_REST_FACETS.update(OPENAIRE_REST_FACETS) RECORDS_REST_FACETS.update(DEPOSIT_REST_FACETS) RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS = { 'query_parsing_exception': ( 'invenio_records_rest.views' ':elasticsearch_query_parsing_exception_handler' ), 'token_mgr_error': ( 'invenio_records_rest.views' ':elasticsearch_query_parsing_exception_handler' ), } """Handlers for ElasticSearch error codes.""" # Previewer # ========= #: Basic bundle which includes Font-Awesome/Bootstrap. PREVIEWER_BASE_CSS_BUNDLES = ['zenodo_theme_css'] #: Basic bundle which includes Bootstrap/jQuery. PREVIEWER_BASE_JS_BUNDLES = ['zenodo_theme_js'] #: Number of bytes read by CSV previewer to validate the file. PREVIEWER_CSV_VALIDATION_BYTES = 16 * 1024 #: Allowed delimiters when detecting CSV dialect PREVIEWER_CSV_SNIFFER_ALLOWED_DELIMITERS = [',', ';', '\t', '|', ' ', ':'] #: Max file size to preview for images PREVIEWER_MAX_IMAGE_SIZE_BYTES = 5 * 1024 * 1024 #: List of previewers (adds IIIF previewer). PREVIEWER_PREFERENCE = [ 'csv_dthreejs', 'iiif_image', 'simple_image', # 'json_prismjs', # 'xml_prismjs', 'mistune', 'pdfjs', # 'ipynb', 'zip', ] # IIIF # ==== #: Improve quality of image resampling using better algorithm IIIF_RESIZE_RESAMPLE = 'PIL.Image:BICUBIC' #: Use the Redis storage backend for caching IIIF images # TODO: Fix Python 3 caching key issue to enable: # https://github.com/inveniosoftware/flask-iiif/issues/66 # IIIF_CACHE_HANDLER = 'flask_iiif.cache.redis:ImageRedisCache' # Redis storage for thumbnails caching. IIIF_CACHE_REDIS_URL = CACHE_REDIS_URL # Precached thumbnails CACHED_THUMBNAILS = { '10': '10,', '50': '50,', '100': '100,', '250': '250,', '750': '750,', '1200': '1200,' } # OAI-PMH # ======= #: Index to use for the OAI-PMH server. OAISERVER_RECORD_INDEX = 'records' #: OAI identifier prefix OAISERVER_ID_PREFIX = 'oai:zenodo.org:' #: Managed OAI identifier prefixes OAISERVER_MANAGED_ID_PREFIXES = [OAISERVER_ID_PREFIX, 'oai:openaire.cern.ch:', ] #: Number of records to return per page in OAI-PMH results. OAISERVER_PAGE_SIZE = 100 #: Increase resumption token expire time. OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME = 2 * 60 #: PIDStore fetcher for OAI ID control numbers OAISERVER_CONTROL_NUMBER_FETCHER = 'zenodo_record_fetcher' #: Support email for OAI-PMH. OAISERVER_ADMIN_EMAILS = [SUPPORT_EMAIL] #: Do not register signals to automatically update records on updates. OAISERVER_REGISTER_RECORD_SIGNALS = False #: Do not register signals to automatically update records on oaiset updates. OAISERVER_REGISTER_OAISET_SIGNALS = False #: Metadata formats for OAI-PMH server OAISERVER_METADATA_FORMATS = { 'marcxml': { 'namespace': 'http://www.loc.gov/MARC21/slim', 'schema': 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_marc21_v1', }, 'marc21': { 'namespace': 'http://www.loc.gov/MARC21/slim', 'schema': 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_marc21_v1', }, 'datacite4': { 'namespace': 'http://datacite.org/schema/kernel-4', 'schema': 'http://schema.datacite.org/meta/kernel-4.1/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_datacite_v41', }, 'datacite3': { 'namespace': 'http://datacite.org/schema/kernel-3', 'schema': 'http://schema.datacite.org/meta/kernel-3/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_datacite_v31', }, 'datacite': { 'namespace': 'http://datacite.org/schema/kernel-4', 'schema': 'http://schema.datacite.org/meta/kernel-4.1/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_datacite_v41', }, 'dcat': { 'namespace': 'https://www.w3.org/ns/dcat', 'schema': 'http://schema.datacite.org/meta/kernel-4.1/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_dcat_v1', }, 'oai_datacite': { 'namespace': 'http://datacite.org/schema/kernel-3', 'schema': 'http://schema.datacite.org/meta/kernel-3/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_oai_datacite', }, 'oai_datacite3': { 'namespace': 'http://datacite.org/schema/kernel-3', 'schema': 'http://schema.datacite.org/meta/kernel-3/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_oai_datacite', }, 'oai_datacite4': { 'namespace': 'http://datacite.org/schema/kernel-4', 'schema': 'http://schema.datacite.org/meta/kernel-4.1/metadata.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_oai_datacite_v41', }, 'oai_dc': { 'namespace': 'http://www.openarchives.org/OAI/2.0/oai_dc/', 'schema': 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd', 'serializer': 'zenodo.modules.records.serializers.oaipmh_oai_dc', } } # Relative URL to XSL Stylesheet, placed under `modules/records/static`. OAISERVER_XSL_URL = '/static/xsl/oai2.xsl' # REST # ==== #: Enable CORS support. REST_ENABLE_CORS = True #: Enable specifying export format via querystring REST_MIMETYPE_QUERY_ARG_NAME = 'format' # OAuth2 Server # ============= #: Include '$' and "'" to cover various issues with search. OAUTH2SERVER_ALLOWED_URLENCODE_CHARACTERS = '=&;:%+~,*@!()/?$\'"' """Special characters that should be valid inside a query string.""" # Accounts # ======== #: Recaptcha public key (change to enable). RECAPTCHA_PUBLIC_KEY = None #: Recaptcha private key (change to enable). RECAPTCHA_PRIVATE_KEY = None #: User registration template. SECURITY_REGISTER_USER_TEMPLATE = \ "zenodo_theme/security/register_user.html" #: Login registration template. SECURITY_LOGIN_USER_TEMPLATE = \ "zenodo_theme/security/login_user.html" SECURITY_CONFIRM_SALT = "CHANGE_ME" SECURITY_EMAIL_SENDER = SUPPORT_EMAIL SECURITY_EMAIL_SUBJECT_REGISTER = _("Welcome to Zenodo!") SECURITY_LOGIN_SALT = "CHANGE_ME" SECURITY_PASSWORD_SALT = "CHANGE_ME" SECURITY_REMEMBER_SALT = "CHANGE_ME" SECURITY_RESET_SALT = "CHANGE_ME" SECURITY_PASSWORD_HASH = "pbkdf2_sha512" SECURITY_PASSWORD_SCHEMES = [ 'pbkdf2_sha512', 'sha512_crypt', 'invenio_aes_encrypted_email'] SECURITY_DEPRECATED_PASSWORD_SCHEMES = [ 'sha512_crypt', 'invenio_aes_encrypted_email'] #: Session and User ID headers ACCOUNTS_USERINFO_HEADERS = True # Search # ====== #: Default API endpoint for search UI. SEARCH_UI_SEARCH_API = "/api/records/" #: Accept header fro search-js SEARCH_UI_SEARCH_MIMETYPE = "application/vnd.zenodo.v1+json" #: Default template for search UI. SEARCH_UI_SEARCH_TEMPLATE = "zenodo_search_ui/search.html" #: Angular template for rendering search results. SEARCH_UI_JSTEMPLATE_RESULTS = "templates/zenodo_search_ui/results.html" #: Angular template for rendering search facets. SEARCH_UI_JSTEMPLATE_FACETS = "templates/zenodo_search_ui/facets.html" #: Angular template for rendering search errors. SEARCH_UI_JSTEMPLATE_ERROR = "templates/zenodo_search_ui/error.html" #: Default Elasticsearch document type. SEARCH_DOC_TYPE_DEFAULT = None #: Do not map any keywords. SEARCH_ELASTIC_KEYWORD_MAPPING = {} #: Only create indexes we actually need. SEARCH_MAPPINGS = [ 'deposits', 'funders', 'grants', 'licenses', 'records', ] #: ElasticSearch index prefix SEARCH_INDEX_PREFIX = 'zenodo-dev-' # Communities # =========== #: Override templates to use custom search-js COMMUNITIES_COMMUNITY_TEMPLATE = "zenodo_theme/communities/base.html" #: Override templates to use custom search-js COMMUNITIES_CURATE_TEMPLATE = "zenodo_theme/communities/curate.html" #: Override templates to use custom search-js COMMUNITIES_SEARCH_TEMPLATE = "zenodo_theme/communities/search.html" #: Override detail page template COMMUNITIES_DETAIL_TEMPLATE = "zenodo_theme/communities/detail.html" #: Override about page template COMMUNITIES_ABOUT_TEMPLATE = "zenodo_theme/communities/about.html" #: Angular template for rendering search results for curation. COMMUNITIES_JSTEMPLATE_RESULTS_CURATE = \ "templates/zenodo_search_ui/results_curate.html" #: Email sender for communities emails. COMMUNITIES_REQUEST_EMAIL_SENDER = SUPPORT_EMAIL # Theme # ===== #: Default site name. THEME_SITENAME = _("Zenodo") #: Default site URL (used only when not in a context - e.g. like celery tasks). THEME_SITEURL = "http://localhost:5000" #: Endpoint for breadcrumb root. THEME_BREADCRUMB_ROOT_ENDPOINT = 'zenodo_frontpage.index' #: Twitter handle. THEME_TWITTERHANDLE = "@zenodo_org" #: Path to logo file. THEME_LOGO = "img/zenodo.svg" #: Google Site Verification ids. THEME_GOOGLE_SITE_VERIFICATION = [ "5fPGCLllnWrvFxH9QWI0l1TadV7byeEvfPcyK2VkS_s", "Rp5zp04IKW-s1IbpTOGB7Z6XY60oloZD5C3kTM-AiY4" ] #: Piwik site id. THEME_PIWIK_ID = None THEME_MATHJAX_CDN = ( '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js' '?config=TeX-AMS-MML_HTMLorMML' ) #: Base template for entire site. BASE_TEMPLATE = "zenodo_theme/page.html" #: Cover template for entire site. COVER_TEMPLATE = "zenodo_theme/page_cover.html" #: Settings template for entire site. SETTINGS_TEMPLATE = "invenio_theme/page_settings.html" #: Header template for entire site. HEADER_TEMPLATE = "zenodo_theme/header.html" #: JavaScript file containing the require.js build configuration. REQUIREJS_CONFIG = "js/zenodo-build.js" # User profile # ============ #: Extend account registration form with user profiles fields. USERPROFILES_EXTEND_SECURITY_FORMS = True # Database # ======== #: Default database host. SQLALCHEMY_DATABASE_URI = os.environ.get( "SQLALCHEMY_DATABASE_URI", "postgresql+psycopg2://zenodo:zenodo@localhost/zenodo") #: Do not print SQL queries to console. SQLALCHEMY_ECHO = False #: Track modifications to objects. SQLALCHEMY_TRACK_MODIFICATIONS = True # StatsD # ====== #: Default StatsD host (i.e. no request timing) STATSD_HOST = None #: Default StatsD port STATSD_PORT = 8125 #: Default StatsD port STATSD_PREFIX = "zenodo" # Stats # ===== STATS_EVENTS = { 'file-download': { 'signal': 'invenio_files_rest.signals.file_downloaded', 'templates': 'zenodo.modules.stats.templates.events', 'event_builders': [ 'invenio_stats.contrib.event_builders.file_download_event_builder', 'zenodo.modules.stats.event_builders:skip_deposit', 'zenodo.modules.stats.event_builders:add_record_metadata', ], 'cls': EventsIndexer, 'params': { 'preprocessors': [ 'invenio_stats.processors:flag_robots', # Don't index robot events lambda doc: doc if not doc['is_robot'] else None, 'invenio_stats.processors:flag_machines', 'invenio_stats.processors:anonymize_user', 'invenio_stats.contrib.event_builders:build_file_unique_id', ], # Keep only 1 file download for each file and user every 30 sec 'double_click_window': 30, # Create one index per month which will store file download events 'suffix': '%Y-%m', }, }, 'record-view': { 'signal': 'invenio_records_ui.signals.record_viewed', 'templates': 'zenodo.modules.stats.templates.events', 'event_builders': [ 'invenio_stats.contrib.event_builders.record_view_event_builder', 'zenodo.modules.stats.event_builders:skip_deposit', 'zenodo.modules.stats.event_builders:add_record_metadata', ], 'cls': EventsIndexer, 'params': { 'preprocessors': [ 'invenio_stats.processors:flag_robots', # Don't index robot events lambda doc: doc if not doc['is_robot'] else None, 'invenio_stats.processors:flag_machines', 'invenio_stats.processors:anonymize_user', 'invenio_stats.contrib.event_builders:build_record_unique_id', ], # Keep only 1 file download for each file and user every 30 sec 'double_click_window': 30, # Create one index per month which will store file download events 'suffix': '%Y-%m', }, }, } #: Enabled aggregations from 'zenoodo.modules.stats.registrations' STATS_AGGREGATIONS = { 'record-view-agg': dict( templates='zenodo.modules.stats.templates.aggregations', cls=StatAggregator, params=dict( client=current_stats_search_client, event='record-view', field='recid', interval='day', index_interval='month', copy_fields=dict( record_id='record_id', recid='recid', conceptrecid='conceptrecid', doi='doi', conceptdoi='conceptdoi', communities=lambda d, _: ( list(d.communities) if d.communities else None), owners=lambda d, _: (list(d.owners) if d.owners else None), is_parent=lambda *_: False ), metric_fields=dict( unique_count=('cardinality', 'unique_session_id', {'precision_threshold': 1000}), ) ) ), 'record-view-all-versions-agg': dict( templates='zenodo.modules.stats.templates.aggregations', cls=StatAggregator, params=dict( client=current_stats_search_client, event='record-view', field='conceptrecid', interval='day', index_interval='month', copy_fields=dict( conceptrecid='conceptrecid', conceptdoi='conceptdoi', communities=lambda d, _: ( list(d.communities) if d.communities else None), owners=lambda d, _: (list(d.owners) if d.owners else None), is_parent=lambda *_: True ), metric_fields=dict( unique_count=( 'cardinality', 'unique_session_id', {'precision_threshold': 1000}), ) ) ), 'record-download-agg': dict( templates='zenodo.modules.stats.templates.aggregations', cls=StatAggregator, params=dict( client=current_stats_search_client, event='file-download', field='recid', interval='day', index_interval='month', copy_fields=dict( bucket_id='bucket_id', record_id='record_id', recid='recid', conceptrecid='conceptrecid', doi='doi', conceptdoi='conceptdoi', communities=lambda d, _: ( list(d.communities) if d.communities else None), owners=lambda d, _: (list(d.owners) if d.owners else None), is_parent=lambda *_: False ), metric_fields=dict( unique_count=('cardinality', 'unique_session_id', {'precision_threshold': 1000}), volume=('sum', 'size', {}), ) ) ), 'record-download-all-versions-agg': dict( templates='zenodo.modules.stats.templates.aggregations', cls=StatAggregator, params=dict( client=current_stats_search_client, event='file-download', field='conceptrecid', interval='day', copy_fields=dict( conceptrecid='conceptrecid', conceptdoi='conceptdoi', communities=lambda d, _: ( list(d.communities) if d.communities else None), owners=lambda d, _: (list(d.owners) if d.owners else None), is_parent=lambda *_: True ), metric_fields=dict( unique_count=( 'cardinality', 'unique_session_id', {'precision_threshold': 1000}), volume=('sum', 'size', {}), ) ) ), } def stats_queries_permission_factory(query_name, params): """Queries permission factory.""" return Permission(ActionNeed('admin-access')) #: Enabled queries from 'zenoodo.modules.stats.registrations' STATS_QUERIES = { 'record-view': dict( cls=ESTermsQuery, permission_factory=stats_queries_permission_factory, params=dict( index='stats-record-view', copy_fields=dict( record_id='record_id', recid='recid', conceptrecid='conceptrecid', doi='doi', conceptdoi='conceptdoi', communities='communities', owners='owners', is_parent='is_parent' ), required_filters=dict( recid='recid', ), metric_fields=dict( count=('sum', 'count', {}), unique_count=('sum', 'unique_count', {}), ) ) ), 'record-view-all-versions': dict( cls=ESTermsQuery, permission_factory=stats_queries_permission_factory, params=dict( index='stats-record-view', copy_fields=dict( conceptrecid='conceptrecid', conceptdoi='conceptdoi', communities='communities', owners='owners', is_parent='is_parent' ), query_modifiers=[ lambda query, **_: query.filter('term', is_parent=True) ], required_filters=dict( conceptrecid='conceptrecid', ), metric_fields=dict( count=('sum', 'count', {}), unique_count=('sum', 'unique_count', {}), ) ) ), 'record-download': dict( cls=ESTermsQuery, permission_factory=stats_queries_permission_factory, params=dict( index='stats-file-download', copy_fields=dict( bucket_id='bucket_id', record_id='record_id', recid='recid', conceptrecid='conceptrecid', doi='doi', conceptdoi='conceptdoi', communities='communities', owners='owners', is_parent='is_parent' ), required_filters=dict( recid='recid', ), metric_fields=dict( count=('sum', 'count', {}), unique_count=('sum', 'unique_count', {}), volume=('sum', 'volume', {}), ) ), ), 'record-download-all-versions': dict( cls=ESTermsQuery, permission_factory=stats_queries_permission_factory, params=dict( index='stats-file-download', copy_fields=dict( conceptrecid='conceptrecid', conceptdoi='conceptdoi', communities='communities', owners='owners', is_parent='is_parent' ), query_modifiers=[ lambda query, **_: query.filter('term', is_parent=True) ], required_filters=dict( conceptrecid='conceptrecid', ), metric_fields=dict( count=('sum', 'count', {}), unique_count=('sum', 'unique_count', {}), volume=('sum', 'volume', {}), ) ) ), } # Queues # ====== QUEUES_BROKER_URL = CELERY_BROKER_URL # Proxy configuration #: Number of proxies in front of application. WSGI_PROXIES = 0 #: Set the session cookie to be secure - should be set to true in production. SESSION_COOKIE_SECURE = False # Configuration for limiter. RATELIMIT_STORAGE_URL = CACHE_REDIS_URL RATELIMIT_PER_ENDPOINT = { 'zenodo_frontpage.index': '10 per second', 'security.login': '10 per second', 'zenodo_redirector.contact': '10 per second', 'zenodo_support.support': '10 per second', # Badge endpoints 'invenio_github_badge.latest_doi_old': '10 per second', 'invenio_github_badge.latest_doi': '10 per second', 'invenio_github_badge.index': '10 per second', 'invenio_github_badge.index_old': '10 per second', 'invenio_formatter_badges.badge': '10 per second', } RATELIMIT_KEY_FUNC = useragent_and_ip_limit_key # Error templates THEME_429_TEMPLATE = "zenodo_errors/429.html" THEME_400_TEMPLATE = "zenodo_errors/400.html" failed_login_msg = (_("Login failed; Invalid user or password."), 'error') SECURITY_MSG_USER_DOES_NOT_EXIST = failed_login_msg SECURITY_MSG_PASSWORD_NOT_SET = failed_login_msg SECURITY_MSG_INVALID_PASSWORD = failed_login_msg SECURITY_MSG_CONFIRMATION_REQUIRED = failed_login_msg ZENODO_RECORDS_SAFELIST_INDEX_THRESHOLD = 1000 ZENODO_RECORDS_SEARCH_SAFELIST = False COMMUNITIES_CAN_CREATE = is_user_verified
63,729
Python
.py
1,650
32.116364
91
0.655954
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,418
factory.py
zenodo_zenodo/zenodo/factory.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 application factories.""" from __future__ import absolute_import from invenio_app.factory import create_api, create_app from invenio_app.factory import create_ui as create_celery __all__ = ('create_app', 'create_api', 'create_celery')
1,216
Python
.py
28
42.285714
76
0.771115
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,419
cli.py
zenodo_zenodo/zenodo/cli.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 CLI module.""" from __future__ import absolute_import, print_function from invenio_app.cli import cli __all__ = ('cli', )
1,103
Python
.py
27
39.703704
76
0.764925
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,420
__init__.py
zenodo_zenodo/zenodo/__init__.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. r"""Zenodo usage documentation for developers. .. _running: Running ------- Starting a development server is as simple as (note, if you are using docker, simply run ``docker-compose up``): .. code-block:: console $ zenodo run Celery workers can be started using the command: .. code-block:: console $ celery worker -A zenodo.celery -l INFO You enable debug mode by setting the ``FLASK_DEBUG`` environment variable: .. code-block:: console $ export FLASK_DEBUG=1 An interactive Python shell is started with the command: .. code-block:: console $ zenodo shell or, if you prefer to use IPython, you can start an interactive IPython shell using the command: .. code-block:: console $ zenodo konch Configuration ------------- Out-of-the-box Zenodo is configured to run in a local development environment with all services running on localhost. Some Zenodo features are dependent on external services, which by default are not configured - e.g. ORCID/GitHub sign-in. In order to make these features work, please follow the guide below for how to configure them. Instance configuration ~~~~~~~~~~~~~~~~~~~~~~ You can configure your specific instance by either setting environment variables (prefixed with ``APP_``) and/or using the instance configuration file (recommended) located at: .. code-block:: console ${VIRTUAL_ENV}/var/instance/invenio.cfg Secure session cookie ~~~~~~~~~~~~~~~~~~~~~ By default, the Flask session cookie will be sent over both HTTP and HTTPS as mostly during development we run the local Flask development server which is HTTP-only. Production deployments are however are HTTPS only, and thus for better security you should ensure the session cookie is only set over HTTPS using the following Flask configuration variable: .. code-block:: python SESSION_COOKIE_SECURE = True Recaptcha ~~~~~~~~~ To enable Recaptcha on the sign up page, you need to get a public and private key from https://www.google.com/recaptcha/ and add them to your configuration: .. code-block:: python RECAPTCHA_PUBLIC_KEY = '...' RECAPTCHA_PRIVATE_KEY = '...' ORCID Login ~~~~~~~~~~~ In order to enable ORCID login you must get an OAuth client id and client secret from ORCID and add them to: .. code-block:: python ORCID_APP_CREDENTIALS = dict( consumer_key='...', consumer_secret='...', ) GitHub Login ~~~~~~~~~~~~ In order to enable GitHub login you must get an OAuth client id and client secret from GitHub (register a new application on e.g. https://github.com/settings/developers) and add them to: .. code-block:: python GITHUB_APP_CREDENTIALS = dict( consumer_key='...', consumer_secret='...', ) For the GitHub integration to work with a self-signed SSL certificate you need to set (only use this during development): .. code-block:: python GITHUB_INSECURE_SSL = True For production instances, you should set the following shared secret (note, do not use your ``SECRET_KEY`` for this): .. code-block:: python GITHUB_SHARED_SECRET = '...' Last, set the URL template on which GitHub will send webhook events: .. code-block:: python GITHUB_WEBHOOK_RECEIVER_URL = \ 'http://example.org/' \ 'api/hooks/receivers/github/events/?access_token={token}' Note, ``{token}`` will be interpolated with the user's OAuth access token. GitHub for localhost ~~~~~~~~~~~~~~~~~~~~ For development machines running Zenodo on localhost and/or behind firewalls, you also need a public IP address which GitHub can reach you on. You can achieve this by using a service such as `ngrok <https://ngrok.com>`_: 1. Go to https://ngrok.com and sign-up with your GitHub account. 2. Install ngrok (e.g. ``brew cask install ngrok`` on OS X). 3. Get the authtoken from the dashboard and start a tunnel to ``localhost:5000``: .. code-block:: console $ ngrok authtoken <your-authtoken> $ ngrok http 5000 4. Grab the public ngrok address (e.g. ``http://<id>.ngrok.io``) and set the ``GITHUB_WEBHOOK_RECEIVER_URL`` configuration variable: .. code-block:: python GITHUB_WEBHOOK_RECEIVER_URL = \ 'http://<id>.ngrok.io/' \ 'api/hooks/receivers/github/events/?access_token={token}' 5. Add the public ngrok address to the allowed hosts configuration: .. code-block:: python APP_ALLOWED_HOSTS = ['<id>.ngrok.io', 'localhost'] DataCite DOI minting ~~~~~~~~~~~~~~~~~~~~ For DOI minting to work you must provide the DataCite prefix and credentials like this: .. code-block:: python PIDSTORE_DATACITE_USERNAME = '...' PIDSTORE_DATACITE_PASSWORD = '...' PIDSTORE_DATACITE_DOI_PREFIX = '10.5072' Google Site Verification ~~~~~~~~~~~~~~~~~~~~~~~~ If you want to use Google Webmasters toolkit you can add the site verification id in to the templates by setting the following configuration: .. code-block:: python GOOGLE_SITE_VERIFICATION = ['<id1>', '<id2>', ...] Elasticsearch ~~~~~~~~~~~~~ If you need to configure Elasticsearch to connect to an ES cluster with HTTPS proxy using HTTP Basic authentication it can be done like this: .. code-block:: python SEARCH_ELASTIC_KWARGS = dict( port=443, http_auth=('myuser', 'mypassword'), use_ssl=True, verify_certs=False, ) SEARCH_ELASTIC_HOSTS = [ dict(host='es1.example.org', **SEARCH_ELASTIC_KWARGS), dict(host='es2.example.org', **SEARCH_ELASTIC_KWARGS), dict(host='es2.example.org', **SEARCH_ELASTIC_KWARGS), ] PostgreSQL, RabbitMQ, Redis ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In case you want to use a remote database, broker and cache you can change the defaults using the following configuration variables: .. code-block:: python SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://dbhost/db' REDIS_URL = 'redis://redishost:6379' BROKER_URL = 'amqp://rabbitmqhost:5672/myvhost" ACCOUNTS_SESSION_REDIS_URL = '{0}/0'.format(REDIS_URL) CACHE_REDIS_URL = '{0}/0'.format(REDIS_URL) CELERY_RESULT_BACKEND = '{0}/1'.format(REDIS_URL) Storage ~~~~~~~ You can configure the default storage location using the configuration variable: .. code-block:: python FIXTURES_FILES_LOCATION = \ 'root://eospublic.cern.ch//eos/zenodo/prod/data/' In case you need XRootD support, please ensure that `XRootDPyFS <https://github.com/inveniosoftware/xrootdpyfs>`_ have been installed by e.g. installing Zenodo with the ``xrootd`` extras: .. code-block:: console $ pip install -e .[postgresql,elasticsearch2,xrootd] Sentry ~~~~~~ If you would like error logging to Sentry, set the configuration variable: .. code-block:: python SENTRY_DSN = 'https://user:pw@sentry.example.org/' Theme ~~~~~ Piwik analytics can be configured with the configuration variable: .. code-block:: python THEME_PIWIK_ID = 123 You can add a message to all pages, in order to show that a certain instance is not a production instance, e.g." .. code-block:: python THEME_TAG = 'Sandbox' Assets ~~~~~~ For non-development installation be sure to set the static file collection to copy files instead of symlinking: .. code-block:: python COLLECT_STORAGE = 'flask_collect.storage.file' StatsD ~~~~~~ Zenodo uses StatsD to measure request performance. .. code-block:: python STATSD_HOST = "localhost" STATSD_PORT = 8125 STATSD_PREFIX = "zenodo" Proxy configuration ~~~~~~~~~~~~~~~~~~~ In order for Zenodo to correctly determine a client's IP address, you must set how many proxies are in-front of the application (Zenodo production has e.g. two proxies in front - HAproxy and Nginx): .. code-block:: python WSGI_PROXIES = 2 Vocabularies ------------ Zenodo relies on external vocabularies/authorities for linking records to funders/grants and licenses. Since some of the vocabularies can be rather big, the actual important is done using the task queue. Hence, before executing any of the commands below, please first start Celery (see :ref:`running`). Licenses ~~~~~~~~ Licenses are imported from `opendefinition.org <http://licenses.opendefinition.org>`_: .. code-block:: console (zenodo)$ zenodo opendefinition loadlicenses Funders and grants ~~~~~~~~~~~~~~~~~~ Funders are imported from `FundRef <http://www.crossref.org/fundingdata/>`_. Currently the dataset contains more than 10.000 funders: .. code-block:: console (zenodo)$ zenodo openaire loadfunders Grants are imported from `OpenAIRE <http://api.openaire.eu/#cha_oai_pmh>`_. Currently the full dataset contains more than 600.000 grants spread over a handful of funders. You can harvest grants selectively from the funders you need: .. code-block:: console (zenodo)$ zenodo openaire loadgrants --setspec=FP7Projects The ``--setspec`` option should be one of the following: * Australian Research Council: ``ARCProjects`` * European Commission FP7: ``FP7Projects`` * European Commission Horizon 2020: ``H2020Projects`` * European Commission: ``ECProjects`` (contains both FP7Projects and ``H2020Projects``) * Foundation for Science and Technology, Portugal: ``FCTProjects`` * National Health and Medical Research Council: ``NHMRCProjects`` * National Science Foundation: ``NSFProjects`` * Wellcome Trust: ``WTProjects`` """ from __future__ import absolute_import, print_function import urllib3 from invenio_app.factory import create_app, create_ui from invenio_base.signals import app_created from .version import __version__ urllib3.disable_warnings() def disable_strict_slashes(sender, app=None, **kwargs): """Disable strict slashes on URL map.""" app.url_map.strict_slashes = False # Legacy support app_created.connect(disable_strict_slashes, sender=create_app) app_created.connect(disable_strict_slashes, sender=create_ui) __all__ = ('__version__', )
10,738
Python
.py
262
38.385496
79
0.738286
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,421
wsgi.py
zenodo_zenodo/zenodo/wsgi.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 WSGI application.""" from __future__ import absolute_import, print_function from invenio_app.wsgi import application __all__ = ('application', )
1,126
Python
.py
27
40.555556
76
0.769863
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,422
version.py
zenodo_zenodo/zenodo/version.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. """Version information for Zenodo. This file is imported by ``zenodo.__init__``, and parsed by ``setup.py``. """ from __future__ import absolute_import, print_function __version__ = "3.0.0.dev20150000"
1,173
Python
.py
29
39.310345
76
0.762281
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,423
__init__.py
zenodo_zenodo/zenodo/modules/__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 modules."""
990
Python
.py
24
40.208333
76
0.769948
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,424
writers.py
zenodo_zenodo/zenodo/modules/exporter/writers.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. """Data model package.""" from __future__ import absolute_import, print_function from datetime import datetime from invenio_db import db from invenio_files_rest.models import ObjectVersion class BucketWriter(object): """Export writer that writes to an object in a bucket.""" def __init__(self, bucket_id=None, key=None, **kwargs): """Initialize writer.""" self.bucket_id = bucket_id self.key = key self.obj = None def open(self): """Open the bucket for writing.""" self.obj = ObjectVersion.create( self.bucket_id, self.key() if callable(self.key) else self.key ) db.session.commit() return self def write(self, stream): """Write the data stream to the object.""" self.obj.set_contents(stream) def close(self): """Close bucket file.""" db.session.commit() class NullWriter(object): """Export writer that does not write anywhere.""" def __init__(self, **kwargs): """Initialize writer.""" def open(self): """Dummy open.""" return self def write(self, stream): """Dummy write.""" def close(self): """Dummy close.""" def filename_factory(**kwargs): """Get a function which generates a filename with a timestamp.""" return lambda: '{name}-{timestamp}.{format}'.format( timestamp=datetime.utcnow().replace(microsecond=0).isoformat(), **kwargs )
2,459
Python
.py
66
32.409091
76
0.682105
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,425
ext.py
zenodo_zenodo/zenodo/modules/exporter/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. """Exporter extension.""" from __future__ import absolute_import, print_function from flask import current_app from . import config class InvenioExporter(object): """Exporter 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('EXPORTER_'): app.config.setdefault(k, getattr(config, k)) def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['invenio-exporter'] = self def job(self, job_id): """Get export job definition.""" return current_app.config['EXPORTER_JOBS'].get(job_id, None)
1,802
Python
.py
46
35
76
0.706758
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,426
errors.py
zenodo_zenodo/zenodo/modules/exporter/errors.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. """Exporter errors.""" class FailedExportJobError(Exception): """Error for failed export job.""" def __init__(self, record_ids=None): """Initialize the error with the list of not serialized records.""" msg = "Serialization failed for the following records: {}"\ .format(', '.join(record_ids)) super(FailedExportJobError, self).__init__(msg)
1,356
Python
.py
31
41.193548
76
0.738077
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,427
config.py
zenodo_zenodo/zenodo/modules/exporter/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. """Exporter programmatic API.""" from __future__ import absolute_import, print_function from zenodo.modules.records.fetchers import zenodo_record_fetcher from zenodo.modules.records.serializers import json_v1 from .streams import BZip2ResultStream from .writers import BucketWriter, filename_factory EXPORTER_BUCKET_UUID = '00000000-0000-0000-0000-000000000001' EXPORTER_JOBS = { 'records': { 'index': 'records', 'serializer': json_v1, 'writer': BucketWriter( bucket_id=EXPORTER_BUCKET_UUID, key=filename_factory(name='records', format='json.bz2'), ), 'resultstream_cls': BZip2ResultStream, 'pid_fetcher': zenodo_record_fetcher, 'query': "+_exists_:recid +_missing_:removal_reason" } } """Export jobs definitions."""
1,778
Python
.py
44
37.272727
76
0.740162
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,428
streams.py
zenodo_zenodo/zenodo/modules/exporter/streams.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. """Result stream serialization.""" from __future__ import absolute_import, print_function import bz2 from .errors import FailedExportJobError class ResultStream(object): """Stream of serialized records for a search. The result stream implements a simple iterator that iterates over all records in a specific search and serializes each record. In addition, it emulates a stream API with the ``read()`` method, so that the serialized records can be written to an output. :param search: Elasticsearch DSL search instance configured for specific index. :param pid_fetcher: Persistent identifier fetcher that matches configured index. :param serializer: Serializer that supports export (i.e. the serialize must have implement the API ``serialize_exporter(pid, record)``). """ def __init__(self, search, pid_fetcher, serializer): """Initialize result stream.""" self.pid_fetcher = pid_fetcher self.search = search self.serializer = serializer self._iter = None self.failed_record_ids = [] def __next__(self): """Fetch next serialized record.""" # Initialize iterator (i.e. execute scroll search), if not already # initialized. if self._iter is None: self._iter = self.search.scan() # Fetch next hit. hit = next(self._iter) # Serialize and return hit. result = '' try: result = self.serializer.serialize_exporter( self.pid_fetcher(hit.meta.id, hit), dict(_source=hit._d_, _version=0), ) except Exception as e: self.failed_record_ids.append(hit.meta.id) return result def __iter__(self): """Iterator.""" return self def next(self): """Python 2.x compatibility function.""" return self.__next__() def read(self, *args): """Read next serialized record for search results. The method will return an empty string for repeated calls once all records have been read. """ try: return next(self) except StopIteration: if self.failed_record_ids: # raise an exception with the list of not serialized records raise FailedExportJobError(record_ids=self.failed_record_ids) return b'' class BZip2ResultStream(ResultStream): """BZip2 compressed stream of serialized records for a search. Works like :py:data:`ResultStream`, except that the output is compressed with BZip2. """ def __init__(self, *args, **kwargs): """Initialize result stream.""" super(BZip2ResultStream, self).__init__(*args, **kwargs) self.compressor = bz2.BZ2Compressor() def __next__(self): """Fetch next serialized bzip2 compressed chunk of records(s).""" try: data = None while not data: data = self.compressor.compress( super(BZip2ResultStream, self).__next__() ) return data except StopIteration: # Once we have read all records, make sure we flush the data left # in compressor. Repeated calls to flush will raise a ValueError. try: return self.compressor.flush() except ValueError: raise StopIteration
4,426
Python
.py
108
33.462963
77
0.65449
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,429
tasks.py
zenodo_zenodo/zenodo/modules/exporter/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. """Celery tasks for export jobs.""" from __future__ import absolute_import, print_function from celery import shared_task from flask import current_app from .api import Exporter @shared_task def export_job(job_id=None): """Export job.""" job_definition = current_app.extensions['invenio-exporter'].job(job_id) Exporter(**job_definition).run()
1,328
Python
.py
33
38.69697
76
0.767261
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,430
api.py
zenodo_zenodo/zenodo/modules/exporter/api.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. """Exporter programmatic API.""" from __future__ import absolute_import, print_function from elasticsearch_dsl import Q from flask import current_app from invenio_search.api import RecordsSearch from .errors import FailedExportJobError from .streams import ResultStream class Exporter(object): """Export controller. Takes as input an index, a query, a serializer and an output writer and executes the export job. """ def __init__(self, index='records', pid_fetcher=None, query=None, resultstream_cls=ResultStream, search_cls=RecordsSearch, serializer=None, writer=None, ): """Initialize exporter.""" self._index = index self._pid_fetcher = pid_fetcher self._query = query self._resultstream_cls = resultstream_cls self._search_cls = search_cls self._serializer = serializer self._writer = writer @property def search(self): """Get Elasticsearch search instance.""" s = self._search_cls(index=self._index) if self._query: s = s.query(Q('query_string', query=self._query)) return s def run(self, progress_updater=None): """Run export job.""" fp = self._writer.open() try: fp.write(self._resultstream_cls( self.search, self._pid_fetcher, self._serializer)) except FailedExportJobError as e: current_app.logger.exception(e.message) finally: fp.close()
2,491
Python
.py
63
34.15873
76
0.693962
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,431
utils.py
zenodo_zenodo/zenodo/modules/exporter/utils.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 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. """Utils for exporter.""" from __future__ import absolute_import, print_function from uuid import UUID from flask import current_app from invenio_db import db from invenio_files_rest.errors import FilesException from invenio_files_rest.models import Bucket, Location def initialize_exporter_bucket(): """Initialize the bucket for exporter module metadata dumps. :raises: `invenio_files_rest.errors.FilesException` """ bucket_id = UUID(current_app.config['EXPORTER_BUCKET_UUID']) if Bucket.query.get(bucket_id): raise FilesException("Bucket with UUID {} already exists.".format( bucket_id)) else: storage_class = current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS'] location = Location.get_default() bucket = Bucket(id=bucket_id, location=location, default_storage_class=storage_class) db.session.add(bucket) db.session.commit()
1,938
Python
.py
45
38.955556
78
0.734218
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,432
__init__.py
zenodo_zenodo/zenodo/modules/exporter/__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. """Exporter programmatic API.""" from __future__ import absolute_import, print_function from .api import Exporter from .streams import BZip2ResultStream, ResultStream from .writers import BucketWriter, filename_factory
1,189
Python
.py
28
41.357143
76
0.783247
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,433
indexer.py
zenodo_zenodo/zenodo/modules/deposit/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 import copy from flask import current_app from invenio_pidrelations.contrib.records import index_siblings from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidrelations.serializers.utils import serialize_relations from invenio_pidstore.models import PersistentIdentifier from zenodo.modules.records.utils import build_record_custom_fields from .api import ZenodoDeposit def indexer_receiver(sender, json=None, record=None, index=None, **dummy_kwargs): """Connect to before_record_index signal to transform record for ES. In order to avoid that a record and published deposit differs (e.g. if an embargo task updates the record), every time we index a record we also index the deposit and overwrite the content with that of the record. :param sender: Sender of the signal. :param json: JSON to be passed for the elastic search. :type json: `invenio_records.api.Deposit` :param record: Indexed deposit record. :type record: `invenio_records.api.Deposit` :param index: Elasticsearch index name. :type index: str """ if not index.startswith('deposits-records-'): return if not isinstance(record, ZenodoDeposit): record = ZenodoDeposit(record, model=record.model) if record['_deposit']['status'] == 'published': schema = json['$schema'] pub_record = record.fetch_published()[1] # Temporarily set to draft mode to ensure that `clear` can be called json['_deposit']['status'] = 'draft' json.clear() json.update(copy.deepcopy(pub_record.replace_refs())) # Set back to published mode and restore schema. json['_deposit']['status'] = 'published' json['$schema'] = schema json['_updated'] = pub_record.updated else: json['_updated'] = record.updated json['_created'] = record.created # Compute filecount and total file size files = json.get('_files', []) json['filecount'] = len(files) json['size'] = sum([f.get('size', 0) for f in files]) recid = record.get('recid') if recid: pid = PersistentIdentifier.get('recid', recid) pv = PIDVersioning(child=pid) relations = serialize_relations(pid) if pv.exists: if pv.draft_child_deposit: is_last = (pv.draft_child_deposit.pid_value == record['_deposit']['id']) relations['version'][0]['is_last'] = is_last relations['version'][0]['count'] += 1 else: relations = {'version': [{'is_last': True, 'index': 0}, ]} if relations: json['relations'] = relations for loc in json.get('locations', []): if loc.get('lat') and loc.get('lon'): loc['point'] = {'lat': loc['lat'], 'lon': loc['lon']} custom_es_fields = build_record_custom_fields(json) for es_field, es_value in custom_es_fields.items(): json[es_field] = es_value def index_versioned_record_siblings(sender, action=None, pid=None, deposit=None): """Send previous version of published record for indexing.""" first_publish = (deposit.get('_deposit', {}).get('pid', {}) .get('revision_id')) == 0 if action == "publish" and first_publish: recid_pid, _ = deposit.fetch_published() current_app.logger.info(u'indexing siblings of %s', recid_pid) index_siblings(recid_pid, neighbors_eager=True)
4,596
Python
.py
99
40.080808
77
0.674559
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,434
ext.py
zenodo_zenodo/zenodo/modules/deposit/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. """ZenodoDeposit module.""" from __future__ import absolute_import, print_function from invenio_deposit.signals import post_action from invenio_indexer.signals import before_record_index from . import config from .indexer import index_versioned_record_siblings, indexer_receiver from .receivers import datacite_register_after_publish, \ openaire_direct_index_after_publish, sipstore_write_files_after_publish class ZenodoDeposit(object): """Zenodo deposit extension.""" def __init__(self, app=None): """Extension initialization.""" if app: self.init_app(app) self.register_signals(app) def init_app(self, app): """Flask application initialization.""" self.init_config(app) @app.before_first_request def deposit_redirect(): from .views import legacy_index, new app.view_functions['invenio_deposit_ui.index'] = legacy_index app.view_functions['invenio_deposit_ui.new'] = new app.extensions['zenodo-deposit'] = self @staticmethod def register_signals(app): """Register Zenodo Deposit signals.""" before_record_index.connect(indexer_receiver, sender=app, weak=False) post_action.connect(datacite_register_after_publish, sender=app, weak=False) post_action.connect(index_versioned_record_siblings, sender=app, weak=False) post_action.connect(openaire_direct_index_after_publish, sender=app, weak=False) post_action.connect(sipstore_write_files_after_publish, sender=app, weak=False) @staticmethod def init_config(app): """Initialize configuration.""" for k in dir(config): if k.startswith('ZENODO_'): app.config.setdefault(k, getattr(config, k))
2,868
Python
.py
65
37.584615
77
0.6933
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,435
errors.py
zenodo_zenodo/zenodo/modules/deposit/errors.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. """Deposit errors.""" from __future__ import absolute_import, print_function, unicode_literals import json from flask_babelex import gettext as _ from invenio_rest.errors import FieldError, RESTValidationError class MissingFilesError(RESTValidationError): """Error for when no files have been provided.""" errors = [ FieldError(None, _('Minimum one file must be provided.'), code=10) ] class VersioningFilesError(RESTValidationError): """Error when new version's files exist in one of the old versions.""" errors = [ FieldError(None, _( "New version's files must differ from all previous versions."), code=10) ] class OngoingMultipartUploadError(RESTValidationError): """Error for when no files have been provided.""" errors = [ FieldError(None, _( 'A multipart file upload is in progress. Please wait for it to ' 'finish or delete the multipart filed upload.' ), code=10) ] class MissingCommunityError(RESTValidationError): """Error for invalid community IDs.""" def __init__(self, community_ids, *args, **kwargs): """Initialize the error with community IDs.""" msg = _('Provided community does not exist: ') self.errors = [FieldError('metadata.communities', msg + c_id) for c_id in community_ids] super(MissingCommunityError, self).__init__(*args, **kwargs) class MarshmallowErrors(RESTValidationError): """Marshmallow validation errors.""" def __init__(self, errors): """Store marshmallow errors.""" self.errors = errors super(MarshmallowErrors, self).__init__() def __str__(self): """Print exception with errors.""" return "{base}. Encountered errors: {errors}".format( base=super(RESTValidationError, self).__str__(), errors=self.errors) def iter_errors(self, errors, prefix=''): """Iterator over marshmallow errors.""" res = [] for field, error in errors.items(): if isinstance(error, list): res.append(dict( field='{0}{1}'.format(prefix, field), message=' '.join([str(x) for x in error]) )) elif isinstance(error, dict): res.extend(self.iter_errors( error, prefix='{0}{1}.'.format(prefix, field) )) return res def get_body(self, environ=None): """Get the request body.""" body = dict( status=self.code, message=self.get_description(environ), ) if self.errors: body['errors'] = self.iter_errors(self.errors) return json.dumps(body)
3,768
Python
.py
91
34.21978
76
0.648782
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,436
config.py
zenodo_zenodo/zenodo/modules/deposit/config.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. """Configuration for Zenodo Records.""" from __future__ import absolute_import, print_function from zenodo.modules.deposit.utils import is_user_verified ZENODO_BUCKET_QUOTA_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB """Maximum quota per bucket.""" ZENODO_EXTRA_FORMATS_BUCKET_QUOTA_SIZE = 100 * 1000 * 1000 # 100 MB """Maximum quota per extra formats bucket.""" ZENODO_MAX_FILE_SIZE = ZENODO_BUCKET_QUOTA_SIZE """Maximum file size accepted.""" ZENODO_USER_BUCKET_QUOTAS = {} """Custom per-user quotas. A dictionary with user ID as key and their default deposit quotas as values. .. code-block:: python ZENODO_USER_BUCKET_QUOTAS = { 12345: (80 * 1000 * 1000 * 1000), # 80GB } """ ZENODO_DEPOSIT_CREATE_PERMISSION = is_user_verified """Deposit create permission."""
1,764
Python
.py
42
40.333333
76
0.752632
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,437
links.py
zenodo_zenodo/zenodo/modules/deposit/links.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. """Deposit links factory.""" from __future__ import absolute_import, print_function from flask import current_app, request from invenio_deposit.links import deposit_links_factory def links_factory(pid, **kwargs): """Deposit links factory.""" links = deposit_links_factory(pid) links['html'] = current_app.config['DEPOSIT_UI_ENDPOINT'].format( host=request.host, scheme=request.scheme, pid_value=pid.pid_value, ) return links
1,443
Python
.py
36
37.666667
76
0.752857
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,438
tasks.py
zenodo_zenodo/zenodo/modules/deposit/tasks.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. """Celery tasks for Zenodo Deposit.""" from __future__ import absolute_import from celery import shared_task from flask import current_app from invenio_db import db from invenio_indexer.api import RecordIndexer from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_pidstore.providers.datacite import DataCiteProvider from invenio_records_files.api import Record from invenio_search.api import RecordsSearch from zenodo.modules.records.minters import is_local_doi from zenodo.modules.records.serializers import datacite_v41 @shared_task(ignore_result=True, max_retries=6, default_retry_delay=10 * 60, rate_limit='100/m') def datacite_register(pid_value, record_uuid): """Mint DOI and Concept DOI with DataCite. :param pid_value: Value of record PID, with pid_type='recid'. :type pid_value: str :param record_uuid: Record Metadata UUID. :type record_uuid: str """ try: record = Record.get_record(record_uuid) # Bail out if not a Zenodo DOI. if not is_local_doi(record['doi']): return dcp = DataCiteProvider.get(record['doi']) doc = datacite_v41.serialize(dcp.pid, record) url = current_app.config['ZENODO_RECORDS_UI_LINKS_FORMAT'].format( recid=pid_value) if dcp.pid.status == PIDStatus.REGISTERED: dcp.update(url, doc) else: dcp.register(url, doc) # If this is the latest record version, update/register the Concept DOI # using the metadata of the record. recid = PersistentIdentifier.get('recid', str(record['recid'])) pv = PIDVersioning(child=recid) conceptdoi = record.get('conceptdoi') if conceptdoi and pv.exists and pv.is_last_child: conceptrecid = record.get('conceptrecid') concept_dcp = DataCiteProvider.get(conceptdoi) url = current_app.config['ZENODO_RECORDS_UI_LINKS_FORMAT'].format( recid=conceptrecid) doc = datacite_v41.serialize(concept_dcp.pid, record) if concept_dcp.pid.status == PIDStatus.REGISTERED: concept_dcp.update(url, doc) else: concept_dcp.register(url, doc) db.session.commit() except Exception as exc: datacite_register.retry(exc=exc) @shared_task(ignore_result=True, max_retries=6, default_retry_delay=10 * 60, rate_limit='100/m') def datacite_inactivate(pid_value): """Mint the DOI with DataCite. :param pid_value: Value of record PID, with pid_type='recid'. :type pid_value: str """ try: dcp = DataCiteProvider.get(pid_value) dcp.delete() db.session.commit() except Exception as exc: datacite_inactivate.retry(exc=exc) @shared_task(ignore_result=True) def cleanup_indexed_deposits(): """Delete indexed deposits that do not exist in the database. .. note:: This task exists because of deposit REST API calls sometimes failing after the deposit has already been sent for indexing to ES, leaving an inconsistent state of a deposit existing in ES and not in the database. It should be removed once a proper signal mechanism has been implemented in the ``invenio-records-rest`` and ``invenio-deposit`` modules. """ search = RecordsSearch(index='deposits') q = (search .query('term', **{'_deposit.status': 'draft'}) .source(['_deposit.id'])) res = q.scan() failed_depids, es_depids_info = [], [] for d in res: try: es_depids_info.append((d.to_dict()['_deposit']['id'], d.meta.id, d.meta.index)) es_depids = {p[0] for p in es_depids_info} except Exception: failed_depids.append(d.meta.id) db_depids_query = PersistentIdentifier.query.filter( PersistentIdentifier.pid_type == 'depid', PersistentIdentifier.pid_value.in_(es_depids)) db_depids = {d.pid_value for d in db_depids_query} missing_db_depids = filter(lambda d: d[0] not in db_depids, es_depids_info) indexer = RecordIndexer() for _, deposit_id, index in missing_db_depids: indexer.client.delete(id=str(deposit_id), index=index) if failed_depids: current_app.logger.warning( 'Missing depids from metadata', extra={'failed deposits': failed_depids} )
5,493
Python
.py
125
37.376
79
0.684496
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,439
api.py
zenodo_zenodo/zenodo/modules/deposit/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. """Deposit API.""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager from copy import copy from flask import after_this_request, current_app, request from flask_security import current_user from invenio_communities.models import Community, InclusionRequest from invenio_db import db from invenio_deposit.api import Deposit, index, preserve from invenio_deposit.utils import mark_as_action from invenio_files_rest.models import Bucket, MultipartObject, ObjectVersion, \ Part from invenio_pidrelations.contrib.records import RecordDraft, index_siblings from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.errors import PIDInvalidAction from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records_files.models import RecordsBuckets from invenio_sipstore.api import RecordSIP from invenio_sipstore.archivers import BagItArchiver from invenio_sipstore.models import SIP as SIPModel from invenio_sipstore.models import RecordSIP as RecordSIPModel from zenodo.modules.communities.api import ZenodoCommunity from zenodo.modules.communities.signals import record_accepted from zenodo.modules.records.api import ZenodoFileObject, ZenodoFilesIterator, \ ZenodoFilesMixin, ZenodoRecord from zenodo.modules.records.minters import doi_generator, is_local_doi, \ zenodo_concept_doi_minter, zenodo_doi_updater from zenodo.modules.records.utils import is_doi_locally_managed, \ is_valid_openaire_type from zenodo.modules.spam.utils import check_and_handle_spam from .errors import MissingCommunityError, MissingFilesError, \ OngoingMultipartUploadError, VersioningFilesError from .fetchers import zenodo_deposit_fetcher from .minters import zenodo_deposit_minter PRESERVE_FIELDS = ( '_deposit', '_buckets', '_files', '_internal', '_oai', 'relations', 'owners', 'recid', 'conceptrecid', 'conceptdoi', ) """Fields which will not be overwritten on edit.""" def sync_buckets(src_bucket, dest_bucket, delete_extras=False): """Sync source bucket ObjectVersions to the destination bucket. The bucket is fully mirrored with the destination bucket following the logic: * same ObjectVersions are not touched * new ObjectVersions are added to destination * deleted ObjectVersions are deleted in destination * extra ObjectVersions in dest are deleted if `delete_extras` param is True :param src_bucket: Source bucket. :param dest_bucket: Destination bucket. :param delete_extras: Delete extra ObjectVersions in destination if True. :returns: The bucket with an exact copy of ObjectVersions in ` `src_bucket``. """ assert not dest_bucket.locked src_ovs = ObjectVersion.query.filter( ObjectVersion.bucket_id == src_bucket.id, ObjectVersion.is_head.is_(True) ).all() dest_ovs = ObjectVersion.query.filter( ObjectVersion.bucket_id == dest_bucket.id, ObjectVersion.is_head.is_(True) ).all() # transform into a dict { key: object version } src_keys = {ov.key: ov for ov in src_ovs} dest_keys = {ov.key: ov for ov in dest_ovs} for key, ov in src_keys.items(): if not ov.deleted: if key not in dest_keys or \ ov.file_id != dest_keys[key].file_id: ov.copy(bucket=dest_bucket) elif key in dest_keys and not dest_keys[key].deleted: ObjectVersion.delete(dest_bucket, key) if delete_extras: for key, ov in dest_keys.items(): if key not in src_keys: ObjectVersion.delete(dest_bucket, key) return dest_bucket class ZenodoDeposit(Deposit, ZenodoFilesMixin): """Define API for changing deposit state.""" file_cls = ZenodoFileObject files_iter_cls = ZenodoFilesIterator published_record_class = ZenodoRecord deposit_fetcher = staticmethod(zenodo_deposit_fetcher) deposit_minter = staticmethod(zenodo_deposit_minter) @property def multipart_files(self): """Get all multipart files.""" return MultipartObject.query_by_bucket(self.files.bucket) def is_published(self): """Check if deposit is published.""" return self['_deposit'].get('pid') is not None def has_minted_doi(self): """Check if deposit has a minted DOI.""" return is_local_doi(self['doi']) if self.is_published() else False @staticmethod def _create_inclusion_requests(comms, record): """Create inclusion requests for communities. :param comms: Community IDs for which the inclusion requests might should be created (if they don't exist already). :type comms: list of str :param record: Record corresponding to this deposit. :type record: `invenio_records.api.Record` """ for comm_id in comms: comm_api = ZenodoCommunity(comm_id) # Check if InclusionRequest exists for any version already pending_irs = comm_api.get_comm_irs(record) if pending_irs.count() == 0 and not comm_api.has_record(record): comm = Community.get(comm_id) notify = comm_id not in \ current_app.config['ZENODO_COMMUNITIES_NOTIFY_DISABLED'] InclusionRequest.create(comm, record, notify=notify) @staticmethod def _remove_obsolete_irs(comms, record): """Remove obsolete inclusion requests. :param comms: Community IDs as declared in deposit. Used to remove obsolete inclusion requests. :type comms: list of str :param record: Record corresponding to this deposit. :type record: `invenio_records.api.Record` """ pid = PersistentIdentifier.get('recid', record['recid']) pv = PIDVersioning(child=pid) sq = pv.children.with_entities( PersistentIdentifier.object_uuid).subquery() db.session.query(InclusionRequest).filter( InclusionRequest.id_record.in_(sq), InclusionRequest.id_community.notin_(comms)).delete( synchronize_session='fetch') def _prepare_edit(self, record): """Prepare deposit for editing. Extend the deposit's communities metadata by the pending inclusion requests. """ data = super(ZenodoDeposit, self)._prepare_edit(record) data.setdefault('communities', []).extend( [c.id_community for c in InclusionRequest.get_by_record(record.id)]) data['communities'] = sorted(list(set(data['communities']))) # Remove the OpenAIRE subtype if the record is no longer pending, # nor in the relevant community oa_type = data['resource_type'].get('openaire_subtype') if oa_type and not is_valid_openaire_type( data['resource_type'], data['communities']): del data['resource_type']['openaire_subtype'] if not data['communities']: del data['communities'] # If non-Zenodo DOI unlock the bucket to allow file-editing if not is_doi_locally_managed(data['doi']): self.files.bucket.locked = False return data @staticmethod def _get_synced_oaisets(rec_comms): """Sync oaiset specs with communities in the record. This is necessary as not all communities modifications go through Community.add_record/remove_record API, hence OAISet can be left outdated. """ fmt = current_app.config['COMMUNITIES_OAI_FORMAT'] new_c_sets = [fmt.format(community_id=c) for c in rec_comms] return new_c_sets # TODO: # record['_oai']['updated'] = datetime_to_datestamp(datetime.utcnow()) @staticmethod def _sync_oaisets_with_communities(record): """Sync oaiset specs with communities in the record. This is necessary as not all communities modifications go through Community.add_record/remove_record API, hence OAISet can be left outdated. """ if current_app.config['COMMUNITIES_OAI_ENABLED']: from invenio_oaiserver.models import OAISet comms = record.get('communities', []) oai_sets = record['_oai'].get('sets', []) c_sets = [s for s in oai_sets if s.startswith('user-') and not OAISet.query.filter_by(spec=s).one().search_pattern] fmt = current_app.config['COMMUNITIES_OAI_FORMAT'] new_c_sets = [fmt.format(community_id=c) for c in comms] removals = set(c_sets) - set(new_c_sets) additions = set(new_c_sets) - set(c_sets) for s in removals: oaiset = OAISet.query.filter_by(spec=s).one() oaiset.remove_record(record) for s in additions: oaiset = OAISet.query.filter_by(spec=s).one() oaiset.add_record(record) return record def _filter_by_owned_communities(self, comms): """Filter the list of communities for auto accept. :param comms: Community IDs to be filtered by the deposit owners. :type comms: list of str :returns: Community IDs, which are owned by one of the deposit owners. :rtype: list """ return [c for c in comms if Community.get(c).id_user in self['_deposit']['owners']] def _get_auto_requested(self, record): """Get communities which are to be auto-requested to each record.""" if not current_app.config['ZENODO_COMMUNITIES_AUTO_ENABLED']: return [] comms = copy(current_app.config['ZENODO_COMMUNITIES_AUTO_REQUEST']) pid = PersistentIdentifier.get('recid', record['conceptrecid']) pv = PIDVersioning(parent=pid) rec_grants = [ZenodoRecord.get_record( p.get_assigned_object()).get('grants') for p in pv.children] if self.get('grants') or any(rec_grants): comms.extend( current_app.config['ZENODO_COMMUNITIES_REQUEST_IF_GRANTS']) return comms def _get_auto_added(self, record): """Get communities which are to be auto added to each record.""" if not current_app.config['ZENODO_COMMUNITIES_AUTO_ENABLED']: return [] comms = [] pid = PersistentIdentifier.get('recid', record['conceptrecid']) pv = PIDVersioning(parent=pid) rec_grants = [ZenodoRecord.get_record( p.get_assigned_object()).get('grants') for p in pv.children] if self.get('grants') or any(rec_grants): comms = copy(current_app.config[ 'ZENODO_COMMUNITIES_ADD_IF_GRANTS']) return comms @contextmanager def _process_files(self, record_id, data): """Snapshot bucket and add files in record during first publishing.""" if self.files: file_uuids = set() for f in self.files: fs, path = f.file.storage()._get_fs() if not (fs.exists(path) and f.file.verify_checksum(throws=False)): file_uuids.add(str(f.file.id)) if file_uuids: raise Exception('One of more files were not written to' ' the storage: {}.'.format(file_uuids)) assert not self.files.bucket.locked self.files.bucket.locked = True snapshot = self.files.bucket.snapshot(lock=True) data['_files'] = self.files.dumps(bucket=snapshot.id) data['_buckets']['record'] = str(snapshot.id) yield data db.session.add(RecordsBuckets( record_id=record_id, bucket_id=snapshot.id )) # Add extra_formats bucket if 'extra_formats' in self['_buckets']: db.session.add(RecordsBuckets( record_id=record_id, bucket_id=self.extra_formats.bucket.id )) else: yield data def _get_new_communities(self, dep_comms, rec_comms, record): # New communities, which should be added automatically owned_comms = set(self._filter_by_owned_communities(dep_comms)) # Communities which are to be added to every published record auto_added = set(self._get_auto_added(record)) new_rec_comms = (dep_comms & rec_comms) | owned_comms | auto_added auto_requested = set(self._get_auto_requested(record)) # New communities, for which the InclusionRequests should be made new_ir_comms = (dep_comms - new_rec_comms) | auto_requested new_dep_comms = new_rec_comms | new_ir_comms return new_dep_comms, new_rec_comms, new_ir_comms def _sync_communities(self, dep_comms, rec_comms, record): new_dep_comms, new_rec_comms, new_ir_comms = \ self._get_new_communities(dep_comms, rec_comms, record) # Update Communities and OAISet information for all record versions conceptrecid = PersistentIdentifier.get('recid', record['conceptrecid']) pv = PIDVersioning(parent=conceptrecid) for pid in pv.children: rec = ZenodoRecord.get_record(pid.get_assigned_object()) if rec.id != record.id: rec['communities'] = sorted(new_rec_comms) if current_app.config['COMMUNITIES_OAI_ENABLED']: rec = self._sync_oaisets_with_communities(rec) if not rec['communities']: del rec['communities'] rec.commit() depid = PersistentIdentifier.get( 'depid', rec['_deposit']['id']) deposit = ZenodoDeposit.get_record(depid.get_assigned_object()) deposit['communities'] = sorted(new_dep_comms) if not deposit['communities']: del deposit['communities'] deposit.commit() # Update new version deposit if pv.draft_child_deposit: draft_dep = ZenodoDeposit.get_record( pv.draft_child_deposit.get_assigned_object()) if draft_dep.id != self.id: draft_dep['communities'] = sorted(new_dep_comms) if not draft_dep['communities']: del draft_dep['communities'] draft_dep.commit() record['communities'] = sorted(new_rec_comms) if current_app.config['COMMUNITIES_OAI_ENABLED']: record = self._sync_oaisets_with_communities(record) if not record['communities']: del record['communities'] self['communities'] = sorted(new_dep_comms) if not self['communities']: del self['communities'] # Create Inclusion requests against this record self._create_inclusion_requests(new_ir_comms, record) # Remove obsolete InclusionRequests again the record and its versions self._remove_obsolete_irs(new_ir_comms, record) return record def _publish_new(self, id_=None): """Publish new deposit with communities handling.""" dep_comms = set(self.pop('communities', [])) record = super(ZenodoDeposit, self)._publish_new(id_=id_) conceptrecid = PersistentIdentifier.get('recid', record['conceptrecid']) pv = PIDVersioning(parent=conceptrecid) if pv.children.count() > 1: files_set = set(f.get_version().file.checksum for f in self.files) for prev_recid in pv.children.all()[:-1]: rec = ZenodoRecord.get_record(prev_recid.object_uuid) prev_files_set = set(f.get_version().file.checksum for f in rec.files) if files_set == prev_files_set: raise VersioningFilesError() prev_recid = pv.children.all()[-2] rec_comms = set(ZenodoRecord.get_record( prev_recid.get_assigned_object()).get('communities', [])) else: rec_comms = set() record = self._sync_communities(dep_comms, rec_comms, record) record.commit() new_comms = set(record.get('communities', [])) - (rec_comms or set()) self._send_community_signals(record, new_comms) # Update the concept recid redirection pv.update_redirect() RecordDraft.unlink(record.pid, self.pid) index_siblings(record.pid, neighbors_eager=True, with_deposits=True) return record def _publish_edited(self): """Publish the edited deposit with communities merging.""" dep_comms = set(self.get('communities', [])) pid, record = self.fetch_published() rec_comms = set(record.get('communities', [])) edited_record = super(ZenodoDeposit, self)._publish_edited() # Preserve some of the previously published record fields preserve_record_fields = ['_files', '_oai', '_buckets', '_internal'] for k in preserve_record_fields: if k in record: edited_record[k] = record[k] # If non-Zenodo DOIs also sync files if not is_doi_locally_managed(self['doi']): record_bucket = edited_record.files.bucket # Unlock the record's bucket record_bucket.locked = False sync_buckets( src_bucket=self.files.bucket, dest_bucket=record_bucket, delete_extras=True, ) # Update the record's metadata edited_record['_files'] = self.files.dumps(bucket=record_bucket.id) # Lock both record and deposit buckets record_bucket.locked = True self.files.bucket.locked = True zenodo_doi_updater(edited_record.id, edited_record) edited_record = self._sync_communities(dep_comms, rec_comms, edited_record) new_comms = set(edited_record.get('communities', [])) - (rec_comms or set()) self._send_community_signals(edited_record, new_comms) return edited_record def _send_community_signals(self, record, communities): for community_id in communities: if request: @after_this_request def send_record_accepted_signal(response): try: record_accepted.send( current_app._get_current_object(), record_id=record.id, community_id=community_id, ) except Exception: pass return response def validate_publish(self): """Validate deposit.""" super(ZenodoDeposit, self).validate() if len(self.files) == 0: raise MissingFilesError() if self.multipart_files.count() != 0: raise OngoingMultipartUploadError() if 'communities' in self: missing = [c for c in self['communities'] if Community.get(c) is None] if missing: raise MissingCommunityError(missing) @mark_as_action def publish(self, pid=None, id_=None, user_id=None, sip_agent=None, spam_check=True): """Publish the Zenodo deposit.""" self['owners'] = self['_deposit']['owners'] self.validate_publish() if spam_check: check_and_handle_spam(deposit=self) is_first_publishing = not self.is_published() deposit = super(ZenodoDeposit, self).publish(pid, id_) recid, record = deposit.fetch_published() pv = PIDVersioning(child=recid) is_new_version = pv.children.count() > 1 # a) Fetch the last SIP from the previous version if it's a new version # b) Fetch the previous SIP if publishing the metadata edit if is_new_version or (not is_first_publishing): if is_new_version: sip_recid = pv.children.all()[-2] else: # (not is_first_publishing) sip_recid = recid # Get the last SIP of the relevant recid, i.e.: either last # version or the current one sip_patch_of = ( db.session.query(SIPModel) .join(RecordSIPModel, RecordSIPModel.sip_id == SIPModel.id) .filter(RecordSIPModel.pid_id == sip_recid.id) .order_by(SIPModel.created.desc()) .first() ) else: sip_patch_of = None recordsip = RecordSIP.create( recid, record, archivable=True, create_sip_files=is_first_publishing, user_id=user_id, agent=sip_agent) archiver = BagItArchiver( recordsip.sip, include_all_previous=(not is_first_publishing), patch_of=sip_patch_of) archiver.save_bagit_metadata() return deposit @staticmethod def _get_bucket_settings(): """Return bucket creation config.""" res = { 'quota_size': current_app.config['ZENODO_BUCKET_QUOTA_SIZE'], 'max_file_size': current_app.config['ZENODO_MAX_FILE_SIZE'], } # Determine bucket quota per-user user_quotas = current_app.config.get('ZENODO_USER_BUCKET_QUOTAS') or {} if current_user and current_user.is_authenticated: creator_id = int(current_user.get_id()) if creator_id in user_quotas: res['quota_size'] = user_quotas[creator_id] res['max_file_size'] = res['quota_size'] return res @classmethod def create(cls, data, id_=None): """Create a deposit. Adds bucket creation immediately on deposit creation. """ bucket = Bucket.create(**cls._get_bucket_settings()) data['_buckets'] = {'deposit': str(bucket.id)} deposit = super(ZenodoDeposit, cls).create(data, id_=id_) RecordsBuckets.create(record=deposit.model, bucket=bucket) recid = PersistentIdentifier.get( 'recid', str(data['recid'])) conceptrecid = PersistentIdentifier.get( 'recid', str(data['conceptrecid'])) depid = PersistentIdentifier.get( 'depid', str(data['_deposit']['id'])) PIDVersioning(parent=conceptrecid).insert_draft_child(child=recid) RecordDraft.link(recid, depid) return deposit @preserve(result=False, fields=PRESERVE_FIELDS) def clear(self, *args, **kwargs): """Clear only drafts.""" super(ZenodoDeposit, self).clear(*args, **kwargs) @preserve(result=False, fields=PRESERVE_FIELDS) def update(self, *args, **kwargs): """Update only drafts.""" super(ZenodoDeposit, self).update(*args, **kwargs) @preserve(fields=PRESERVE_FIELDS) def patch(self, *args, **kwargs): """Patch only drafts.""" return super(ZenodoDeposit, self).patch(*args, **kwargs) @index(delete=True) def delete(self, delete_published=False, *args, **kwargs): """Delete the deposit. :param delete_published: If True, even deposit of a published record will be deleted (usually used by admin operations). :type delete_published: bool """ is_published = self['_deposit'].get('pid') if is_published and not delete_published: raise PIDInvalidAction() # Delete the recid recid = PersistentIdentifier.get( pid_type='recid', pid_value=self['recid']) versioning = PIDVersioning(child=recid) if versioning.exists: if versioning.draft_child and \ self.pid == versioning.draft_child_deposit: versioning.remove_draft_child() if versioning.last_child: index_siblings(versioning.last_child, children=versioning.children.all(), include_pid=True, neighbors_eager=True, with_deposits=True) if recid.status == PIDStatus.RESERVED: db.session.delete(recid) if 'conceptrecid' in self: concept_recid = PersistentIdentifier.get( pid_type='recid', pid_value=self['conceptrecid']) if concept_recid.status == PIDStatus.RESERVED: db.session.delete(concept_recid) # Completely remove bucket bucket = self.files.bucket extra_formats_bucket = None if 'extra_formats' in self['_buckets']: extra_formats_bucket = self.extra_formats.bucket with db.session.begin_nested(): # Remove Record-Bucket link RecordsBuckets.query.filter_by(record_id=self.id).delete() mp_q = MultipartObject.query_by_bucket(bucket) # Remove multipart objects Part.query.filter( Part.upload_id.in_(mp_q.with_entities( MultipartObject.upload_id).subquery()) ).delete(synchronize_session='fetch') mp_q.delete(synchronize_session='fetch') if extra_formats_bucket: extra_formats_bucket.remove() bucket.locked = False bucket.remove() depid = kwargs.get('pid', self.pid) if depid: depid.delete() # NOTE: We call the parent of Deposit, invenio_records.api.Record since # we need to completely override eveything that the Deposit.delete # method does. return super(Deposit, self).delete(*args, **kwargs) @mark_as_action def newversion(self, pid=None): """Create a new version deposit.""" if not self.is_published(): raise PIDInvalidAction() # Check that there is not a newer draft version for this record pid, record = self.fetch_published() pv = PIDVersioning(child=pid) if (not pv.draft_child and is_doi_locally_managed(record['doi'])): with db.session.begin_nested(): # Get copy of the latest record latest_record = ZenodoRecord.get_record( pv.last_child.object_uuid) data = latest_record.dumps() # Get the communities from the last deposit # and push those to the new version latest_depid = PersistentIdentifier.get( 'depid', data['_deposit']['id']) latest_deposit = ZenodoDeposit.get_record( latest_depid.object_uuid) last_communities = latest_deposit.get('communities', []) owners = data['_deposit']['owners'] # TODO: Check other data that may need to be removed keys_to_remove = ( '_deposit', 'doi', '_oai', '_files', '_buckets', '$schema') for k in keys_to_remove: data.pop(k, None) # NOTE: We call the superclass `create()` method, because we # don't want a new empty bucket, but an unlocked snapshot of # the old record's bucket. deposit = (super(ZenodoDeposit, self).create(data)) # Injecting owners is required in case of creating new # version this outside of request context deposit['_deposit']['owners'] = owners if last_communities: deposit['communities'] = last_communities ### conceptrecid = PersistentIdentifier.get( 'recid', data['conceptrecid']) recid = PersistentIdentifier.get( 'recid', str(data['recid'])) depid = PersistentIdentifier.get( 'depid', str(data['_deposit']['id'])) PIDVersioning(parent=conceptrecid).insert_draft_child( child=recid) RecordDraft.link(recid, depid) # Pre-fill the Zenodo DOI to prevent the user from changing it # to a custom DOI. deposit['doi'] = doi_generator(recid.pid_value) pv = PIDVersioning(child=pid) index_siblings(pv.draft_child, neighbors_eager=True, with_deposits=True) with db.session.begin_nested(): # Create snapshot from the record's bucket and update data snapshot = latest_record.files.bucket.snapshot(lock=False) snapshot.locked = False if 'extra_formats' in latest_record['_buckets']: extra_formats_snapshot = \ latest_record.extra_formats.bucket.snapshot( lock=False) deposit['_buckets'] = {'deposit': str(snapshot.id)} RecordsBuckets.create(record=deposit.model, bucket=snapshot) if 'extra_formats' in latest_record['_buckets']: deposit['_buckets']['extra_formats'] = \ str(extra_formats_snapshot.id) RecordsBuckets.create( record=deposit.model, bucket=extra_formats_snapshot) deposit.commit() return self @mark_as_action def registerconceptdoi(self, pid=None): """Register the conceptdoi for the deposit and record.""" if not self.is_published() and is_doi_locally_managed(self['doi']): raise PIDInvalidAction() pid, record = self.fetch_published() zenodo_concept_doi_minter(record.id, record) record.commit() self['conceptdoi'] = record['conceptdoi'] self.commit() if current_app.config['DEPOSIT_DATACITE_MINTING_ENABLED']: from zenodo.modules.deposit.tasks import datacite_register datacite_register.delay(pid.pid_value, str(record.id)) return self
31,284
Python
.py
652
36.668712
84
0.612763
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,440
receivers.py
zenodo_zenodo/zenodo/modules/deposit/receivers.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. """Zenodo Deposit module receivers.""" from __future__ import absolute_import, print_function from flask import current_app from invenio_sipstore.models import RecordSIP from zenodo.modules.deposit.tasks import datacite_register from zenodo.modules.openaire.tasks import openaire_direct_index from zenodo.modules.sipstore.tasks import archive_sip def datacite_register_after_publish(sender, action=None, pid=None, deposit=None): """Mind DOI with DataCite after the deposit has been published.""" if action == 'publish' and \ current_app.config['DEPOSIT_DATACITE_MINTING_ENABLED']: recid_pid, record = deposit.fetch_published() datacite_register.delay(recid_pid.pid_value, str(record.id)) def openaire_direct_index_after_publish(sender, action=None, pid=None, deposit=None): """Send published record for direct indexing at OpenAIRE.""" if action == 'publish' and \ current_app.config['OPENAIRE_DIRECT_INDEXING_ENABLED']: _, record = deposit.fetch_published() openaire_direct_index.delay(record_uuid=str(record.id)) def sipstore_write_files_after_publish(sender, action=None, pid=None, deposit=None): """Send the SIP for archiving.""" if action == 'publish' and \ current_app.config['SIPSTORE_ARCHIVER_WRITING_ENABLED']: recid_pid, record = deposit.fetch_published() sip = ( RecordSIP.query .filter_by(pid_id=recid_pid.id) .order_by(RecordSIP.created.desc()) .first().sip ) archive_sip.delay(str(sip.id))
2,671
Python
.py
57
40.649123
76
0.698157
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,441
utils.py
zenodo_zenodo/zenodo/modules/deposit/utils.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. """Utilities for Zenodo deposit.""" from __future__ import absolute_import, unicode_literals import itertools import uuid import pycountry from elasticsearch.exceptions import NotFoundError from flask import abort, current_app, request from flask_security import current_user from invenio_accounts.models import User from invenio_db import db from invenio_indexer.api import RecordIndexer from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.errors import PIDDoesNotExistError from invenio_pidstore.models import PersistentIdentifier from invenio_records_files.models import RecordsBuckets from six import string_types, text_type from werkzeug.local import LocalProxy from werkzeug.routing import PathConverter from zenodo_accessrequests.models import AccessRequest, SecretLink from zenodo.modules.deposit.resolvers import deposit_resolver from zenodo.modules.deposit.tasks import datacite_inactivate, datacite_register from zenodo.modules.openaire.helpers import openaire_datasource_id, \ openaire_original_id, openaire_type from zenodo.modules.openaire.tasks import openaire_delete from zenodo.modules.records.api import ZenodoRecord from zenodo.modules.records.minters import is_local_doi from zenodo.modules.spam.proxies import current_domain_forbiddenlist def file_id_to_key(value): """Convert file UUID to value if in request context.""" from invenio_files_rest.models import ObjectVersion _, record = request.view_args['pid_value'].data if value in record.files: return value try: value = uuid.UUID(value) except ValueError: abort(404) object_version = ObjectVersion.query.filter_by( bucket_id=record.files.bucket.id, file_id=value ).first() if object_version: return object_version.key return value class FileKeyConverter(PathConverter): """Convert file UUID for key.""" def to_python(self, value): """Lazily convert value from UUID to key if need be.""" return LocalProxy(lambda: file_id_to_key(value)) def get_all_deposit_siblings(deposit): """Get all siblings of the deposit.""" from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.models import PersistentIdentifier recid = deposit['recid'] rec_pid = PersistentIdentifier.get(pid_type='recid', pid_value=str(recid)) pv = PIDVersioning(child=rec_pid) return [pid.get_assigned_object() for pid in pv.children] def fetch_depid(pid): """Fetch depid from any pid.""" try: if isinstance(pid, PersistentIdentifier): if pid.pid_type == 'depid': return pid elif pid.pid_type == 'recid': return ZenodoRecord.get_record(pid.object_uuid).depid elif isinstance(pid, (string_types, int)): return PersistentIdentifier.get('depid', pid_value=pid) else: raise Exception('"[{}] cannot be resolved to depid'.format(pid)) except Exception: # FIXME: Handle or let it bubble pass def delete_record(record_uuid, reason, user): """Delete the record and it's PIDs. :param record_uuid: UUID of the record to be removed. :param reason: Reason for removal. Either one of: 'spam', 'uploader', 'takedown' (see 'ZENODO_REMOVAL_REASONS' variable in config), otherwise using it as a verbatim "Reason" string. :param user: ID or email of the Zenodo user (admin) responsible for the removal. """ from invenio_github.models import ReleaseStatus if isinstance(user, text_type): user_id = User.query.filter_by(email=user).one().id elif isinstance(user, int): user_id = User.query.get(user).id else: raise TypeError("User cannot be determined from argument: {0}".format( user)) record = ZenodoRecord.get_record(record_uuid) # Remove the record from versioning and delete the recid recid = PersistentIdentifier.get('recid', record['recid']) pv = PIDVersioning(child=recid) pv.remove_child(recid) pv.update_redirect() recid.delete() # Remove the record from index try: RecordIndexer().delete(record) except NotFoundError: pass # Remove buckets record_bucket = record.files.bucket RecordsBuckets.query.filter_by(record_id=record.id).delete() record_bucket.locked = False record_bucket.remove() removal_reasons = dict(current_app.config['ZENODO_REMOVAL_REASONS']) if reason in removal_reasons: reason = removal_reasons[reason] depid, deposit = deposit_resolver.resolve(record['_deposit']['id']) try: doi = PersistentIdentifier.get('doi', record['doi']) except PIDDoesNotExistError: doi = None # Record OpenAIRE info try: original_id = openaire_original_id(record, openaire_type(record))[1] datasource_id = openaire_datasource_id(record) except PIDDoesNotExistError: original_id = None datasource_id = None if pv.children.count() == 0: conceptrecid = PersistentIdentifier.get('recid', record['conceptrecid']) conceptrecid.delete() new_last_child = None else: new_last_child = (pv.last_child.pid_value, str(pv.last_child.object_uuid)) if 'conceptdoi' in record: conceptdoi_value = record['conceptdoi'] else: conceptdoi_value = None # Completely delete the deposit # Deposit will be removed from index deposit.delete(delete_published=True) # Clear the record and put the deletion information record.clear() record.update({ 'removal_reason': reason, 'removed_by': user_id, }) record.commit() # Delete access requests as well as access links secret_links = SecretLink.query.join(AccessRequest).filter( AccessRequest.recid == int(recid.pid_value) ) link_ids = [l.id for l in secret_links] with db.session.begin_nested(): AccessRequest.query.filter( AccessRequest.recid == int(recid.pid_value)).delete() SecretLink.query.filter(SecretLink.id.in_(link_ids)).delete(synchronize_session=False) # Mark the relevant GitHub Release as deleted for ghr in record.model.github_releases: ghr.status = ReleaseStatus.DELETED if not is_local_doi(doi.pid_value): db.session.delete(doi) db.session.commit() # After successful DB commit, sync the DOIs with DataCite if is_local_doi(doi.pid_value): datacite_inactivate.delay(doi.pid_value) if conceptdoi_value: if new_last_child: # Update last child (updates also conceptdoi) pid_value, rec_uuid = new_last_child datacite_register.delay(pid_value, rec_uuid) else: datacite_inactivate.delay(conceptdoi_value) # Also delete from OpenAIRE index if current_app.config['OPENAIRE_DIRECT_INDEXING_ENABLED'] and original_id \ and datasource_id: openaire_delete.delay( record_uuid=str(record.id), original_id=original_id, datasource_id=datasource_id ) def suggest_language(q, limit=5): """Get language suggestions based on query q from a fixed dictionary. :param q: Query string to look for (e.g. 'Polish', 'ger', 'english') :type q: str :param limit: limit the result to 'limit' items :type limit: int :return: list of pycountry.db.Language """ q = q.lower().strip() lut = None langs = [] # If query is 2 or 3 char long, lookup for the ISO code if 2 <= len(q) <= 3: try: lut = pycountry.languages.lookup(q) except LookupError: pass # For queries longer than 2 characters, search by name if len(q) > 2: langs = list(itertools.islice( (l for l in pycountry.languages if q in l.name.lower()), limit)) # Include the ISO-fetched language (if available) on first position if lut: langs = ([lut, ] + [l for l in langs if l != lut])[:limit] return langs def is_user_verified(user=None): """Permission function that evaluates if the user can create a deposit.""" user = user or current_user if user.is_anonymous: return False, '' if user.email: email_domain = user.email.rsplit('@', 1)[-1].lower() if current_domain_forbiddenlist.matches(email_domain): return False, ( 'You have registered on Zenodo using an email address domain ' 'that has recently been used to upload spam on Zenodo. If ' 'this is not the case please contact us via our support line.' ) if user.external_identifiers: return True, '' if not user.confirmed_at: return False, ( 'To continue please verify your email. You can resend the ' 'verification email from your profile settings. Alternatively you ' 'can link your Zenodo account with either your GitHub or ORCID ' 'account.' ) return True, ''
10,169
Python
.py
246
34.902439
94
0.690563
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,442
scopes.py
zenodo_zenodo/zenodo/modules/deposit/scopes.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. """OAuth2 deposit scopes.""" from __future__ import absolute_import, print_function from flask_babelex import lazy_gettext as _ from invenio_deposit.scopes import DepositScope extra_formats_scope = DepositScope( 'extra_formats', help_text=_('Allow CRUD operations on extra formats files.'), internal=True, ) """Allow CRUD operations on extra formats files."""
1,343
Python
.py
33
39.212121
76
0.770291
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,443
__init__.py
zenodo_zenodo/zenodo/modules/deposit/__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 deposit additions.""" from __future__ import absolute_import, print_function
1,056
Python
.py
25
41.16
76
0.772595
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,444
fetchers.py
zenodo_zenodo/zenodo/modules/deposit/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. """Persistent identifier fetchers.""" from __future__ import absolute_import, print_function from invenio_pidstore.fetchers import FetchedPID def zenodo_deposit_fetcher(record_uuid, data): """Fetch a deposit identifier.""" pid_value = data.get('_deposit', {}).get('id') return FetchedPID( provider=None, pid_type='depid', pid_value=pid_value, ) if pid_value else None
1,380
Python
.py
34
38.264706
76
0.749441
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,445
minters.py
zenodo_zenodo/zenodo/modules/deposit/minters.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 minters.""" from __future__ import absolute_import from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \ RecordIdentifier def zenodo_concept_recid_minter(record_uuid=None, data=None): """Mint the Concept RECID. Reserves the Concept RECID for the record. """ parent_id = RecordIdentifier.next() conceptrecid = PersistentIdentifier.create( pid_type='recid', pid_value=str(parent_id), status=PIDStatus.RESERVED, ) data['conceptrecid'] = conceptrecid.pid_value return conceptrecid def zenodo_deposit_minter(record_uuid, data): """Mint the DEPID, and reserve the Concept RECID and RECID PIDs.""" if 'conceptrecid' not in data: zenodo_concept_recid_minter(data=data) recid = zenodo_reserved_record_minter(data=data) # Create depid with same pid_value of the recid depid = PersistentIdentifier.create( 'depid', str(recid.pid_value), object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED, ) data.update({ '_deposit': { 'id': depid.pid_value, 'status': 'draft', }, }) return depid def zenodo_reserved_record_minter(record_uuid=None, data=None): """Reserve a recid.""" id_ = RecordIdentifier.next() recid = PersistentIdentifier.create( 'recid', str(id_), status=PIDStatus.RESERVED ) data['recid'] = int(recid.pid_value) return recid
2,481
Python
.py
67
32.58209
76
0.71113
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,446
query.py
zenodo_zenodo/zenodo/modules/deposit/query.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. """Query factories for deposit REST API.""" from flask import abort from flask_security import current_user from zenodo.modules.records.query import \ search_factory as record_search_factory def search_factory(*args, **kwargs): """Check user is logged in and then parse.""" if not current_user.is_authenticated: abort(401) return record_search_factory(*args, **kwargs)
1,367
Python
.py
33
39.484848
76
0.764883
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,447
resolvers.py
zenodo_zenodo/zenodo/modules/deposit/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 ZenodoDeposit.""" from __future__ import absolute_import, print_function from invenio_pidstore.resolver import Resolver from .api import ZenodoDeposit deposit_resolver = Resolver( pid_type='depid', object_type='rec', getter=ZenodoDeposit.get_record ) """'depid'-PID resolver for Zenodo Deposits."""
1,296
Python
.py
31
40.516129
76
0.77619
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,448
extra_formats.py
zenodo_zenodo/zenodo/modules/deposit/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 utilities.""" from flask import current_app from invenio_files_rest.models import Bucket from invenio_records_files.models import RecordsBuckets from werkzeug.local import LocalProxy class ExtraFormats(object): """Extra formats utilities.""" mimetype_whitelist = LocalProxy( lambda: current_app.config.get( 'ZENODO_EXTRA_FORMATS_MIMETYPE_WHITELIST', {}) ) """MIMEType whitelist.""" @classmethod def get_or_create_bucket(cls, record): """Get or create the extra formats bucket for a record (or deposit).""" if not record.get('_buckets', {}).get('extra_formats'): extra_formats_bucket = Bucket.create( quota_size=current_app.config[ 'ZENODO_EXTRA_FORMATS_BUCKET_QUOTA_SIZE'], max_file_size=current_app.config['ZENODO_MAX_FILE_SIZE'], locked=False ) cls.link_to_record(record, extra_formats_bucket) else: extra_formats_bucket = Bucket.query.get( record['_buckets']['extra_formats']) return extra_formats_bucket @classmethod def link_to_record(cls, record, bucket): """Link a record its extra formats bucket.""" if not record.get('_buckets', {}).get('extra_formats'): record.setdefault('_buckets', {}) record['_buckets']['extra_formats'] = str(bucket.id) record.commit() RecordsBuckets.create(record=record.model, bucket=bucket)
2,496
Python
.py
58
37.086207
79
0.685726
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,449
views_rest.py
zenodo_zenodo/zenodo/modules/deposit/views_rest.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016, 2017, 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. """Redirects for legacy URLs.""" from __future__ import absolute_import, print_function from functools import wraps from flask import Blueprint, abort, jsonify, request from flask.views import MethodView from flask_principal import ActionNeed from flask_security import login_required from invenio_access import Permission from invenio_db import db from invenio_files_rest import current_files_rest from invenio_files_rest.models import ObjectVersion from invenio_records_rest.views import pass_record from ..records.permissions import deposit_update_permission_factory from .extra_formats import ExtraFormats from .scopes import extra_formats_scope from .utils import suggest_language blueprint = Blueprint( 'zenodo_deposit', __name__, url_prefix='', ) @blueprint.route( '/language/', methods=['GET'] ) @login_required def language(): """Suggest a language on the deposit form.""" q = request.args.get('q', '') limit = int(request.args.get('limit', '5').lower()) langs = suggest_language(q, limit=limit) langs = [{'code': l.alpha_3, 'name': l.name} for l in langs] d = { 'suggestions': langs } return jsonify(d) def pass_extra_formats_mimetype(from_query_string=None, from_content_type=None, from_accept=None): """Decorator to validate the request's extra formats MIMEType.""" assert from_content_type or from_accept or from_query_string def decorator(f): @wraps(f) def inner(*args, **kwargs): mimetype = None if from_query_string: mimetype = request.args.get('mimetype') if not mimetype and from_content_type: mimetype = request.headers.get('Content-Type') if not mimetype and from_accept: mimetype = next((m for m, _ in request.accept_mimetypes), None) if mimetype not in ExtraFormats.mimetype_whitelist: abort(400, '"{}" is not an acceptable MIMEType.' .format(mimetype)) return f(*args, mimetype=mimetype, **kwargs) return inner return decorator def extra_formats_scope_permission(): """Helper function to check the existence of extra_formats_scope.""" if getattr(request, 'oauth', None) is not None: token_scopes = set(request.oauth.access_token.scopes) return extra_formats_scope.id in token_scopes return False def check_extra_formats_permission(f): """Extra formats permission decorator.""" @wraps(f) def decorator(self, record=None, *args, **kwargs): if Permission(ActionNeed('admin-access')) or \ (deposit_update_permission_factory(record=record).can() and extra_formats_scope_permission()): return f(self, record=record, *args, **kwargs) abort(403) return decorator class DepositExtraFormatsResource(MethodView): """Deposit extra formats resource.""" @pass_extra_formats_mimetype(from_query_string=True, from_accept=True) @pass_record @check_extra_formats_permission def get(self, pid, record, mimetype=None, **kwargs): """Get an extra format.""" depid, deposit = pid, record # this is a deposit endpoint if mimetype in deposit.extra_formats: fileobj = deposit.extra_formats[mimetype] return fileobj.obj.send_file(trusted=True) return abort(404, 'No extra format "{}".'.format(mimetype)) @pass_extra_formats_mimetype(from_content_type=True) @pass_record @check_extra_formats_permission def put(self, pid, record, mimetype=None, **kwargs): """Create or replace an extra format.""" depid, deposit = pid, record # this is a deposit endpoint stream, content_length, content_md5 = \ current_files_rest.upload_factory() with db.session.begin_nested(): extra_formats_bucket = ExtraFormats.get_or_create_bucket(deposit) # Link bucket to published record if needed if deposit.is_published(): recid, record = deposit.fetch_published() ExtraFormats.link_to_record(record, extra_formats_bucket) obj = ObjectVersion.create( extra_formats_bucket, mimetype, mimetype=mimetype) obj.set_contents( stream, size=content_length, size_limit=extra_formats_bucket.size_limit) db.session.commit() return jsonify({ 'message': 'Extra format "{}" updated.'.format(mimetype) }) @pass_extra_formats_mimetype(from_content_type=True) @pass_record @check_extra_formats_permission def delete(self, pid, record, mimetype=None, **kwargs): """Delete an extra format.""" depid, deposit = pid, record # this is a deposit endpoint if mimetype in deposit.extra_formats: del deposit.extra_formats[mimetype] db.session.commit() return jsonify({ 'message': 'Extra format "{}" deleted.'.format(mimetype)}) @pass_record @check_extra_formats_permission def options(self, pid, record, **kwargs): """Get a list of all extra formats.""" depid, deposit = pid, record # this is a deposit endpoint if deposit.extra_formats: return jsonify(deposit.extra_formats.dumps()) else: return jsonify([]) class RecordExtraFormatsResource(MethodView): """Record extra formats resource.""" # NOTE: No permissions (allow all) # this is considered record metadata (not files) @pass_extra_formats_mimetype(from_query_string=True, from_accept=True) @pass_record def get(self, 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) return abort(404, 'No extra format "{}".'.format(mimetype)) # NOTE: No permissions (allow all), # this is considered extra_formats (not files) @pass_record def options(self, pid, record, **kwargs): """Get available extra formats.""" if record.extra_formats: return jsonify(record.extra_formats.dumps()) else: return jsonify([]) _DEPID = 'pid(depid,record_class="zenodo.modules.deposit.api:ZenodoDeposit")' _RECID = 'pid(recid,record_class="zenodo.modules.records.api:ZenodoRecord")' blueprint.add_url_rule( '/deposit/depositions/<{}:pid_value>/formats'.format(_DEPID), view_func=DepositExtraFormatsResource.as_view('depid_extra_formats'), ) blueprint.add_url_rule( '/records/<{}:pid_value>/formats'.format(_RECID), view_func=RecordExtraFormatsResource.as_view('recid_extra_formats'), )
7,822
Python
.py
182
36.214286
79
0.67613
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,450
forms.py
zenodo_zenodo/zenodo/modules/deposit/forms.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. """Forms for deposit module.""" from __future__ import absolute_import, print_function from flask_babelex import lazy_gettext as _ from flask_wtf import Form from wtforms import BooleanField, SelectField, StringField, SubmitField, \ TextAreaField def strip_filter(text): """Filter for trimming whitespace.""" return text.strip() if text else text class RecordDeleteForm(Form): """Form for deleting a record.""" reason = TextAreaField( _('Removal reason (custom)'), description=_( 'Please provide a reason for removing the record. This reason will' ' be displayed on the record tombstone page.'), filters=[strip_filter], ) standard_reason = SelectField( _('Removal reason (standard options)'), coerce=str, ) remove_files = BooleanField( _('Remove files from disk?'), default=True, description=_( 'Files will be removed from disk. Recovery of files possible if ' 'SIPs are not removed.'), ) remove_sips = BooleanField( _('Remove SIPs?'), description=_( 'Also, remove Submission Information Packages for record. Recovery' ' of files will not be possible.'), default=False, ) confirm = StringField( _('Confirm deletion'), description=_( 'Please manually type the record identifier in order to confirm' ' the deletion.') ) delete = SubmitField(_("Permanently delete record"))
2,511
Python
.py
66
32.909091
79
0.690789
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,451
views.py
zenodo_zenodo/zenodo/modules/deposit/views.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. """Redirects for legacy URLs.""" from __future__ import absolute_import, print_function, unicode_literals from datetime import datetime from functools import wraps from flask import Blueprint, Markup, abort, current_app, flash, redirect, \ render_template, request, url_for from flask_babelex import gettext as _ from flask_security import current_user, login_required from invenio_accounts.models import User from invenio_communities.models import Community from invenio_db import db from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.errors import PIDDeletedError, PIDDoesNotExistError from invenio_pidstore.models import PersistentIdentifier from invenio_pidstore.resolver import Resolver from invenio_records_ui.signals import record_viewed from zenodo.modules.deposit.utils import delete_record from zenodo.modules.openaire import current_openaire from zenodo.modules.records import current_zenodo_records from zenodo.modules.records.permissions import has_admin_permission, \ record_permission_factory from zenodo.modules.utils import obj_or_import_string from .api import ZenodoDeposit from .fetchers import zenodo_deposit_fetcher from .forms import RecordDeleteForm blueprint = Blueprint( 'zenodo_deposit', __name__, url_prefix='', template_folder='templates', static_folder='static', ) @blueprint.errorhandler(PIDDeletedError) def tombstone_errorhandler(error): """Render tombstone page.""" return render_template( current_app.config['RECORDS_UI_TOMBSTONE_TEMPLATE'], pid=error.pid, record=error.record or {}, ), 410 def pass_record(action, deposit_cls=ZenodoDeposit): """Pass record and deposit record to function.""" def decorator(f): @wraps(f) def inner(pid_value): # Resolve pid_value to record pid and record pid, record = pid_value.data # Check permissions. permission = record_permission_factory( record=record, action=action) if not permission.can(): abort(403) # Fetch deposit id from record and resolve deposit record and pid. depid = zenodo_deposit_fetcher(None, record) if not depid: abort(404) depid, deposit = Resolver( pid_type=depid.pid_type, object_type='rec', getter=deposit_cls.get_record, ).resolve(depid.pid_value) return f(pid=pid, record=record, depid=depid, deposit=deposit) return inner return decorator def can_user_create(f): """Check if the user is verified for the appropriate amount of time.""" @wraps(f) def inner(*args, **kwargs): 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(None, None): return f(*args, **kwargs) flash(error_message, category='warning') abort(403) return inner @login_required def legacy_index(): """Legacy deposit.""" c_id = request.args.get('c', type=str) if c_id: return redirect(url_for('invenio_deposit_ui.new', c=c_id)) return render_template(current_app.config['DEPOSIT_UI_INDEX_TEMPLATE']) @login_required @can_user_create def new(): """Create a new deposit.""" c = Community.get(request.args.get('c', type=str)) return render_template(current_app.config['DEPOSIT_UI_NEW_TEMPLATE'], record={'_deposit': {'id': None}}, community=c) @blueprint.route( '/record/<pid(recid,record_class=' '"zenodo.modules.records.api:ZenodoRecord"):pid_value>', methods=['POST'] ) @login_required @pass_record('update') def edit(pid=None, record=None, depid=None, deposit=None): """Edit a record.""" # If the record doesn't have a DOI, its deposit shouldn't be editable. if 'doi' not in record: abort(404) return redirect(url_for( 'invenio_deposit_ui.{0}'.format(depid.pid_type), pid_value=depid.pid_value )) @blueprint.route( '/record/<pid(recid,record_class=' '"zenodo.modules.records.api:ZenodoRecord"):pid_value>' '/newversion', methods=['POST'] ) @login_required @pass_record('newversion') def newversion(pid=None, record=None, depid=None, deposit=None): """Create a new version of a record.""" # If the record doesn't have a DOI, its deposit shouldn't be editable. if 'doi' not in record: abort(404) # FIXME: Maybe this has to go inside the API (`ZenodoDeposit.newversion`) # If this is not the latest version, get the latest and extend it latest_pid = PIDVersioning(child=pid).last_child if pid != latest_pid: # We still want to do a POST, so we specify a 307 redirect code return redirect(url_for('zenodo_deposit.newversion', pid_value=latest_pid.pid_value), code=307) deposit.newversion() db.session.commit() new_version_deposit = PIDVersioning(child=pid).draft_child_deposit return redirect(url_for( 'invenio_deposit_ui.{0}'.format(new_version_deposit.pid_type), pid_value=new_version_deposit.pid_value )) @blueprint.route( '/record/<pid(recid,record_class=' '"zenodo.modules.records.api:ZenodoRecord"):pid_value>' '/registerconceptdoi', methods=['POST'] ) @login_required @pass_record('registerconceptdoi') def registerconceptdoi(pid=None, record=None, depid=None, deposit=None): """Register the Concept DOI for the record.""" # If the record doesn't have a DOI, its deposit shouldn't be editable. if 'conceptdoi' in record: abort(404) # TODO: Abort with better code if record is versioned deposit.registerconceptdoi() db.session.commit() return redirect(url_for('invenio_records_ui.recid', pid_value=pid.pid_value)) @blueprint.route( '/record' '/<pid(recid,record_class=' '"zenodo.modules.records.api:ZenodoRecord"):pid_value>' '/admin/delete', methods=['GET', 'POST'] ) @login_required @pass_record('delete') def delete(pid=None, record=None, depid=None, deposit=None): """Delete a record.""" # View disabled until properly implemented and tested. try: doi = PersistentIdentifier.get('doi', record['doi']) except PIDDoesNotExistError: doi = None owners = User.query.filter(User.id.in_(record.get('owners', []))).all() pids = [pid, depid, doi] if 'conceptdoi' in record: conceptdoi = PersistentIdentifier.get('doi', record['conceptdoi']) pids.append(conceptdoi) else: conceptdoi = None if 'conceptrecid' in record: conceptrecid = PersistentIdentifier.get('recid', record['conceptrecid']) pids.append(conceptrecid) else: conceptrecid = None form = RecordDeleteForm() form.standard_reason.choices = current_app.config['ZENODO_REMOVAL_REASONS'] if form.validate_on_submit(): reason = form.reason.data or dict( current_app.config['ZENODO_REMOVAL_REASONS'] )[form.standard_reason.data] delete_record(record.id, reason, int(current_user.get_id())) flash( _('Record %(recid)s and associated objects successfully deleted.', recid=pid.pid_value), category='success' ) return redirect(url_for('zenodo_frontpage.index')) return render_template( 'zenodo_deposit/delete.html', form=form, owners=owners, pid=pid, pids=pids, record=record, deposit=deposit, ) @blueprint.app_context_processor def current_datetime(): """Template contex processor which adds current datetime to the context.""" now = datetime.utcnow() return { 'current_datetime': now, 'current_date': now.date(), 'current_time': now.time(), } @blueprint.app_context_processor def current_openaire_ctx(): """Current OpenAIRE context.""" return dict(current_openaire=current_openaire) @blueprint.app_template_filter('tolinksjs') def to_links_js(pid, deposit=None): """Get API links.""" if not isinstance(deposit, ZenodoDeposit): return [] self_url = current_app.config['DEPOSIT_RECORDS_API'].format( pid_value=pid.pid_value) links = { 'self': self_url, 'html': url_for( 'invenio_deposit_ui.{}'.format(pid.pid_type), pid_value=pid.pid_value), 'bucket': current_app.config['DEPOSIT_FILES_API'] + '/{0}'.format( str(deposit.files.bucket.id)), 'discard': self_url + '/actions/discard', 'edit': self_url + '/actions/edit', 'publish': self_url + '/actions/publish', 'newversion': self_url + '/actions/newversion', 'registerconceptdoi': self_url + '/actions/registerconceptdoi', 'files': self_url + '/files', } # Add versioning links conceptrecid = deposit.get('conceptrecid') if conceptrecid: conceptrecid = PersistentIdentifier.get('recid', conceptrecid) pv = PIDVersioning(parent=conceptrecid) latest_record = pv.last_child if latest_record: links['latest'] = current_app.config['RECORDS_API'].format( pid_value=latest_record.pid_value) links['latest_html'] = url_for( 'invenio_records_ui.recid', pid_value=latest_record.pid_value) draft_child_depid = pv.draft_child_deposit if draft_child_depid: links['latest_draft'] = ( current_app.config['DEPOSIT_RECORDS_API'] .format(pid_value=draft_child_depid.pid_value)) links['latest_draft_html'] = url_for( 'invenio_deposit_ui.{}'.format(draft_child_depid.pid_type), pid_value=draft_child_depid.pid_value) return links @blueprint.app_template_filter('tofilesjs') def to_files_js(deposit): """List files in a deposit.""" if not isinstance(deposit, ZenodoDeposit): return [] res = [] for f in deposit.files: res.append({ 'key': f.key, 'version_id': f.version_id, 'checksum': f.file.checksum, 'size': f.file.size, 'completed': True, 'progress': 100, 'links': { 'self': ( current_app.config['DEPOSIT_FILES_API'] + u'/{bucket}/{key}?versionId={version_id}'.format( bucket=f.bucket_id, key=f.key, version_id=f.version_id, )), } }) for f in deposit.multipart_files.all(): res.append({ 'key': f.key, 'size': f.size, 'multipart': True, 'completed': f.completed, 'processing': True, 'progress': 100, 'links': { 'self': ( current_app.config['DEPOSIT_FILES_API'] + u'/{bucket}/{key}?uploadId={upload_id}'.format( bucket=f.bucket_id, key=f.key, upload_id=f.upload_id, )), } }) return res def default_view_method(pid, record, template=None): """Default view method for updating record. Sends ``record_viewed`` signal and renders template. :param pid: PID object ('depid'-type PID). :param record: Record object (Deposit API). :param template: Template to render. """ # Put deposit in edit mode if not already. if record['_deposit']['status'] != 'draft': record = record.edit() db.session.commit() record_viewed.send( current_app._get_current_object(), pid=pid, record=record, ) return render_template( template, pid=pid, record=record, )
13,211
Python
.py
344
30.938953
79
0.643292
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,452
bundles.py
zenodo_zenodo/zenodo/modules/deposit/bundles.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. """Bundles for Zenodo deposit form.""" from flask_assets import Bundle from invenio_assets import NpmBundle from invenio_deposit.bundles import js_dependecies_autocomplete, \ js_dependecies_schema_form, js_dependencies_ckeditor, \ js_dependencies_jquery, js_dependencies_ui_sortable, js_main js_zenodo_deposit = Bundle( 'js/zenodo_deposit/filters.js', 'js/zenodo_deposit/directives.js', 'js/zenodo_deposit/controllers.js', 'js/zenodo_deposit/providers.js', 'js/zenodo_deposit/config.js', depends=( 'js/zenodo_deposit/*.js', ), ) # NOTE: Override to use `@inveniosoftware/invenio-files-js v0.0.6` js_dependecies_uploader = NpmBundle( 'node_modules/ng-file-upload/dist/ng-file-upload-all.js', 'node_modules/@inveniosoftware/invenio-files-js/dist/invenio-files-js.js', npm={ '@inveniosoftware/invenio-files-js': '~0.0.6', 'ng-file-upload': '~12.0.4', 'underscore': '~1.8.3', } ) js_deposit = NpmBundle( js_dependencies_jquery, js_main, js_dependecies_uploader, js_dependecies_schema_form, js_dependecies_autocomplete, js_dependencies_ui_sortable, js_dependencies_ckeditor, js_zenodo_deposit, filters='uglifyjs', output='gen/zenodo.deposit.%(version)s.js', )
2,251
Python
.py
61
33.786885
78
0.736384
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,453
__init__.py
zenodo_zenodo/zenodo/modules/deposit/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,454
__init__.py
zenodo_zenodo/zenodo/modules/deposit/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,455
__init__.py
zenodo_zenodo/zenodo/modules/deposit/loaders/__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. """Deposit loaders.""" from __future__ import absolute_import, print_function from zenodo.modules.records.serializers.schemas.json import RecordSchemaV1 from zenodo.modules.records.serializers.schemas.legacyjson import \ LegacyRecordSchemaV1 from .base import json_loader, marshmallow_loader # Translators # =========== #: JSON v1 deposit translator. deposit_json_v1_translator = marshmallow_loader(RecordSchemaV1) #: Legacy deposit dictionary translator. legacyjson_v1_translator = marshmallow_loader(LegacyRecordSchemaV1) # Loaders # ======= #: JSON deposit record loader. deposit_json_v1 = json_loader( translator=deposit_json_v1_translator, ) #: Legacy deposit JSON record loader. legacyjson_v1 = json_loader( translator=legacyjson_v1_translator, )
1,738
Python
.py
45
37.222222
76
0.783047
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,456
base.py
zenodo_zenodo/zenodo/modules/deposit/loaders/base.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. """Loaders for records.""" from __future__ import absolute_import, print_function from flask import current_app, has_request_context, request from zenodo.modules.records.minters import doi_generator from ..errors import MarshmallowErrors def json_loader(pre_validator=None, post_validator=None, translator=None): """Basic JSON loader with translation and pre/post validation support.""" def loader(data=None): data = data or request.json if pre_validator: pre_validator(data) if translator: data = translator(data) if post_validator: post_validator(data) return data return loader def marshmallow_loader(schema_class, **kwargs): """Basic marshmallow loader generator.""" def translator(data): # Replace refs when we are in request context. context = dict(replace_refs=has_request_context()) # DOI validation context if request and request.view_args.get('pid_value'): managed_prefix = current_app.config['PIDSTORE_DATACITE_DOI_PREFIX'] _, record = request.view_args.get('pid_value').data context['recid'] = record['recid'] if record.has_minted_doi() or record.get('conceptdoi'): # if record has Zenodo DOI it's not allowed to change context['required_doi'] = record['doi'] elif not record.is_published(): context['allowed_dois'] = [doi_generator(record['recid'])] if record.is_published() or record.get('conceptdoi'): # if the record is published or this is a new version # of a published record then the DOI is required context['doi_required'] = True data.setdefault('metadata', {}) if 'doi' not in data['metadata']: # if the payload doesn't contain the DOI field # for the record keep the existing one data['metadata']['doi'] = record['doi'] context['managed_prefixes'] = [managed_prefix] context['banned_prefixes'] = \ ['10.5072'] if managed_prefix != '10.5072' else [] # Extra context context.update(kwargs) # Load data result = schema_class(context=context).load(data) if result.errors: raise MarshmallowErrors(result.errors) return result.data return translator
3,444
Python
.py
75
38.133333
79
0.660602
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,457
__init__.py
zenodo_zenodo/zenodo/modules/deposit/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 deposit jsonschemas.""" from __future__ import absolute_import, print_function
1,058
Python
.py
25
41.24
76
0.773036
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,458
records.py
zenodo_zenodo/zenodo/modules/auditor/records.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 Auditor for records.""" from invenio_accounts.models import User from invenio_communities.models import Community from invenio_oaiserver.models import OAISet from invenio_pidstore.models import PersistentIdentifier from jsonschema import SchemaError, ValidationError from werkzeug.utils import cached_property from .api import Audit, Check from .utils import duplicates class RecordAudit(Audit): """Record Audit.""" def __init__(self, audit_id, logger, records): """Initialize a Record audit.""" super(RecordAudit, self).__init__(audit_id, logger) self._checks = (RecordCheck(self, r) for r in records) @cached_property def all_communities(self): """Set of all the existing community identifiers.""" return {c.id for c in Community.query.all()} @cached_property def all_owners(self): """Set of all the existing owner identifiers.""" return {c.id for c in User.query.all()} @cached_property def custom_oai_sets(self): """Set of OAI sets that follow a record search pattern.""" oai_sets = OAISet.query.filter(OAISet.search_pattern.isnot(None)).all() return {o.spec for o in oai_sets} @cached_property def all_oai_pids(self): """Set of OAI identifiers.""" oai_pids = (PersistentIdentifier.query .filter(PersistentIdentifier.pid_type == 'oai') .all()) return {p.pid_value for p in oai_pids} class RecordCheck(Check): """Record Check.""" def __init__(self, audit, record): """Initialize a Record check.""" super(RecordCheck, self).__init__() self.audit = audit self.record = record def communities(self): """Check communities.""" self._unresolvable_communities() self._duplicate_communities() def _unresolvable_communities(self): comms = set(self.record.get('communities', [])) unresolvable_communities = comms - self.audit.all_communities if unresolvable_communities: self.issues['communities']['unresolvable'] = \ list(unresolvable_communities) def _duplicate_communities(self): duplicate_comms = duplicates(self.record.get('communities', [])) if duplicate_comms: self.issues['communities']['duplicates'] = duplicate_comms def owners(self): """Check owners.""" self._duplicate_owners() self._unresolvable_owners() def _duplicate_owners(self): duplicate_owners = duplicates(self.record.get('owners', [])) if duplicate_owners: self.issues['owners']['duplicates'] = duplicate_owners def _unresolvable_owners(self): owners = set(self.record.get('owners', [])) unresolvable_owners = owners - self.audit.all_owners if unresolvable_owners: self.issues['owners']['unresolvable'] = list(unresolvable_owners) def files(self): """Check files.""" self._duplicate_files() self._missing_files() self._multiple_buckets() self._bucket_mismatch() def _duplicate_files(self): files = self.record.get('_files', []) duplicate_keys = duplicates([f['key'] for f in files]) duplicate_version_ids = duplicates([f['version_id'] for f in files]) duplicate_files = [f for f in files if (f['key'] in duplicate_keys or f['version_id'] in duplicate_version_ids)] if duplicate_files: self.issues['files']['duplicates'] = duplicate_files def _missing_files(self): files = self.record.get('_files', []) if not files: self.issues['files']['missing'] = True def _multiple_buckets(self): files = self.record.get('_files', []) buckets = {f['bucket'] for f in files} if len(buckets) > 1: self.issues['files']['multiple_buckets'] = list(buckets) def _bucket_mismatch(self): """Check if buckets in '_files' don't match the ones '_buckets'.""" files = self.record.get('_files', []) record_bucket = self.record.get('_buckets', {}).get('record') bucket_mismatch = [f for f in files if f['bucket'] != record_bucket] if bucket_mismatch: self.issues['files']['bucket_mismatch'] = bucket_mismatch def grants(self): """Check grants.""" self._duplicate_grants() def _duplicate_grants(self): grant_ids = [g.get('$ref') for g in self.record.get('grants', [])] duplicate_grants = duplicates(grant_ids) if any(duplicate_grants): self.issues['grants']['duplicates'] = duplicate_grants def oai(self): """Check OAI data.""" self._oai_required() self._oai_non_minted_pid() self._oai_duplicate_sets() self._oai_community_correspondence() def _oai_required(self): oai_data = self.record.get('_oai', {}) if not oai_data.get('id'): self.issues['oai']['missing']['id'] = True if not oai_data.get('updated'): self.issues['oai']['missing']['updated'] = True def _oai_non_minted_pid(self): oai_data = self.record.get('_oai', {}) oai_pid = oai_data.get('id') if oai_pid and oai_pid not in self.audit.all_oai_pids: self.issues['oai']['non_minted_pid'] = oai_data.get('id') def _oai_duplicate_sets(self): oai_sets = self.record.get('_oai', {}).get('sets', []) duplicate_oai_sets = duplicates(oai_sets) if duplicate_oai_sets: self.issues['oai']['duplicate_oai_sets'] = duplicate_oai_sets def _oai_community_correspondence(self): oai_sets = set(self.record.get('_oai', {}).get('sets', [])) comms = set(self.record.get('communities', [])) if oai_sets or comms: comm_oai_sets = {s for s in oai_sets if (s.startswith('user-') and s not in self.audit.custom_oai_sets)} comm_specs = {u'user-{c}'.format(c=c) for c in comms} missing_comm_oai_sets = comm_specs - comm_oai_sets if missing_comm_oai_sets: self.issues['oai']['missing_oai_sets'] = \ list(missing_comm_oai_sets) redundant_oai_sets = comm_oai_sets - comm_specs if redundant_oai_sets: self.issues['oai']['redundant_oai_sets'] = \ list(redundant_oai_sets) def jsonschema(self): """Check JSONSchema.""" try: self.record.validate() except (ValidationError, SchemaError) as e: self.issues['jsonschema'] = str(e.message) def perform(self): """Perform record checks.""" self.jsonschema() self.communities() self.files() self.owners() self.grants() self.oai() def dump(self): """Dump record check.""" record_data = { 'recid': self.record['recid'], 'object_uuid': str(self.record.id), } result = super(RecordCheck, self).dump() result.update({'record': record_data}) return result
8,270
Python
.py
193
34.388601
79
0.614897
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,459
ext.py
zenodo_zenodo/zenodo/modules/auditor/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. """Module for auditing of Zenodo data.""" from __future__ import absolute_import, print_function class ZenodoAuditor(object): """Zenodo-Auditor extension.""" def __init__(self, app=None): """Extension initialization.""" if app: self.init_app(app) def init_app(self, app): """Flask application initialization.""" app.extensions['zenodo-auditor'] = self
1,381
Python
.py
34
37.794118
76
0.734526
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,460
cli.py
zenodo_zenodo/zenodo/modules/auditor/cli.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. """CLI for Zenodo-Auditor tasks.""" from __future__ import absolute_import, print_function import click from flask.cli import with_appcontext from .tasks import audit_oai, audit_records @click.group() def audit(): """Zenodo Auditor CLI.""" @audit.command('records') @click.option('--logfile', '-l', type=click.Path(exists=False, dir_okay=False, resolve_path=True)) @click.option('--eager', '-e', is_flag=True) @with_appcontext def _audit_records(logfile, eager): """Audit all records.""" if eager: audit_records.apply((logfile,), throw=True) else: audit_records.apply_async((logfile,)) @audit.command('oai') @click.option('--logfile', '-l', type=click.Path(exists=False, dir_okay=False, resolve_path=True)) @click.option('--eager', '-e', is_flag=True) @with_appcontext def _audit_oai(logfile, eager): """Audit OAI Sets.""" if eager: audit_oai.apply((logfile,), throw=True) else: audit_oai.apply_async((logfile,))
2,048
Python
.py
53
34.471698
78
0.695214
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,461
tasks.py
zenodo_zenodo/zenodo/modules/auditor/tasks.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 Auditor tasks.""" from __future__ import absolute_import import uuid from celery import shared_task from flask import current_app from invenio_communities.models import Community from .oai import OAIAudit from .records import RecordAudit from .utils import all_records, get_file_logger @shared_task(ignore_results=True) def audit_records(logfile=None): """Audit all records. :param str logfile: Logfile path for encountered issues. """ logger = current_app.logger audit_id = audit_records.request.id or uuid.uuid4() if logfile: logger = get_file_logger(logfile, 'records', audit_id) audit = RecordAudit(audit_id, logger, all_records()) for check in audit: pass @shared_task(ignore_results=True) def audit_oai(logfile=None): """Audit OAI sets. :param str logfile: Logfile path for encountered issues. """ logger = current_app.logger audit_id = audit_oai.request.id or uuid.uuid4() if logfile: logger = get_file_logger(logfile, 'oai', audit_id) audit = OAIAudit(audit_id, logger, Community.query.all()) try: for check in audit: pass except Exception: raise finally: audit.clear_db_oai_set_cache()
2,215
Python
.py
61
32.967213
76
0.734951
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,462
api.py
zenodo_zenodo/zenodo/modules/auditor/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. """Zenodo Auditor API.""" import json from .utils import tree class Audit(object): """Audit base class.""" def __init__(self, audit_id, logger): """Initialize an Audit with a logger.""" self.audit_id = audit_id self.logger = logger self._checks = None def __iter__(self): """Get iterator.""" return self def next(self): """Python 2.7 compatibility.""" return self.__next__() def __next__(self): """Get, perform and log the next check.""" check = next(self._checks) try: check.perform() except Exception: self.logger.exception(json.dumps(check.dump())) finally: if not check.is_ok: print(json.dumps(check.dump())) self.logger.error(json.dumps(check.dump())) return check class Check(object): """Audit Check base class.""" def __init__(self): """Initialize a Check.""" self.issues = tree() def perform(self, **kwargs): """Perform the check.""" raise NotImplementedError() def dump(self): """Dump check issues.""" return {'issues': self.issues} @property def is_ok(self): """Get if check is considered passed.""" return not bool(self.issues)
2,309
Python
.py
66
29.393939
76
0.650359
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,463
utils.py
zenodo_zenodo/zenodo/modules/auditor/utils.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. """Utilities for Zenodo-Auditor.""" from __future__ import absolute_import, print_function, unicode_literals import logging from collections import Counter from logging.handlers import MemoryHandler from flask import current_app, url_for from invenio_db import db from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.models import RecordMetadata from mock import MagicMock from ..records.api import ZenodoRecord def all_records(): """Return a ZenodoRecord generator with all records.""" records = (db.session.query(RecordMetadata) .join(PersistentIdentifier, RecordMetadata.id == PersistentIdentifier.object_uuid) .filter(PersistentIdentifier.pid_type == 'recid', PersistentIdentifier.status == PIDStatus.REGISTERED)) return (ZenodoRecord(data=r.json, model=r) for r in records) class tree(dict): """Self-vivified dictionary.""" def __missing__(self, key): """Return a new instance of self.""" value = self[key] = type(self)() return value def duplicates(l): """Return duplicate elements from an iterable.""" return [i for i, c in Counter(l).items() if c > 1] def sickle_requests_get_mock(): """Return a mock `request.get` for `sickle` that uses `Flask.test_client`. Because `sickle.Sickle` is strongly dependent on the `requests` library to make all its OAI-PMH harvesting calls, it is not possible to use it for local usage without running a live instance of Invenio-OAIServer. To bypass this we are making a function mock that makes a request using the `Flask.test_client`, and returns a mock containing the text response. """ def get(endpoint, params, **kwargs): """Mock `request.get` method.""" with current_app.test_request_context(): with current_app.test_client() as client: if endpoint == 'http://auditor/oai2d': oai_url = url_for('invenio_oaiserver.response', **params) res = client.get(oai_url) mock_res = MagicMock() mock_res.text = res.get_data(as_text=True) return mock_res return MagicMock(side_effect=get) def get_file_logger(logfile, audit_type, audit_id): """Return a buffered file logger.""" logger = logging.getLogger('zenodo.auditor.{type}.{id}' .format(type=audit_type, id=audit_id)) if logfile: file_handler = logging.FileHandler(logfile, mode='w') logger.addHandler(MemoryHandler(100, target=file_handler)) return logger
3,635
Python
.py
78
40.641026
79
0.698785
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,464
__init__.py
zenodo_zenodo/zenodo/modules/auditor/__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 Auditor.""" from __future__ import absolute_import, print_function
1,046
Python
.py
25
40.76
76
0.771344
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,465
oai.py
zenodo_zenodo/zenodo/modules/auditor/oai.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 Auditor for OAI-PMH.""" from __future__ import absolute_import, print_function, unicode_literals from itertools import chain from elasticsearch_dsl import Q from flask import current_app from invenio_cache import current_cache from invenio_communities.models import Community from invenio_db import db from invenio_oaiserver.models import OAISet from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.models import RecordMetadata from invenio_search import RecordsSearch from mock import patch from sickle import Sickle from .api import Audit, Check from .utils import sickle_requests_get_mock class OAIAudit(Audit): """OAI Audit.""" def __init__(self, audit_id, logger, communities): """Initialize an OAI audit.""" super(OAIAudit, self).__init__(audit_id, logger) self._build_oai_sets_from_db() self._checks = chain(iter((OAICorrespondenceCheck(),)), (OAISetResultCheck(self, c) for c in communities)) def _build_oai_sets_from_db(self): # NOTE: We're relying on Redis-specific data types and commands, so we # have to be sure that we have Redis as our cache type. if current_app.config.get('CACHE_TYPE') != 'redis': raise Exception('OAIAudit: Redis cache type required.') self.cache = current_cache.cache._write_client self.cache_prefix = 'zenodo.auditor.oai:{}'.format(str(self.audit_id)) record_oai_sets = ( db.session.query(RecordMetadata) .join( PersistentIdentifier, RecordMetadata.id == PersistentIdentifier.object_uuid) .filter( PersistentIdentifier.pid_type == 'oai', PersistentIdentifier.status == PIDStatus.REGISTERED) .with_entities( PersistentIdentifier.pid_value, RecordMetadata.json) ) for oai_id, record in record_oai_sets: for s in record.get('_oai', {}).get('sets', []): oai_control_number = oai_id.split(':')[-1] self.cache.sadd('{}:{}'.format(self.cache_prefix, s), oai_control_number) def pop_db_oai_set(self, oai_set): """Return and remove from cache an OAI Set.""" key = '{}:{}'.format(self.cache_prefix, oai_set) # TODO: Remove map as it needs to be string oai_sets = set(map(int, self.cache.smembers(key))) self.cache.delete(key) return oai_sets def clear_db_oai_set_cache(self): """Clear all cached OAI Sets generated for this audit.""" for key in self.cache.scan_iter('{}:*'.format(self.cache_prefix)): self.cache.delete(key) class OAICorrespondenceCheck(Check): """OAI Global Check.""" def sets_correspondence(self): """Check correspondence of Communities and their OAI Sets.""" missing_oai_sets = [] for c in Community.query.all(): if not OAISet.query.filter_by(spec=c.oaiset_spec).count(): missing_oai_sets.append(c.id) if missing_oai_sets: self.issues['missing_oai_set'] = missing_oai_sets missing_communities = [] for s in OAISet.query.filter(OAISet.search_pattern.is_(None), OAISet.spec.startswith('user-')): if not Community.query.filter_by(id=s.spec[5:]).count(): missing_communities.append(s.spec) if missing_communities: self.issues['missing_community'] = missing_communities def perform(self): """Perform OAI Set correspondence checks.""" self.sets_correspondence() class OAISetResultCheck(Check): """OAI Set Count check.""" def __init__(self, audit, community): """Initialize an OAI Set result check.""" super(OAISetResultCheck, self).__init__() self.audit = audit self.community = community def results_consistency(self): """Check for consistent Community OAI Set results. There are three points of reference for OAI Set data: - Database Records - Elasticsearch Records Index - The `/oai2d` Endpoint Checking that the set of identifiers is consistent throughout these sources is vital. """ db_ids = self._db_identifiers() es_ids = self._es_identifiers() oai2d_ids = self._oai2d_endpoint_identifiers() all_ids = (db_ids | es_ids | oai2d_ids) for source, ids in zip(('db', 'es', 'oai2d'), (db_ids, es_ids, oai2d_ids)): missing_ids = list(all_ids - ids) if missing_ids: self.issues['missing_ids'][source] = missing_ids def _db_identifiers(self): """Return a set of the Community OAI Set recids from the database.""" return self.audit.pop_db_oai_set(self.community.oaiset_spec) def _es_identifiers(self): """Return a set of the Community OAI Set recids from Elasticsearch.""" query = Q('bool', filter=Q('exists', field='_oai.id'), must=Q('match', **{'_oai.sets': self.community.oaiset_spec})) index = current_app.config['OAISERVER_RECORD_INDEX'] search = RecordsSearch(index=index).source(['_oai.id']).query(query) return {int(r._oai.id.rsplit(':', 1)[-1]) for r in search.scan()} def _oai2d_endpoint_identifiers(self): """Return a set of the Community OAI Set recids from OAI endpoint.""" with patch('sickle.app.requests.get', new=sickle_requests_get_mock()): sickle = Sickle('http://auditor/oai2d') ids = sickle.ListIdentifiers(set=self.community.oaiset_spec, metadataPrefix='oai_dc') return {int(i.identifier.rsplit(':', 1)[-1]) for i in ids} def perform(self): """Perform OAI Set result checks.""" self.results_consistency() def dump(self): """Dump OAI Set result check.""" community_data = { 'id': self.community.id, 'oaiset_spec': self.community.oaiset_spec, } result = super(OAISetResultCheck, self).dump() result.update({'community': community_data}) return result
7,324
Python
.py
157
37.980892
79
0.637982
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,466
schemas.py
zenodo_zenodo/zenodo/modules/github/schemas.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016-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. """GitHub schemas.""" from __future__ import absolute_import, print_function, unicode_literals import arrow import six from invenio_records_rest.schemas.fields import GenMethod from marshmallow import Schema, ValidationError, fields, missing, post_dump, \ post_load, pre_dump, pre_load, validate, validates, validates_schema from zenodo.modules.records.models import ObjectType from zenodo.modules.records.serializers.fields import DateString, \ PersistentId, SanitizedHTML, SanitizedUnicode from zenodo.modules.records.serializers.schemas.common import RefResolverMixin class AuthorSchema(Schema): """Schema for a person.""" name = GenMethod(deserialize='load_name') affiliation = SanitizedUnicode() orcid = PersistentId(scheme='ORCID') def load_name(self, value, data): """Load name field.""" family_name = data.get('family-names') given_name = data.get('given-names') org_name = data.get('name') if org_name: return org_name if family_name and given_name: return u'{}, {}'.format(family_name, given_name) return family_name or given_name @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 CitationMetadataSchema(Schema, RefResolverMixin): """Citation metadata schema.""" description = SanitizedHTML(load_from='abstract') creators = fields.Nested( AuthorSchema, many=True, load_from='authors') keywords = fields.List(SanitizedUnicode()) license = SanitizedUnicode() title = SanitizedUnicode(required=True, validate=validate.Length(min=3)) notes = SanitizedHTML(load_from='message') # TODO: Add later # alternate_identifiers = fields.Raw(load_from='identifiers') # related_identifiers = fields.Raw(load_from='references') subschema = { "audiovisual": "video", "art": "other", "bill": "other", "blog": "other", "catalogue": "other", "conference-paper": "conference", "database": "data", "dictionary": "other", "edited-work": "other", "encyclopedia": "other", "film-broadcast": "video", "government-document": "other", "grant": "other", "hearing": "other", "historical-work": "other", "legal-case": "other", "legal-rule": "other", "magazine-article": "other", "manual": "other", "map": "other", "multimedia": "video", "music": "other", "newspaper-article": "other", "pamphlet": "other", "patent": "other", "personal-communication": "other", "proceedings": "other", "report": "other", "serial": "other", "slides": "other", "software-code": "software", "software-container": "software", "software-executable": "software", "software-virtual-machine": "software", "sound-recording": "other", "standard": "other", "statute": "other", "website": "other" } # @pre_load() # def preload_related_identifiers(self, data): # """Default publication date.""" # final = [] # for reference in data['references']: # resource_type = reference['type'] # if self.subschema.get(resource_type): # resource_type = self.subschema[resource_type] # else: # resource_type = ObjectType.get_cff_type(resource_type) # # data-type grab instead? # for item in reference['identifiers']: # schemes = idutils.detect_identifier_schemes(item['value']) # if not schemes or (item['type'] not in schemes): # errors = self.context['release'].errors # cff_errors = errors.get('CITATION.cff', []) # cff_errors.append( # 'We could not process the identifier: {} in our system' # .format(item['value'])) # errors['CITATION.cff'] = cff_errors # continue # final.append({ # 'identifier': item['value'], # 'scheme': item['type'], # 'resource_type': resource_type, # 'relation': 'references' # }) # data['references'] = final # @pre_load() # def preload_alternate_identifiers(self, data): # """Default publication date.""" # final = [] # resource_type = data.get('type', 'other') # if self.subschema.get(resource_type): # resource_type = self.subschema[resource_type] # else: # resource_type = ObjectType.get_cff_type(resource_type) # # data-type grab instead? # for item in data.get('identifiers', []): # schemes = idutils.detect_identifier_schemes(item['value']) # if not schemes or (item['type'] not in schemes): # errors = self.context['release'].errors # cff_errors = errors.get('CITATION.cff', []) # cff_errors.append( # 'We could not process the identifier: {} in our system' # .format(item['value'])) # errors['CITATION.cff'] = cff_errors # continue # final.append({ # 'identifier': item['value'], # 'scheme': item['type'], # 'resource_type': resource_type # }) # data['identifiers'] = final
6,766
Python
.py
164
35.445122
81
0.594989
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,467
cli.py
zenodo_zenodo/zenodo/modules/github/cli.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. """Click command-line interface for GitHub management.""" from __future__ import absolute_import, print_function import click from flask.cli import with_appcontext from invenio_accounts.models import User from invenio_db import db from invenio_github.api import GitHubAPI from invenio_github.models import Repository from sqlalchemy.orm.exc import NoResultFound @click.group() def github(): """Management commands for GitHub.""" def resolve_user(user_param): """Resolve user from CLI input parameter (email or User ID).""" if user_param is None: return if '@' in user_param: # Try to resolve as email try: user = User.query.filter_by(email=user_param.strip()).one() except NoResultFound: raise Exception("User {0} not found.".format(user_param)) else: try: user_id = int(user_param) user = User.query.get(user_id) except ValueError: raise Exception("User parameter must be either an email or ID") if user is None: raise Exception("User {0} not found.".format(user_param)) return user def resolve_repo(repo_param): """Resolve GitGub repository CLI input parameter (name or GitHub ID).""" if repo_param is None: return try: if '/' in repo_param: repo = Repository.query.filter_by(name=repo_param).one() else: try: github_id = int(repo_param) except ValueError: raise Exception('GitHub repository parameter must be either' ' a name or GitHub ID') repo = Repository.query.filter_by(github_id=github_id).one() except NoResultFound: raise Exception("Repository {0} not found.".format(repo_param)) return repo def resolve_repos(repo_params): """Resolve multiple GitHub repository param with 'multiple' flag.""" return tuple(resolve_repo(p) for p in repo_params) def verify_email(user): """Check if user's GitHub and account emails match.""" gha = GitHubAPI(user_id=user.id) gh_email = gha.api.me().email if gh_email != user.email: click.confirm("Warning: User's GitHub email ({0}) does not match" " the account's ({1}). Continue?".format(gh_email, user.email), abort=True) @github.command('list') @click.argument('user') @click.option('--sync', '-s', is_flag=True, help='Sync the repository prior to listing.') @click.option('with_all', '--all', '-a', is_flag=True, help='List all repositories available.') @click.option('skip_email', '--skip-email-verification', '-E', is_flag=True, help="Skip GitHub email verification.") @with_appcontext def repo_list(user, sync, with_all, skip_email): """List user's repositories hooks. Lists repositories currently `enabled` by the user. If `--all` flag is specified, lists full list of repositories from remote account extra data. For best result `--all` should be used with `--sync`, so that the GitHub information is fresh. Positional argument USER can be either an email or user ID. Examples: github list foo@bar.baz github list 12345 --sync --all """ user = resolve_user(user) gha = GitHubAPI(user_id=user.id) if not skip_email: verify_email(user) if sync: gha.sync(hooks=True, async_hooks=False) # Sync hooks asynchronously db.session.commit() if with_all: repos = gha.account.extra_data['repos'] click.echo("User has {0} repositories in total.".format(len(repos))) for gid, repo in repos.items(): click.echo(' {name}:{gid}'.format(name=repo['full_name'], gid=gid)) repos = Repository.query.filter(Repository.user_id == user.id, Repository.hook.isnot(None)) click.echo("User has {0} enabled repositories.".format(repos.count())) for r in repos: click.echo(" {0}".format(r)) def move_repository(repo, gha_old_user, gha_new_user): """Transfer repository model and hook from one user to another.""" # TODO: Check if both operations are permitted gha_old_user.remove_hook(repo.github_id, repo.name) gha_new_user.create_hook(repo.github_id, repo.name) db.session.commit() @github.command() @click.argument('user') @click.argument('repos', nargs=-1) @click.option('skip_email', '--skip-email-verification', '-E', is_flag=True, help="Skip GitHub email verification.") @click.option('--yes-i-know', is_flag=True, default=False, help='Suppress the confirmation prompt.') @with_appcontext def assign(user, repos, skip_email, yes_i_know): """Assign an already owned repository to another user. First argument, USER, is the user to whom the repository will be assigned. Value of USER can be either the email or user's ID. Arguments REPOS specify one or more repositories, each can be either a repository names or a repository GitHub IDs. Examples: Assign repository 'foobar-org/repo-name' to user 'user1@foo.org': github assign user1@foo.org foobar-org/repo-name Assign three GitHub repositories to user with ID 999: github assign 999 15001500 baz-org/somerepo 12001200 """ user = resolve_user(user) repos = resolve_repos(repos) prompt_msg = 'This will change the ownership for {0} repositories' \ '. Continue?'.format(len(repos)) if not (yes_i_know or click.confirm(prompt_msg)): click.echo('Aborted.') return gha_new = GitHubAPI(user_id=user.id) if not skip_email: verify_email(user) for repo in repos: gha_prev = GitHubAPI(user_id=repo.user_id) move_repository(repo, gha_prev, gha_new) @github.command() @click.argument('user') @click.option('--hooks', default=False, type=bool, help='Synchronize with hooks (Warning: slower)') @click.option('--async-hooks', default=False, type=bool, help='Synchronize hooks asynchronously (--hooks required)') @click.option('skip_email', '--skip-email-verification', '-E', is_flag=True, help="Skip GitHub email verification.") @with_appcontext def sync(user, hooks, async_hooks, skip_email): """Sync user's repositories. USER can be either an email or user ID. Examples: github sync foo@bar.baz github sync 999 """ user = resolve_user(user) gh_api = GitHubAPI(user_id=user.id) gh_api.sync(hooks=hooks, async_hooks=async_hooks) if not skip_email: verify_email(user) db.session.commit() @github.command() @click.argument('user') @click.argument('repo') @click.option('skip_email', '--skip-email-verification', '-E', is_flag=True, help="Skip GitHub email verification.") @click.option('--yes-i-know', is_flag=True, default=False, help='Suppress the confirmation prompt.') @with_appcontext def createhook(user, repo, skip_email, yes_i_know): """Create the hook in repository for given user. USER can be either an email or a user ID. REPO can be either the repository name (e.g. `some-organization/some-repository`) or its GitHub ID. Examples: github createhook abc@foo.bar foobar-org/foobar-repo github createhook 12345 55555 """ user = resolve_user(user) repo = resolve_repo(repo) if repo.user: click.secho('Hook is already installed for {user}'.format( user=repo.user), fg='red') return msg = "Creating a hook for {user} and {repo}. Continue?".format( user=user, repo=repo) if not (yes_i_know or click.confirm(msg)): click.echo('Aborted.') gha = GitHubAPI(user_id=user.id) if not skip_email: verify_email(user) gha.create_hook(repo.github_id, repo.name) db.session.commit() @github.command() @click.argument('repo') @click.option('--user', '-u', help='Attempt to remove hook using given user') @click.option('skip_email', '--skip-email-verification', '-E', is_flag=True, help="Skip GitHub email verification.") @click.option('--yes-i-know', is_flag=True, default=False, help='Suppress the confirmation prompt.') @with_appcontext def removehook(repo, user, skip_email, yes_i_know): """Remove the hook from GitHub repository. Positional argument REPO can be either the repository name, e.g. `some-organization/some-repository` or its GitHub ID. Option '--user' can be either an email or a user ID. Examples: github removehook foobar-org/foobar-repo github removehook 55555 -u foo@bar.baz """ repo = resolve_repo(repo) if not repo.user and not user: click.secho("Repository doesn't have an owner, please specify a user.") return if user: user = resolve_user(user) if not repo.user: click.secho('Warning: Repository is not owned by any user.', fg='yellow') elif repo.user != user: click.secho('Warning: Specified user is not the owner of this' ' repository.', fg='yellow') else: user = repo.user if not skip_email: verify_email(user) msg = "Removing the hook for {user} and {repo}. Continue?".format( user=user, repo=repo) if not (yes_i_know or click.confirm(msg)): click.echo('Aborted.') return gha = GitHubAPI(user_id=user.id) gha.remove_hook(repo.github_id, repo.name) db.session.commit()
10,632
Python
.py
253
35.454545
79
0.664019
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,468
api.py
zenodo_zenodo/zenodo/modules/github/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. """Zenodo GitHub API.""" from __future__ import absolute_import, print_function, unicode_literals import uuid from flask import current_app from invenio_db import db from invenio_files_rest.models import ObjectVersion from invenio_github.api import GitHubRelease from invenio_github.models import Release, ReleaseStatus from invenio_github.utils import get_contributors, get_owner from invenio_indexer.api import RecordIndexer from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.models import PersistentIdentifier from werkzeug.utils import cached_property from zenodo.modules.deposit.api import ZenodoDeposit from zenodo.modules.deposit.tasks import datacite_register from zenodo.modules.records.api import ZenodoRecord from ..deposit.loaders import legacyjson_v1_translator from ..jsonschemas.utils import current_jsonschemas class ZenodoGitHubRelease(GitHubRelease): """Zenodo GitHub Release.""" @property def metadata(self): """Return extracted metadata.""" output = dict(self.defaults) if self.use_extra_metadata: extra_metadata = self.extra_metadata # If `.zenodo.json` is there use it if extra_metadata: output.update(extra_metadata) # If not check for `CITATION.cff` and use else: citation_metadata = self.citation_metadata if citation_metadata: output.update(citation_metadata) # Add creators if not specified if 'creators' not in output: output['creators'] = get_contributors(self.gh.api, self.repository['id']) if not output['creators']: output['creators'] = get_owner(self.gh.api, self.author) if not output['creators']: output['creators'] = [dict(name='Unknown', affiliation='')] return legacyjson_v1_translator({'metadata': output}) @property def repo_model(self): """Return repository model from relationship.""" return self.model.repository @cached_property def recid(self): """Get RECID object for the Release record.""" if self.record: return PersistentIdentifier.get('recid', str(self.record['recid'])) def publish(self): """Publish GitHub release as record.""" id_ = uuid.uuid4() deposit_metadata = dict(self.metadata) deposit = None try: db.session.begin_nested() # TODO: Add filter on Published releases previous_releases = self.model.repository.releases.filter_by( status=ReleaseStatus.PUBLISHED) versioning = None stashed_draft_child = None if previous_releases.count(): last_release = previous_releases.order_by( Release.created.desc()).first() last_recid = PersistentIdentifier.get( 'recid', last_release.record['recid']) versioning = PIDVersioning(child=last_recid) last_record = ZenodoRecord.get_record( versioning.last_child.object_uuid) deposit_metadata['conceptrecid'] = last_record['conceptrecid'] if 'conceptdoi' not in last_record: last_depid = PersistentIdentifier.get( 'depid', last_record['_deposit']['id']) last_deposit = ZenodoDeposit.get_record( last_depid.object_uuid) last_deposit = last_deposit.registerconceptdoi() last_recid, last_record = last_deposit.fetch_published() deposit_metadata['conceptdoi'] = last_record['conceptdoi'] if last_record.get('communities'): deposit_metadata.setdefault('communities', last_record['communities']) if versioning.draft_child: stashed_draft_child = versioning.draft_child versioning.remove_draft_child() deposit = self.deposit_class.create(deposit_metadata, id_=id_) deposit['_deposit']['created_by'] = self.event.user_id deposit['_deposit']['owners'] = [self.event.user_id] # Fetch the deposit files for key, url in self.files: # Make a HEAD request to get GitHub to compute the # Content-Length. res = self.gh.api.session.head(url, allow_redirects=True) # Now, download the file res = self.gh.api.session.get(url, stream=True, allow_redirects=True) if res.status_code != 200: raise Exception( "Could not retrieve archive from GitHub: {url}" .format(url=url) ) size = int(res.headers.get('Content-Length', 0)) ObjectVersion.create( bucket=deposit.files.bucket, key=key, stream=res.raw, size=size or None, mimetype=res.headers.get('Content-Type'), ) # GitHub-specific SIP store agent sip_agent = { '$schema': current_jsonschemas.path_to_url( current_app.config['SIPSTORE_GITHUB_AGENT_JSONSCHEMA']), 'user_id': self.event.user_id, 'github_id': self.release['author']['id'], 'email': self.gh.account.user.email, } deposit.publish( user_id=self.event.user_id, sip_agent=sip_agent, spam_check=False) recid_pid, record = deposit.fetch_published() self.model.recordmetadata = record.model if versioning and stashed_draft_child: versioning.insert_draft_child(stashed_draft_child) record_id = str(record.id) db.session.commit() # Send Datacite DOI registration task if current_app.config['DEPOSIT_DATACITE_MINTING_ENABLED']: datacite_register.delay(recid_pid.pid_value, record_id) # Index the record RecordIndexer().index_by_id(record_id) except Exception: db.session.rollback() # Remove deposit from index since it was not commited. if deposit and deposit.id: try: RecordIndexer().delete(deposit) except Exception: current_app.logger.exception( "Failed to remove uncommited deposit from index.") raise
7,819
Python
.py
166
35.018072
79
0.606053
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,469
__init__.py
zenodo_zenodo/zenodo/modules/github/__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 GitHub integration.""" from __future__ import absolute_import, print_function
1,057
Python
.py
25
41.2
76
0.772816
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,470
error_handlers.py
zenodo_zenodo/zenodo/modules/github/error_handlers.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2019-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. """Error handlers for GitHub release exceptions.""" def versioning_files_error(release, ex): """Handler for VersioningFileError.""" release.model.errors = { 'errors': ex.get_errors()[0]['message'] } def authentification_failed(release, ex): """Handler for AuthentificationFailed.""" release.model.errors = { 'errors': ( 'The GitHub OAuth token we have for your account is invalid or ' 'expired. Please renew your token by disconnecting and ' 'connecting your GitHub account at our "Linked accounts" settings ' 'page. You can then contact us via our support form to have this ' 'release published.' ) } def stale_data_error(release, ex): """Handler for StaleDataError.""" pass def marshmallow_error(release, ex): """Handler for MarshmallowFileError.""" release.model.errors = {'errors': str(ex.errors)} def repository_access_error(release, ex): """Handler for RepositoryAccessError.""" pass def invalid_request_error(release, ex): """Handler for InvalidRequestError.""" pass def connection_error(release, ex): """Handler for ConnectionError.""" pass def forbidden_error(release, ex): """Handler for ForbiddenError.""" pass def server_error(release, ex): """Handler for ServerError.""" pass def client_error(release, ex): """Handler for ClientError.""" pass def integrity_error(release, ex): """Handler for IntegrityError.""" pass def default_error(release, ex): """Default error handler acting as a fallback.""" release.model.errors = { 'errors': ( 'Something went wrong when we tried to publish your release. ' 'If your release has not been published within the next hour, ' 'please contact us via our support form to resolve this issue.' )} def invalid_json_error(release, ex): """Error for invalid JSON format.""" release.model.errors = { 'errors': str(ex), } def invalid_ref_error(release, ex): """Error for invalid JSON reference.""" release.model.errors = { 'errors': 'The license ID you have selected is not present in our ' 'system. For the available licenses please check in the following URL ' 'https://developers.zenodo.org/#licenses', }
3,344
Python
.py
87
33.712644
79
0.695881
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,471
ext.py
zenodo_zenodo/zenodo/modules/support/ext.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. """Support and contact module for Zenodo.""" from __future__ import absolute_import, print_function from collections import OrderedDict from werkzeug.utils import cached_property from . import config class ZenodoSupport(object): """Zenodo support form.""" @cached_property def categories(self): """Return support issue categories.""" return OrderedDict( (c['key'], c) for c in self.app.config['SUPPORT_ISSUE_CATEGORIES']) 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) app.extensions['zenodo-support'] = self def init_config(self, app): """Flask application initialization.""" for k in dir(config): if k.startswith("SUPPORT_"): app.config.setdefault(k, getattr(config, k))
1,951
Python
.py
49
35.408163
79
0.706504
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,472
config.py
zenodo_zenodo/zenodo/modules/support/config.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. """Configuration for Zenodo Support.""" from __future__ import absolute_import, print_function #: Maximum size of attachment in contact form. SUPPORT_ATTACHMENT_MAX_SIZE = 1000 * 1000 * 10 # 10 MB #: Description maximum length. SUPPORT_DESCRIPTION_MAX_LENGTH = 5000 #: Description minimum length. SUPPORT_DESCRIPTION_MIN_LENGTH = 20 #: Email body template. SUPPORT_EMAIL_BODY_TEMPLATE = 'zenodo_support/email_body.html' #: Email title template. SUPPORT_EMAIL_TITLE_TEMPLATE = 'zenodo_support/email_title.html' #: Support confirmation email body. SUPPORT_EMAIL_CONFIRM_BODY = """Thank you for contacting Zenodo support. We have received your message, and we will do our best to get back to you as \ soon as possible. This is an automated confirmation of your request, please do not reply to this\ email. Zenodo Support https://zenodo.org """ #: Support confirmation email title. SUPPORT_EMAIL_CONFIRM_TITLE = 'Zenodo Support' 'zenodo_support/email_confirm_title.html' #: Issue category for contact form. SUPPORT_ISSUE_CATEGORIES = [ { 'key': 'file-modification', 'title': 'File modification', 'description': ( 'All requests related to updating files in already published ' 'record(s). This includes new file addition, file removal or ' 'file replacement. ' 'Before sending a request, please consider creating a ' '<a href="http://help.zenodo.org/#versioning">new version</a> ' 'of your upload. Please first consult our ' '<a href="http://help.zenodo.org/#general">FAQ</a> to get familiar' ' with the file update conditions, to see if your case is ' 'eligible.<br /><br />' 'You request has to contain <u>all</u> of the points below:' '<ol>' '<li>Provide a justification for the file change in the ' 'description.</li>' '<li>Mention any use of the record(s) DOI in publications or ' 'online, e.g.: list papers that cite your record and ' 'provide links to posts on blogs and social media. ' 'Otherwise, state that to the best of your knowledge the DOI has ' 'not been used anywhere.</li>' '<li>Specify the record(s) you want to update <u>by the Zenodo' ' URL</u>, e.g.: "https://zenodo.org/record/8428".<br />' "<u>Providing only the record's title, publication date or a " "screenshot with search result is not explicit enough</u>.</li>" '<li>If you want to delete or update a file, specify it ' '<u>by its filename</u>, and mention if you want the name to ' 'remain as is or changed (by default the filename of the new ' 'file will be used).</li>' '<li>Upload the new files below or provide a publicly-accessible ' 'URL(s) with the files in the description.</li>' '</ol>' '<b><u>Not providing full information on any of the points above ' 'will significantly slow down your request resolution</u></b>, ' 'since our support staff will have to reply back with a request ' 'for missing information.' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'upload-quota', 'title': 'File upload quota increase', 'description': ( 'All requests for a quota increase beyond the 50GB limit. ' 'Please include the following information with your request:' '<ol>' '<li>The total size of your dataset, number of files and the ' 'largest file in the dataset. When referring to file sizes' ' use <a href="https://en.wikipedia.org/wiki/IEEE_1541-2002">' 'SI units</a></li>' '<li>Information related to the organization, project or grant ' 'which was involved in the research, which produced the ' 'dataset.</li>' '<li>Information on the currently in-review or future papers that ' 'will cite this dataset (if applicable). If possible specify the ' 'journal or conference.</li>' '</ol>' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'record-inactivation', 'title': 'Record inactivation', 'description': ( 'Requests related to record inactivation, either by the record ' 'owner or a third party. Please specify the record(s) in question ' 'by the URL(s), and reason for the inactivation.' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'openaire', 'title': 'OpenAIRE', 'description': ( 'All questions related to OpenAIRE reporting and grants. ' 'Before sending a request, make sure your problem was not ' 'already resolved, see OpenAIRE ' '<a href="https://www.openaire.eu/faqs">FAQ</a>. ' 'For questions unrelated to Zenodo, you should contact OpenAIRE ' '<a href="https://www.openaire.eu/support/helpdesk">' 'helpdesk</a> directly.' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'partnership', 'title': 'Partnership, outreach and media', 'description': ( 'All questions related to possible partnerships, outreach, ' 'invited talks and other official inquiries by media.' 'If you are a journal, organization or conference organizer ' 'interested in using Zenodo as archive for your papers, software ' 'or data, please provide details for your usecase.' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'tech-support', 'title': 'Security issue, bug or spam report', 'description': ( 'Report a technical issue or a spam content on Zenodo. ' 'Please provide details on how to reproduce the bug. ' 'Upload any screenshots or files which are relevant to the issue ' 'or to means of reproducing it. Include error messages and ' 'error codes you might be getting in the description.<br /> ' 'For REST API errors, provide a minimal code which produces the ' 'issues. Use external services for scripts and long text' ', e.g.: <a href="https://gist.github.com/">GitHub Gist</a>. ' '<strong>Do not disclose your password or REST API access tokens.' '</strong>' ), 'recipients': ['info@zenodo.org'], }, { 'key': 'other', 'title': 'Other', 'description': ( 'Questions which do not fit into any other category.'), 'recipients': ['info@zenodo.org'], }, ] #: Email address of sender. SUPPORT_SENDER_EMAIL = 'info@zenodo.org' #: Name of the sender SUPPORT_SENDER_NAME = 'Zenodo' #: Email address for support. SUPPORT_SUPPORT_EMAIL = ['info@zenodo.org']
8,024
Python
.py
177
37.389831
79
0.632103
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,473
utils.py
zenodo_zenodo/zenodo/modules/support/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. """Utils for Zenodo support module.""" from __future__ import absolute_import, print_function, unicode_literals import bleach from flask import current_app, request from flask_mail import Message from ua_parser import user_agent_parser from zenodo.modules.records.serializers.fields.html import ALLOWED_ATTRS, \ ALLOWED_TAGS from .proxies import current_support_categories def render_template_to_string(template, context): """Render a Jinja template with the given context.""" template = current_app.jinja_env.get_or_select_template(template) return template.render(context) def check_attachment_size(attachment_files): """Function to check size of attachment within limits.""" if len(attachment_files) == 0: return False if request.content_length: file_size = int(request.content_length) if file_size > current_app.config['SUPPORT_ATTACHMENT_MAX_SIZE']: return False else: size = 0 for f in attachment_files: f.seek(current_app.config['SUPPORT_ATTACHMENT_MAX_SIZE'] - size) if f.read(1) == '': return False size += len(f) return True def format_user_email(email, name): """Format the user's email as 'Full Name <email>' or 'email'.""" if name: email = '{name} <{email}>'.format(name=name, email=email) # Remove commas (',') since they mess with the "TO" email field return email.replace(',', '') def format_user_email_ctx(context): """Format the user's email from form context.""" return format_user_email( context.get('info', {}).get('email'), context.get('info', {}).get('name', None) ) def get_support_email_recipients(context): """Return recipients for the support email.""" issue_category = context.get('info', {}).get('issue_category') category_config = current_support_categories.get(issue_category, {}) return category_config.get( 'recipients', current_app.config['SUPPORT_SUPPORT_EMAIL']) def send_support_email(context): """Signal for sending emails after contact form validated.""" sanitized_description = bleach.clean( context['info']['description'], tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS, strip=True, ).strip() context['info']['description'] = sanitized_description msg_body = render_template_to_string( current_app.config['SUPPORT_EMAIL_BODY_TEMPLATE'], context) msg_title = render_template_to_string( current_app.config['SUPPORT_EMAIL_TITLE_TEMPLATE'], context) sender = format_user_email_ctx(context) recipients = get_support_email_recipients(context) msg = Message( msg_title, sender=sender, recipients=recipients, reply_to=context.get('info', {}).get('email'), body=msg_body ) attachments = request.files.getlist("attachments") if attachments: for upload in attachments: msg.attach(upload.filename, 'application/octet-stream', upload.read()) current_app.extensions['mail'].send(msg) def send_confirmation_email(context): """Sending support confirmation email.""" recipient = format_user_email_ctx(context) sender = format_user_email( current_app.config['SUPPORT_SENDER_EMAIL'], current_app.config['SUPPORT_SENDER_NAME'] ) title = current_app.config['SUPPORT_EMAIL_CONFIRM_TITLE'] body = current_app.config['SUPPORT_EMAIL_CONFIRM_BODY'] msg = Message( title, body=body, sender=sender, recipients=[recipient, ], ) current_app.extensions['mail'].send(msg) def format_uap_info(info): """Format a ua-parser field. :param info: Dictionary of ua-parser field. :returns: Return user agent parsed string. :rtype: str """ info_version = '.'.join( [v for v in (info.get('major'), info.get('minor'), info.get('patch')) if v] ) return '{info} {info_version}'.format( info=info.get('family'), info_version=info_version ) def user_agent_information(): """Function to get user agent information. :returns: Dictionary with user agent information. :rtype: dict """ uap = user_agent_parser.Parse(str(request.user_agent)) os = format_uap_info(uap.get('os')) browser = format_uap_info(uap.get('user_agent')) device = ' '.join( [v for v in ( uap.get('device').get('family'), uap.get('device').get('brand'), uap.get('device').get('model') ) if v] ) return dict(os=os, browser=browser, device=device)
5,702
Python
.py
145
33.268966
76
0.668898
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,474
__init__.py
zenodo_zenodo/zenodo/modules/support/__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 support and contact module.""" from __future__ import absolute_import, print_function from .ext import ZenodoSupport __all__ = ('ZenodoSupport', )
1,128
Python
.py
27
40.62963
76
0.769371
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,475
proxies.py
zenodo_zenodo/zenodo/modules/support/proxies.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. """Proxies for Zenodo support module.""" from __future__ import absolute_import, print_function from flask import current_app from werkzeug.local import LocalProxy current_support_categories = LocalProxy( lambda: current_app.extensions['zenodo-support'].categories) """Proxy to current support issue categories."""
1,290
Python
.py
30
41.733333
76
0.779459
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,476
forms.py
zenodo_zenodo/zenodo/modules/support/forms.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. """Forms for Zenodo Pages.""" from __future__ import absolute_import, print_function from flask import current_app from flask_babelex import lazy_gettext as _ from flask_security import current_user from flask_wtf import FlaskForm, Recaptcha, RecaptchaField from flask_wtf.file import FileField from jinja2.filters import do_filesizeformat from wtforms import BooleanField, SelectField, StringField, SubmitField, \ TextAreaField from wtforms.validators import DataRequired, Length from .proxies import current_support_categories def strip_filter(text): """Filter for trimming whitespace.""" return text.strip() if text else text class ContactForm(FlaskForm): """Form for contact form.""" field_sets = ['name', 'email', 'subject', 'issue_category', 'description', 'attachments', 'include_os_browser', 'recaptcha'] # # Methods # def get_field_by_name(self, name): """Return field by name.""" try: return self._fields[name] except KeyError: return None # # Fields # name = StringField( _('Name'), description=_('Required.'), filters=[strip_filter], validators=[DataRequired()], ) email = StringField( _('Email'), description=_('Required.'), filters=[strip_filter], validators=[DataRequired()], ) subject = StringField( _('Subject'), description=_('Required.'), filters=[strip_filter], validators=[DataRequired()], ) issue_category = SelectField( _('Category'), description=_('Required.'), coerce=str, validators=[DataRequired()], ) description = TextAreaField( _('How can we help?'), description=_('Required.'), filters=[strip_filter], ) include_os_browser = BooleanField( _('Browser & OS'), default="checked", ) submit = SubmitField(_('Send Request')) attachments = FileField( _('Attachments'), render_kw={'multiple': True}, ) class RecaptchaContactForm(ContactForm): """Recaptcha-enabled form.""" recaptcha = RecaptchaField(validators=[ Recaptcha(message=_("Please complete the reCAPTCHA.")) ]) def contact_form_factory(): """Return configured contact form.""" if current_app.config.get('RECAPTCHA_PUBLIC_KEY') and \ current_app.config.get('RECAPTCHA_PRIVATE_KEY') and \ not current_user.is_authenticated: form = RecaptchaContactForm() else: form = ContactForm() if current_user.is_authenticated: form.email.data = current_user.email form.name.data = form.name.data or (current_user.profile.full_name if current_user.profile else None) # Load form choices and validation from config form.issue_category.choices = \ [(c['key'], c['title']) for c in current_support_categories.values()] form.description.validators.append(Length( min=current_app.config['SUPPORT_DESCRIPTION_MIN_LENGTH'], max=current_app.config['SUPPORT_DESCRIPTION_MAX_LENGTH'], )) form.attachments.description = 'Optional. Max attachments size: ' + \ do_filesizeformat(current_app.config['SUPPORT_ATTACHMENT_MAX_SIZE']) return form
4,339
Python
.py
119
30.630252
78
0.673182
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,477
views.py
zenodo_zenodo/zenodo/modules/support/views.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. """Zenodo support views.""" from __future__ import absolute_import, print_function import smtplib from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_babelex import lazy_gettext as _ from flask_security import current_user from .forms import contact_form_factory from .proxies import current_support_categories from .utils import check_attachment_size, send_confirmation_email, \ send_support_email, user_agent_information blueprint = Blueprint( 'zenodo_support', __name__, template_folder='templates', ) @blueprint.route('/support', methods=['GET', 'POST']) def support(): """Render contact form.""" uap = user_agent_information() form = contact_form_factory() if form.validate_on_submit(): attachments = request.files.getlist("attachments") if attachments and not check_attachment_size(attachments): form.attachments.errors.append('File size exceeded. ' 'Please add URLs to the files ' 'or make a smaller selection.') else: context = { 'user_id': current_user.get_id(), 'info': form.data, 'uap': uap } try: send_support_email(context) send_confirmation_email(context) except smtplib.SMTPSenderRefused: flash( _('There was an issue sending an email to the provided ' 'address, please make sure it is correct. ' 'If this issue persists you can send ' 'us an email directly to info@zenodo.org.'), category='danger' ) except Exception: flash( _("There was an issue sending the support request." 'If this issue persists send ' 'us an email directly to info@zenodo.org.'), category='danger' ) raise else: flash( _('Request sent successfully. ' 'You should receive a confirmation email within several ' 'minutes - if this does not happen you should retry or ' 'send us an email directly to info@zenodo.org.'), category='success' ) return redirect(url_for('zenodo_frontpage.index')) return render_template( 'zenodo_support/contact_form.html', uap=uap, form=form, categories=current_support_categories )
3,686
Python
.py
89
31.662921
79
0.613712
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,478
__init__.py
zenodo_zenodo/zenodo/modules/search_ui/__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. """Search interface customizations.""" from __future__ import absolute_import, print_function
1,063
Python
.py
25
41.44
76
0.774131
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,479
views.py
zenodo_zenodo/zenodo/modules/search_ui/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. """Blueprint for Zenodo-Records.""" from __future__ import absolute_import, print_function from flask import Blueprint blueprint = Blueprint( 'zenodo_search_ui', __name__, template_folder='templates', static_folder='static', ) @blueprint.app_template_filter() def filter_sort_options(sort_options): """Filters the search sort options based on the "display" key.""" return {k: v for k, v in sort_options.items() if v.get('display', True)}
1,435
Python
.py
36
38.027778
76
0.754487
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,480
cli.py
zenodo_zenodo/zenodo/modules/utils/cli.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. """CLI for Zenodo-specific tasks.""" from __future__ import absolute_import, print_function import json import os from io import SEEK_END, SEEK_SET import click from flask.cli import with_appcontext 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.models import RecordMetadata from zenodo.modules.deposit.resolvers import deposit_resolver from zenodo.modules.deposit.tasks import datacite_register from zenodo.modules.records.resolvers import record_resolver from .grants import OpenAIREGrantsDump from .openaire import OpenAIRECommunitiesMappingUpdater from .tasks import has_corrupted_files_meta, repair_record_metadata, \ sync_record_oai, update_oaisets_cache, update_search_pattern_sets @click.group() def utils(): """Zenodo helper CLI.""" @utils.command('datacite_register') @click.argument('recid', type=str) @click.option('--eager', '-e', is_flag=True) @with_appcontext def datecite_register(recid, eager): """Send a record to DataCite for registration.""" pid, record = record_resolver.resolve(recid) if eager: datacite_register.s(pid.pid_value, str(record.id)).apply(throw=True) else: datacite_register.s(pid.pid_value, str(record.id)).apply_async() @utils.command('add_file') @click.argument('recid', type=str) @click.argument('fp', type=click.File('rb')) @click.option('--replace-existing', '-f', is_flag=True, default=False) @with_appcontext def add_file(recid, fp, replace_existing): """Add a new file to a published record.""" pid, record = record_resolver.resolve(recid) bucket = record.files.bucket key = os.path.basename(fp.name) obj = ObjectVersion.get(bucket, key) if obj is not None and not replace_existing: click.echo(click.style(u'File with key "{key}" already exists.' u' Use `--replace-existing/-f` to overwrite it.'.format( key=key, recid=recid), fg='red')) return fp.seek(SEEK_SET, SEEK_END) size = fp.tell() fp.seek(SEEK_SET) click.echo(u'Will add the following file:\n') click.echo(click.style( u' key: "{key}"\n' u' bucket: {bucket}\n' u' size: {size}\n' u''.format( key=key.decode('utf-8'), bucket=bucket.id, size=size), fg='green')) click.echo(u'to record:\n') click.echo(click.style( u' Title: "{title}"\n' u' RECID: {recid}\n' u' UUID: {uuid}\n' u''.format( recid=record['recid'], title=record['title'], uuid=record.id), fg='green')) if replace_existing and obj is not None: click.echo(u'and remove the file:\n') click.echo(click.style( u' key: "{key}"\n' u' bucket: {bucket}\n' u' size: {size}\n' u''.format( key=obj.key, bucket=obj.bucket, size=obj.file.size), fg='green')) if click.confirm(u'Continue?'): bucket.locked = False if obj is not None and replace_existing: bucket.size -= obj.file.size ObjectVersion.delete(bucket, obj.key) ObjectVersion.create(bucket, key, stream=fp, size=size) bucket.locked = True record.files.flush() record.commit() db.session.commit() click.echo(click.style(u'File added successfully.', fg='green')) else: click.echo(click.style(u'File addition aborted.', fg='green')) @utils.command('remove_file') @click.argument('recid', type=str) @click.argument('key', type=str) @with_appcontext def remove_file(recid, key=None, index=None): """Remove a file from a published record.""" pid, record = record_resolver.resolve(recid) bucket = record.files.bucket obj = ObjectVersion.get(bucket, key) if obj is None: click.echo(click.style(u'File with key "{key}" not found.'.format( key=key, recid=recid), fg='red')) return click.echo(u'Will remove the following file:\n') click.echo(click.style( u' key: "{key}"\n' u' {checksum}\n' u' bucket: {bucket}\n' u''.format( key=key.decode('utf-8'), checksum=obj.file.checksum, bucket=bucket.id), fg='green')) click.echo('from record:\n') click.echo(click.style( u' Title: "{title}"\n' u' RECID: {recid}\n' u' UUID: {uuid}\n' u''.format( recid=record['recid'], title=record['title'], uuid=record.id), fg='green')) if click.confirm(u'Continue?'): bucket.locked = False bucket.size -= obj.file.size ObjectVersion.delete(bucket, obj.key) bucket.locked = True record.files.flush() record.commit() db.session.commit() click.echo(click.style(u'File removed successfully.', fg='green')) else: click.echo(click.style(u'Aborted file removal.', fg='green')) @utils.command('rename_file') @click.argument('recid', type=str) @click.argument('key', type=str) @click.argument('new_key', type=str) @with_appcontext def rename_file(recid, key, new_key): """Remove a file from a published record.""" pid, record = record_resolver.resolve(recid) bucket = record.files.bucket obj = ObjectVersion.get(bucket, key) if obj is None: click.echo(click.style(u'File with key "{key}" not found.'.format( key=key), fg='red')) return new_obj = ObjectVersion.get(bucket, new_key) if new_obj is not None: click.echo(click.style(u'File with key "{key}" already exists.'.format( key=new_key), fg='red')) return if click.confirm(u'Rename "{key}" to "{new_key}" on bucket {bucket}.' u' Continue?'.format( key=obj.key, new_key=new_key, bucket=bucket.id)): bucket.locked = False file_id = obj.file.id bucket.size -= obj.file.size ObjectVersion.delete(bucket, obj.key) ObjectVersion.create(bucket, new_key, _file_id=file_id) bucket.locked = True record.files.flush() record.commit() db.session.commit() click.echo(click.style(u'File renamed successfully.', fg='green')) else: click.echo(click.style(u'Aborted file rename.', fg='green')) @utils.command('attach_file') @click.option('--file-id', type=str) @click.option('--pid-type1', type=str) @click.option('--pid-value1', type=str) @click.option('--key1', type=str) @click.option('--pid-type2', type=str) @click.option('--pid-value2', type=str) @click.option('--key2', type=str) @with_appcontext def attach_file(file_id, pid_type1, pid_value1, key1, pid_type2, pid_value2, key2): """Attach a file to a record or deposit. You must provide the information which will determine the first file, i.e.: either 'file-id' OR 'pid-type1', 'pid-value1' and 'key1'. Additionally you need to specify the information on the target record/deposit, i.e.: 'pid-type2', 'pid-value2' and 'key2'. """ assert ((file_id or (pid_type1 and pid_value1 and key1)) and (pid_type2 and pid_value2 and key2)) msg = u"PID type must be 'recid' or 'depid'." if pid_type1: assert pid_type1 in ('recid', 'depid', ), msg assert pid_type2 in ('recid', 'depid', ), msg if not file_id: resolver = record_resolver if pid_type1 == 'recid' \ else deposit_resolver pid1, record1 = resolver.resolve(pid_value1) bucket1 = record1.files.bucket obj1 = ObjectVersion.get(bucket1, key1) if obj1 is None: click.echo(click.style(u'File with key "{key}" not found.'.format( key=key1), fg='red')) return file_id = obj1.file.id resolver = record_resolver if pid_type2 == 'recid' else deposit_resolver pid2, record2 = resolver.resolve(pid_value2) bucket2 = record2.files.bucket obj2 = ObjectVersion.get(bucket2, key2) if obj2 is not None: click.echo(click.style(u'File with key "{key}" already exists on' u' bucket {bucket}.'.format( key=key2, bucket=bucket2.id), fg='red')) return if click.confirm(u'Attaching file "{file_id}" to bucket {bucket2}' u' as "{key2}". Continue?'.format( file_id=file_id, key2=key2, bucket2=bucket2.id)): record2.files.bucket.locked = False ObjectVersion.create(bucket2, key2, _file_id=file_id) if pid_type2 == 'recid': record2.files.bucket.locked = True record2.files.flush() record2.commit() db.session.commit() click.echo(click.style(u'File attached successfully.', fg='green')) else: click.echo(click.style(u'Aborted file attaching.', fg='green')) @utils.command('list_files') @click.argument('recid', type=str) @with_appcontext def list_files(recid): """List files for the record.""" pid, record = record_resolver.resolve(recid) click.echo(u'Files for record {recid} (UUID:{uuid}) ({cnt} file(s)):\n' u''.format(recid=recid, uuid=record.id, cnt=len(record.files))) for idx, key in enumerate(record.files.keys): f = record.files[key].obj.file click.echo(click.style( u'{idx:3}: "{key}", {checksum}, size:{size}' u''.format(idx=idx, key=key, checksum=f.checksum, size=f.size), fg='green')) @utils.command('sync_oai') @click.option('--eager', '-e', is_flag=True) @click.option('--oai-cache', is_flag=True) @click.option('--uuid', '-i') @with_appcontext def sync_oai(eager, oai_cache, uuid): """Update OAI IDs in the records.""" if uuid: sync_record_oai(str(uuid)) else: pids = PersistentIdentifier.query.filter( PersistentIdentifier.pid_type == 'recid', PersistentIdentifier.object_type == 'rec', PersistentIdentifier.status == 'R') uuids = (pid.get_assigned_object() for pid in pids) oaisets_cache = {} if oai_cache else None with click.progressbar(uuids, length=pids.count()) as uuids_bar: for uuid in uuids_bar: if oai_cache: rec = Record.get_record(uuid) update_oaisets_cache(oaisets_cache, rec) if eager: sync_record_oai(str(uuid), cache=oaisets_cache) else: sync_record_oai.delay(str(uuid), cache=oaisets_cache) @utils.command('repair_corrupted_metadata') @click.option('--eager', '-e', is_flag=True) @click.option('--uuid', '-i') @with_appcontext def repair_corrupted_metadata(eager, uuid): """Repair the corrupted '_files', '_oai' and '_internal' metadata.""" if uuid: record = Record.get_record(uuid) if has_corrupted_files_meta(record): repair_record_metadata(str(uuid)) else: rms = db.session.query(RecordMetadata).join( PersistentIdentifier, PersistentIdentifier.object_uuid == RecordMetadata.id).filter( PersistentIdentifier.pid_type == 'recid', PersistentIdentifier.status == 'R', PersistentIdentifier.object_type == 'rec') uuids = [r.id for r in rms if has_corrupted_files_meta(r.json)] if not click.confirm('Will update {cnt} records. Continue?'.format( cnt=len(uuids))): return with click.progressbar(uuids, length=len(uuids)) as uuids_bar: for uuid in uuids_bar: if eager: repair_record_metadata(str(uuid)) else: repair_record_metadata.delay(str(uuid)) @utils.command('update_search_pattern_sets') @with_appcontext def update_search_pattern_sets_cli(): """Update records belonging to all search-pattern OAISets.""" update_search_pattern_sets.delay() @utils.command('split_openaire_grants_dump') @click.argument('source', type=click.Path(exists=True, dir_okay=False)) @click.argument('target_prefix') @click.option('--grants-per-file', '-n', type=int, default=None) @click.option('--sqlite-write-rows-buffer', type=int, default=None) @with_appcontext def split_openaire_grants_dump(source, target_prefix, grants_per_file=None, sqlite_write_rows_buffer=None): """Split an OpenAIRE grants dump into multiple SQLite files. The file can then be imported via ``zenodo openaire loadgrants ...``. """ grants_dump = OpenAIREGrantsDump( source, rows_write_chunk_size=sqlite_write_rows_buffer) split_files = grants_dump.split( target_prefix, grants_per_file=grants_per_file) total_rows = 0 for filepath, row_count in split_files: total_rows += row_count click.secho('{0} - {1} (Total: {2})' .format(filepath, row_count, total_rows), fg='blue') @utils.command('update_openaire_communities') @click.argument('path', type=click.Path(exists=True, dir_okay=False)) @with_appcontext def update_openaire_communities(path): """Get the updated mapping between OpenAIRE and Zenodo communities.""" mapping_updater = OpenAIRECommunitiesMappingUpdater(path) mapping, unresolved_communities = mapping_updater\ .update_communities_mapping() click.secho('Communities not found:\n{0}'.format(json.dumps( unresolved_communities, indent=4, separators=(', ', ': ')))) click.secho('{0}'.format(json.dumps(mapping, indent=4, separators=(', ', ': '))), fg='blue')
14,892
Python
.py
358
34.100559
79
0.635297
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,481
tasks.py
zenodo_zenodo/zenodo/modules/utils/tasks.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. """Celery tasks for Zenodo utility functions.""" from __future__ import absolute_import, unicode_literals from collections import namedtuple from datetime import datetime from itertools import chain as ichain import sqlalchemy as sa from celery import chain, group, shared_task from celery.utils.log import get_task_logger from dictdiffer import diff from elasticsearch_dsl import Q from flask import current_app from flask_mail import Message from invenio_db import db from invenio_files_rest.models import FileInstance from invenio_indexer.api import RecordIndexer from invenio_oaiserver.minters import oaiid_minter from invenio_oaiserver.models import OAISet from invenio_oaiserver.query import OAIServerSearch from invenio_oaiserver.utils import datetime_to_datestamp from invenio_pidstore.models import PersistentIdentifier from invenio_records.api import Record from invenio_records_files.models import RecordsBuckets from six.moves import filter from zenodo.modules.records.serializers.schemas.common import ui_link_for from zenodo.modules.records.utils import is_deposit, is_record logger = get_task_logger(__name__) # # OAI Syncing task # # Cache object for fetched OAISets OAISetCache = namedtuple('OAISetCache', ('search_pattern', )) def update_oaisets_cache(cache, data): """Update the OAISet cache with OAISets from data.""" specs = data.get('_oai', {}).get('sets', []) for spec in specs: if spec not in cache: q = OAISet.query.filter_by(spec=spec) if q.count(): cache[spec] = OAISetCache( search_pattern=q.one().search_pattern) def resolve_oaiset(spec, cache=None): """Resolve OAISet from spec with cache support.""" if cache is not None and spec in cache: return cache[spec] else: oaiset = OAISet.query.filter_by(spec=spec).one() if cache is not None: cache[spec] = OAISetCache(search_pattern=oaiset.search_pattern) return oaiset def get_synced_sets(record, cache=None): """Get the synced OAI set list.""" comms = record.get('communities', []) sets = record.get('_oai', {}).get('sets', []) other_sets = [s for s in sets if not (s.startswith('user-') and not resolve_oaiset(s, cache=cache).search_pattern)] s_comms = ['user-{0}'.format(c) for c in comms] return sorted(other_sets + s_comms) def comm_sets_match(record, cache=None): """Check if communities definition and OAI sets match.""" # OAI sets of communities comms = record.get('communities', []) s_comms = ['user-{0}'.format(c) for c in comms] # Community-based OAI sets sets = record.get('_oai', {}).get('sets', []) c_sets = [s for s in sets if s.startswith('user-') and not resolve_oaiset(s, cache=cache).search_pattern] return set(c_sets) == set(s_comms) def requires_sync(record, cache=None): """Determine whether record requries OAI information syncing.""" oai = record.get('_oai', {}) return (not oai.get('id')) or (oai.get('updated') is None) or \ (not comm_sets_match(record, cache=cache)) @shared_task def sync_record_oai(uuid, cache=None): """Mint OAI ID information for the record. :type uuid: str """ rec = Record.get_record(uuid) recid_s = str(rec['recid']) # Try to get the already existing OAI PID for this record oai_pid_q = PersistentIdentifier.query.filter_by(pid_type='oai', object_uuid=rec.id) if oai_pid_q.count() == 0: pid = oaiid_minter(rec.id, rec) synced_sets = get_synced_sets(rec, cache=cache) rec['_oai']['sets'] = synced_sets rec.commit() db.session.commit() RecordIndexer().bulk_index([str(rec.id), ]) logger.info('Minted new OAI PID ({pid}) for record {id}'.format( pid=pid, id=uuid)) elif oai_pid_q.count() == 1: pid = oai_pid_q.one() managed_prefixes = current_app.config['OAISERVER_MANAGED_ID_PREFIXES'] if not any(pid.pid_value.startswith(p) for p in managed_prefixes): logger.exception('Unknown OAIID prefix: {0}'.format(pid.pid_value)) elif str(pid.get_assigned_object()) != uuid: logger.exception( 'OAI PID ({pid}) for record {id} ({recid}) is ' 'pointing to a different object ({id2})'.format( pid=pid, id=uuid, id2=str(pid.get_assigned_object()), recid=recid_s)) elif requires_sync(rec, cache=cache): rec.setdefault('_oai', {}) rec['_oai']['id'] = pid.pid_value rec['_oai']['updated'] = datetime_to_datestamp(datetime.utcnow()) synced_sets = get_synced_sets(rec, cache=cache) rec['_oai']['sets'] = synced_sets if not rec['_oai']['sets']: del rec['_oai']['sets'] # Don't store empty list rec.commit() db.session.commit() RecordIndexer().bulk_index([str(rec.id), ]) logger.info('Matching OAI PID ({pid}) for record {id}'.format( pid=pid, id=uuid)) # # Files metadata repair task # def has_corrupted_files_meta(record): """Determine whether the metadata contains corrupted files information.""" rb = record['_buckets']['record'] return any(f['bucket'] != rb for f in record.get('_files', [])) def recent_non_corrupted_revision(record): """Get the most recent non-corrupted revision of a record.""" return next(filter(lambda rev: not has_corrupted_files_meta(rev), reversed(record.revisions))) def files_diff_safe(files_diff): """Make sure there is no unsafe operation on files dictionaries.""" # Mark diff as unsafe if there are any additions or removals of files if any(op[0] in ('add', 'remove') for op in files_diff): return False # Mark diff as unsafe if the changes include fields other than the # bucket or version_if changes = filter(lambda op: op[0] == 'change', files_diff) if any(op[1][1] not in ('bucket', 'version_id') for op in changes): return False return True @shared_task def repair_record_metadata(uuid): """Repair the record's metadata using a reference revision.""" rec = Record.get_record(uuid) good_revision = recent_non_corrupted_revision(rec) if '_internal' in good_revision: rec['_internal'] = good_revision['_internal'] files_diff = list(diff(rec['_files'], good_revision['_files'])) if files_diff_safe(files_diff): rec['_files'] = good_revision['_files'] rec.commit() db.session.commit() RecordIndexer().bulk_index([str(rec.id), ]) @shared_task def remove_oaiset_spec(record_uuid, spec): """Remove the OAI spec from the record and commit.""" rec = Record.get_record(record_uuid) rec['_oai']['sets'] = sorted(set([s for s in rec['_oai'].get('sets', []) if s != spec])) rec['_oai']['updated'] = datetime_to_datestamp(datetime.utcnow()) if not rec['_oai']['sets']: del rec['_oai']['sets'] rec.commit() db.session.commit() RecordIndexer().bulk_index([str(rec.id), ]) @shared_task def add_oaiset_spec(record_uuid, spec): """Add the OAI spec to the record and commit.""" rec = Record.get_record(record_uuid) rec['_oai']['sets'] = sorted(set(rec['_oai'].get('sets', []) + [spec, ])) rec['_oai']['updated'] = datetime_to_datestamp(datetime.utcnow()) rec.commit() db.session.commit() RecordIndexer().bulk_index([str(rec.id), ]) def iter_record_oai_tasks(query, spec, func): """Turn an ES query and a task function into an iterable of celery tasks. :param query: Elasticsearch query :type query: elasticsearch_dsl.Q :param spec: OAISet.spec name :type spec: str :param func: shared_task function to execute for given record :type func: function """ search = OAIServerSearch( index=current_app.config['OAISERVER_RECORD_INDEX'], ).query(query) for result in search.scan(): yield func.si(result.meta.id, spec) def make_oai_task_group(oais): """Make a celery group for an OAISet. Since for each OAISet any given record has to be modified by either removing or adding the OAISet.spec, it's save to create a single group per OAISet for all records (no risk of racing conditions in parallel execution). :param oais: OAISet for which the task group is to be made. :type oais: invenio_oaiserver.modules.OAISet """ spec_q = Q('match', **{'_oai.sets': oais.spec}) pattern_q = Q('query_string', query=oais.search_pattern) spec_remove_q = Q('bool', must=spec_q, must_not=pattern_q) spec_add_q = Q('bool', must=pattern_q, must_not=spec_q) return group(ichain(iter_record_oai_tasks(spec_remove_q, oais.spec, remove_oaiset_spec), iter_record_oai_tasks(spec_add_q, oais.spec, add_oaiset_spec))) @shared_task def update_search_pattern_sets(): """Update all records affected by search-patterned OAISets. In order to avoid racing condition when editing the records, all OAISet task groups are chained. """ oaisets = OAISet.query.filter(OAISet.search_pattern.isnot(None)) chain(make_oai_task_group(oais) for oais in oaisets).apply_async() def format_file_integrity_report(report): """Format the email body for the file integrity report.""" lines = [] for entry in report: f = entry['file'] lines.append('ID: {}'.format(str(f.id))) lines.append('URI: {}'.format(f.uri)) lines.append('Name: {}'.format(entry.get('filename'))) lines.append('Created: {}'.format(f.created)) lines.append('Checksum: {}'.format(f.checksum)) lines.append('Last Check: {}'.format(f.last_check_at)) if 'record' in entry: lines.append(u'Record: {}'.format( ui_link_for('record_html', id=entry['record'].get('recid')) )) if 'deposit' in entry: lines.append(u'Deposit: {}'.format( ui_link_for( 'deposit_html', id=entry['deposit'].get('_deposit', {}).get('id')) )) lines.append(('-' * 80) + '\n') return '\n'.join(lines) @shared_task def file_integrity_report(): """Send a report of uhealthy/missing files to Zenodo admins.""" # First retry verifying files that errored during their last check files = FileInstance.query.filter(FileInstance.last_check.is_(None)) for f in files: try: f.clear_last_check() db.session.commit() f.verify_checksum(throws=False) db.session.commit() except Exception: pass # Don't fail sending the report in case of some file error report = [] unhealthy_files = ( FileInstance.query .filter(sa.or_(FileInstance.last_check.is_(None), FileInstance.last_check.is_(False))) .order_by(FileInstance.created.desc())) for f in unhealthy_files: entry = {'file': f} for o in f.objects: entry['filename'] = o.key # Find records/deposits for the files rb = RecordsBuckets.query.filter( RecordsBuckets.bucket_id == o.bucket_id).one_or_none() if rb and rb.record and rb.record.json: if is_deposit(rb.record.json): entry['deposit'] = rb.record.json elif is_record(rb.record.json): entry['record'] = rb.record.json report.append(entry) if report: # Format and send the email subject = u'Zenodo files integrity report [{}]'.format(datetime.now()) body = format_file_integrity_report(report) sender = current_app.config['ZENODO_SYSTEM_SENDER_EMAIL'] recipients = [current_app.config['ZENODO_ADMIN_EMAIL']] msg = Message(subject, sender=sender, recipients=recipients, body=body) current_app.extensions['mail'].send(msg)
13,005
Python
.py
291
37.408935
79
0.64337
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,482
grants.py
zenodo_zenodo/zenodo/modules/utils/grants.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. """Grants utilities.""" from __future__ import absolute_import, print_function, unicode_literals import json import os import sqlite3 from base64 import b64decode from gzip import GzipFile from itertools import islice, repeat from zipfile import ZipFile from six import BytesIO from six.moves import zip class OpenAIREGrantsDump(object): """Utility class to manage OpenAIRE grant dumps.""" def __init__(self, path, rows_write_chunk_size=10000): """Initialize the OpenAIRE grants dump.""" self.path = path self.rows_write_chunk_size = rows_write_chunk_size def _parse_grant_line(self, line): json_data = json.loads(line) body = json_data['body']['$binary'] zip_bytes = BytesIO(b64decode(body)) with ZipFile(zip_bytes) as zf: return zf.read('body').decode('utf-8') @property def _grants_iterator(self): with GzipFile(self.path) as gf: for line in gf: yield self._parse_grant_line(line.decode('utf-8')) def split(self, filepath_prefix, grants_per_file=None): """Dump grants into multiple SQLite files. :param str filepath_prefix: Path which will be used as a prefix for the generated SQLite files. e.g. passing ``/tmp/grants-`` will generate ``/tmp/grants-01.db``, ``/tmp/grants-02.db``, etc. :param int grants_per_file: The maximum number of grants that will be stored per file. If ``None``, only one file will be used. """ file_idx = 0 grants_iter = self._grants_iterator file_row_count = 1 while file_row_count > 0: filepath = '{0}{1:02d}.db'.format(filepath_prefix, file_idx) file_row_count = self.write( filepath, islice(grants_iter, grants_per_file)) file_idx += 1 if file_row_count > 0: yield filepath, file_row_count def write(self, filepath, grants, chunk_size=None): """Write grants to an SQLite file. In case no rows were written to the file, the file is removed. :param str filepath: Path to the SQLite file to be written. :param grants: Iterable of grants that will be written to the database. :return: Number of rows written to the file. """ chunk_size = chunk_size or self.rows_write_chunk_size with sqlite3.connect(filepath) as conn: conn.execute('CREATE TABLE grants (data text, format text)') total_rows_inserted = 0 rows_inserted = 1 while rows_inserted > 0: rows_inserted = conn.executemany( 'INSERT INTO grants VALUES (?, ?)', zip(islice(grants, chunk_size), repeat('xml')) ).rowcount if rows_inserted > 0: total_rows_inserted += rows_inserted if total_rows_inserted <= 0: # delete a zero-rows file os.unlink(filepath) return total_rows_inserted
4,018
Python
.py
92
36.304348
79
0.654908
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,483
__init__.py
zenodo_zenodo/zenodo/modules/utils/__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 utils.""" from __future__ import absolute_import, print_function from .common import obj_or_import_string __all__ = ( 'obj_or_import_string', )
1,129
Python
.py
29
37.655172
76
0.763686
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,484
openaire.py
zenodo_zenodo/zenodo/modules/utils/openaire.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. """Communities utilities.""" import csv from flask import current_app from invenio_communities.models import Community from invenio_db import db class OpenAIRECommunitiesMappingUpdater: """Utility class to update OpenAIRE communities mapping.""" def __init__(self, path): """Initialize the OpenAIRE communities updater.""" self.path = path def _parse_line(self, line): community_id = line[0] community_name = line[1] zenodo_communities = line[2].split(';') if len(line) == 3 else [] openaire_community = dict(id=community_id, name=community_name, communities=zenodo_communities) return openaire_community @property def _communities_iterator(self): with open(self.path, 'rb') as csv_file: csv_reader = csv.reader(csv_file) csv_reader.next() # skip csv header for line in csv_reader: yield self._parse_line(line) def update_communities_mapping(self): """Update communities mapping.""" mapping = current_app.config['ZENODO_OPENAIRE_COMMUNITIES'] unresolved_communities = [] for openaire_community in self._communities_iterator: zenodo_community_ids = [] for zenodo_community in openaire_community.get('communities'): # search for the corresponding community in Zenodo query = db.session.query(Community).filter( Community.title.like(zenodo_community + '%') ) comm = query.one_or_none() if comm is not None: zenodo_community_ids.append(comm.id) else: unresolved_communities.append(dict( openaire_community=openaire_community['id'], zenodo_community=zenodo_community)) comm_id = openaire_community['id'] if mapping.get(comm_id): mapping[comm_id]['name'] = openaire_community['name'] mapping[comm_id]['communities'] = zenodo_community_ids else: mapping[comm_id] = dict(name=openaire_community['name'], communities=zenodo_community_ids, types={}) return mapping, unresolved_communities
3,400
Python
.py
75
35.626667
76
0.632548
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,485
files.py
zenodo_zenodo/zenodo/modules/utils/files.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. """Files utilities.""" from __future__ import absolute_import, print_function import sqlalchemy as sa from flask import current_app from invenio_files_rest.models import FileInstance def checksum_verification_files_query(): """Return a FileInstance query taking into account file URI prefixes.""" files = FileInstance.query uri_prefixes = current_app.config.get( 'FILES_REST_CHECKSUM_VERIFICATION_URI_PREFIXES') if uri_prefixes: files = files.filter( sa.or_(*[FileInstance.uri.startswith(p) for p in uri_prefixes])) return files
1,549
Python
.py
37
39.432432
76
0.759124
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,486
common.py
zenodo_zenodo/zenodo/modules/utils/common.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. """Zenodo common utils.""" from __future__ import absolute_import, print_function import six from werkzeug.utils import import_string def obj_or_import_string(value, default=None): """Import string or return object. :params value: Import path or class object to instantiate. :params default: Default object to return if the import fails. :returns: The imported object. """ if isinstance(value, six.string_types): return import_string(value) elif value: return value return default
1,502
Python
.py
38
37.105263
76
0.757202
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,487
ext.py
zenodo_zenodo/zenodo/modules/metrics/ext.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-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. """ZenodoMetrics module.""" from __future__ import absolute_import, print_function from flask import current_app from . import config class ZenodoMetrics(object): """Zenodo frontpage 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_METRICS'): app.config.setdefault(k, getattr(config, k)) def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['zenodo-metrics'] = self @property def metrics_start_date(self): """Get get metrics start date from config.""" return current_app.config['ZENODO_METRICS_START_DATE']
1,846
Python
.py
47
35.085106
76
0.711012
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,488
config.py
zenodo_zenodo/zenodo/modules/metrics/config.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-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 Metrics.""" from __future__ import absolute_import, print_function import datetime from .api import ZenodoMetric ZENODO_METRICS_START_DATE = datetime.datetime(2021, 1, 1) ZENODO_METRICS_CACHE_TIMEOUT = int(datetime.timedelta(hours=1).total_seconds()) ZENODO_METRICS_CACHE_UPDATE_INTERVAL = datetime.timedelta(minutes=30) ZENODO_METRICS_UPTIME_ROBOT_METRIC_IDS = {} ZENODO_METRICS_UPTIME_ROBOT_URL = 'https://api.uptimerobot.com/v2/getMonitors' ZENODO_METRICS_UPTIME_ROBOT_API_KEY = None ZENODO_METRICS_DATA = { 'openaire-nexus': [ { 'name': 'zenodo_nexus_data_transfer_bytes_total', 'help': ( 'Bytes of data transferred from/to Zenodo during the ' 'OpenAIRE-NEXUS project (i.e. from 2021-01-01).' ), 'type': 'counter', 'value': ZenodoMetric.get_data_transfer }, { 'name': 'zenodo_nexus_unique_visitors_web_total', 'help': ( 'Total of daily unique visitors on Zenodo portal during the ' 'OpenAIRE-NEXUS project (i.e. from 2021-01-01).' ), 'type': 'counter', 'value': ZenodoMetric.get_visitors }, { 'name': 'zenodo_last_month_uptime_ratio', 'help': 'Zenodo uptime percentage for the last month.', 'type': 'gauge', 'value': ZenodoMetric.get_uptime }, { 'name': 'zenodo_researchers', 'help': 'Number of researchers registered on Zenodo', 'type': 'gauge', 'value': ZenodoMetric.get_researchers }, { 'name': 'zenodo_files', 'help': 'Number of files hosted on Zenodo', 'type': 'gauge', 'value': ZenodoMetric.get_files }, { 'name': 'zenodo_communities', 'help': 'Number of Zenodo communities created', 'type': 'gauge', 'value': ZenodoMetric.get_communities }, ] }
3,043
Python
.py
79
31.35443
79
0.635103
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,489
tasks.py
zenodo_zenodo/zenodo/modules/metrics/tasks.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2023 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 metrics.""" from celery import shared_task from . import utils @shared_task(ignore_result=True) def calculate_metrics(metric_id=None): """Calculate metrics for the passed metric ID.""" utils.calculate_metrics(metric_id)
1,212
Python
.py
30
39
76
0.770798
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,490
api.py
zenodo_zenodo/zenodo/modules/metrics/api.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016-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. """Zenodo Metrics API.""" from __future__ import absolute_import import calendar from datetime import datetime, timedelta import requests from elasticsearch_dsl import Search from flask import current_app from invenio_accounts.models import User from invenio_communities.models import Community from invenio_files_rest.models import FileInstance from invenio_search import current_search_client from invenio_search.utils import build_alias_name from .proxies import current_metrics class ZenodoMetric(object): """API class for Zenodo Metrics.""" @staticmethod def get_data_transfer(): """Get file transfer volume in TB.""" time_range = {'gte': current_metrics.metrics_start_date.isoformat()} search = Search( using=current_search_client, index=build_alias_name('stats-file-download-*') ).filter( 'range', timestamp=time_range, ).filter( 'term', is_parent=False, ).params(request_timeout=120) search.aggs.metric('download_volume', 'sum', field='volume') result = search[:0].execute().aggregations.to_dict() download_volume = result.get('download_volume', {}).get('value', 0) search = Search( using=current_search_client, index=build_alias_name('records') ).filter('range', created=time_range).params(request_timeout=120) search.aggs.metric('upload_volume', 'sum', field='size') result = search[:0].execute().aggregations.to_dict() upload_volume = result.get('upload_volume', {}).get('value', 0) return int(download_volume + upload_volume) @staticmethod def get_visitors(): """Get number of unique zenodo users.""" time_range = {'gte': current_metrics.metrics_start_date.isoformat()} search = Search( using=current_search_client, index=build_alias_name('events-stats-*') ).filter('range', timestamp=time_range).params(request_timeout=120) search.aggs.metric( 'visitors_count', 'cardinality', field='visitor_id' ) result = search[:0].execute() if 'visitors_count' not in result.aggregations: return 0 return int(result.aggregations.visitors_count.value) @staticmethod def get_uptime(): """Get Zenodo uptime.""" metrics = current_app.config['ZENODO_METRICS_UPTIME_ROBOT_METRIC_IDS'] url = current_app.config['ZENODO_METRICS_UPTIME_ROBOT_URL'] api_key = current_app.config['ZENODO_METRICS_UPTIME_ROBOT_API_KEY'] end = datetime.utcnow().replace( day=1, hour=0, minute=0, second=0, microsecond=0) start = (end - timedelta(days=1)).replace(day=1) end_ts = calendar.timegm(end.utctimetuple()) start_ts = calendar.timegm(start.utctimetuple()) res = requests.post(url, json={ 'api_key': api_key, 'custom_uptime_ranges': '{}_{}'.format(start_ts, end_ts), }) return sum( float(d['custom_uptime_ranges']) for d in res.json()['monitors'] if d['id'] in metrics ) / len(metrics) @staticmethod def get_researchers(): """Get number of unique zenodo users.""" return User.query.filter( User.confirmed_at.isnot(None), User.active.is_(True), ).count() @staticmethod def get_files(): """Get number of files.""" return FileInstance.query.count() @staticmethod def get_communities(): """Get number of active communities.""" return Community.query.filter( Community.deleted_at.is_(None) ).count()
4,698
Python
.py
113
34.778761
78
0.663306
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,491
utils.py
zenodo_zenodo/zenodo/modules/metrics/utils.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-2023 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 metrics module.""" from copy import deepcopy from flask import current_app from invenio_cache import current_cache def get_metrics(metric_id): cached_data = current_cache.get('ZENODO_METRICS_CACHE::{}'.format(metric_id)) if cached_data is not None: return cached_data def calculate_metrics(metric_id, cache=True): """Calculate a metric's result.""" result = deepcopy( current_app.config['ZENODO_METRICS_DATA'][metric_id]) for metric in result: metric['value'] = metric['value']() if cache: current_cache.set( 'ZENODO_METRICS_CACHE::{}'.format(metric_id), result, timeout=current_app.config['ZENODO_METRICS_CACHE_TIMEOUT'], ) return result def formatted_response(metrics): """Format metrics into Prometheus format.""" response = '' for metric in metrics: response += "# HELP {name} {help}\n# TYPE {name} {type}\n{name} " \ "{value}\n".format(**metric) return response
2,004
Python
.py
50
36.12
81
0.712667
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,492
__init__.py
zenodo_zenodo/zenodo/modules/metrics/__init__.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-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. """Zenodo metrics module."""
1,002
Python
.py
24
40.708333
76
0.770727
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,493
proxies.py
zenodo_zenodo/zenodo/modules/metrics/proxies.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-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. """Proxy objects for easier access to application objects.""" from flask import current_app from werkzeug.local import LocalProxy current_metrics = LocalProxy( lambda: current_app.extensions['zenodo-metrics'])
1,189
Python
.py
28
41.214286
76
0.778929
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,494
views.py
zenodo_zenodo/zenodo/modules/metrics/views.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2017-2023 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 module that adds support for prometheus metrics.""" from flask import Blueprint, Response, current_app import humanize from . import utils, tasks blueprint = Blueprint( 'zenodo_metrics', __name__ ) @blueprint.route('/metrics/<string:metric_id>') def metrics(metric_id): """Metrics endpoint.""" if metric_id not in current_app.config['ZENODO_METRICS_DATA']: return Response('Invalid key', status=404, mimetype='text/plain') metrics = utils.get_metrics(metric_id) if metrics: response = utils.formatted_response(metrics) return Response(response, mimetype='text/plain') # Send off task to compute metrics tasks.calculate_metrics.delay(metric_id) retry_after = current_app.config["ZENODO_METRICS_CACHE_UPDATE_INTERVAL"] return Response( "Metrics not available. Try again after {}.".format( humanize.naturaldelta(retry_after) ), status=503, headers={"Retry-After": int(retry_after.total_seconds())}, )
2,000
Python
.py
50
36.6
76
0.73378
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,495
config.py
zenodo_zenodo/zenodo/modules/redirector/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 Zenodo Redirector.""" from __future__ import absolute_import, print_function ZENODO_TYPE_SUBTYPE_LEGACY = { 'publications': ('publication', None), 'books': ('publication', 'book'), 'books-sections': ('publication', 'section'), 'conference-papers': ('publication', 'conferencepaper'), 'journal-articles': ('publication', 'article'), 'patents': ('publication', 'patent'), 'preprints': ('publication', 'preprint'), 'deliverable': ('publication', 'deliverable'), 'milestone': ('publication', 'milestone'), 'proposal': ('publication', 'proposal'), 'reports': ('publication', 'report'), 'theses': ('publication', 'thesis'), 'technical-notes': ('publication', 'technicalnote'), 'working-papers': ('publication', 'workingpaper'), 'other-publications': ('publication', 'other'), 'posters': ('poster', None), 'presentations': ('presentation', None), 'datasets': ('dataset', None), 'images': ('image', None), 'figures': ('image', 'figure'), 'drawings': ('image', 'drawing'), 'diagrams': ('image', 'diagram'), 'photos': ('image', 'photo'), 'other-images': ('image', 'other'), 'videos': ('video', None), 'software': ('software', None), 'lessons': ('lesson', None), 'physicalobject': ('physicalobject', None), 'workflows': ('workflow', None), 'other': ('other', None), } #: External redirect URLs REDIRECTOR_EXTERNAL_REDIRECTS = [ ['/dev', 'dev', 'http://developers.zenodo.org'], ['/faq', 'faq', 'http://help.zenodo.org'], ['/features', 'features', 'http://help.zenodo.org/features/'], ['/whatsnew', 'whatsnew', 'http://help.zenodo.org/whatsnew/'], ['/about', 'about', 'http://about.zenodo.org'], ['/contact', 'contact', 'http://about.zenodo.org/contact/'], ['/policies', 'policies', 'http://about.zenodo.org/policies/'], ['/privacy-policy', 'privacy-policy', 'http://about.zenodo.org/privacy-policy/'], ['/terms', 'terms', 'http://about.zenodo.org/terms/'], ['/donate', 'donate', 'https://donate.cernandsocietyfoundation.cern/zenodo/~my-donation?_cv=1'], ]
3,117
Python
.py
72
39.722222
79
0.666667
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,496
__init__.py
zenodo_zenodo/zenodo/modules/redirector/__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 redirector.""" from __future__ import absolute_import, print_function
1,049
Python
.py
25
40.88
76
0.772016
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,497
views.py
zenodo_zenodo/zenodo/modules/redirector/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. """Zenodo redirector.""" from __future__ import absolute_import, print_function from flask import Blueprint, redirect, request, url_for from invenio_search_ui.views import search as search_ui_search from .config import REDIRECTOR_EXTERNAL_REDIRECTS, ZENODO_TYPE_SUBTYPE_LEGACY blueprint = Blueprint( 'zenodo_redirector', __name__, template_folder='templates', static_folder='static', ) @blueprint.record_once def configure_search_handler(blueprint_setup): """Update the search endpoint.""" blueprint_setup.app.view_functions[ 'invenio_search_ui.search'] = search_handler # https://zenodo.org/collection/user-<id> # https://zenodo.org/communities/<id>/ @blueprint.route('/collection/user-<id>') def community_redirect(id): """Redirect from the old community details to the new one.""" values = request.args.to_dict() values['community_id'] = id return redirect(url_for('invenio_communities.detail', **values)) # https://zenodo.org/communities/about/<id>/ # https://zenodo.org/communities/<id>/about/ @blueprint.route('/communities/about/<id>/') def communities_about_redirect(id): """.""" values = request.args.to_dict() values['community_id'] = id return redirect(url_for('invenio_communities.about', **values)) # https://zenodo.org/collection/<type> # https://zenodo.org/search?type=<general type>&subtype=<sub type> @blueprint.route('/collection/<type>') def collections_type_redirect(type): """.""" values = request.args.to_dict() type, subtype = ZENODO_TYPE_SUBTYPE_LEGACY.get(type, ('', None)) values['type'] = type if subtype: values['subtype'] = subtype return redirect(url_for('invenio_search_ui.search', **values)) def _pop_p(values): if 'p' in values: values['q'] = values.pop('p') values.pop('action_search', None) # May need to be removed later: values.pop('ln', None) def search_handler(): """Search handler.""" if 'cc' in request.args: if request.args.get('cc', '').startswith('user-'): return community_search_redirect() elif request.args.get('cc', '').startswith('provisional-user-'): return communities_provisional_user_redirect() else: return collections_search_redirect() elif 'p' in request.args: values = request.args.to_dict() _pop_p(values) return redirect(url_for('invenio_search_ui.search', **values)) else: return search_ui_search() # https://zenodo.org/search?ln=en&cc=user-<id>&p=<query>&action_search= # https://zenodo.org/communities/<id>/search?q=<query> def community_search_redirect(): """Redirect from the old community search to the new one.""" values = request.args.to_dict() values['community_id'] = values.pop('cc')[5:] # len('user-') == 5 _pop_p(values) return redirect(url_for('invenio_communities.search', **values)) # https://zenodo.org/search?cc=provisional-user-<id>&p=<query> # https://zenodo.org/communities/<id>/curate/?q=<query> def communities_provisional_user_redirect(): """Redirect from the old communities provisional search to the new one.""" values = request.args.to_dict() # len('provisional-user-') == 17 values['community_id'] = values.pop('cc')[17:] _pop_p(values) return redirect(url_for('invenio_communities.curate', **values)) # https://zenodo.org/search?ln=en&cc=<type> # https://zenodo.org/search?type=<general type>&subtype=<sub type> def collections_search_redirect(): """.""" values = request.args.to_dict() type, subtype = ZENODO_TYPE_SUBTYPE_LEGACY.get( values.pop('cc'), ('', None)) values['type'] = type if subtype: values['subtype'] = subtype _pop_p(values) return redirect(url_for('invenio_search_ui.search', **values)) def redirect_view_factory(url): """Create a view which redirects to given URL.""" return (lambda: redirect(url)) # Add url rules for external redirects for rule, endpoint, url in REDIRECTOR_EXTERNAL_REDIRECTS: blueprint.add_url_rule(rule, endpoint, redirect_view_factory(url))
5,099
Python
.py
122
37.868852
78
0.702102
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,498
ext.py
zenodo_zenodo/zenodo/modules/openaire/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. """Zenodo OpenAIRE extension.""" from __future__ import absolute_import, print_function from collections import defaultdict from werkzeug.utils import cached_property from . import config class _ZenodoOpenAIREState(object): """Store the OpenAIRE mappings.""" def __init__(self, app): self.app = app @cached_property def openaire_communities(self): """Configuration for OpenAIRE communities types.""" return self.app.config['ZENODO_OPENAIRE_COMMUNITIES'] @cached_property def inverse_openaire_community_map(self): """Lookup for Zenodo community -> OpenAIRE community.""" comm_map = self.openaire_communities items = defaultdict(list) for oa_comm, cfg in comm_map.items(): for z_comm in cfg['communities']: items[z_comm].append(oa_comm) return items class ZenodoOpenAIRE(object): """Zenodo OpenAIRE 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_OPENAIRE_'): app.config.setdefault(k, getattr(config, k)) def init_app(self, app): """Flask application initialization.""" self.init_config(app) state = _ZenodoOpenAIREState(app) self._state = app.extensions['zenodo-openaire'] = state
2,471
Python
.py
62
34.741935
76
0.698413
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)
23,499
errors.py
zenodo_zenodo/zenodo/modules/openaire/errors.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. """Deposit errors.""" from __future__ import absolute_import, print_function class OpenAIRERequestError(Exception): """Error for failed requests on the OpenAIRE API."""
1,144
Python
.py
27
41.074074
76
0.770889
zenodo/zenodo
906
241
543
GPL-2.0
9/5/2024, 5:13:26 PM (Europe/Amsterdam)