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