ldp_nr.py 4.7 KB

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