| 1 |
""" |
| 2 |
A simple client of OAI-http. |
| 3 |
|
| 4 |
This includes both some high-level functions and rudimentary parsers |
| 5 |
that can serve as bases for more specialized parsers. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import functools |
| 15 |
import io |
| 16 |
import hashlib |
| 17 |
import os |
| 18 |
import pickle |
| 19 |
import re |
| 20 |
import urllib.parse |
| 21 |
from xml import sax |
| 22 |
from xml.sax import saxutils |
| 23 |
|
| 24 |
from gavo import base |
| 25 |
from gavo import utils |
| 26 |
|
| 27 |
|
| 28 |
class FailedQuery(Exception): |
| 29 |
def __init__(self, msg, code="?", value="?"): |
| 30 |
Exception.__init__(self, msg) |
| 31 |
self.code, self.value = code, value |
| 32 |
|
| 33 |
|
| 34 |
class NoRecordsMatch(Exception): |
| 35 |
pass |
| 36 |
|
| 37 |
|
| 38 |
class PrefixIsTaken(Exception): |
| 39 |
pass |
| 40 |
|
| 41 |
# Canonical prefixes, i.e., essentially fixed prefixes for certain |
| 42 |
# namespaces. This is all an ugly nightmare, but this is what you |
| 43 |
# get for having namespace prefixes in attributes. |
| 44 |
|
| 45 |
class CanonicalPrefixes(object): |
| 46 |
"""a self-persisting dictionary of the prefixes we use in our |
| 47 |
OAI interface. |
| 48 |
|
| 49 |
CanonicalPrefixes objects are constructed with the name of a |
| 50 |
pickle file containing a list of (prefix, uri) pairs. |
| 51 |
|
| 52 |
This reproduces some code from stanxml.NSRegistry, but we want that |
| 53 |
stuff as instance method here, not as class method. |
| 54 |
""" |
| 55 |
def __init__(self, pickleName): |
| 56 |
self.pickleName = str(pickleName) |
| 57 |
self._registry = {} |
| 58 |
self._reverseRegistry = {} |
| 59 |
self._loadData() |
| 60 |
|
| 61 |
def registerPrefix(self, prefix, ns, save=True): |
| 62 |
if prefix in self._registry: |
| 63 |
if ns!=self._registry[prefix]: |
| 64 |
raise PrefixIsTaken(prefix) |
| 65 |
return |
| 66 |
self._registry[prefix] = ns |
| 67 |
if ns in self._reverseRegistry and self._reverseRegistry[ns]!=prefix: |
| 68 |
raise ValueError("Namespace %s already has prefix %s, will" |
| 69 |
" not clobber with %s"%(ns, self._reverseRegistry[ns], prefix)) |
| 70 |
self._reverseRegistry[ns] = prefix |
| 71 |
if save: |
| 72 |
self._saveData() |
| 73 |
|
| 74 |
def registerPrefixOrMakeUp(self, prefix, ns): |
| 75 |
"""registers prefix for ns or, if prefix is already taken, makes |
| 76 |
up a new prefix for the namespace URI ns. |
| 77 |
""" |
| 78 |
try: |
| 79 |
self.registerPrefix(prefix, ns) |
| 80 |
except PrefixIsTaken: |
| 81 |
origPrefix, uniquer = prefix, 0 |
| 82 |
while True: |
| 83 |
try: |
| 84 |
prefix = origPrefix+str(uniquer) |
| 85 |
self.registerPrefix(prefix, ns) |
| 86 |
except PrefixIsTaken: |
| 87 |
uniquer += 1 |
| 88 |
else: |
| 89 |
break |
| 90 |
|
| 91 |
def getPrefixForNS(self, ns): |
| 92 |
try: |
| 93 |
return self._reverseRegistry[ns] |
| 94 |
except KeyError: |
| 95 |
raise base.NotFoundError(ns, "XML namespace", |
| 96 |
"registry of XML namespaces.") |
| 97 |
|
| 98 |
def haveNS(self, ns): |
| 99 |
return ns in self._reverseRegistry |
| 100 |
|
| 101 |
def getNSForPrefix(self, prefix): |
| 102 |
try: |
| 103 |
return self._registry[prefix] |
| 104 |
except KeyError: |
| 105 |
raise base.NotFoundError(prefix, "XML namespace prefix", |
| 106 |
"registry of prefixes.") |
| 107 |
|
| 108 |
def iterNS(self): |
| 109 |
return iter(self._registry.items()) |
| 110 |
|
| 111 |
def _fillFromPairs(self, pairs): |
| 112 |
"""fills the instance from a list of prefix, uri pairs. |
| 113 |
|
| 114 |
Pairs is what is stored in the pickle. |
| 115 |
""" |
| 116 |
for prefix, uri in pairs: |
| 117 |
self.registerPrefix(prefix, uri, save=False) |
| 118 |
|
| 119 |
def _bootstrap(self): |
| 120 |
"""sets up our canonical prefixes from DaCHS' (stanxml) namespace |
| 121 |
registry. |
| 122 |
""" |
| 123 |
from gavo import api #noflake: hope most prefixes are registered after that |
| 124 |
from gavo.utils import stanxml |
| 125 |
self._fillFromPairs(iter(stanxml.NSRegistry._registry.items())) |
| 126 |
self._saveData() |
| 127 |
|
| 128 |
def _loadData(self): |
| 129 |
try: |
| 130 |
with open(self.pickleName, "rb") as f: |
| 131 |
self._fillFromPairs(pickle.load(f)) |
| 132 |
except IOError: # most likely, the file does not exist yet |
| 133 |
base.ui.notifyWarning("Starting new canonical prefixes") |
| 134 |
self._bootstrap() |
| 135 |
|
| 136 |
def _saveData(self): |
| 137 |
toPersist = list(sorted(self._registry.items())) |
| 138 |
try: |
| 139 |
with open(self.pickleName+".tmp", "wb") as f: |
| 140 |
pickle.dump(toPersist, f) |
| 141 |
os.rename(self.pickleName+".tmp", self.pickleName) |
| 142 |
except IOError as msg: |
| 143 |
base.ui.notifyWarning("Could not persist canonical prefixes: %s"% |
| 144 |
msg) |
| 145 |
|
| 146 |
|
| 147 |
@functools.cache |
| 148 |
def getCanonicalPrefixes(): |
| 149 |
return CanonicalPrefixes( |
| 150 |
base.getConfig("cacheDir") / "rrOaiPrefixes.pickle") |
| 151 |
|
| 152 |
|
| 153 |
class OAIErrorMixin(object): |
| 154 |
def _end_error(self, name, attrs, content): |
| 155 |
if attrs["code"]=="noRecordsMatch": |
| 156 |
raise NoRecordsMatch() |
| 157 |
raise FailedQuery("Registry bailed with code %s, value %s"%( |
| 158 |
attrs["code"], content), attrs["code"], content) |
| 159 |
|
| 160 |
|
| 161 |
class IdParser(utils.StartEndHandler, OAIErrorMixin): |
| 162 |
"""A parser for simple OAI-PMH headers. |
| 163 |
|
| 164 |
Records end up as a list of dictionaries in the recs attribute. |
| 165 |
""" |
| 166 |
resumptionToken = None |
| 167 |
|
| 168 |
def __init__(self, initRecs=None): |
| 169 |
utils.StartEndHandler.__init__(self) |
| 170 |
if initRecs is None: |
| 171 |
self.recs = [] |
| 172 |
else: |
| 173 |
self.recs = initRecs |
| 174 |
|
| 175 |
def getResult(self): |
| 176 |
return self.recs |
| 177 |
|
| 178 |
def _end_identifier(self, name, attrs, content): |
| 179 |
self.recs[-1]["id"] = content.strip() |
| 180 |
|
| 181 |
def _end_datestamp(self, name, attrs, content): |
| 182 |
try: |
| 183 |
self.recs[-1]["date"] = utils.parseISODT(content) |
| 184 |
except ValueError: # don't fail just because of a broken date |
| 185 |
self.recs[-1]["date"] = None |
| 186 |
|
| 187 |
def _start_header(self, name, attrs): |
| 188 |
self.recs.append({}) |
| 189 |
|
| 190 |
def _end_resumptionToken(self, name, attrs, content): |
| 191 |
if content.strip(): |
| 192 |
self.resumptionToken = content |
| 193 |
|
| 194 |
|
| 195 |
class RecordParser(IdParser, OAIErrorMixin): |
| 196 |
"""A simple parser for ivo_vor records. |
| 197 |
|
| 198 |
This only pulls out a number of the most salient items; more will |
| 199 |
probably follow as needed. |
| 200 |
""" |
| 201 |
def _end_title(self, name, attrs, content): |
| 202 |
if self.getParentTag()=="Resource": |
| 203 |
self.recs[-1][name] = content |
| 204 |
|
| 205 |
def _end_email(self, name, attrs, content): |
| 206 |
if self.getParentTag()=="contact": |
| 207 |
self.recs[-1]["contact.email"] = content |
| 208 |
|
| 209 |
def _end_name(self, name, attrs, content): |
| 210 |
if self.getParentTag()=="creator": |
| 211 |
self.recs[-1].setdefault(name, []).append(content) |
| 212 |
|
| 213 |
def _end_subject(self, name, attrs, content): |
| 214 |
self.recs[-1].setdefault(name, []).append(content) |
| 215 |
|
| 216 |
def _handleContentChild(self, name, attrs, content): |
| 217 |
if self.getParentTag()=="content": |
| 218 |
self.recs[-1][name] = content |
| 219 |
|
| 220 |
_end_description = _end_source = _end_referenceURL = \ |
| 221 |
_handleContentChild |
| 222 |
|
| 223 |
def _end_datestamp(self, name, attrs, content): |
| 224 |
# nuke IdParser implementation, we take our date from ri:Resource |
| 225 |
pass |
| 226 |
|
| 227 |
def _startResource(self, name, attrs): |
| 228 |
self.recs.append({}) |
| 229 |
|
| 230 |
def _end_Resource(self, name, attrs, content): |
| 231 |
self.recs[-1]["date"] = utils.parseISODT(attrs["updated"]) |
| 232 |
|
| 233 |
def _end_accessURL(self, name, attrs, content): |
| 234 |
self.recs[-1].setdefault(name, []).append(content) |
| 235 |
|
| 236 |
|
| 237 |
class OAIRecordsParser(sax.ContentHandler, OAIErrorMixin): |
| 238 |
"""a SAX ContentHandler generating tuples of some record-level metadata |
| 239 |
and pre-formatted XML of simple implementation of the OAI interface. |
| 240 |
|
| 241 |
canonicalPrefixes is a CanonicalPrefixesInstance built from |
| 242 |
res/canonicalPrefixes.pickle |
| 243 |
|
| 244 |
Note that we *require* that records actually carry ivo_vor metadata. |
| 245 |
|
| 246 |
Note that this is nothing people should need in normal operation. |
| 247 |
GAVO Heidelberg needs this for infrastructure services |
| 248 |
(including OAI on RegTAP, but we needed it beyond that). |
| 249 |
""" |
| 250 |
# attribute names the values of which should be disambiguated to |
| 251 |
# reduce the likelihood of clashes when ids are reused between documents. |
| 252 |
# (see _normalizeAttrs) |
| 253 |
_referringAttributeNames = set(["id", "ref", |
| 254 |
"coord_system_id"]) |
| 255 |
|
| 256 |
resumptionToken = None |
| 257 |
|
| 258 |
def __init__(self, canonicalPrefixes=None): |
| 259 |
self.canonicalPrefixes = canonicalPrefixes or getCanonicalPrefixes() |
| 260 |
sax.ContentHandler.__init__(self) |
| 261 |
self.buffer = None |
| 262 |
self.writer = None |
| 263 |
self.rowdicts = [] |
| 264 |
self.prefixMap = {} |
| 265 |
self.prefixesToTranslate = {} |
| 266 |
|
| 267 |
def startPrefixMapping(self, prefix, uri): |
| 268 |
self.prefixMap.setdefault(prefix, []).append(uri) |
| 269 |
|
| 270 |
if prefix: |
| 271 |
# Here, we make sure we find a globally unique prefix for every |
| 272 |
# namespace URI. canonicalPrefixes makes sure this unique prefix |
| 273 |
# is persistent and later available to the OAI interface |
| 274 |
if not self.canonicalPrefixes.haveNS(uri): |
| 275 |
self.canonicalPrefixes.registerPrefixOrMakeUp(prefix, uri) |
| 276 |
|
| 277 |
canonPrefix = self.canonicalPrefixes.getPrefixForNS(uri) |
| 278 |
if prefix!=canonPrefix or prefix in self.prefixesToTranslate: |
| 279 |
self.prefixesToTranslate.setdefault(prefix, []).append(canonPrefix) |
| 280 |
|
| 281 |
def endPrefixMapping(self, prefix): |
| 282 |
self.prefixMap[prefix].pop() |
| 283 |
if prefix in self.prefixesToTranslate: |
| 284 |
self.prefixesToTranslate[prefix].pop() |
| 285 |
if not self.prefixesToTranslate[prefix]: |
| 286 |
del self.prefixesToTranslate[prefix] |
| 287 |
|
| 288 |
def startElementNS(self, namePair, ignored, attrs): |
| 289 |
ns, name = namePair |
| 290 |
if ns is not None: |
| 291 |
name = self.canonicalPrefixes.getPrefixForNS(ns)+":"+name |
| 292 |
if attrs: |
| 293 |
attrs = self._normalizeAttrs(attrs) |
| 294 |
|
| 295 |
if name in self.startHandlers: |
| 296 |
self.startHandlers[name](self, name, attrs) |
| 297 |
|
| 298 |
if self.writer: |
| 299 |
self.writer.startElement(name, attrs) |
| 300 |
|
| 301 |
self._lastChars = [] |
| 302 |
|
| 303 |
def endElementNS(self, namePair, name): |
| 304 |
ns, name = namePair |
| 305 |
if ns is not None: |
| 306 |
name = self.canonicalPrefixes.getPrefixForNS(ns)+":"+name |
| 307 |
if self.writer: |
| 308 |
self.writer.endElement(name) |
| 309 |
if name in self.endHandlers: |
| 310 |
self.endHandlers[name](self, name) |
| 311 |
|
| 312 |
def characters(self, stuff): |
| 313 |
if self.writer: |
| 314 |
self.writer.characters(stuff) |
| 315 |
# Hack, see _getLastContent |
| 316 |
self._lastChars.append(stuff) |
| 317 |
|
| 318 |
def normalizeNamespace(self, name): |
| 319 |
"""fixes the namespace prefix of name if necessary. |
| 320 |
|
| 321 |
name must be a qualified name, i.e., contain exactly one colon. |
| 322 |
|
| 323 |
"normalize" here means make sure the prefix matches our canonical prefix |
| 324 |
and change it to the canonical one if necessary. |
| 325 |
""" |
| 326 |
prefix, base = name.split(":") |
| 327 |
if prefix not in self.prefixesToTranslate: |
| 328 |
return name |
| 329 |
return self.prefixesToTranslate[prefix][-1]+":"+base |
| 330 |
|
| 331 |
def _normalizeAttrs(self, attrs): |
| 332 |
"""fixes attribute name and attribute value namespaces if necessary. |
| 333 |
|
| 334 |
It also always checks for xsi:type and fixes namespaced attribute |
| 335 |
values as necessary. |
| 336 |
|
| 337 |
See also normalizeNamespace. |
| 338 |
""" |
| 339 |
newAttrs = {} |
| 340 |
for ns, name in list(attrs.keys()): |
| 341 |
value = attrs[(ns, name)] |
| 342 |
if ns is None: |
| 343 |
newName = name |
| 344 |
else: |
| 345 |
newName = self.canonicalPrefixes.getPrefixForNS(ns)+":"+name |
| 346 |
|
| 347 |
if newName=="xsi:type": |
| 348 |
if ":" in value: |
| 349 |
value = self.normalizeNamespace(value) |
| 350 |
|
| 351 |
# to uniqueify id/ref-pairs, prepend an md5-digest of the ivoid |
| 352 |
# to selected ids. This isn't guaranteed to always work, but |
| 353 |
# if someone is devious enough to cause collisions here, they |
| 354 |
# deserve no better. |
| 355 |
if newName in self._referringAttributeNames: |
| 356 |
value = value+hashlib.md5(self.ivoid.encode("utf-8")).hexdigest() |
| 357 |
|
| 358 |
newAttrs[newName] = value |
| 359 |
|
| 360 |
return newAttrs |
| 361 |
|
| 362 |
def _getLastContent(self): |
| 363 |
"""returns the entire character content since the last XML event. |
| 364 |
""" |
| 365 |
return "".join(self._lastChars) |
| 366 |
|
| 367 |
def notifyError(self, err): |
| 368 |
self._errorOccurred = True |
| 369 |
|
| 370 |
def shipout(self, role, record): |
| 371 |
# see _end_identifier for an explanation of the following condition |
| 372 |
if self.ivoid is None: |
| 373 |
return |
| 374 |
# see our docstring on why we need the following |
| 375 |
if not self.metadataSeen: |
| 376 |
return |
| 377 |
if self._errorOccurred: |
| 378 |
return |
| 379 |
|
| 380 |
# _start_header sets _isDeleted |
| 381 |
if self._isDeleted: |
| 382 |
return |
| 383 |
self.rowdicts.append((role, record)) |
| 384 |
|
| 385 |
def _start_oai_header(self, name, attrs): |
| 386 |
self._isDeleted = attrs.get("status", "").lower()=="deleted" |
| 387 |
|
| 388 |
def _start_oai_record(self, name, attrs): |
| 389 |
self._errorOccurred = False |
| 390 |
self.curXML = io.BytesIO() |
| 391 |
self.writer = saxutils.XMLGenerator( |
| 392 |
self.curXML, |
| 393 |
"utf-8", |
| 394 |
short_empty_elements=True) |
| 395 |
self.writer.startDocument() |
| 396 |
self.ivoid, self.updated = None, None |
| 397 |
self.metadataSeen = False |
| 398 |
self.oaiSets = set() |
| 399 |
|
| 400 |
def _start_ri_Resource(self, anme, attrs): |
| 401 |
self.metadataSeen = True |
| 402 |
|
| 403 |
def _end_oai_record(self, name): |
| 404 |
if self.writer is not None: |
| 405 |
self.writer.endDocument() |
| 406 |
# yeah, we decode the serialized result right away; it's easier |
| 407 |
# to store character streams in the DB the way I'm doing things. |
| 408 |
oaixml = self.curXML.getvalue().decode("utf-8") |
| 409 |
# unfortunately, XMLGenerator insists on adding an XML declaration, |
| 410 |
# which I can't have here. I remove it manually |
| 411 |
if oaixml.startswith("<?xml"): |
| 412 |
oaixml = oaixml[oaixml.index("?>")+2:] |
| 413 |
self.shipout("oairecs", { |
| 414 |
"ivoid": self.ivoid, |
| 415 |
"updated": self.updated, |
| 416 |
"oaixml": oaixml}) |
| 417 |
self.writer = None |
| 418 |
self.curXML = None |
| 419 |
|
| 420 |
def _end_oai_setSpec(self, name): |
| 421 |
self.oaiSets.add(self._getLastContent()) |
| 422 |
|
| 423 |
def _end_oai_identifier(self, name): |
| 424 |
self.ivoid = self._getLastContent().lower().strip() |
| 425 |
|
| 426 |
def _end_oai_resumptionToken(self, name): |
| 427 |
self.resumptionToken = self._getLastContent() |
| 428 |
|
| 429 |
def _start_oai_error(self, name, attrs): |
| 430 |
self._errorAttrs = attrs |
| 431 |
|
| 432 |
def _end_oai_error(self, name): |
| 433 |
self._end_error(name, self._errorAttrs, self._getLastContent()) |
| 434 |
|
| 435 |
def getResult(self): |
| 436 |
return self.rowdicts |
| 437 |
|
| 438 |
startHandlers = { |
| 439 |
"oai:record": _start_oai_record, |
| 440 |
"oai:header": _start_oai_header, |
| 441 |
"ri:Resource": _start_ri_Resource, |
| 442 |
"oai:error": _start_oai_error, |
| 443 |
} |
| 444 |
endHandlers = { |
| 445 |
"oai:record": _end_oai_record, |
| 446 |
"oai:setSpec": _end_oai_setSpec, |
| 447 |
"oai:resumptionToken": _end_oai_resumptionToken, |
| 448 |
"oai:identifier": _end_oai_identifier, |
| 449 |
"oai:error": _end_oai_error, |
| 450 |
} |
| 451 |
|
| 452 |
|
| 453 |
class ServerProperties(object): |
| 454 |
"""A container for what an OAI-PMH server gives in response to |
| 455 |
identify. |
| 456 |
""" |
| 457 |
repositoryName = None |
| 458 |
baseURL = None |
| 459 |
protocolVersion = None |
| 460 |
adminEmails = () |
| 461 |
earliestDatestamp = None |
| 462 |
deletedRecord = None |
| 463 |
granularity = None |
| 464 |
repositoryName = None |
| 465 |
compressions = () |
| 466 |
|
| 467 |
def __init__(self): |
| 468 |
self.adminEmails = [] |
| 469 |
self.compressions = [] |
| 470 |
self.descriptions = [] |
| 471 |
|
| 472 |
def set(self, name, value): |
| 473 |
setattr(self, name, value) |
| 474 |
|
| 475 |
def add(self, name, value): |
| 476 |
getattr(self, name).append(value) |
| 477 |
|
| 478 |
|
| 479 |
class IdentifyParser(utils.StartEndHandler, OAIErrorMixin): |
| 480 |
"""A parser for the result of the identify operation. |
| 481 |
|
| 482 |
The result (an instance of ServerProperties) is in the serverProperties |
| 483 |
attribute. |
| 484 |
""" |
| 485 |
resumptionToken = None |
| 486 |
serverProperties = None |
| 487 |
|
| 488 |
def getResult(self): |
| 489 |
if not self.serverProperties: |
| 490 |
raise FailedQuery("Identify request did not contain an Identify" |
| 491 |
" element") |
| 492 |
return self.serverProperties |
| 493 |
|
| 494 |
def _start_Identify(self, name, attrs): |
| 495 |
self.serverProperties = ServerProperties() |
| 496 |
|
| 497 |
def _endListThing(self, name, attrs, content): |
| 498 |
self.serverProperties.add(name+"s", content.strip()) |
| 499 |
|
| 500 |
_end_adminEmail = _end_compression \ |
| 501 |
= _endListThing |
| 502 |
|
| 503 |
def _endStringThing(self, name, attrs, content): |
| 504 |
self.serverProperties.set(name, content.strip()) |
| 505 |
|
| 506 |
_end_repositoryName = _end_baseURL = _end_protocolVersion \ |
| 507 |
= _end_granularity = _end_deletedRecord = _end_earliestDatestamp \ |
| 508 |
= _end_repositoryName = _endStringThing |
| 509 |
|
| 510 |
|
| 511 |
class OAIQuery(object): |
| 512 |
"""A container for queries to OAI interfaces. |
| 513 |
|
| 514 |
Construct it with the oai endpoint and the OAI verb, plus some optional |
| 515 |
query attributes. If you want to retain or access the raw responses |
| 516 |
of the server, pass a contentCallback function -- it will be called |
| 517 |
with a byte string containing the payload of the server response if |
| 518 |
it was parsed successfully. Error responses cannot be obtained in |
| 519 |
this way. |
| 520 |
|
| 521 |
The OAIQuery is constructed with OAI-PMH parameters (verb, startDate, |
| 522 |
endDate, set, metadataPrefix; see the OAI-PMH docs for what they mean, |
| 523 |
only verb is mandatory). In addition, you can pass granularity, |
| 524 |
which is the granularity |
| 525 |
""" |
| 526 |
startDate = None |
| 527 |
endDate = None |
| 528 |
set = None |
| 529 |
registry = None |
| 530 |
metadataPrefix = None |
| 531 |
|
| 532 |
# maxRecords is mainly used in test_oai; that's why there's no |
| 533 |
# constructor parameter for it |
| 534 |
maxRecords = None |
| 535 |
|
| 536 |
# a timeout on HTTP operations |
| 537 |
timeout = 100 |
| 538 |
|
| 539 |
def __init__(self, registry, verb, startDate=None, endDate=None, set=None, |
| 540 |
metadataPrefix="ivo_vor", identifier=None, contentCallback=None, |
| 541 |
granularity=None): |
| 542 |
self.registry = registry |
| 543 |
self.verb, self.set = verb, set |
| 544 |
self.startDate, self.endDate = startDate, endDate |
| 545 |
self.identifier = identifier |
| 546 |
self.metadataPrefix = metadataPrefix |
| 547 |
self.contentCallback = contentCallback |
| 548 |
self.granularity = granularity |
| 549 |
if not self.granularity: |
| 550 |
self.granularity = "YYYY-MM-DD" |
| 551 |
|
| 552 |
def getKWs(self, **moreArgs): |
| 553 |
"""returns a dictionary containing query keywords for OAI interfaces |
| 554 |
from what's specified on the command line. |
| 555 |
""" |
| 556 |
kws = {"verb": self.verb} |
| 557 |
if self.metadataPrefix: |
| 558 |
kws["metadataPrefix"] = self.metadataPrefix |
| 559 |
kws.update(moreArgs) |
| 560 |
|
| 561 |
if self.granularity=='YY-MM-DD': |
| 562 |
dateFormat = "%Y-%m-%d" |
| 563 |
else: |
| 564 |
dateFormat = "%Y-%m-%dT%H:%M:%SZ" |
| 565 |
if self.startDate: |
| 566 |
kws["from"] = self.startDate.strftime(dateFormat) |
| 567 |
if self.endDate: |
| 568 |
kws["until"] = self.endDate.strftime(dateFormat) |
| 569 |
|
| 570 |
if self.set: |
| 571 |
kws["set"] = self.set |
| 572 |
if self.maxRecords: |
| 573 |
kws["maxRecords"] = str(self.maxRecords) |
| 574 |
|
| 575 |
if self.identifier: |
| 576 |
kws["identifier"] = self.identifier |
| 577 |
|
| 578 |
if "resumptionToken" in kws: |
| 579 |
kws = {"resumptionToken": kws["resumptionToken"], |
| 580 |
"verb": kws["verb"]} |
| 581 |
return kws |
| 582 |
|
| 583 |
def doHTTP(self, **moreArgs): |
| 584 |
"""returns the result of parsing the current query plus |
| 585 |
moreArgs to the current registry. |
| 586 |
|
| 587 |
The result is returned as a string. |
| 588 |
""" |
| 589 |
srcURL = self.registry.rstrip("?" |
| 590 |
)+"?"+self._getOpQS(**self.getKWs(**moreArgs)) |
| 591 |
base.ui.notifyInfo("OAI query %s"%srcURL) |
| 592 |
f = utils.urlopenRemote(srcURL, timeout=self.timeout) |
| 593 |
res = f.read() |
| 594 |
f.close() |
| 595 |
return res |
| 596 |
|
| 597 |
def _getOpQS(self, **args): |
| 598 |
"""returns a properly quoted HTTP query part from its (keyword) arguments. |
| 599 |
""" |
| 600 |
# we don't use urllib.urlencode to not encode empty values like a=&b=val |
| 601 |
qString = "&".join("%s=%s"%(k, urllib.parse.quote(v)) |
| 602 |
for k, v in args.items() if v) |
| 603 |
return "%s"%(qString) |
| 604 |
|
| 605 |
def talkOAI(self, parserClass): |
| 606 |
"""processes an OAI dialogue for verb using the IdParser-derived |
| 607 |
parserClass. |
| 608 |
""" |
| 609 |
res = self.doHTTP(verb=self.verb) |
| 610 |
if not res.strip(): |
| 611 |
# empty reply is not admissible XML here |
| 612 |
raise FailedQuery("Empty HTTP response") |
| 613 |
|
| 614 |
handler = parserClass() |
| 615 |
try: |
| 616 |
xmlReader = sax.make_parser() |
| 617 |
xmlReader.setFeature(sax.handler.feature_namespaces, True) |
| 618 |
xmlReader.setContentHandler(handler) |
| 619 |
xmlReader.parse(io.BytesIO(res)) |
| 620 |
if self.contentCallback: |
| 621 |
self.contentCallback(res) |
| 622 |
except NoRecordsMatch: |
| 623 |
return [] |
| 624 |
oaiResult = handler.getResult() |
| 625 |
|
| 626 |
while handler.resumptionToken is not None: |
| 627 |
resumptionToken = handler.resumptionToken |
| 628 |
handler = parserClass(oaiResult) |
| 629 |
try: |
| 630 |
res = self.doHTTP(verb=self.verb, |
| 631 |
resumptionToken=resumptionToken) |
| 632 |
sax.parseString(res, handler) |
| 633 |
if self.contentCallback: |
| 634 |
self.contentCallback(res) |
| 635 |
except NoRecordsMatch: |
| 636 |
break |
| 637 |
|
| 638 |
return oaiResult |
| 639 |
|
| 640 |
|
| 641 |
def getIdentifiers(registry, startDate=None, endDate=None, set=None, |
| 642 |
granularity=None): |
| 643 |
"""returns a list of "short" records for what's in the registry specified |
| 644 |
by args. |
| 645 |
""" |
| 646 |
q = OAIQuery(registry, verb="ListIdentifiers", startDate=startDate, |
| 647 |
endDate=endDate, set=set) |
| 648 |
return q.talkOAI(IdParser) |
| 649 |
|
| 650 |
|
| 651 |
def getRecords(registry, startDate=None, endDate=None, set=None, |
| 652 |
granularity=None): |
| 653 |
"""returns a list of "long" records for what's in the registry specified |
| 654 |
by args. |
| 655 |
|
| 656 |
parser should be a subclass of RecordParser; otherwise, you'll miss |
| 657 |
resumption and possibly other features. |
| 658 |
""" |
| 659 |
q = OAIQuery(registry, verb="ListRecords", startDate=startDate, |
| 660 |
endDate=endDate, set=set, granularity=granularity) |
| 661 |
return q.talkOAI(RecordParser) |
| 662 |
|
| 663 |
|
| 664 |
def guessPrefixesUsed(xmlLiteral): |
| 665 |
"""returns a set of xml namespace prefixes probably used in xmlLiteral. |
| 666 |
|
| 667 |
This is an ugly hack based on REs necessary because in the OAIRecordsParser |
| 668 |
we discard the namespace declarations. It won't work with CDATA |
| 669 |
sections, and it'll make a hash of things if namespace declarations are |
| 670 |
already present. However, for the use case of making the mutilated |
| 671 |
resource records coming out of the OAIRecordsParser valid, it will just |
| 672 |
do. |
| 673 |
|
| 674 |
Without an XML schema and a full parse (which of course is impossible |
| 675 |
without the necessary declarations), this is, really, not possible. But |
| 676 |
the whole idea of canonical namespace prefixes is a mess, and so we |
| 677 |
hack along; in particular, we accept any string of the form \\w+: within |
| 678 |
what looks like an XML tag as a namespace. Oh my. |
| 679 |
""" |
| 680 |
prefixesUsed = set() |
| 681 |
for elementContent in re.finditer("<[^>]+>", xmlLiteral): |
| 682 |
prefixesUsed |= set(re.findall(r"([a-zA-Z_-][\w-]*):[a-zA-Z_]", |
| 683 |
elementContent.group())) |
| 684 |
return prefixesUsed |
| 685 |
|
| 686 |
|
| 687 |
def _addCanonicalNSDecls(xmlLiteral): |
| 688 |
"""adds XML namespace declarations for namespace prefixes we |
| 689 |
suspect in xmlLiteral. |
| 690 |
|
| 691 |
See guessPrefixesUsed for why this a rough approximation that in |
| 692 |
particular won't work when a document re-binds ns prefixes. Well, |
| 693 |
let's make it so that doesn't happen in the Registry. |
| 694 |
""" |
| 695 |
prefixesUsed = guessPrefixesUsed(xmlLiteral) |
| 696 |
|
| 697 |
cp = getCanonicalPrefixes() |
| 698 |
nsDecls = " ".join('xmlns:%s=%s'%( |
| 699 |
pref, utils.escapeAttrVal(cp.getNSForPrefix(pref))) |
| 700 |
for pref in prefixesUsed) |
| 701 |
return re.sub(r"<([\w:-]+)", r"<\1 "+nsDecls, xmlLiteral, 1) |
| 702 |
|
| 703 |
|
| 704 |
def getRecord(registry, identifier): |
| 705 |
"""returns the XML form of an OAI-PMH record for identifier from |
| 706 |
the OAI-PMH endpoint at URL registry. |
| 707 |
|
| 708 |
This uses the OAIRecordsParser which enforces canonical prefixes, |
| 709 |
and the function will add their declarations as necessary. This also means |
| 710 |
that evil registry records could be broken by us. |
| 711 |
""" |
| 712 |
q = OAIQuery(registry, verb="GetRecord", identifier=identifier) |
| 713 |
res = q.talkOAI(OAIRecordsParser) |
| 714 |
dest, row = res[0] |
| 715 |
assert dest=='oairecs' |
| 716 |
return _addCanonicalNSDecls(row["oaixml"]) |
| 717 |
|
| 718 |
|
| 719 |
def parseRecord(recordXML): |
| 720 |
"""returns some main properties from an XML-encoded VOResource record. |
| 721 |
|
| 722 |
recordXML can be an OAI-PMH response or just a naked record. If multiple |
| 723 |
records are contained in recordXML, only the first will be returned. |
| 724 |
|
| 725 |
What's coming back is a dictionary as produced by RecordParser. |
| 726 |
""" |
| 727 |
handler = RecordParser() |
| 728 |
sax.parseString(recordXML, handler) |
| 729 |
return handler.recs[0] |
| 730 |
|
| 731 |
|
| 732 |
def getServerProperties(registry): |
| 733 |
"""returns a ServerProperties instance for registry. |
| 734 |
|
| 735 |
In particular, you can retrieve the granularity argument that |
| 736 |
actually matches the registry from the result's granularity attribute. |
| 737 |
""" |
| 738 |
q = OAIQuery(registry, verb="Identify", metadataPrefix=None) |
| 739 |
return q.talkOAI(IdentifyParser) |