ldp_nr.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import logging
  2. import pdb
  3. from rdflib import Graph
  4. from rdflib.namespace import RDF, XSD
  5. from rdflib.resource import Resource
  6. from rdflib.term import URIRef, Literal, Variable
  7. from lakesuperior import env
  8. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  9. from lakesuperior.model.ldp.ldpr import Ldpr
  10. from lakesuperior.model.ldp.ldp_rs import LdpRs
  11. nonrdfly = env.app_globals.nonrdfly
  12. logger = logging.getLogger(__name__)
  13. default_hash_algo = env.app_globals.config['application']['uuid']['algo']
  14. class LdpNr(Ldpr):
  15. """LDP-NR (Non-RDF Source).
  16. Definition: https://www.w3.org/TR/ldp/#ldpnr
  17. """
  18. base_types = {
  19. nsc['fcrepo'].Binary,
  20. nsc['fcrepo'].Resource,
  21. nsc['ldp'].Resource,
  22. nsc['ldp'].NonRDFSource,
  23. }
  24. def __init__(self, uuid, stream=None, mimetype=None,
  25. disposition=None, prov_cksum_algo=None, prov_cksum=None,
  26. **kwargs):
  27. """
  28. Extends Ldpr.__init__ by adding LDP-NR specific parameters.
  29. """
  30. super().__init__(uuid, **kwargs)
  31. self._imr_options = {}
  32. if stream:
  33. self.workflow = self.WRKF_INBOUND
  34. self.stream = stream
  35. else:
  36. self.workflow = self.WRKF_OUTBOUND
  37. if mimetype:
  38. self.mimetype = mimetype
  39. else:
  40. self.mimetype = (
  41. str(self.metadata.value(nsc['ebucore'].hasMimeType))
  42. if self.is_stored
  43. else 'application/octet-stream')
  44. self.prov_cksum_algo = prov_cksum_algo
  45. self.prov_cksum = prov_cksum
  46. self.disposition = disposition
  47. @property
  48. def filename(self):
  49. """
  50. File name of the original uploaded file.
  51. :rtype: str
  52. """
  53. return self.metadata.value(nsc['ebucore'].filename)
  54. @property
  55. def content(self):
  56. """
  57. Binary content.
  58. :return: File handle of the resource content.
  59. :rtype: io.BufferedReader
  60. """
  61. return open(self.local_path, 'rb')
  62. @property
  63. def content_size(self):
  64. """
  65. Byte size of the binary content.
  66. :rtype: int
  67. """
  68. return int(self.metadata.value(nsc['premis'].hasSize))
  69. @property
  70. def local_path(self):
  71. """
  72. Path on disk of the binary content.
  73. :rtype: str
  74. """
  75. cksum_term = self.metadata.value(nsc['premis'].hasMessageDigest)
  76. cksum = str(cksum_term).replace(f'urn:{default_hash_algo}:','')
  77. return nonrdfly.__class__.local_path(
  78. nonrdfly.root, cksum, nonrdfly.bl, nonrdfly.bc)
  79. def create_or_replace(self, create_only=False):
  80. """
  81. Create a new binary resource with a corresponding RDF representation.
  82. :param bool create_only: Whether the resource is being created or
  83. updated.
  84. """
  85. # Persist the stream.
  86. self.digest, self.size = nonrdfly.persist(
  87. self.uid, self.stream, prov_cksum_algo=self.prov_cksum_algo,
  88. prov_cksum=self.prov_cksum)
  89. # Try to persist metadata. If it fails, delete the file.
  90. logger.debug('Persisting LDP-NR triples in {}'.format(self.uri))
  91. try:
  92. ev_type = super().create_or_replace(create_only)
  93. except:
  94. # self.digest is also the file UID.
  95. nonrdfly.delete(self.digest)
  96. raise
  97. else:
  98. return ev_type
  99. ## PROTECTED METHODS ##
  100. def _add_srv_mgd_triples(self, *args, **kwargs):
  101. """
  102. Add all metadata for the RDF representation of the LDP-NR.
  103. :param BufferedIO stream: The uploaded data stream.
  104. :param str mimetype: MIME type of the uploaded file.
  105. :param defaultdict disposition: The ``Content-Disposition`` header
  106. content, parsed through ``parse_rfc7240``.
  107. """
  108. super()._add_srv_mgd_triples(*args, **kwargs)
  109. # File size.
  110. logger.debug('Data stream size: {}'.format(self.size))
  111. self.provided_imr.set((
  112. self.uri, nsc['premis'].hasSize, Literal(self.size)))
  113. # Checksum.
  114. cksum_term = URIRef(f'urn:{default_hash_algo}:{self.digest}')
  115. self.provided_imr.set((
  116. self.uri, nsc['premis'].hasMessageDigest, cksum_term))
  117. # MIME type.
  118. self.provided_imr.set((
  119. self.uri, nsc['ebucore']['hasMimeType'], Literal(self.mimetype)))
  120. # File name.
  121. logger.debug('Disposition: {}'.format(self.disposition))
  122. try:
  123. self.provided_imr.set((
  124. self.uri, nsc['ebucore']['filename'], Literal(
  125. self.disposition['attachment']['parameters']['filename'])))
  126. except (KeyError, TypeError) as e:
  127. pass