ldp_factory.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import logging
  2. from pprint import pformat
  3. from uuid import uuid4
  4. from rdflib import Graph, parser, plugin, serializer
  5. from rdflib.resource import Resource
  6. from rdflib.namespace import RDF
  7. from lakesuperior.model.ldpr import Ldpr
  8. from lakesuperior.model.ldp_nr import LdpNr
  9. from lakesuperior.model.ldp_rs import LdpRs, Ldpc, LdpDc, LdpIc
  10. from lakesuperior.config_parser import config
  11. from lakesuperior.env import env
  12. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  13. from lakesuperior.exceptions import (
  14. IncompatibleLdpTypeError, InvalidResourceError, ResourceExistsError,
  15. ResourceNotExistsError, TombstoneError)
  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(identifier=nsc['fcres'][uid]))
  32. return rsrc
  33. @staticmethod
  34. def from_stored(uid, repr_opts={}, **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. graph store.
  40. N.B. The resource must exist.
  41. :param uid: UID of the instance.
  42. """
  43. #logger.info('Retrieving stored resource: {}'.format(uid))
  44. imr_urn = nsc['fcres'][uid]
  45. rsrc_meta = rdfly.get_metadata(uid)
  46. #logger.debug('Extracted metadata: {}'.format(
  47. # pformat(set(rsrc_meta))))
  48. rdf_types = set(rsrc_meta[imr_urn : RDF.type])
  49. if LDP_NR_TYPE in rdf_types:
  50. logger.info('Resource is a LDP-NR.')
  51. rsrc = LdpNr(uid, repr_opts, **kwargs)
  52. elif LDP_RS_TYPE in rdf_types:
  53. logger.info('Resource is a LDP-RS.')
  54. rsrc = LdpRs(uid, repr_opts, **kwargs)
  55. else:
  56. raise ResourceNotExistsError(uid)
  57. # Sneak in the already extracted metadata to save a query.
  58. rsrc._metadata = rsrc_meta
  59. return rsrc
  60. @staticmethod
  61. def from_provided(uid, mimetype=None, stream=None, graph=None, **kwargs):
  62. r"""
  63. Create and LDPR instance from provided data.
  64. the LDP class (LDP-RS, LDP_NR, etc.) is determined by the contents
  65. passed.
  66. :param str uid: UID of the resource to be created or updated.
  67. :param str mimetype: The provided content MIME type. If this is
  68. specified the resource is considered a LDP-NR and a ``stream``
  69. *must* be provided.
  70. :param IOStream stream: The provided data stream.
  71. :param rdflib.Graph graph: Initial graph to populate the
  72. resource with. This can be used for LDP-RS and LDP-NR types alike.
  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. provided_imr = Graph(identifier=uri)
  79. if graph:
  80. provided_imr += graph
  81. #logger.debug('Provided graph: {}'.format(
  82. # pformat(set(provided_imr))))
  83. if stream is None:
  84. # Resource is a LDP-RS.
  85. if mimetype:
  86. raise ValueError(
  87. 'Binary stream must be provided if mimetype is specified.')
  88. # Determine whether it is a basic, direct or indirect container.
  89. if Ldpr.MBR_RSRC_URI in provided_imr.predicates() and \
  90. Ldpr.MBR_REL_URI in provided_imr.predicates():
  91. if Ldpr.INS_CNT_REL_URI in provided_imr.predicates():
  92. cls = LdpIc
  93. else:
  94. cls = LdpDc
  95. else:
  96. cls = Ldpc
  97. inst = cls(uid, provided_imr=provided_imr, **kwargs)
  98. # Make sure we are not updating an LDP-NR with an LDP-RS.
  99. if inst.is_stored and LDP_NR_TYPE in inst.ldp_types:
  100. raise IncompatibleLdpTypeError(uid, mimetype)
  101. if kwargs.get('handling', 'strict') != 'none':
  102. inst.check_mgd_terms(inst.provided_imr)
  103. else:
  104. # Resource is a LDP-NR.
  105. if not mimetype:
  106. mimetype = 'application/octet-stream'
  107. inst = LdpNr(uid, stream=stream, mimetype=mimetype,
  108. provided_imr=provided_imr, **kwargs)
  109. # Make sure we are not updating an LDP-RS with an LDP-NR.
  110. if inst.is_stored and LDP_RS_TYPE in inst.ldp_types:
  111. raise IncompatibleLdpTypeError(uid, mimetype)
  112. logger.debug('Creating resource of type: {}'.format(
  113. inst.__class__.__name__))
  114. return inst
  115. @staticmethod
  116. def is_rdf_parsable(mimetype):
  117. """
  118. Checks whether a MIME type support RDF parsing by a RDFLib plugin.
  119. :param str mimetype: MIME type to check.
  120. """
  121. try:
  122. plugin.get(mimetype, parser.Parser)
  123. except plugin.PluginException:
  124. return False
  125. else:
  126. return True
  127. @staticmethod
  128. def is_rdf_serializable(mimetype):
  129. """
  130. Checks whether a MIME type support RDF serialization by a RDFLib plugin
  131. :param str mimetype: MIME type to check.
  132. """
  133. try:
  134. plugin.get(mimetype, serializer.Serializer)
  135. except plugin.PluginException:
  136. return False
  137. else:
  138. return True
  139. @staticmethod
  140. def mint_uid(parent_uid, path=None):
  141. """
  142. Mint a new resource UID based on client directives.
  143. This method takes a parent ID and a tentative path and returns an LDP
  144. resource UID.
  145. This may raise an exception resulting in a 404 if the parent is not
  146. found or a 409 if the parent is not a valid container.
  147. :param str parent_uid: UID of the parent resource. It must be an
  148. existing LDPC.
  149. :param str path: path to the resource, relative to the parent.
  150. :rtype: str
  151. :return: The confirmed resource UID. This may be different from
  152. what has been indicated.
  153. """
  154. def split_if_legacy(uid):
  155. if config['application']['store']['ldp_rs']['legacy_ptree_split']:
  156. uid = tbox.split_uuid(uid)
  157. return uid
  158. if path and path.startswith('/'):
  159. raise ValueError('Slug cannot start with a slash.')
  160. # Shortcut!
  161. if not path and parent_uid == '/':
  162. return '/' + split_if_legacy(str(uuid4()))
  163. if not parent_uid.startswith('/'):
  164. raise ValueError('Invalid parent UID: {}'.format(parent_uid))
  165. parent = LdpFactory.from_stored(parent_uid)
  166. if nsc['ldp'].Container not in parent.types:
  167. raise InvalidResourceError(parent_uid,
  168. 'Parent {} is not a container.')
  169. pfx = parent_uid.rstrip('/') + '/'
  170. if path:
  171. cnd_uid = pfx + path
  172. if not rdfly.ask_rsrc_exists(cnd_uid):
  173. return cnd_uid
  174. return pfx + split_if_legacy(str(uuid4()))