ldp.py 19 KB

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