-
Notifications
You must be signed in to change notification settings - Fork 71
/
upload.py
214 lines (153 loc) · 6.85 KB
/
upload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# Copyright (C) 2019 Simon Biggs
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import hashlib
import json
import pathlib
import urllib
from pymedphys._imports import keyring, requests
from .zenodo import get_zenodo_access_token, get_zenodo_record_id
HEADERS = {"Content-Type": "application/json"}
def zenodo_api_with_helpful_fallback(url, method, **kwargs):
hostname = urllib.parse.urlparse(url).hostname
access_token = get_zenodo_access_token(hostname)
kwargs["params"] = {"access_token": access_token}
r = getattr(requests, method)(url, **kwargs)
if r.status_code == 401:
print("The access token you provided is invalid.\n")
keyring.delete_password("Zenodo", hostname)
return zenodo_api_with_helpful_fallback(url, **kwargs)
if r.status_code == 403:
print(
"The access token you provided doesn't appear to have the right scopes. "
"Make sure that the access token you provide has the scopes "
"`deposit:actions`, `deposit:write`, and `user:email`.\n"
)
keyring.delete_password("Zenodo", hostname)
return zenodo_api_with_helpful_fallback(url, **kwargs)
return r
def create_metadata(title, author=None):
if author is None:
author = "PyMedPhys Contributors"
metadata = {
"metadata": {
"title": title,
"upload_type": "dataset",
"creators": [{"name": author}],
"description": "<p>This is an automated upload from the PyMedPhys library.</p>",
"license": "Apache-2.0",
"access_right": "open",
}
}
return json.dumps(metadata)
def publish_deposition(deposition_id, use_sandbox=False):
deposition_url = get_deposition_url(deposition_id, use_sandbox=use_sandbox)
publish_url = f"{deposition_url}/actions/publish"
r = zenodo_api_with_helpful_fallback(publish_url, "post")
if r.status_code != 202:
raise ValueError(
f"Unexpected status code when publishing the file. Expected 202, got {r.status_code}."
)
def get_zenodo_url(use_sandbox):
if use_sandbox:
zenodo_url = "https://sandbox.zenodo.org/"
else:
zenodo_url = "https://zenodo.org/"
return zenodo_url
def get_deposition_url(deposition_id, use_sandbox=False):
root_depositions_url = get_root_depositions_url(use_sandbox)
deposition_url = f"{root_depositions_url}/{deposition_id}"
return deposition_url
def get_root_depositions_url(use_sandbox):
zenodo_url = get_zenodo_url(use_sandbox)
root_depositions_url = f"{zenodo_url}api/deposit/depositions"
return root_depositions_url
def get_files_url(deposition_id, use_sandbox=False):
deposition_url = get_deposition_url(deposition_id, use_sandbox=use_sandbox)
files_url = f"{deposition_url}/files"
return files_url
def delete_filenames_within_record(filenames, deposition_id, use_sandbox=False):
files_url = get_files_url(deposition_id, use_sandbox=use_sandbox)
r = zenodo_api_with_helpful_fallback(files_url, "get")
record_filenames = [record["filename"] for record in r.json()]
for filename in filenames:
if filename in record_filenames:
file_self_urls = [
record["links"]["self"]
for record in r.json()
if record["filename"] == filename
]
if len(file_self_urls) > 1:
raise ValueError("Unexpected number of file_ids found")
file_self_url = file_self_urls[0]
zenodo_api_with_helpful_fallback(file_self_url, "delete")
def upload_filepaths(filepaths, deposition_id, use_sandbox=False):
files_url = get_files_url(deposition_id, use_sandbox=use_sandbox)
for filepath in filepaths:
md5 = hashlib.md5()
with open(filepath, "rb") as upload_file:
md5.update(upload_file.read())
upload_file.seek(0)
r = zenodo_api_with_helpful_fallback(
files_url,
"post",
data={"name": filepath.name},
files={"file": upload_file},
)
response = r.json()
try:
record_checksum = response["checksum"]
except KeyError:
raise ValueError(
f"The response when uploading was not as expected:\n {response}"
)
if md5.hexdigest() != record_checksum:
raise ValueError(
"The uploaded Zenodo's checksum does not match the local checksum.\n"
f" Zenodo's Checksum: {record_checksum}\n"
f" Local Checksum: {md5.hexdigest()}"
)
def set_metadata(metadata, deposition_id, use_sandbox=False):
deposition_url = get_deposition_url(deposition_id, use_sandbox=use_sandbox)
zenodo_api_with_helpful_fallback(
deposition_url, "put", data=metadata, headers=HEADERS
)
def upload_files_to_zenodo(
filepaths, title, author=None, use_sandbox=False, record_name=None
):
filepaths = [pathlib.Path(filepath) for filepath in filepaths]
root_depositions_url = get_root_depositions_url(use_sandbox)
if record_name is not None:
if use_sandbox:
raise ValueError("Cannot use sandbox when `record_name` is provided")
old_deposition_id = get_zenodo_record_id(record_name)
old_deposition_url = f"{root_depositions_url}/{old_deposition_id}"
new_version_url = f"{old_deposition_url}/actions/newversion"
r = zenodo_api_with_helpful_fallback(new_version_url, "post")
deposition_id = int(r.json()["links"]["latest_draft"].split("/")[-1])
else:
r = zenodo_api_with_helpful_fallback(
root_depositions_url, "post", json={}, headers=HEADERS
)
try:
response = r.json()
except json.JSONDecodeError:
raise ValueError(f"Unexpected response: {r.text}")
try:
deposition_id = response["id"]
except KeyError:
raise ValueError(f"Unexpected response: {response}")
metadata = create_metadata(title, author)
set_metadata(metadata, deposition_id, use_sandbox=use_sandbox)
filenames = [path.name for path in filepaths]
delete_filenames_within_record(filenames, deposition_id, use_sandbox=use_sandbox)
upload_filepaths(filepaths, deposition_id, use_sandbox=use_sandbox)
publish_deposition(deposition_id, use_sandbox=use_sandbox)
return deposition_id