ldp_factory.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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=Resource(Graph(), 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.graph))))
  48. rdf_types = set(rsrc_meta.graph[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, stream=None, **kwargs):
  62. '''
  63. Determine LDP type from request content.
  64. @param uid (string) UID of the resource to be created or updated.
  65. @param mimetype (string) The provided content MIME type.
  66. @param stream (IOStream | None) The provided data stream. This can be
  67. RDF or non-RDF content, or None. In the latter case, an empty container
  68. is created.
  69. '''
  70. uri = nsc['fcres'][uid]
  71. if not stream:
  72. # Create empty LDPC.
  73. logger.info('No data received in request. '
  74. 'Creating empty container.')
  75. inst = Ldpc(uid, provided_imr=Resource(Graph(), uri), **kwargs)
  76. elif __class__.is_rdf_parsable(mimetype):
  77. # Create container and populate it with provided RDF data.
  78. input_rdf = stream.read()
  79. gr = Graph().parse(data=input_rdf, format=mimetype, publicID=uri)
  80. #logger.debug('Provided graph: {}'.format(
  81. # pformat(set(provided_gr))))
  82. provided_imr = Resource(gr, uri)
  83. # Determine whether it is a basic, direct or indirect container.
  84. if Ldpr.MBR_RSRC_URI in gr.predicates() and \
  85. Ldpr.MBR_REL_URI in gr.predicates():
  86. if Ldpr.INS_CNT_REL_URI in gr.predicates():
  87. cls = LdpIc
  88. else:
  89. cls = LdpDc
  90. else:
  91. cls = Ldpc
  92. inst = cls(uid, provided_imr=provided_imr, **kwargs)
  93. # Make sure we are not updating an LDP-RS with an LDP-NR.
  94. if inst.is_stored and LDP_NR_TYPE in inst.ldp_types:
  95. raise IncompatibleLdpTypeError(uid, mimetype)
  96. if kwargs.get('handling', 'strict') != 'none':
  97. inst._check_mgd_terms(inst.provided_imr.graph)
  98. else:
  99. # Create a LDP-NR and equip it with the binary file provided.
  100. provided_imr = Resource(Graph(), uri)
  101. inst = LdpNr(uid, stream=stream, mimetype=mimetype,
  102. provided_imr=provided_imr, **kwargs)
  103. # Make sure we are not updating an LDP-NR with an LDP-RS.
  104. if inst.is_stored and LDP_RS_TYPE in inst.ldp_types:
  105. raise IncompatibleLdpTypeError(uid, mimetype)
  106. logger.info('Creating resource of type: {}'.format(
  107. inst.__class__.__name__))
  108. try:
  109. types = inst.types
  110. except (TombstoneError, ResourceNotExistsError):
  111. types = set()
  112. return inst
  113. @staticmethod
  114. def is_rdf_parsable(mimetype):
  115. '''
  116. Checks whether a MIME type support RDF parsing by a RDFLib plugin.
  117. @param mimetype (string) MIME type to check.
  118. '''
  119. try:
  120. plugin.get(mimetype, parser.Parser)
  121. except plugin.PluginException:
  122. return False
  123. else:
  124. return True
  125. @staticmethod
  126. def is_rdf_serializable(mimetype):
  127. '''
  128. Checks whether a MIME type support RDF serialization by a RDFLib plugin
  129. @param mimetype (string) MIME type to check.
  130. '''
  131. try:
  132. plugin.get(mimetype, serializer.Serializer)
  133. except plugin.PluginException:
  134. return False
  135. else:
  136. return True
  137. @staticmethod
  138. def mint_uid(parent_uid, path=None):
  139. '''
  140. Mint a new resource UID based on client directives.
  141. This method takes a parent ID and a tentative path and returns an LDP
  142. resource UID.
  143. This may raise an exception resulting in a 404 if the parent is not
  144. found or a 409 if the parent is not a valid container.
  145. @param parent_uid (string) UID of the parent resource. It must be an
  146. existing LDPC.
  147. @param path (string) path to the resource, relative to the parent.
  148. @return string The confirmed resource UID. This may be different from
  149. what has been indicated.
  150. '''
  151. def split_if_legacy(uid):
  152. if config['application']['store']['ldp_rs']['legacy_ptree_split']:
  153. uid = tbox.split_uuid(uid)
  154. return uid
  155. if path and path.startswith('/'):
  156. raise ValueError('Slug cannot start with a slash.')
  157. # Shortcut!
  158. if not path and parent_uid == '/':
  159. return split_if_legacy(str(uuid4()))
  160. if not parent_uid.startswith('/'):
  161. raise ValueError('Invalid parent UID: {}'.format(parent_uid))
  162. parent = LdpFactory.from_stored(parent_uid)
  163. if nsc['ldp'].Container not in parent.types:
  164. raise InvalidResourceError(parent_uid,
  165. 'Parent {} is not a container.')
  166. pfx = parent_uid.rstrip('/') + '/'
  167. if path:
  168. cnd_uid = pfx + path
  169. if not rdfly.ask_rsrc_exists(cnd_uid):
  170. return cnd_uid
  171. return pfx + split_if_legacy(str(uuid4()))