Skip to content
Snippets Groups Projects
Select Git revision
  • master
1 result

228.nfa

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    MetadataController.cs 9.38 KiB
    using Coscine.Api.Project.Models;
    using Coscine.ApiCommons;
    using Coscine.ApiCommons.Exceptions;
    using Coscine.ApiCommons.Factories;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Linq;
    using VDS.RDF.Writing;
    using VDS.RDF.Parsing;
    using VDS.RDF;
    using Metadata;
    using System.Web;
    using Microsoft.AspNetCore.Authorization;
    
    namespace Coscine.Api.Project.Controllers
    {
    
        [Authorize]
        public class MetadataController : Controller
        {
            private readonly Authenticator _authenticator;
            private readonly MetadataModel _metadataModel;
            private readonly ResourceModel _resourceModel;
            private readonly ProjectModel _projectModel;
            private readonly Util _util;
    
            public MetadataController()
            {
                _authenticator = new Authenticator(this, Program.Configuration);
                _metadataModel = new MetadataModel();
                _resourceModel = new ResourceModel();
                _projectModel = new ProjectModel();
                _util = new Util();
            }
    
            [Route("[controller]")]
            public IActionResult Index()
            {
                return NoContent();
            }
    
            // returns the basic application profile
            [HttpGet("[controller]/resource/{projectId}/ap/{applicationProfileId}")]
            public IActionResult GetApplicationProfile(Guid projectId, string applicationProfileId)
            {
                var user = _authenticator.GetUser();
    
                if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
                {
                    var graph = _util.GetGraph(HttpUtility.UrlDecode(applicationProfileId));                
    
                    var json = JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter()));
                    
                    return Json(json);
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
    
            }
    
            // returns the application profile with the fixed values
            [HttpGet("[controller]/resource/{resourceId}/apc/{applicationProfileId}")]
            public IActionResult GetApplicationProfileComplete(string resourceId, string applicationProfileId)
            {
                var user = _authenticator.GetUser();
    
                var resource = _resourceModel.GetById(Guid.Parse(resourceId));
                if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member) && applicationProfileId != null)
                {
                    var graph = _util.GetGraph(HttpUtility.UrlDecode(applicationProfileId));
                    var fixedValuesGraph = new Graph();
    
                    fixedValuesGraph.LoadFromString(resource.FixedValues, new RdfJsonParser());
    
                    graph.Merge(fixedValuesGraph);
    
                    var json = JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter()));
    
                    return Ok(json);
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
    
            }
    
            [HttpGet("[controller]/project/{projectId}/aplist/")]
            public IActionResult ListAllApplicationProfiles(Guid projectId)
            {
                var user = _authenticator.GetUser();
                if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
                {
                    var graphUris = _util.ListGraphs();
    
                    return Json(new JArray(graphUris.Select(x => x.ToString()).Where(x => x.StartsWith("https://purl.org/coscine/ap/"))));
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
            }
    
            [HttpGet("[controller]/resource/{resourceId}/filename/{filename}/ver/{version}")]
            public IActionResult GetMetadataForFile(string resourceId, string filename, string version)
            {
                var user = _authenticator.GetUser();
                var resource = _resourceModel.GetById(Guid.Parse(resourceId));
                if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
                {
                    var id = _metadataModel.GenerateId(resourceId, filename, version);
                    var uri = _metadataModel.CreateUri(id);
                    var graph = _util.GetGraph(uri);
                    return Json(JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter())).ToString());
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
            }
    
            [HttpPut("[controller]/resource/{resourceId}/filename/{filename}/ver/{version}")]
            public IActionResult StoreMetadataForFile(string resourceId, string filename, string version)
            {
                var innerBlock = ObjectFactory<JToken>.DeserializeFromStream(Request.Body);
                var graphName = _metadataModel.GenerateId(resourceId, filename, version);
                var graphNameUri = _metadataModel.CreateUri(graphName);
                var json = new JObject
                {
                    [graphName] = innerBlock
                };
    
                var user = _authenticator.GetUser();
                var resource = _resourceModel.GetById(Guid.Parse(resourceId));
                    
                if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
                {
                    json[graphName]["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"] = new JArray
                    {
                        new JObject
                        {
                            ["value"] = resource.ApplicationProfile.Substring(0, resource.ApplicationProfile.Length-1),
                            ["type"] = "uri"
                        }
                    };
                    // throw bad request if empty node value is detected
                    JToken root = json.First.First;
                    foreach (var node in root)
                    {
                        string nodeValue = node.First.First["value"].ToString().ToLower();
                        if (String.IsNullOrEmpty(nodeValue))
                        {
                            throw new ArgumentException("Empty values in application profile are not accepted.");
                        }
                    }
    
                    var graph = new Graph();
                    graph.LoadFromString(json.ToString(), new RdfJsonParser());
    
                    var fixedValuesGraph = new Graph();
                    fixedValuesGraph.LoadFromString(resource.FixedValues, new RdfJsonParser());
    
                    foreach(var triple in fixedValuesGraph.Triples.Where(x => x.Predicate.ToString() == "https://purl.org/coscine/fixedValue"))
                    {
                        // Remove any existing triples
                        foreach (var triple2 in graph.GetTriplesWithSubjectPredicate(graph.CreateUriNode(graphNameUri), triple.Subject).ToList())
                        {
                            graph.Retract(triple2);
                        }
                        graph.Assert(graph.CreateUriNode(graphNameUri), triple.Subject, triple.Object);
                    }
    
                    // Default values is not checked or added
    
                    // validate the data
                    if (_util.ValidateShacl(graph, graphNameUri))
                    {
                        // store the data
                        if (_util.HasGraph(graphNameUri))
                        {
                            _util.ClearGraph(graphNameUri);
                        }
                        else
                        {
                            _util.CreateNamedGraph(graphNameUri);
                        }
    
                        // BaseUri must be set for the sparql query
                        graph.BaseUri = graphNameUri;
                        _util.AddGraph(graph);
    
                        return NoContent();
                    }
                    else
                    {
                        throw new NotAuthorizedException("Data has the wrong format!");
                    }
    
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
            }
    
            [HttpGet("[controller]/vocabulary/{projectId}/{path}")]
            public IActionResult GetVocabulary(Guid projectId, string path)
            {
                var user = _authenticator.GetUser();
                if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
                {
                    var graph = _util.GetGraph(HttpUtility.UrlDecode(path));
    
                    var de = new JArray();
                    foreach (var kv in _util.GetVocabularyLabels(graph, "de"))
                    {
                        JObject obj = new JObject
                        {
                            ["value"] = kv.Key,
                            ["name"] = kv.Value
                        };
                        de.Add(obj);
                    }
    
                    var en = new JArray();
                    foreach(var kv in _util.GetVocabularyLabels(graph, "en"))
                    {
                        JObject obj = new JObject
                        {
                            ["value"] = kv.Key,
                            ["name"] = kv.Value
                        };
                        en.Add(obj);
                    }
    
                    JObject json = new JObject
                    {
                        ["de"] = de,
                        ["en"] = en
                    };
    
                    return Json(json);
                }
                else
                {
                    throw new NotAuthorizedException("User is no project member!");
                }
            }
    
        }
    }