ldp_factory.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import logging
  2. from pprint import pformat
  3. from uuid import uuid4
  4. from rdflib.resource import Resource
  5. from rdflib.namespace import RDF
  6. from lakesuperior import env
  7. from lakesuperior import exceptions as exc
  8. from lakesuperior.model.ldp.ldpr import Ldpr
  9. from lakesuperior.model.ldp.ldp_nr import LdpNr
  10. from lakesuperior.model.ldp.ldp_rs import LdpRs, Ldpc, LdpDc, LdpIc
  11. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  12. from lakesuperior.model.rdf.graph import Graph, from_rdf
  13. from lakesuperior.util.toolbox import rel_uri_to_urn
  14. LDP_NR_TYPE = nsc['ldp'].NonRDFSource
  15. LDP_RS_TYPE = nsc['ldp'].RDFSource
  16. rdfly = env.app_globals.rdfly
  17. logger = logging.getLogger(__name__)
  18. class LdpFactory:
  19. """
  20. Generate LDP instances.
  21. The instance classes are based on provided client data or on stored data.
  22. """
  23. @staticmethod
  24. def new_container(uid):
  25. if not uid.startswith('/') or uid == '/':
  26. raise exc.InvalidResourceError(uid)
  27. if rdfly.ask_rsrc_exists(uid):
  28. raise exc.ResourceExistsError(uid)
  29. rsrc = Ldpc(uid, provided_imr=Graph(uri=nsc['fcres'][uid]))
  30. return rsrc
  31. @staticmethod
  32. def from_stored(uid, ver_label=None, repr_options={}, strict=True, **kwargs):
  33. """
  34. Create an instance for retrieval purposes.
  35. This factory method creates and returns an instance of an LDPR subclass
  36. based on information that needs to be queried from the underlying
  37. g"http://api.edu/location/id/1234/thumbnail"raph store.
  38. N.B. The resource must exist.
  39. :param str uid: UID of the instance.
  40. """
  41. # This will blow up if strict is True and the resource is a tombstone.
  42. rsrc_meta = rdfly.get_metadata(uid, strict=strict)
  43. rdf_types = rsrc_meta[nsc['fcres'][uid] : RDF.type]
  44. if LDP_NR_TYPE in rdf_types:
  45. logger.info('Resource is a LDP-NR.')
  46. cls = LdpNr
  47. elif LDP_RS_TYPE in rdf_types:
  48. logger.info('Resource is a LDP-RS.')
  49. cls = LdpRs
  50. else:
  51. raise exc.ResourceNotExistsError(uid)
  52. rsrc = cls(uid, repr_options, **kwargs)
  53. # Sneak in the already extracted metadata to save a query.
  54. rsrc._metadata = rsrc_meta
  55. return rsrc
  56. @staticmethod
  57. def from_provided(
  58. uid, mimetype=None, stream=None, graph=None, rdf_data=None,
  59. rdf_fmt=None, **kwargs):
  60. r"""
  61. Create and LDPR instance from provided data.
  62. the LDP class (LDP-RS, LDP_NR, etc.) is determined by the contents
  63. passed.
  64. :param str uid: UID of the resource to be created or updated.
  65. :param str mimetype: The provided content MIME type. If this is
  66. specified the resource is considered a LDP-NR and a ``stream``
  67. *must* be provided.
  68. :param IOStream stream: The provided data stream.
  69. :param rdflib.Graph graph: Initial graph to populate the
  70. resource with. This can be used for LDP-RS and LDP-NR types alike.
  71. :param bytes rdf_data: Serialized RDF to build the initial graph.
  72. :param str rdf_fmt: Serialization format of RDF data.
  73. :param \*\*kwargs: Arguments passed to the LDP class constructor.
  74. :raise ValueError: if ``mimetype`` is specified but no data stream is
  75. provided.
  76. """
  77. uri = nsc['fcres'][uid]
  78. if rdf_data:
  79. try:
  80. provided_imr = from_rdf(
  81. uri=uri, data=rdf_data,
  82. format=rdf_fmt, publicID=nsc['fcres'][uid])
  83. except Exception as e:
  84. raise exc.RdfParsingError(rdf_fmt, str(e))
  85. elif graph:
  86. provided_imr = Graph(
  87. uri=uri, data={
  88. (rel_uri_to_urn(s, uid), p, rel_uri_to_urn(o, uid))
  89. for s, p, o in graph
  90. }
  91. )
  92. else:
  93. provided_imr = Graph(uri=uri)
  94. #logger.debug('Provided graph: {}'.format(
  95. # pformat(set(provided_imr))))
  96. if stream is None:
  97. # Resource is a LDP-RS.
  98. if mimetype:
  99. raise ValueError(
  100. 'Binary stream must be provided if mimetype is specified.')
  101. # Determine whether it is a basic, direct or indirect container.
  102. if provided_imr[nsc['rdf'].type] == nsc['ldp'].IndirectContainer:
  103. cls = LdpIc
  104. elif provided_imr[nsc['rdf'].type] == nsc['ldp'].DirectContainer:
  105. cls = LdpDc
  106. else:
  107. cls = Ldpc
  108. inst = cls(uid, provided_imr=provided_imr, **kwargs)
  109. # Make sure we are not updating an LDP-NR with an LDP-RS.
  110. if inst.is_stored and LDP_NR_TYPE in inst.ldp_types:
  111. raise exc.IncompatibleLdpTypeError(uid, mimetype)
  112. if kwargs.get('handling', 'strict') != 'none':
  113. inst.check_mgd_terms(inst.provided_imr)
  114. else:
  115. # Resource is a LDP-NR.
  116. if not mimetype:
  117. mimetype = 'application/octet-stream'
  118. inst = LdpNr(uid, stream=stream, mimetype=mimetype,
  119. provided_imr=provided_imr, **kwargs)
  120. # Make sure we are not updating an LDP-RS with an LDP-NR.
  121. if inst.is_stored and LDP_RS_TYPE in inst.ldp_types:
  122. raise exc.IncompatibleLdpTypeError(uid, mimetype)
  123. logger.debug('Creating resource of type: {}'.format(
  124. inst.__class__.__name__))
  125. return inst
  126. @staticmethod
  127. def mint_uid(parent_uid, path=None):
  128. """
  129. Mint a new resource UID based on client directives.
  130. This method takes a parent ID and a tentative path and returns an LDP
  131. resource UID.
  132. This may raise an exception resulting in a 404 if the parent is not
  133. found or a 409 if the parent is not a valid container.
  134. :param str parent_uid: UID of the parent resource. It must be an
  135. existing LDPC.
  136. :param str path: path to the resource, relative to the parent.
  137. :rtype: str
  138. :return: The confirmed resource UID. This may be different from
  139. what has been indicated.
  140. """
  141. if path and path.startswith('/'):
  142. raise ValueError('Slug cannot start with a slash.')
  143. # Shortcut!
  144. if not path and parent_uid == '/':
  145. return f'/{uuid4()}'
  146. if not parent_uid.startswith('/'):
  147. raise ValueError('Invalid parent UID: {}'.format(parent_uid))
  148. parent = LdpFactory.from_stored(parent_uid)
  149. if nsc['ldp'].Container not in parent.types:
  150. raise exc.InvalidResourceError(parent_uid,
  151. 'Parent {} is not a container.')
  152. pfx = parent_uid.rstrip('/') + '/'
  153. if path:
  154. cnd_uid = pfx + path
  155. if not rdfly.ask_rsrc_exists(cnd_uid):
  156. return cnd_uid
  157. return f'{pfx}{uuid4()}'