Exemplo n.º 1
0
 def __call__(self, uri, **kwargs):
     from invenio_jsonschemas import current_jsonschemas
     from invenio_jsonschemas.errors import JSONSchemaNotFound
     try:
         return current_jsonschemas.get_schema(uri)
     except JSONSchemaNotFound:
         return super(TestJSONResolver, self).__call__(uri, *kwargs)
Exemplo n.º 2
0
    def get_record_schemas(self, obj):
        deposit = CAPDeposit.get_record(obj['pid'].object_uuid)

        schema = current_jsonschemas.get_schema(deposit.schema.record_path,
                                                with_refs=True,
                                                resolved=True)
        uiSchema = deposit.schema.record_options

        return dict(schema=copy.deepcopy(schema), uiSchema=uiSchema)
Exemplo n.º 3
0
 def get_schema(self, schema_path):
     schema_data = current_jsonschemas.get_schema(schema_path,
                                                  with_refs=False,
                                                  resolved=False)
     schema_data = JsonRef.replace_refs(
         schema_data,
         base_uri=current_jsonschemas.path_to_url(schema_path),
         loader=internal_invenio_loader)
     return current_jsonschemas.resolver_cls(schema_data)
Exemplo n.º 4
0
def internal_invenio_loader(relative_schema, *args, **kwargs):
    parts = urlsplit(relative_schema)
    if not parts.netloc:
        relative_schema = urlunparse(
            (current_app.config['JSONSCHEMAS_URL_SCHEME'],
             current_app.config['JSONSCHEMAS_HOST'], relative_schema, None,
             None, None))
    path = current_jsonschemas.url_to_path(relative_schema)
    return current_jsonschemas.get_schema(path)
Exemplo n.º 5
0
    def __call__(self, uri, **kwargs):
        """Method invoked when an uri has to be resolved.

        If URI is present in registered JSON schemas list, it resolves in the
        common schemas, else lets the loader from jsonref do the job.
        """
        if uri in current_jsonschemas.list_schemas():
            return current_jsonschemas.get_schema(uri)

        return super(CustomJsonLoader, self).__call__(uri, *kwargs)
Exemplo n.º 6
0
def schemaform(document_type):
    """Return schema and form options for the editor."""
    doc_type = document_type
    doc_type = re.sub('ies$', 'y', doc_type)
    doc_type = re.sub('s$', '', doc_type)
    data = {}
    schema = None
    schema_name = None
    try:
        current_jsonschemas.get_schema.cache_clear()
        schema_name = '{}/{}-v0.0.1.json'.format(document_type, doc_type)
        schema = current_jsonschemas.get_schema(schema_name)
        data['schema'] = prepare_jsonschema(schema)
    except JSONSchemaNotFound:
        abort(404)

    try:
        form = current_jsonschemas.get_schema(
            'form_{}/{}-v0.0.1.json'.format(document_type, doc_type))
        data['layout'] = prepare_form_option(form)
    except JSONSchemaNotFound as e:
        raise(e)
    return jsonify(data)
Exemplo n.º 7
0
    def validate(vocabulary):
        """Validate vocabulary."""
        if not isinstance(vocabulary, Vocabulary):
            raise VocabularyError("{} is not a vocabulary".format(vocabulary))

        # Validate vocabulary type
        if vocabulary.type not in current_app.config["ILS_VOCABULARIES"]:
            raise VocabularyError("Invalid vocabulary type: {}".format(
                vocabulary.type))

        # JSONSchema validation
        schema = current_jsonschemas.get_schema(vocabulary._schema)
        data = vocabulary.dumps()
        validate_schema(data, schema)
Exemplo n.º 8
0
def schemas(record_type):
    """Return schema for the editor.

    :param record_type: Type of resource.
    :returns: JSONified schema or a 404 if not found.
    """
    rec_type = record_type
    rec_type = re.sub('ies$', 'y', rec_type)
    rec_type = re.sub('s$', '', rec_type)

    try:
        current_jsonschemas.get_schema.cache_clear()
        schema_name = '{}/{}-v1.0.0.json'.format(record_type, rec_type)
        schema = current_jsonschemas.get_schema(schema_name)

        # TODO: Maybe find a proper way to do this.
        if record_type in [
                'users', 'documents'
        ] and not current_user.is_anonymous and current_user_record:
            if record_type == 'users':
                # If user is admin, restrict available roles list.
                if current_user_record.is_admin:
                    reachable_roles = current_user_record.\
                        get_all_reachable_roles()

                    schema['properties']['role']['form']['options'] = []
                    for role in reachable_roles:
                        schema['properties']['role']['form']['options'].append(
                            {
                                'label': 'role_{role}'.format(role=role),
                                'value': role
                            })

                    schema['properties']['role'][
                        'enum'] = current_user_record.get_all_reachable_roles(
                        )
                # User cannot select role
                else:
                    schema['properties'].pop('role')
                    if 'role' in schema.get('propertiesOrder', []):
                        schema['propertiesOrder'].remove('role')

            if not current_user_record.is_superuser:
                schema['properties'].pop('organisation')
                if 'organisation' in schema.get('propertiesOrder', []):
                    schema['propertiesOrder'].remove('organisation')

        return jsonify({'schema': prepare_schema(schema)})
    except JSONSchemaNotFound:
        abort(404)
Exemplo n.º 9
0
    def _load_schema(self):
        """Process and return the JSON schema.

        :returns: The schema corresponding to the resource.
        """
        rec_type = self._resource_type
        rec_type = re.sub('ies$', 'y', rec_type)
        rec_type = re.sub('s$', '', rec_type)

        current_jsonschemas.get_schema.cache_clear()
        schema_name = f'{self._resource_type}/{rec_type}-v1.0.0.json'

        if has_custom_resource(self._resource_type):
            schema_name = f'{current_organisation["code"]}/{schema_name}'

        self._schema = copy.deepcopy(
            current_jsonschemas.get_schema(schema_name))
Exemplo n.º 10
0
def schemaform(document_type):
    """Return schema and form options for the editor."""
    doc_type = document_type
    doc_type = re.sub('ies$', 'y', doc_type)
    doc_type = re.sub('s$', '', doc_type)
    data = {}
    schema = None
    schema_name = None
    try:
        if current_app.debug:
            current_jsonschemas.get_schema.cache_clear()
        schema_name = '{}/{}-v0.0.1.json'.format(document_type, doc_type)
        schema = current_jsonschemas.get_schema(schema_name, with_refs=True)
        data['schema'] = prepare_jsonschema(schema)
    except JSONSchemaNotFound:
        abort(404)

    return jsonify(data)
Exemplo n.º 11
0
def schema_docs(schemas):
    """Generates jsonschema docs for data models."""
    for schema_path in schemas:
        click.secho(f'Generating docs for schema {schema_path}')
        schema = current_jsonschemas.get_schema(schema_path, with_refs=False, resolved=False)
        schema = JsonRef.replace_refs(
            schema,
            jsonschema=True,
            base_uri=current_app.config.get('JSONSCHEMAS_HOST'),
            loader=_records_state.loader_cls(),
        )

        # TODO: this is necessary to resolve JSONRefs in allOf
        schema = json.loads(json.dumps(schema, default=lambda x: x.__subject__))

        # Generate and save html docs for the schema
        with tempfile.NamedTemporaryFile(mode="w+") as schema_source:
            schema_source.write(json.dumps(schema))
            schema_source.flush()

            with open(f'docs/schemas/{basename(schema_path.rstrip(".json"))}.html', mode='w+') as result_file:
                click.secho(f'Writing schema docs to {result_file.name}', color='green')
                generate_from_file_object(
                    schema_file=schema_source,
                    result_file=result_file,
                    minify=True,
                    expand_buttons=True
                )

    # Generate and save schema index page
    index_md = r"""---
layout: default
---

# Data Models Schema Docs

"""
    for f in os.listdir('docs/schemas/'):
        if f.endswith('.html'):
            index_md += f'- [{f.rstrip(".html")}](./{f})\n'

    with open(f'docs/schemas/index.md', mode='w+') as index_file:
        index_file.write(index_md)
Exemplo n.º 12
0
def get_profile_countries():
    """Get country list from the jsonschema."""
    schema = current_jsonschemas.get_schema('common/countries-v0.0.1.json')
    options = schema['country']['form']['options']
    return [(option.get('value'), _((option.get('label'))))
            for option in options]
Exemplo n.º 13
0
 def get_deposit_schemas(self, obj):
     ui_schema = obj['deposit'].schema.deposit_options
     schema = current_jsonschemas.get_schema(
         obj['deposit'].schema.deposit_path, with_refs=True, resolved=True)
     return dict(schema=copy.deepcopy(schema), uiSchema=ui_schema)