-
Notifications
You must be signed in to change notification settings - Fork 6
/
ezid.py
executable file
·304 lines (278 loc) · 9.17 KB
/
ezid.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#! /usr/bin/env python
# EZID command line client. Input metadata (from command line
# parameters and files) is assumed to be UTF-8 encoded, and output
# metadata is UTF-8 encoded, unless overriden by the -e option. By
# default, ANVL responses (currently, that's all responses) are left
# in %-encoded form.
#
# Usage: ezid.py [options] credentials operation...
#
# options:
# -d decode ANVL responses
# -e ENCODING character encoding; defaults to UTF-8
# -o one line per ANVL value: convert newlines to spaces
# -t format timestamps
#
# credentials:
# username:password
# username (password will be prompted for)
# sessionid=... (as returned by previous login)
# - (none)
#
# operation:
# m[int] shoulder [element value ...]
# c[reate][!] identifier [element value ...]
# create! = create or update
# v[iew][!] identifier
# view! = match longest identifier prefix
# u[pdate] identifier [element value ...]
# d[elete] identifier
# login
# logout
# s[tatus]
#
# In the above, if an element is "@", the subsequent value is treated
# as a filename and metadata elements are read from the named
# ANVL-formatted file. For example, if file metadata.txt contains:
#
# erc.who: Proust, Marcel
# erc.what: Remembrance of Things Past
# erc.when: 1922
#
# then an identifier with that metadata can be minted by invoking:
#
# ezid.py username:password mint ark:/99999/fk4 @ metadata.txt
#
# Otherwise, if a value has the form "@filename", a (single) value is
# read from the named file. For example, if file metadata.xml
# contains a DataCite XML record, then an identifier with that record
# as the value of the 'datacite' element can be minted by invoking:
#
# ezid.py username:password mint doi:10.5072/FK2 datacite @metadata.xml
#
# In both of the above cases, the interpretation of @ can be defeated
# by doubling it.
#
# Greg Janee <gjanee@ucop.edu>
# May 2013
import codecs
import getpass
import optparse
import re
import sys
import time
import types
import urllib
import urllib2
KNOWN_SERVERS = {
"p": "https://ezid.cdlib.org"
}
OPERATIONS = {
# operation: (number of arguments, accepts bang)
"mint": (lambda l: l%2 == 1, False),
"create": (lambda l: l%2 == 1, True),
"view": (1, True),
"update": (lambda l: l%2 == 1, False),
"delete": (1, False),
"login": (0, False),
"logout": (0, False),
"status": (0, False)
}
USAGE_TEXT = """Usage: ezid.py [options] credentials operation...
options:
-d decode ANVL responses
-e ENCODING character encoding; defaults to UTF-8
-o one line per ANVL value: convert newlines to spaces
-t format timestamps
credentials:
username:password
username (password will be prompted for)
sessionid=... (as returned by previous login)
- (none)
operation:
m[int] shoulder [element value ...]
c[reate][!] identifier [element value ...]
create! = create or update
v[iew][!] identifier
view! = match longest identifier prefix
u[pdate] identifier [element value ...]
d[elete] identifier
login
logout
s[tatus]
"""
# Global variables that are initialized farther down.
_options = None
_server = None
_opener = None
_cookie = None
class MyHelpFormatter (optparse.IndentedHelpFormatter):
def format_usage (self, usage):
return USAGE_TEXT
class MyHTTPErrorProcessor (urllib2.HTTPErrorProcessor):
def http_response (self, request, response):
# Bizarre that Python leaves this out.
if response.code == 201:
return response
else:
return urllib2.HTTPErrorProcessor.http_response(self, request, response)
https_response = http_response
def formatAnvlRequest (args):
request = []
for i in range(0, len(args), 2):
k = args[i].decode(_options.encoding)
if k == "@":
f = codecs.open(args[i+1], encoding=_options.encoding)
request += [l.strip("\r\n") for l in f.readlines()]
f.close()
else:
if k == "@@":
k = "@"
else:
k = re.sub("[%:\r\n]", lambda c: "%%%02X" % ord(c.group(0)), k)
v = args[i+1].decode(_options.encoding)
if v.startswith("@@"):
v = v[1:]
elif v.startswith("@") and len(v) > 1:
f = codecs.open(v[1:], encoding=_options.encoding)
v = f.read()
f.close()
v = re.sub("[%\r\n]", lambda c: "%%%02X" % ord(c.group(0)), v)
request.append("%s: %s" % (k, v))
return "\n".join(request)
def encode (id):
return urllib.quote(id, ":/")
def issueRequest (path, method, data=None, returnHeaders=False,
streamOutput=False):
request = urllib2.Request("%s/%s" % (_server, path))
request.get_method = lambda: method
if data:
request.add_header("Content-Type", "text/plain; charset=UTF-8")
request.add_data(data.encode("UTF-8"))
if _cookie: request.add_header("Cookie", _cookie)
try:
connection = _opener.open(request)
if streamOutput:
while True:
sys.stdout.write(connection.read(1))
sys.stdout.flush()
else:
response = connection.read()
if returnHeaders:
return response.decode("UTF-8"), connection.info()
else:
return response.decode("UTF-8")
except urllib2.HTTPError, e:
sys.stderr.write("%d %s\n" % (e.code, e.msg))
if e.fp != None:
response = e.fp.read()
if not response.endswith("\n"): response += "\n"
sys.stderr.write(response)
sys.exit(1)
def printAnvlResponse (response, sortLines=False):
response = response.splitlines()
if sortLines and len(response) >= 1:
statusLine = response[0]
response = response[1:]
response.sort()
response.insert(0, statusLine)
for line in response:
if _options.formatTimestamps and (line.startswith("_created:") or\
line.startswith("_updated:")):
ls = line.split(":")
line = ls[0] + ": " + time.strftime("%Y-%m-%dT%H:%M:%S",
time.localtime(int(ls[1])))
if _options.decode:
line = re.sub("%([0-9a-fA-F][0-9a-fA-F])",
lambda m: chr(int(m.group(1), 16)), line)
if _options.oneLine: line = line.replace("\n", " ").replace("\r", " ")
print line.encode(_options.encoding)
# Process command line arguments.
parser = optparse.OptionParser(formatter=MyHelpFormatter())
parser.add_option("-d", action="store_true", dest="decode", default=False)
parser.add_option("-e", action="store", dest="encoding", default="UTF-8")
parser.add_option("-o", action="store_true", dest="oneLine", default=False)
parser.add_option("-t", action="store_true", dest="formatTimestamps",
default=False)
_options, args = parser.parse_args()
# Simulate selection of the production server (server selection is not
# supported in this public version of the code).
args.insert(0, "p")
if len(args) < 3: parser.error("insufficient arguments")
_server = KNOWN_SERVERS.get(args[0], args[0])
_opener = urllib2.build_opener(MyHTTPErrorProcessor())
if args[1].startswith("sessionid="):
_cookie = args[1]
elif args[1] != "-":
if ":" in args[1]:
username, password = args[1].split(":", 1)
else:
username = args[1]
password = getpass.getpass()
h = urllib2.HTTPBasicAuthHandler()
h.add_password("EZID", _server, username, password)
_opener.add_handler(h)
if args[2].endswith("!"):
bang = True
args[2] = args[2][:-1]
else:
bang = False
operation = filter(lambda o: o.startswith(args[2]), OPERATIONS)
if len(operation) != 1: parser.error("unrecognized or ambiguous operation")
operation = operation[0]
if bang and not OPERATIONS[operation][1]:
parser.error("unrecognized operation")
args = args[3:]
if (type(OPERATIONS[operation][0]) is int and\
len(args) != OPERATIONS[operation][0]) or\
(type(OPERATIONS[operation][0]) is types.LambdaType and\
not OPERATIONS[operation][0](len(args))):
parser.error("incorrect number of arguments for operation")
# Perform the operation.
if operation == "mint":
shoulder = args[0]
if len(args) > 1:
data = formatAnvlRequest(args[1:])
else:
data = None
response = issueRequest("shoulder/"+encode(shoulder), "POST", data)
printAnvlResponse(response)
elif operation == "create":
id = args[0]
if len(args) > 1:
data = formatAnvlRequest(args[1:])
else:
data = None
path = "id/"+encode(id)
if bang: path += "?update_if_exists=yes"
response = issueRequest(path, "PUT", data)
printAnvlResponse(response)
elif operation == "view":
id = args[0]
path = "id/"+encode(id)
if bang: path += "?prefix_match=yes"
response = issueRequest(path, "GET")
printAnvlResponse(response, sortLines=True)
elif operation == "update":
id = args[0]
if len(args) > 1:
data = formatAnvlRequest(args[1:])
else:
data = None
response = issueRequest("id/"+encode(id), "POST", data)
printAnvlResponse(response)
elif operation == "delete":
id = args[0]
response = issueRequest("id/"+encode(id), "DELETE")
printAnvlResponse(response)
elif operation == "login":
response, headers = issueRequest("login", "GET", returnHeaders=True)
response += "\nsessionid=%s\n" %\
headers["set-cookie"].split(";")[0].split("=")[1]
printAnvlResponse(response)
elif operation == "logout":
response = issueRequest("logout", "GET")
printAnvlResponse(response)
elif operation == "status":
response = issueRequest("status", "GET")
printAnvlResponse(response)