ldp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import logging
  2. import pdb
  3. from collections import defaultdict
  4. from io import BytesIO
  5. from pprint import pformat
  6. from uuid import uuid4
  7. import arrow
  8. from flask import (
  9. Blueprint, g, make_response, render_template,
  10. request, send_file)
  11. from rdflib.namespace import XSD
  12. from rdflib.term import Literal
  13. from lakesuperior.api import resource as rsrc_api
  14. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  15. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  16. from lakesuperior.exceptions import (ResourceNotExistsError, TombstoneError,
  17. ServerManagedTermError, InvalidResourceError, SingleSubjectError,
  18. ResourceExistsError, IncompatibleLdpTypeError)
  19. from lakesuperior.globals import RES_CREATED
  20. from lakesuperior.model.ldp_factory import LdpFactory
  21. from lakesuperior.model.ldp_nr import LdpNr
  22. from lakesuperior.model.ldp_rs import LdpRs
  23. from lakesuperior.model.ldpr import Ldpr
  24. from lakesuperior.store.ldp_rs.lmdb_store import TxnManager
  25. from lakesuperior.toolbox import Toolbox
  26. logger = logging.getLogger(__name__)
  27. # Blueprint for LDP REST API. This is what is usually found under `/rest/` in
  28. # standard fcrepo4. Here, it is under `/ldp` but initially `/rest` can be kept
  29. # for backward compatibility.
  30. ldp = Blueprint(
  31. 'ldp', __name__, template_folder='templates',
  32. static_url_path='/static', static_folder='../../static')
  33. accept_patch = (
  34. 'application/sparql-update',
  35. )
  36. accept_rdf = (
  37. 'application/ld+json',
  38. 'application/n-triples',
  39. 'application/rdf+xml',
  40. #'application/x-turtle',
  41. #'application/xhtml+xml',
  42. #'application/xml',
  43. #'text/html',
  44. 'text/n3',
  45. #'text/plain',
  46. 'text/rdf+n3',
  47. 'text/turtle',
  48. )
  49. std_headers = {
  50. 'Accept-Patch' : ','.join(accept_patch),
  51. 'Accept-Post' : ','.join(accept_rdf),
  52. #'Allow' : ','.join(allow),
  53. }
  54. """Predicates excluded by view."""
  55. vw_blacklist = {
  56. }
  57. @ldp.url_defaults
  58. def bp_url_defaults(endpoint, values):
  59. url_prefix = getattr(g, 'url_prefix', None)
  60. if url_prefix is not None:
  61. values.setdefault('url_prefix', url_prefix)
  62. @ldp.url_value_preprocessor
  63. def bp_url_value_preprocessor(endpoint, values):
  64. g.url_prefix = values.pop('url_prefix')
  65. g.webroot = request.host_url + g.url_prefix
  66. # Normalize leading slashes for UID.
  67. if 'uid' in values:
  68. values['uid'] = '/' + values['uid'].lstrip('/')
  69. if 'parent_uid' in values:
  70. values['parent_uid'] = '/' + values['parent_uid'].lstrip('/')
  71. @ldp.before_request
  72. def log_request_start():
  73. logger.info('** Start {} {} **'.format(request.method, request.url))
  74. @ldp.before_request
  75. def instantiate_req_vars():
  76. g.tbox = Toolbox()
  77. @ldp.after_request
  78. def log_request_end(rsp):
  79. logger.info('** End {} {} **'.format(request.method, request.url))
  80. return rsp
  81. ## REST SERVICES ##
  82. @ldp.route('/<path:uid>', methods=['GET'], strict_slashes=False)
  83. @ldp.route('/', defaults={'uid': '/'}, methods=['GET'], strict_slashes=False)
  84. @ldp.route('/<path:uid>/fcr:metadata', defaults={'out_fmt' : 'rdf'},
  85. methods=['GET'])
  86. @ldp.route('/<path:uid>/fcr:content', defaults={'out_fmt' : 'non_rdf'},
  87. methods=['GET'])
  88. def get_resource(uid, out_fmt=None):
  89. """
  90. https://www.w3.org/TR/ldp/#ldpr-HTTP_GET
  91. Retrieve RDF or binary content.
  92. :param str uid: UID of resource to retrieve. The repository root has
  93. an empty string for UID.
  94. :param str out_fmt: Force output to RDF or non-RDF if the resource is
  95. a LDP-NR. This is not available in the API but is used e.g. by the
  96. `*/fcr:metadata` and `*/fcr:content` endpoints. The default is False.
  97. """
  98. logger.info('UID: {}'.format(uid))
  99. out_headers = std_headers
  100. repr_options = defaultdict(dict)
  101. if 'prefer' in request.headers:
  102. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  103. logger.debug('Parsed Prefer header: {}'.format(pformat(prefer)))
  104. if 'return' in prefer:
  105. repr_options = parse_repr_options(prefer['return'])
  106. try:
  107. rsrc = rsrc_api.get(uid, repr_options)
  108. except ResourceNotExistsError as e:
  109. return str(e), 404
  110. except TombstoneError as e:
  111. return _tombstone_response(e, uid)
  112. else:
  113. if out_fmt is None:
  114. out_fmt = (
  115. 'rdf'
  116. if isinstance(rsrc, LdpRs) or is_accept_hdr_rdf_parsable()
  117. else 'non_rdf')
  118. out_headers.update(_headers_from_metadata(rsrc))
  119. uri = g.tbox.uid_to_uri(uid)
  120. if out_fmt == 'rdf':
  121. ggr = g.tbox.globalize_graph(rsrc.out_graph)
  122. ggr.namespace_manager = nsm
  123. return _negotiate_content(ggr, out_headers, uid=uid, uri=uri)
  124. else:
  125. if not getattr(rsrc, 'local_path', False):
  126. return ('{} has no binary content.'.format(rsrc.uid), 404)
  127. logger.debug('Streaming out binary content.')
  128. rsp = make_response(send_file(
  129. rsrc.local_path, as_attachment=True,
  130. attachment_filename=rsrc.filename,
  131. mimetype=rsrc.mimetype))
  132. logger.debug('Out headers: {}'.format(out_headers))
  133. rsp.headers.add('Link',
  134. '<{}/fcr:metadata>; rel="describedby"'.format(uri))
  135. for link in out_headers['Link']:
  136. rsp.headers.add('Link', link)
  137. return rsp
  138. @ldp.route('/<path:uid>/fcr:versions', methods=['GET'])
  139. def get_version_info(uid):
  140. """
  141. Get version info (`fcr:versions`).
  142. """
  143. try:
  144. gr = rsrc_api.get_version_info(uid)
  145. except ResourceNotExistsError as e:
  146. return str(e), 404
  147. except InvalidResourceError as e:
  148. return str(e), 409
  149. except TombstoneError as e:
  150. return _tombstone_response(e, uid)
  151. else:
  152. return _negotiate_content(g.tbox.globalize_graph(gr))
  153. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['GET'])
  154. def get_version(uid, ver_uid):
  155. """
  156. Get an individual resource version.
  157. :param str uid: Resource UID.
  158. :param str ver_uid: Version UID.
  159. """
  160. try:
  161. gr = rsrc_api.get_version(uid, ver_uid)
  162. except ResourceNotExistsError as e:
  163. return str(e), 404
  164. except InvalidResourceError as e:
  165. return str(e), 409
  166. except TombstoneError as e:
  167. return _tombstone_response(e, uid)
  168. else:
  169. return _negotiate_content(g.tbox.globalize_graph(gr))
  170. @ldp.route('/<path:parent_uid>', methods=['POST'], strict_slashes=False)
  171. @ldp.route('/', defaults={'parent_uid': '/'}, methods=['POST'],
  172. strict_slashes=False)
  173. def post_resource(parent_uid):
  174. """
  175. https://www.w3.org/TR/ldp/#ldpr-HTTP_POST
  176. Add a new resource in a new URI.
  177. """
  178. out_headers = std_headers
  179. try:
  180. slug = request.headers['Slug']
  181. logger.debug('Slug: {}'.format(slug))
  182. except KeyError:
  183. slug = None
  184. handling, disposition = set_post_put_params()
  185. stream, mimetype = _bistream_from_req()
  186. if LdpFactory.is_rdf_parsable(mimetype):
  187. # If the content is RDF, localize in-repo URIs.
  188. global_rdf = stream.read()
  189. local_rdf = g.tbox.localize_payload(global_rdf)
  190. stream = BytesIO(local_rdf)
  191. is_rdf = True
  192. else:
  193. is_rdf = False
  194. try:
  195. uid = rsrc_api.create(
  196. parent_uid, slug, stream=stream, mimetype=mimetype,
  197. handling=handling, disposition=disposition)
  198. except ResourceNotExistsError as e:
  199. return str(e), 404
  200. except InvalidResourceError as e:
  201. return str(e), 409
  202. except TombstoneError as e:
  203. return _tombstone_response(e, uid)
  204. except ServerManagedTermError as e:
  205. return str(e), 412
  206. uri = g.tbox.uid_to_uri(uid)
  207. hdr = {'Location' : uri}
  208. if mimetype and not is_rdf:
  209. hdr['Link'] = '<{0}/fcr:metadata>; rel="describedby"; anchor="<{0}>"'\
  210. .format(uri)
  211. out_headers.update(hdr)
  212. return uri, 201, out_headers
  213. @ldp.route('/<path:uid>', methods=['PUT'], strict_slashes=False)
  214. @ldp.route('/<path:uid>/fcr:metadata', defaults={'force_rdf' : True},
  215. methods=['PUT'])
  216. def put_resource(uid):
  217. """
  218. https://www.w3.org/TR/ldp/#ldpr-HTTP_PUT
  219. Add or replace a new resource at a specified URI.
  220. """
  221. # Parse headers.
  222. logger.debug('Request headers: {}'.format(request.headers))
  223. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  224. handling, disposition = set_post_put_params()
  225. stream, mimetype = _bistream_from_req()
  226. if LdpFactory.is_rdf_parsable(mimetype):
  227. # If the content is RDF, localize in-repo URIs.
  228. global_rdf = stream.read()
  229. local_rdf = g.tbox.localize_payload(global_rdf)
  230. stream = BytesIO(local_rdf)
  231. is_rdf = True
  232. else:
  233. is_rdf = False
  234. try:
  235. evt = rsrc_api.create_or_replace(uid, stream=stream, mimetype=mimetype,
  236. handling=handling, disposition=disposition)
  237. except (InvalidResourceError, ResourceExistsError) as e:
  238. return str(e), 409
  239. except (ServerManagedTermError, SingleSubjectError) as e:
  240. return str(e), 412
  241. except IncompatibleLdpTypeError as e:
  242. return str(e), 415
  243. except TombstoneError as e:
  244. return _tombstone_response(e, uid)
  245. uri = g.tbox.uid_to_uri(uid)
  246. if evt == RES_CREATED:
  247. rsp_code = 201
  248. rsp_headers['Location'] = rsp_body = uri
  249. if mimetype and not is_rdf:
  250. rsp_headers['Link'] = (
  251. '<{0}/fcr:metadata>; rel="describedby"'.format(uri))
  252. else:
  253. rsp_code = 204
  254. rsp_body = ''
  255. return rsp_body, rsp_code, rsp_headers
  256. @ldp.route('/<path:uid>', methods=['PATCH'], strict_slashes=False)
  257. def patch_resource(uid, is_metadata=False):
  258. """
  259. https://www.w3.org/TR/ldp/#ldpr-HTTP_PATCH
  260. Update an existing resource with a SPARQL-UPDATE payload.
  261. """
  262. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  263. if request.mimetype != 'application/sparql-update':
  264. return 'Provided content type is not a valid parsable format: {}'\
  265. .format(request.mimetype), 415
  266. update_str = request.get_data().decode('utf-8')
  267. local_update_str = g.tbox.localize_ext_str(update_str, nsc['fcres'][uid])
  268. try:
  269. rsrc = rsrc_api.update(uid, local_update_str, is_metadata)
  270. except ResourceNotExistsError as e:
  271. return str(e), 404
  272. except TombstoneError as e:
  273. return _tombstone_response(e, uid)
  274. except (ServerManagedTermError, SingleSubjectError) as e:
  275. return str(e), 412
  276. except InvalidResourceError as e:
  277. return str(e), 415
  278. else:
  279. rsp_headers.update(_headers_from_metadata(rsrc))
  280. return '', 204, rsp_headers
  281. @ldp.route('/<path:uid>/fcr:metadata', methods=['PATCH'])
  282. def patch_resource_metadata(uid):
  283. return patch_resource(uid, True)
  284. @ldp.route('/<path:uid>', methods=['DELETE'])
  285. def delete_resource(uid):
  286. """
  287. Delete a resource and optionally leave a tombstone.
  288. This behaves differently from FCREPO. A tombstone indicated that the
  289. resource is no longer available at its current location, but its historic
  290. snapshots still are. Also, deleting a resource with a tombstone creates
  291. one more version snapshot of the resource prior to being deleted.
  292. In order to completely wipe out all traces of a resource, the tombstone
  293. must be deleted as well, or the `Prefer:no-tombstone` header can be used.
  294. The latter will forget (completely delete) the resource immediately.
  295. """
  296. headers = std_headers
  297. if 'prefer' in request.headers:
  298. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  299. leave_tstone = 'no-tombstone' not in prefer
  300. else:
  301. leave_tstone = True
  302. try:
  303. rsrc_api.delete(uid, leave_tstone)
  304. except ResourceNotExistsError as e:
  305. return str(e), 404
  306. except TombstoneError as e:
  307. return _tombstone_response(e, uid)
  308. return '', 204, headers
  309. @ldp.route('/<path:uid>/fcr:tombstone', methods=['GET', 'POST', 'PUT',
  310. 'PATCH', 'DELETE'])
  311. def tombstone(uid):
  312. """
  313. Handle all tombstone operations.
  314. The only allowed methods are POST and DELETE; any other verb will return a
  315. 405.
  316. """
  317. try:
  318. rsrc = rsrc_api.get(uid)
  319. except TombstoneError as e:
  320. if request.method == 'DELETE':
  321. if e.uid == uid:
  322. rsrc_api.delete(uid, False)
  323. return '', 204
  324. else:
  325. return _tombstone_response(e, uid)
  326. elif request.method == 'POST':
  327. if e.uid == uid:
  328. rsrc_uri = rsrc_api.resurrect(uid)
  329. headers = {'Location' : rsrc_uri}
  330. return rsrc_uri, 201, headers
  331. else:
  332. return _tombstone_response(e, uid)
  333. else:
  334. return 'Method Not Allowed.', 405
  335. except ResourceNotExistsError as e:
  336. return str(e), 404
  337. else:
  338. return '', 404
  339. @ldp.route('/<path:uid>/fcr:versions', methods=['POST', 'PUT'])
  340. def post_version(uid):
  341. """
  342. Create a new resource version.
  343. """
  344. if request.method == 'PUT':
  345. return 'Method not allowed.', 405
  346. ver_uid = request.headers.get('slug', None)
  347. try:
  348. ver_uid = rsrc_api.create_version(uid, ver_uid)
  349. except ResourceNotExistsError as e:
  350. return str(e), 404
  351. except InvalidResourceError as e:
  352. return str(e), 409
  353. except TombstoneError as e:
  354. return _tombstone_response(e, uid)
  355. else:
  356. return '', 201, {'Location': g.tbox.uid_to_uri(ver_uid)}
  357. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['PATCH'])
  358. def patch_version(uid, ver_uid):
  359. """
  360. Revert to a previous version.
  361. NOTE: This creates a new version snapshot.
  362. :param str uid: Resource UID.
  363. :param str ver_uid: Version UID.
  364. """
  365. try:
  366. LdpFactory.from_stored(uid).revert_to_version(ver_uid)
  367. except ResourceNotExistsError as e:
  368. return str(e), 404
  369. except InvalidResourceError as e:
  370. return str(e), 409
  371. except TombstoneError as e:
  372. return _tombstone_response(e, uid)
  373. else:
  374. return '', 204
  375. ## PRIVATE METHODS ##
  376. def _negotiate_content(gr, headers=None, **vw_kwargs):
  377. """
  378. Return HTML or serialized RDF depending on accept headers.
  379. """
  380. if request.accept_mimetypes.best == 'text/html':
  381. return render_template(
  382. 'resource.html', gr=gr, nsc=nsc, nsm=nsm,
  383. blacklist=vw_blacklist, arrow=arrow, **vw_kwargs)
  384. else:
  385. for p in vw_blacklist:
  386. gr.remove((None, p, None))
  387. return (gr.serialize(format='turtle'), headers)
  388. def _bistream_from_req():
  389. """
  390. Find how a binary file and its MIMEtype were uploaded in the request.
  391. """
  392. #logger.debug('Content type: {}'.format(request.mimetype))
  393. #logger.debug('files: {}'.format(request.files))
  394. #logger.debug('stream: {}'.format(request.stream))
  395. if request.mimetype == 'multipart/form-data':
  396. # This seems the "right" way to upload a binary file, with a
  397. # multipart/form-data MIME type and the file in the `file`
  398. # field. This however is not supported by FCREPO4.
  399. stream = request.files.get('file').stream
  400. mimetype = request.files.get('file').content_type
  401. # @TODO This will turn out useful to provide metadata
  402. # with the binary.
  403. #metadata = request.files.get('metadata').stream
  404. else:
  405. # This is a less clean way, with the file in the form body and
  406. # the request as application/x-www-form-urlencoded.
  407. # This is how FCREPO4 accepts binary uploads.
  408. stream = request.stream
  409. # @FIXME Must decide what to do with this.
  410. mimetype = request.mimetype
  411. if mimetype == '' or mimetype == 'application/x-www-form-urlencoded':
  412. if getattr(stream, 'limit', 0) == 0:
  413. stream = mimetype = None
  414. else:
  415. mimetype = 'application/octet-stream'
  416. return stream, mimetype
  417. def _tombstone_response(e, uid):
  418. headers = {
  419. 'Link': '<{}/fcr:tombstone>; rel="hasTombstone"'.format(request.url),
  420. } if e.uid == uid else {}
  421. return str(e), 410, headers
  422. def set_post_put_params():
  423. """
  424. Sets handling and content disposition for POST and PUT by parsing headers.
  425. """
  426. handling = 'strict'
  427. if 'prefer' in request.headers:
  428. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  429. logger.debug('Parsed Prefer header: {}'.format(prefer))
  430. if 'handling' in prefer:
  431. handling = prefer['handling']['value']
  432. try:
  433. disposition = g.tbox.parse_rfc7240(
  434. request.headers['content-disposition'])
  435. except KeyError:
  436. disposition = None
  437. return handling, disposition
  438. def is_accept_hdr_rdf_parsable():
  439. """
  440. Check if any of the 'Accept' header values provided is a RDF parsable
  441. format.
  442. """
  443. for mimetype in request.accept_mimetypes.values():
  444. if LdpFactory.is_rdf_parsable(mimetype):
  445. return True
  446. return False
  447. def parse_repr_options(retr_opts):
  448. """
  449. Set options to retrieve IMR.
  450. Ideally, IMR retrieval is done once per request, so all the options
  451. are set once in the `imr()` property.
  452. :param dict retr_opts:: Options parsed from `Prefer` header.
  453. """
  454. logger.debug('Parsing retrieval options: {}'.format(retr_opts))
  455. imr_options = {}
  456. if retr_opts.get('value') == 'minimal':
  457. imr_options = {
  458. 'embed_children' : False,
  459. 'incl_children' : False,
  460. 'incl_inbound' : False,
  461. 'incl_srv_mgd' : False,
  462. }
  463. else:
  464. # Default.
  465. imr_options = {
  466. 'embed_children' : False,
  467. 'incl_children' : True,
  468. 'incl_inbound' : False,
  469. 'incl_srv_mgd' : True,
  470. }
  471. # Override defaults.
  472. if 'parameters' in retr_opts:
  473. include = retr_opts['parameters']['include'].split(' ') \
  474. if 'include' in retr_opts['parameters'] else []
  475. omit = retr_opts['parameters']['omit'].split(' ') \
  476. if 'omit' in retr_opts['parameters'] else []
  477. logger.debug('Include: {}'.format(include))
  478. logger.debug('Omit: {}'.format(omit))
  479. if str(Ldpr.EMBED_CHILD_RES_URI) in include:
  480. imr_options['embed_children'] = True
  481. if str(Ldpr.RETURN_CHILD_RES_URI) in omit:
  482. imr_options['incl_children'] = False
  483. if str(Ldpr.RETURN_INBOUND_REF_URI) in include:
  484. imr_options['incl_inbound'] = True
  485. if str(Ldpr.RETURN_SRV_MGD_RES_URI) in omit:
  486. imr_options['incl_srv_mgd'] = False
  487. logger.debug('Retrieval options: {}'.format(pformat(imr_options)))
  488. return imr_options
  489. def _headers_from_metadata(rsrc):
  490. """
  491. Create a dict of headers from a metadata graph.
  492. :param lakesuperior.model.ldpr.Ldpr rsrc: Resource to extract metadata
  493. from.
  494. """
  495. out_headers = defaultdict(list)
  496. digest = rsrc.metadata.value(nsc['premis'].hasMessageDigest)
  497. if digest:
  498. etag = digest.identifier.split(':')[-1]
  499. etag_str = (
  500. 'W/"{}"'.format(etag)
  501. if nsc['ldp'].RDFSource in rsrc.ldp_types
  502. else etag)
  503. out_headers['ETag'] = etag_str,
  504. last_updated_term = rsrc.metadata.value(nsc['fcrepo'].lastModified)
  505. if last_updated_term:
  506. out_headers['Last-Modified'] = arrow.get(last_updated_term)\
  507. .format('ddd, D MMM YYYY HH:mm:ss Z')
  508. for t in rsrc.ldp_types:
  509. out_headers['Link'].append(
  510. '{};rel="type"'.format(t.n3()))
  511. mimetype = rsrc.metadata.value(nsc['ebucore'].hasMimeType)
  512. if mimetype:
  513. out_headers['Content-Type'] = mimetype
  514. return out_headers