diff --git a/src/protagonist/DLCS.Mock/.gitignore b/src/protagonist/DLCS.Mock/.gitignore deleted file mode 100644 index 2d0255217..000000000 --- a/src/protagonist/DLCS.Mock/.gitignore +++ /dev/null @@ -1 +0,0 @@ -wwwroot/api-generated-docs diff --git a/src/protagonist/DLCS.Mock/ApiApp/AddHydraApiHeaderFilter.cs b/src/protagonist/DLCS.Mock/ApiApp/AddHydraApiHeaderFilter.cs deleted file mode 100644 index dbb001f7e..000000000 --- a/src/protagonist/DLCS.Mock/ApiApp/AddHydraApiHeaderFilter.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace DLCS.Mock.ApiApp; - -public class AddHydraApiHeaderFilter : ActionFilterAttribute -{ - private readonly MockModel model; - - public AddHydraApiHeaderFilter(MockModel model) - { - this.model = model; - } - - // public override void OnResultExecuted(ResultExecutedContext resultExecutedContext) - // { - // var headers = resultExecutedContext.HttpContext.Response.Headers; - // AddIfMissing(headers, "Link", "<" + settings.BaseUrl + "/vocab#>; rel=\"http://www.w3.org/ns/hydra/core#apiDocumentation\""); - // AddIfMissing(headers, "Access-Control-Allow-Origin", "*"); - // AddIfMissing(headers, "Access-Control-Expose-Headers", "Link"); - // if (resultExecutedContext.HttpContext.Response.ContentType.StartsWith("application/json")) - // { - // resultExecutedContext.HttpContext.Response.ContentType = "application/ld+json"; - // } - // } - - public override void OnActionExecuting(ActionExecutingContext context) - { - if (model.BaseUrl == null) - { - // Initialise the model based on the DISPLAY url of a request - var uri = new Uri(context.HttpContext.Request.GetDisplayUrl()); - - model.Init(uri.Scheme + "://" + uri.Authority); - } - base.OnActionExecuting(context); - } - - public override void OnActionExecuted(ActionExecutedContext actionExecutedContext) - { - var headers = actionExecutedContext.HttpContext.Response.Headers; - AddIfMissing(headers, "Link", "<" + model.BaseUrl + "/vocab#>; rel=\"http://www.w3.org/ns/hydra/core#apiDocumentation\""); - AddIfMissing(headers, "Access-Control-Allow-Origin", "*"); - AddIfMissing(headers, "Access-Control-Expose-Headers", "Link"); - if (actionExecutedContext.HttpContext.Response.ContentType == null) // why is this always true? - { - return; - } - if (actionExecutedContext.HttpContext.Response.ContentType.StartsWith("application/json")) - { - actionExecutedContext.HttpContext.Response.ContentType = "application/ld+json"; - } - } - - private void AddIfMissing(IHeaderDictionary headers, string header, string value) - { - if (!headers.ContainsKey(header)) - { - headers.Add(header, value); - } - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/ApiApp/AttributeUtil.cs b/src/protagonist/DLCS.Mock/ApiApp/AttributeUtil.cs deleted file mode 100644 index cab464ee3..000000000 --- a/src/protagonist/DLCS.Mock/ApiApp/AttributeUtil.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Hydra; - -namespace DLCS.Mock.ApiApp; - -public class AttributeUtil -{ - public static Dictionary GetAttributeMap(string assemblyName, Type attributeType) - { - if (!(typeof (TypeReferencingAttribute)).IsAssignableFrom(attributeType)) - { - throw new ArgumentException("attributeType must extend TypeReferencingAttribute", "attributeType"); - } - - var assembly = AppDomain.CurrentDomain.GetAssemblies() - .SingleOrDefault(a => a.GetName().Name == assemblyName); - - if (assembly == null) - { - throw new ArgumentException("Cannot find assembly " + assemblyName, "assemblyName"); - } - - var dict = new Dictionary(); - foreach (var type in assembly.GetTypes()) - { - var attributes = type.GetCustomAttributes(attributeType, true); - if (attributes.Length == 1) - { - var hydraAttr = (TypeReferencingAttribute) attributes[0]; - var typeAttrIsPointingAt = hydraAttr.ReferencedType; - var instanceOfThatType = Activator.CreateInstance(typeAttrIsPointingAt); - dict.Add(type.Name, instanceOfThatType); - } - } - - return dict; - } - -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/ApiApp/MockHelp.cs b/src/protagonist/DLCS.Mock/ApiApp/MockHelp.cs deleted file mode 100644 index e9563a459..000000000 --- a/src/protagonist/DLCS.Mock/ApiApp/MockHelp.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using DLCS.HydraModel; - -namespace DLCS.Mock.ApiApp; - -public static class MockHelp -{ - public static Customer GetByName(this List customers, string name) - { - return customers.Single(c => c.Name == name); - } - public static AuthService GetByIdPart(this List authServices, string idPart) - { - return authServices.Single(a => a.ModelId == idPart); - } - public static Role GetByCustAndId(this List roles, int customerId, string idPart) - { - return roles.Single(r => r.CustomerId == customerId && r.ModelId == idPart); - } - - public static AuthService MakeAuthService( - string baseUrl, int customerId, string serviceId, string name, string profile, int ttl, - string label, string description, string pageLabel, string pageDescription, string callToAction) - { - return new AuthService(baseUrl, customerId, serviceId) - { - Name = name, - Profile = profile, - TimeToLive = ttl, - Label = label, - Description = description, - PageLabel = pageLabel, - PageDescription = pageDescription, - CallToAction = callToAction - }; - } - - public static CustomerOriginStrategy MakeCustomerOriginStrategy( - string baseUrl, int customerId, string strategyId, - string regex, string credentials, string originStrategy) - { - return new CustomerOriginStrategy(baseUrl, customerId, strategyId) - { - Regex = regex, - Credentials = credentials, - OriginStrategy = originStrategy - }; - } - - - public static Image MakeImage(string baseUrl, int customerId, int space, string modelId, - DateTime created, string? origin, - int? width, int? height, int? maxUnauthorised, - DateTime? queued, DateTime? dequeued, DateTime? finished, bool ingesting, string error, - string[]? tags, string? string1, string? string2, string? string3, - int? number1, int? number2, int? number3, - string imageOptimisationPolicy, string thumbnailPolicy) - { - var image = new Image(baseUrl, customerId, space, modelId); - string mockDlcsPathTemplate = string.Format("/{0}/{1}/{2}", customerId, space, modelId); - image.ImageService = "https://mock.dlcs.io" + mockDlcsPathTemplate; - image.DegradedInfoJson = "https://mock.degraded.dlcs.io" + mockDlcsPathTemplate; - image.ThumbnailImageService = "https://mock.thumbs.dlcs.io" + mockDlcsPathTemplate; - image.Thumbnail400 = "https://mock.thumbs.dlcs.io" + mockDlcsPathTemplate + "/full/400,/0/default.jpg"; - image.Created = created; - image.Origin = origin; - image.Width = width; - image.Height = height; - image.MaxUnauthorised = maxUnauthorised; - image.Queued = queued; - image.Dequeued = dequeued; - image.Finished = finished; - image.Ingesting = ingesting; - image.Error = error; - image.Tags = tags; - image.String1 = string1; - image.String2 = string2; - image.String3 = string3; - image.Number1 = number1; - image.Number2 = number2; - image.Number3 = number3; - image.ImageOptimisationPolicy = imageOptimisationPolicy; - image.ThumbnailPolicy = thumbnailPolicy; - return image; - } - - public static NamedQuery MakeNamedQuery( - string baseUrl, int customerId, string modelId, - string name, bool global, string template) - { - return new NamedQuery(baseUrl, customerId, modelId) - { - Name = name, - Global = global, - Template = template - }; - } - - public static OriginStrategy MakeOriginStrategy( - string baseUrl, string originStrategyId, string name, bool requiresCredentials) - { - return new OriginStrategy(baseUrl, originStrategyId) - { - Name = name, - RequiresCredentials = requiresCredentials - }; - } - - public static PortalUser MakePortalUser( - string baseUrl, int customerId, string userId, - string email, DateTime created, bool enabled) - { - return new PortalUser(baseUrl, customerId, userId) - { - Email = email, - Created = created, - Enabled = enabled - }; - } - - public static Role MakeRole( - string baseUrl, int customerId, string roleId, string name, - string label, string[] aliases) - { - return new Role(baseUrl, customerId, roleId) - { - Name = name, - Label = label, - Aliases = aliases - }; - } - - public static RoleProvider MakeRoleProvider( - string baseUrl, int customerId, string authServiceId, - string configuration, string credentials) - { - return new RoleProvider(baseUrl, customerId, authServiceId) - { - Configuration = configuration, - Credentials = credentials - }; - } - - public static Space MakeSpace( - string baseUrl, int modelId, int customerId, - string name, DateTime? created, string[]? defaultTags, int? maxUnauthorised) - { - return new Space(baseUrl, modelId, customerId) - { - - Name = name, - Created = created, - DefaultTags = defaultTags, - MaxUnauthorised = maxUnauthorised - }; - } - - public static ThumbnailPolicy MakeThumbnailPolicy( - string baseUrl, string thumbnailPolicyId, string name, int[] sizes) - { - return new ThumbnailPolicy(baseUrl, thumbnailPolicyId) - { - Name = name, - Sizes = sizes - }; - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/ApiApp/MockModel.cs b/src/protagonist/DLCS.Mock/ApiApp/MockModel.cs deleted file mode 100644 index 9b0d581a0..000000000 --- a/src/protagonist/DLCS.Mock/ApiApp/MockModel.cs +++ /dev/null @@ -1,421 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using DLCS.HydraModel; - -namespace DLCS.Mock.ApiApp; - -public class MockModel -{ - // Entities - public List Customers { get; set; } - public List PortalUsers { get; set; } - public List NamedQueries { get; set; } - public List OriginStrategies { get; set; } - public List ThumbnailPolicies { get; set; } - public List ImageOptimisationPolicies { get; set; } - public List PortalRoles { get; set; } - public List CustomerOriginStrategies { get; set; } - public List AuthServices { get; set; } - public List RoleProviders { get; set; } - public List Roles { get; set; } - public List Spaces { get; set; } - public List Queues { get; set; } - public List Images { get; set; } - public List Batches { get; set; } - - // collections that can't be generated from entities alone - public Dictionary> AuthServiceParentChild { get; set; } - public Dictionary RoleAuthService { get; set; } - public Dictionary> SpaceDefaultRoles { get; set; } - public Dictionary> ImageRoles { get; set; } - public Dictionary> BatchImages { get; set; } - public Dictionary> PortalUserRoles { get; set; } - - public readonly object ModelLock = new object(); - - public string BaseUrl { get; set; } - - public void Init(string baseUrl) - { - BaseUrl = baseUrl; - var customers = CreateCustomers(); - Customers = customers; - OriginStrategies = CreateOriginStrategies(); - PortalRoles = CreatePortalRoles(); - ImageOptimisationPolicies = CreateImageOptimisationPolicies(); - ThumbnailPolicies = CreateThumbnailPolicies(); - PortalUserRoles = new Dictionary>(); - PortalUsers = CreatePortalUsers(customers, PortalRoles, PortalUserRoles); - NamedQueries = CreateNamedQueries(customers); - CustomerOriginStrategies = CreateCustomerOriginStrategies(customers, OriginStrategies); - AuthServiceParentChild = new Dictionary>(); - AuthServices = CreateAuthServices(customers, AuthServiceParentChild); - RoleProviders = CreateRoleProviders(AuthServices); - RoleAuthService = new Dictionary(); - var roles = CreateRoles(customers, AuthServices, RoleAuthService); - Roles = roles; - SpaceDefaultRoles = new Dictionary>(); - var spaces = CreateSpaces(customers, roles, SpaceDefaultRoles); - Spaces = spaces; - Queues = CreateQueues(customers); - ImageRoles = new Dictionary>(); - var images = CreateImages(spaces, SpaceDefaultRoles, ImageRoles, ImageOptimisationPolicies, ThumbnailPolicies); - Images = images; - BatchImages = new Dictionary>(); - Batches = CreateBatches(images, BatchImages); - RecalculateCounters(); - } - - private List CreateThumbnailPolicies() - { - return new List - { - MockHelp.MakeThumbnailPolicy(BaseUrl, "standard", "standard DLCS thumbs", new[] {1024, 400, 200, 100}) - }; - } - - private List CreateImageOptimisationPolicies() - { - return new List - { - new ImageOptimisationPolicy(BaseUrl, "fast_lossy", "Fast lossy", "kdu_1", true, null) - }; - } - - private List CreatePortalRoles() - { - return new List - { - new PortalRole(BaseUrl, "admin", "Administrator"), - new PortalRole(BaseUrl, "readonly", "Read only"), - new PortalRole(BaseUrl, "samplerole", "Another example role") - }; - } - - private List CreateOriginStrategies() - { - return new List - { - MockHelp.MakeOriginStrategy(BaseUrl, "default", "No credentials over http/s", false), - MockHelp.MakeOriginStrategy(BaseUrl, "basic_https", "Basic Auth over https", true), - MockHelp.MakeOriginStrategy(BaseUrl, "ftps_creds", "FTPS with credentials", true), - MockHelp.MakeOriginStrategy(BaseUrl, "s3", "Fetch from s3 bucket presenting DLCS identity", true), - }; - } - - private List CreateBatches(List images, Dictionary> batchImages) - { - var r = new Random(); - var batches = new List(); - int batchId = 100001; - Batch currentBatch = null; - int batchSize = -1; - int counter = -1; - int currentCustomer = -1; - List imagesInBatch = null; - foreach (var image in images) - { - if (counter++ > batchSize || image.CustomerId != currentCustomer) - { - // save the old batch - if (currentBatch != null) - { - batches.Add(currentBatch); - batchImages.Add(currentBatch.Id, imagesInBatch); - } - // start a new batch - currentCustomer = image.CustomerId; - counter = 1; - batchSize = r.Next(3, 10); - var created = image.Created ?? DateTime.Now; - currentBatch = new Batch(BaseUrl, batchId++, image.CustomerId, created.AddSeconds(-1)); - imagesInBatch = new List(); - } - imagesInBatch.Add(image.Id); - image.Batch = currentBatch.Id; - } - batches.Add(currentBatch); - batchImages.Add(currentBatch.Id, imagesInBatch); - return batches; - } - - private List CreateImages(List spaces, - Dictionary> spaceDefaultRoles, Dictionary> imageRoles, - List imageOptimisationPolicies, List thumbnailPolicies ) - { - var images = new List(); - foreach (var space in spaces) - { - images.AddRange(MakeImagesForSpace(20, space, spaceDefaultRoles, imageRoles, imageOptimisationPolicies, thumbnailPolicies)); - } - return images; - } - - private List MakeImagesForSpace(int howMany, Space space, - Dictionary> spaceDefaultRoles, Dictionary> imageRoles, - List imageOptimisationPolicies, List thumbnailPolicies) - { - Random r = new Random(); - var images = new List(); - var ongoing = space.ModelId%2 == 0; - var queued = ongoing ? DateTime.Now.AddHours(-4) : new DateTime(2015, 11, 30); - for (int i = 0; i < howMany; i++) - { - DateTime? dequeued = ongoing ? (DateTime?) null : queued.AddHours(1).AddSeconds(i * 5); - if (ongoing && i < 6) dequeued = DateTime.Now.AddSeconds(-80 + 9*i); - DateTime? finished = ongoing ? (DateTime?)null : queued.AddSeconds(3608).AddSeconds(i * 7); - if (ongoing && i < 4) finished = DateTime.Now.AddSeconds(-60 + 9 * i); - var id = Guid.NewGuid().ToString().Substring(0, 8) + i.ToString().PadLeft(5, '0'); - var image = MockHelp.MakeImage(BaseUrl, space.CustomerId, space.ModelId ?? 0, id, - DateTime.Now, "https://customer.com/images/" + id + ".tiff", - r.Next(2000,11000), r.Next(3000,11000), space.MaxUnauthorised, - queued, dequeued, finished, !finished.HasValue, null, - space.DefaultTags, "b12345678", null, null, i, 0, 0, - imageOptimisationPolicies.First().Id, thumbnailPolicies.First().Id); - images.Add(image); - if (spaceDefaultRoles.ContainsKey(space.Id)) - { - var roles = spaceDefaultRoles[space.Id]; - if (roles.Any()) - { - imageRoles.Add(image.Id, roles); - } - } - } - return images; - } - - - private List CreateCustomers() - { - return new List - { - new Customer(BaseUrl, 1, "admin", "Administrator"), - new Customer(BaseUrl, 2, "wellcome", "Wellcome"), - new Customer(BaseUrl, 3, "crane", "Crane"), - new Customer(BaseUrl, 4, "iiifly", "IIIF.ly") - }; - } - - private List CreatePortalUsers(List customers, List portalRoles, Dictionary> portalUserRoles) - { - var portalUsers = new List - { - MockHelp.MakePortalUser(BaseUrl, customers.GetByName("admin").ModelId, - "8b083aee", "adam.christie@digirati.co.uk", new DateTime(2005, 10, 31), true), - MockHelp.MakePortalUser(BaseUrl, customers.GetByName("admin").ModelId, - "e3afdce8", "admin@dlcs.io", new DateTime(2016, 1, 1), true), - MockHelp.MakePortalUser(BaseUrl, customers.GetByName("wellcome").ModelId, - "ef132a3f", "r.kiley@wellcome.ac.uk", new DateTime(1961, 10, 31), true), - MockHelp.MakePortalUser(BaseUrl, customers.GetByName("iiifly").ModelId, - "9cee79e8", "tom.crane@digirati.co.uk", new DateTime(2010, 6, 21), true) - }; - - portalUserRoles.Add(portalUsers[0].Id, new List { portalRoles.Single(pr => pr.ModelId == "admin").Id }); - portalUserRoles.Add(portalUsers[1].Id, new List { portalRoles.Single(pr => pr.ModelId == "admin").Id }); - portalUserRoles.Add(portalUsers[2].Id, new List { portalRoles.Single(pr => pr.ModelId == "samplerole").Id }); - portalUserRoles.Add(portalUsers[3].Id, new List { portalRoles.Single(pr => pr.ModelId == "readonly").Id }); - - return portalUsers; - } - - private List CreateNamedQueries(List customers) - { - return new List - { - MockHelp.MakeNamedQuery(BaseUrl, customers.GetByName("iiifly").ModelId, "nq1", "bob", false, "template1-here"), - MockHelp.MakeNamedQuery(BaseUrl, customers.GetByName("iiifly").ModelId, "nq2", "manifest", false, "template2-here") - }; - } - - - private List CreateCustomerOriginStrategies(List customers, List originStrategies) - { - return new List - { - MockHelp.MakeCustomerOriginStrategy(BaseUrl, customers.GetByName("wellcome").ModelId, - "d0060f58-d603-468c-be12-94c2ffa1d7bd", "https://wellcomelibrary.org/service/asset(.+)", "s3://wellcome/path-to-origin-creds", - originStrategies.Single(os => os.ModelId == "basic_https").Id), - MockHelp.MakeCustomerOriginStrategy(BaseUrl, customers.GetByName("iiifly").ModelId, - "4df13bd5-931c-48b3-965b-0be523b6dd06", "https://example.org/images/(.+)", "s3://test/path-to-origin-creds", - originStrategies.Single(os => os.ModelId == "basic_https").Id), - MockHelp.MakeCustomerOriginStrategy(BaseUrl, customers.GetByName("iiifly").ModelId, - "86a02515-08d3-4d8d-be05-ea7190a38d8e", "ftps://example.org/images/(.+)", "s3://test/path-to-ftp-creds", - originStrategies.Single(os => os.ModelId == "ftps_creds").Id) - }; - } - - private List CreateAuthServices(List customers, Dictionary> authServiceParentChild) - { - int wellcome = customers.GetByName("wellcome").ModelId; - int iiifly = customers.GetByName("iiifly").ModelId; - var authServices = new List - { - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-clickthrough-login", "clickthrough", "http://iiif.io/api/auth/0/login", 0, - "Terms and Conditions", "

clickthrough...

", - "Terms and Conditions", "

More detailed info

", "Accept terms"), - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-clickthrough-token", "clickthrough-token", "http://iiif.io/api/auth/0/token", 1800, - "token service", null, null, null, null), - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-clickthrough-logout", "clickthrough-logout", "http://iiif.io/api/auth/0/logout", 0, - "Forget terms", null, null, null, null), - - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-delegated-login", "delegated-login", "http://iiif.io/api/auth/0/login", 0, - "Log in to view protected material", "

More detailed text for login prompt in UV

", - null, null, "Log in"), - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-delegated-token", "delegated-token", "http://iiif.io/api/auth/0/token", 1800, - "token service", null, null, null, null), - MockHelp.MakeAuthService(BaseUrl, wellcome, "wellcome-delegated-logout", "delegated-logout", "http://iiif.io/api/auth/0/logout", 0, - "Log out", null, null, null, null), - - MockHelp.MakeAuthService(BaseUrl, iiifly, "iiifly-clickthrough-login", "clickthrough", "http://iiif.io/api/auth/0/login", 0, - "Terms and Conditions", "

clickthrough...

", - "Terms and Conditions", "

More detailed info

", "Accept terms"), - MockHelp.MakeAuthService(BaseUrl, iiifly, "iiifly-clickthrough-token", "clickthrough-token", "http://iiif.io/api/auth/0/token", 1800, - "token service", null, null, null, null), - MockHelp.MakeAuthService(BaseUrl, iiifly, "iiifly-clickthrough-logout", "clickthrough-logout", "http://iiif.io/api/auth/0/logout", 0, - "Forget terms", null, null, null, null), - }; - - authServiceParentChild.Add( - authServices.GetByIdPart("wellcome-clickthrough-login").Id, - new List { authServices.GetByIdPart("wellcome-clickthrough-token").Id, - authServices.GetByIdPart("wellcome-clickthrough-logout").Id }); - - authServiceParentChild.Add( - authServices.GetByIdPart("wellcome-delegated-login").Id, - new List { authServices.GetByIdPart("wellcome-delegated-token").Id, - authServices.GetByIdPart("wellcome-delegated-logout").Id }); - - authServiceParentChild.Add( - authServices.GetByIdPart("iiifly-clickthrough-login").Id, - new List { authServices.GetByIdPart("iiifly-clickthrough-token").Id, - authServices.GetByIdPart("iiifly-clickthrough-logout").Id }); - - return authServices; - } - - - private List CreateRoleProviders(List authServices) - { - var wellcomeDelegated = authServices.GetByIdPart("wellcome-delegated-login"); - return new List - { - MockHelp.MakeRoleProvider(BaseUrl, wellcomeDelegated.CustomerId, wellcomeDelegated.ModelId, "{ Some CAS or OAuth details }", - "s3://wellcome/path-to-sso-backchannel-creds-if-required") - }; - } - - private List CreateRoles(List customers, List authServices, Dictionary roleAuthService) - { - int wellcome = customers.GetByName("wellcome").ModelId; - int iiifly = customers.GetByName("iiifly").ModelId; - - var roles = new List - { - MockHelp.MakeRole(BaseUrl, wellcome, "clickthrough", "Click through", - "Role for DLCS-enforced auth with no delegation", new [] { "Requires Registration", "reqreg"}), - MockHelp.MakeRole(BaseUrl, wellcome, "clinical", "Clinical Delegate to wellcomelibrary.org", - "Role for DLCS-enforced auth with delegation to customer", new [] { "Clinical Images", "Healthcare professional" }), - MockHelp.MakeRole(BaseUrl, wellcome, "staff", "Staff Delegate to wellcomelibrary.org", - "Role for DLCS-enforced auth with delegation to customer", new [] { "Wellcome Staff Member" }), - MockHelp.MakeRole(BaseUrl, wellcome, "restricted", "Restricted Delegate to wellcomelibrary.org", - "Role for DLCS-enforced auth with delegation to customer", new [] { "restricted" }), - MockHelp.MakeRole(BaseUrl, iiifly, "clickthrough", "Click through", - "Role for DLCS-enforced auth with no delegation", new [] { "acceptterms" }), - }; - - roleAuthService.Add(roles[0].Id, authServices.GetByIdPart("wellcome-clickthrough-login").Id); - roleAuthService.Add(roles[1].Id, authServices.GetByIdPart("wellcome-delegated-login").Id); - roleAuthService.Add(roles[2].Id, authServices.GetByIdPart("wellcome-delegated-login").Id); - roleAuthService.Add(roles[3].Id, authServices.GetByIdPart("wellcome-delegated-login").Id); - roleAuthService.Add(roles[4].Id, authServices.GetByIdPart("iiifly-clickthrough-login").Id); - return roles; - } - - - private List CreateSpaces(List customers, List roles, Dictionary> spaceDefaultRoles) - { - int wellcome = customers.GetByName("wellcome").ModelId; - int iiifly = customers.GetByName("iiifly").ModelId; - var spaces = new List - { - MockHelp.MakeSpace(BaseUrl, 1, wellcome, "wellcome1", DateTime.Now, null, -1), - MockHelp.MakeSpace(BaseUrl, 2, wellcome, "wellcome2", DateTime.Now, null, -1), - MockHelp.MakeSpace(BaseUrl, 11, iiifly, "iiifly1", DateTime.Now, null, 400), - MockHelp.MakeSpace(BaseUrl, 12, iiifly, "iiifly2", DateTime.Now, new [] {"tag1", "tag2"}, -1) - }; - - spaceDefaultRoles.Add( - spaces[1].Id, - new List { roles.GetByCustAndId(wellcome, "clinical").Id }); - spaceDefaultRoles.Add( - spaces[3].Id, - new List { roles.GetByCustAndId(iiifly, "clickthrough").Id }); - - return spaces; - } - - public void RecalculateCounters() - { - lock (ModelLock) - { - SetBatchCounts(); - SetQueueSizes(); - } - } - - private void SetBatchCounts() - { - foreach (var batch in Batches) - { - var imageIds = BatchImages[batch.Id]; - var images = Images.Where(i => imageIds.Contains(i.Id)).ToList(); - batch.Count = images.Count; - batch.Completed = images.Count(i => i.Finished.HasValue); - if (images.All(i => i.Finished.HasValue)) - { - batch.Finished = images.Select(i => i.Finished).Max(); - } - else - { - batch.EstCompletion = DateTime.Now.AddMinutes(3); - } - } - } - - private void SetQueueSizes() - { - var totalByCustomer = new Dictionary(); - foreach (var image in Images) - { - if (!totalByCustomer.ContainsKey(image.CustomerId)) - { - totalByCustomer[image.CustomerId] = 0; - } - if (!image.Finished.HasValue) - { - totalByCustomer[image.CustomerId] += 1; - } - } - foreach (var queue in Queues) - { - if (totalByCustomer.ContainsKey(queue.CustomerId)) - { - queue.Size = totalByCustomer[queue.CustomerId]; - } - } - } - - - private List CreateQueues(List customers) - { - return new List - { - new Queue(BaseUrl, 1), - new Queue(BaseUrl, 2), - new Queue(BaseUrl, 3), - new Queue(BaseUrl, 4) - }; - } -} diff --git a/src/protagonist/DLCS.Mock/Controllers/ContextsController.cs b/src/protagonist/DLCS.Mock/Controllers/ContextsController.cs deleted file mode 100644 index 57b5e2dee..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/ContextsController.cs +++ /dev/null @@ -1,22 +0,0 @@ -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -public class ContextsController : ControllerBase -{ - private readonly MockModel model; - - public ContextsController(MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/contexts/{typeName}.jsonld")] - public DlcsClassContext Index(string typeName) - { - return new(model.BaseUrl, "DLCS.HydraModel." + typeName); - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/CustomersController.cs b/src/protagonist/DLCS.Mock/Controllers/CustomersController.cs deleted file mode 100644 index b94e1ea63..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/CustomersController.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json.Linq; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class CustomersController : ControllerBase -{ - private readonly MockModel model; - - public CustomersController( - MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/customers")] - public HydraCollection Index() - { - var customers = model.Customers - .Select(c => c.GetCollectionForm()).ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = customers, - TotalItems = customers.Length, - Id = Request.GetDisplayUrl() - }; - } - - - [HttpGet] - [Route("/customers/{customerId}")] - public IActionResult Index(int customerId) - { - var customer = model.Customers.SingleOrDefault(c => c.ModelId == customerId); - if (customer == null) - { - return NotFound(); - } - return Ok(customer); - } - - [HttpGet] - [Route("/customers/{customerId}/portalUsers")] - public HydraCollection PortalUsers(int customerId) - { - var portalUsers = model.PortalUsers - .Where(p => p.CustomerId == customerId) - .Select(p => p.GetCollectionForm()).ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = portalUsers, - TotalItems = portalUsers.Length, - Id = Request.GetDisplayUrl() - }; - } - - [HttpGet] - [Route("/customers/{customerId}/portalUsers/{portalUserId}")] - public IActionResult PortalUsers(int customerId, string portalUserId) - { - var user = model.PortalUsers.SingleOrDefault( - u => u.CustomerId == customerId && u.ModelId == portalUserId); - if (user == null) - { - return NotFound(); - } - return Ok(user); - } - - - [HttpGet] - [Route("/customers/{customerId}/originStrategies")] - public HydraCollection OriginStrategies(int customerId) - { - var customerOriginStrategies = model.CustomerOriginStrategies - .Where(os => os.CustomerId == customerId) - .ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = customerOriginStrategies, - TotalItems = customerOriginStrategies.Length, - Id = Request.GetDisplayUrl() - }; - - } - - [HttpGet] - [Route("/customers/{customerId}/originStrategies/{originStrategyId}")] - public IActionResult OriginStrategies(int customerId, string originStrategyId) - { - var cos = model.CustomerOriginStrategies.SingleOrDefault( - u => u.CustomerId == customerId && u.ModelId == originStrategyId); - if (cos == null) - { - return NotFound(); - } - return Ok(cos); - } - - [HttpGet] - [Route("/customers/{customerId}/spaces")] - public HydraCollection Spaces(int customerId) - { - var spaces = model.Spaces - .Where(p => p.CustomerId == customerId) - .Select(p => p.GetCollectionForm()).ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = spaces, - TotalItems = spaces.Length, - Id = Request.GetDisplayUrl() - }; - } - - [HttpPost] - [Route("/customers/{customerId}/spaces")] - public IActionResult Spaces(int customerId, Space space) - { - if (!string.IsNullOrWhiteSpace(space.Id)) - { - return Conflict("You can only POST a new Space"); - } - if (string.IsNullOrWhiteSpace(space.Name)) - { - return BadRequest("The space must be given a name"); - } - // obviously not thread safe.. - var modelId = model.Spaces.Select(s => s.ModelId).Max() + 1; - var newSpace = MockHelp.MakeSpace(model.BaseUrl, modelId ?? 0, customerId, - space.Name, DateTime.UtcNow, space.DefaultTags, space.MaxUnauthorised); - model.Spaces.Add(newSpace); - return Created(newSpace.Id, space); - } - - [HttpGet] - [Route("/customers/{customerId}/spaces/{spaceId}")] - public IActionResult Spaces(int customerId, int spaceId) - { - var space = model.Spaces.SingleOrDefault(s => s.CustomerId == customerId && s.ModelId == spaceId); - if (space == null) - { - return NotFound(); - } - return Ok(space); - } - -} diff --git a/src/protagonist/DLCS.Mock/Controllers/DlcsApiController.cs b/src/protagonist/DLCS.Mock/Controllers/DlcsApiController.cs deleted file mode 100644 index a305538b1..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/DlcsApiController.cs +++ /dev/null @@ -1,24 +0,0 @@ -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class DlcsApiController : ControllerBase -{ - private readonly MockModel model; - - public DlcsApiController( - MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/")] - public EntryPoint Index() - { - return new EntryPoint(model.BaseUrl); - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/DocumentationController.cs b/src/protagonist/DLCS.Mock/Controllers/DocumentationController.cs deleted file mode 100644 index 6b5bdbbbb..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/DocumentationController.cs +++ /dev/null @@ -1,322 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using DLCS.Mock.ApiApp; -using Hydra; -using Hydra.Model; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class DocumentationController : ControllerBase -{ - private readonly MockModel model; - private readonly IWebHostEnvironment hostEnvironment; - private static Dictionary _supportedClasses; - - public DocumentationController( - MockModel model, - IWebHostEnvironment hostEnvironment) - { - this.model = model; - this.hostEnvironment = hostEnvironment; - } - - [HttpGet] - [Route("/vocab/{format}")] - public IActionResult Vocab(string format = null) - { - EnsureClasses(); - var classes = _supportedClasses.Values.Cast().ToArray(); - var vocabId = model.BaseUrl + "/vocab#"; - var vocab = new ApiDocumentation(vocabId, vocabId, classes); - if (format != null) - { - string docRoot = Path.Combine(hostEnvironment.WebRootPath, "api-generated-docs"); - var result = GetContentResult(vocab, format, docRoot); - // If we return this directly we can't set the encoding - return Content(result.Content, result.ContentType, Encoding.UTF8); - } - - return Ok(vocab); - } - - private static readonly object InitLock = new object(); - - private void EnsureClasses() - { - if (_supportedClasses == null) - { - lock (InitLock) - { - if (_supportedClasses == null) - { - _supportedClasses = - AttributeUtil.GetAttributeMap("DLCS.HydraModel", typeof(HydraClassAttribute)); - } - } - } - } - - - private ContentResult GetContentResult(ApiDocumentation vocab, string format, string docDir) - { - var sbMain = new StringBuilder(); - sbMain.Heading(format, 1, "Vocab"); - foreach (var clazz in vocab.SupportedClasses) - { - var sb = new StringBuilder(); - sb.Heading(format, 1, clazz.Label); - if (!string.IsNullOrWhiteSpace(clazz.UnstableNote)) - { - sb.Para(format, clazz.UnstableNote, true); - } - - sb.Para(format, clazz.Description); - sb.Code(format, clazz.UriTemplate); - if (clazz.SupportedOperations != null && clazz.SupportedOperations.Length > 0) - { - sb.Heading(format, 2, "Supported operations"); - // sb.Code(format, clazz.UriTemplate); - AppendSupportedOperationsTable(sb, format, clazz.SupportedOperations); - } - - if (clazz.SupportedProperties != null && clazz.SupportedProperties.Length > 0) - { - sb.Heading(format, 2, "Supported properties"); - foreach (SupportedProperty prop in clazz.SupportedProperties) - { - var linkProp = prop.Property as HydraLinkProperty; - if (linkProp != null) - { - sb.Heading(format, 3, prop.Title + " (🔗)"); - } - else - { - sb.Heading(format, 3, prop.Title); - } - - sb.Para(format, prop.Description); - if (!string.IsNullOrWhiteSpace(prop.UnstableNote)) - { - sb.Para(format, prop.UnstableNote, true); - } - - sb.StartTable(format, "domain", "range", "readonly", "writeonly"); - sb.TableRow(format, NameSpace(prop.Property.Domain), NameSpace(prop.Property.Range), - prop.ReadOnly.ToString(), prop.WriteOnly.ToString()); - sb.EndTable(format); - if (linkProp != null) - { - sb.Code(format, clazz.UriTemplate + "/" + linkProp.Label); - AppendSupportedOperationsTable(sb, format, linkProp.SupportedOperations); - } - } - } - - string classDoc = sb.ToString(); - WriteDocToDisk(format, docDir, clazz, classDoc); - sbMain.Append(classDoc); - } - - return new ContentResult {Content = sbMain.ToString(), ContentType = "text/" + format}; - } - - private static void WriteDocToDisk(string format, string docDir, Class clazz, string classDoc) - { - string extension = "." + VocabHelpers.GetExtension(format); - var path = Path.Combine(docDir, clazz.Label + extension); - System.IO.File.WriteAllText(path, classDoc); - } - - private void AppendSupportedOperationsTable(StringBuilder sb, string format, Operation[] supportedOperations) - { - if (supportedOperations != null && supportedOperations.Length > 0) - { - sb.StartTable(format, "Method", "Label", "Expects", "Returns", "Statuses"); - foreach (var op in supportedOperations) - { - string statuses = ""; - if (op.StatusCodes != null && op.StatusCodes.Length > 0) - { - statuses = string.Join(", ", - op.StatusCodes.Select(code => code.StatusCode + " " + code.Description)); - } - - sb.TableRow(format, op.Method, op.Label, NameSpace(op.Expects), NameSpace(op.Returns), statuses); - } - - sb.EndTable(format); - } - } - - public static string NameSpace(string s) - { - return Names.GetNamespacedVersion(s); - } -} - - - - -public static class VocabHelpers -{ - private const string Markdown = "markdown"; - - public static string GetExtension(string format) - { - if (format == Markdown) return "md"; - return "html"; - } - - public static void Heading(this StringBuilder sb, string format, int level, string text) - { - sb.AppendLine(); - if (format == Markdown) - { - sb.AppendLine(new string('#', level) + " " + text); - } - else - { - sb.AppendFormat("{1}", level, text); - sb.AppendLine(); - } - sb.AppendLine(); - } - - public static void Para(this StringBuilder sb, string format, string text, bool bold=false) - { - if (format == Markdown) - { - if (bold) - { - sb.AppendFormat("**{0}**", text); - sb.AppendLine(); - } - else - { - sb.AppendLine(text); - } - } - else - { - if (bold) - { - sb.AppendFormat("

{0}

", text); - } - else - { - sb.AppendFormat("

{0}

", text); - } - } - sb.AppendLine(); - } - - public static void NewLine(this StringBuilder sb, string format) - { - if (format == Markdown) - { - sb.AppendLine(); - } - else - { - sb.AppendLine("
"); - } - - } - - public static void StartTable(this StringBuilder sb, string format, params string[] headings) - { - sb.AppendLine(); - if (format == Markdown) - { - foreach (var heading in headings) - { - sb.Append("|" + heading); - } - sb.AppendLine("|"); - foreach (var heading in headings) - { - sb.Append("|--"); - } - sb.AppendLine("|"); - } - else - { - sb.AppendLine(""); - foreach (var heading in headings) - { - sb.AppendFormat("", heading); - } - sb.AppendLine(""); - } - } - - public static void TableRow(this StringBuilder sb, string format, params string[] cells) - { - if (format == Markdown) - { - foreach (var cell in cells) - { - var text = cell; - if (string.IsNullOrWhiteSpace(text)) - text = " "; - sb.Append("|" + text); - } - sb.AppendLine("|"); - } - else - { - sb.AppendLine(""); - foreach (var cell in cells) - { - sb.AppendFormat("", cell); - } - sb.AppendLine(""); - } - } - - public static void EndTable(this StringBuilder sb, string format) - { - if (format == Markdown) - { - } - else - { - sb.AppendLine("
{0}
{0}
"); - } - sb.AppendLine(); - } - - public static void Code(this StringBuilder sb, string format, string code) - { - sb.AppendLine(); - if (format == Markdown) - { - sb.AppendLine("```"); - sb.AppendLine(code); - sb.AppendLine("```"); - } - else - { - sb.AppendFormat("
{0}
", code); - sb.AppendLine("
"); - } - sb.AppendLine(); - } - - public static void Bold(this StringBuilder sb, string format, string text) - { - if (format == Markdown) - { - sb.AppendFormat("**{0}**", text); - } - else - { - sb.AppendFormat("{0}", text); - } - } -} diff --git a/src/protagonist/DLCS.Mock/Controllers/ImageOptimisationPoliciesController.cs b/src/protagonist/DLCS.Mock/Controllers/ImageOptimisationPoliciesController.cs deleted file mode 100644 index 99beacc88..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/ImageOptimisationPoliciesController.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class ImageOptimisationPoliciesController : ControllerBase -{ - private readonly MockModel model; - - public ImageOptimisationPoliciesController(MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/imageOptimisationPolicies")] - public HydraCollection Index() - { - var imageOptimisationPolicies = model.ImageOptimisationPolicies.ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = imageOptimisationPolicies, - TotalItems = imageOptimisationPolicies.Length, - Id = Request.GetDisplayUrl() - }; - } - - - [HttpGet] - [Route("/imageOptimisationPolicies/{id}")] - public IActionResult Index(string id) - { - var iop = model.ImageOptimisationPolicies.SingleOrDefault( - p => p.ModelId == id); - if (iop != null) - { - return Ok(iop); - } - return NotFound(); - } - -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/OriginStrategiesController.cs b/src/protagonist/DLCS.Mock/Controllers/OriginStrategiesController.cs deleted file mode 100644 index 719007c7d..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/OriginStrategiesController.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class OriginStrategiesController : ControllerBase -{ - private readonly MockModel model; - - public OriginStrategiesController(MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/originStrategies")] - public HydraCollection Index() - { - var originStrategies = model.OriginStrategies.ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = originStrategies, - TotalItems = originStrategies.Length, - Id = Request.GetDisplayUrl() - }; - } - - - [HttpGet] - [Route("/originStrategies/{id}")] - public IActionResult Index(string id) - { - var originStrategy = model.OriginStrategies.SingleOrDefault(os => os.ModelId == id); - if (originStrategy != null) - { - return Ok(originStrategy); - } - return NotFound(); - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/PortalRolesController.cs b/src/protagonist/DLCS.Mock/Controllers/PortalRolesController.cs deleted file mode 100644 index 918140d1b..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/PortalRolesController.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class PortalRolesController : ControllerBase -{ - private readonly MockModel model; - - public PortalRolesController(MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/portalRoles")] - public HydraCollection Index() - { - var portalRoles = model.PortalRoles.ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = portalRoles, - TotalItems = portalRoles.Length, - Id = Request.GetDisplayUrl() - }; - } - - [HttpGet] - [Route("/portalRoles/{id}")] - public IActionResult Index(string id) - { - var portalRole = model.PortalRoles.SingleOrDefault(pr => pr.ModelId == id); - if (portalRole != null) - { - return Ok(portalRole); - } - return NotFound(); - } - - [HttpGet] - [Route("/customers/{customerId}/portalUsers/{portalUserId}/roles")] - public HydraCollection RolesForUser(int customerId, string portalUserId) - { - var userid = Request.GetDisplayUrl().Replace("/roles", ""); - // need to make this use last part.,, - var roleIdsForUser = model.PortalUserRoles[userid]; - var roles = model.PortalRoles.Where(pr => roleIdsForUser.Contains(pr.Id)).ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = roles, - TotalItems = roles.Length, - Id = Request.GetDisplayUrl() - }; - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/QueueController.cs b/src/protagonist/DLCS.Mock/Controllers/QueueController.cs deleted file mode 100644 index 9662c74a9..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/QueueController.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class QueueController : ControllerBase -{ - private readonly MockModel model; - - public QueueController( - MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/customers/{customerId}/queue")] - public IActionResult Queue(int customerId) - { - var queue = model.Queues.SingleOrDefault(q => q.CustomerId == customerId); - if (queue == null) - { - return NotFound(); - } - return Ok(queue); - } - - [HttpPost] - [Route("/customers/{customerId}/queue")] - public Batch Index(int customerId, [FromBody] HydraCollection images) - { - List initialisedImages = new List(); - - var newBatchId = model.Batches.Select(b => b.ModelId).Max() + 1; - var batch = new Batch(model.BaseUrl, newBatchId, customerId, DateTime.UtcNow); - model.Batches.Add(batch); - foreach (var incomingImage in images.Members) - { - var newImage = MockHelp.MakeImage(model.BaseUrl, customerId, incomingImage.Space.GetValueOrDefault(), incomingImage.ModelId, - DateTime.UtcNow, incomingImage.Origin, - 0, 0, incomingImage.MaxUnauthorised, null, null, null, true, null, - incomingImage.Tags, incomingImage.String1, incomingImage.String2, incomingImage.String3, - incomingImage.Number1, incomingImage.Number2, incomingImage.Number3, - model.ImageOptimisationPolicies.First().Id, - model.ThumbnailPolicies.First().Id); - initialisedImages.Add(newImage); - } - model.Images.AddRange(initialisedImages); - model.BatchImages.Add(batch.Id, initialisedImages.Select(im => im.Id).ToList()); - return batch; - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/SpaceImagesController.cs b/src/protagonist/DLCS.Mock/Controllers/SpaceImagesController.cs deleted file mode 100644 index 898a15c13..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/SpaceImagesController.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class SpaceImagesController : ControllerBase -{ - private readonly MockModel model; - - public SpaceImagesController( - MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/customers/{customerId}/spaces/{spaceId}/images/{id?}")] - public IActionResult Image(int customerId, int spaceId, string? id = null) - { - if (string.IsNullOrWhiteSpace(id)) - { - var images = model.Images.Where(im => im.CustomerId == customerId && im.Space == spaceId).ToList(); - var string1 = Request.Query["string1"]; - if (!string.IsNullOrWhiteSpace(string1)) - { - images = images.Where(im => im.String1 == string1).ToList(); - } - AutoAdvance(images); - var hc = new HydraCollection {Members = images.ToArray()}; - //var hc = new Collection(); - //hc.Members = images.Select(im => im.GetCollectionForm()).ToArray(); - hc.TotalItems = hc.Members.Length; - hc.Id = Request.GetDisplayUrl(); - return Ok(hc); - } - else - { - var image = model.Images.SingleOrDefault( - im => im.CustomerId == customerId - && im.Space == spaceId - && im.ModelId == id); - return Ok(image); - } - } - - private void AutoAdvance(List images) - { - var now = DateTime.UtcNow; - var tenSeconds = new TimeSpan(0, 0, 10); - foreach (var image in images) - { - if (!image.Queued.HasValue) - { - if (now - image.Created > tenSeconds) - { - image.Queued = now; - } - } - else if (!image.Dequeued.HasValue) - { - if (now - image.Queued > tenSeconds) - { - image.Dequeued = now; - } - } - else if (!image.Finished.HasValue) - { - if (now - image.Dequeued > tenSeconds) - { - image.Finished = now; - } - } - } - } - - //[HttpGet] - //// GET: SpaceImages - //public Collection Image(int customerId, int spaceId, string string1 = null) - //{ - // var images = GetModel().Images.Where(im => im.CustomerId == customerId && im.Space == spaceId); - // if (string1 != null) - // { - // images = images.Where(im => im.String1 == string1); - // } - // var hc = new Collection(); - // hc.Members = images.ToArray(); - // hc.TotalItems = hc.Members.Length; - // hc.Id = Request.RequestUri.ToString(); - // return hc; - //} - - [HttpPut] - [Route("/customers/{customerId}/spaces/{spaceId}/images/{id}")] - public Image Image(int customerId, int spaceId, string id, [FromBody]Image incomingImage) - { - var newImage = MockHelp.MakeImage(model.BaseUrl, customerId, spaceId, incomingImage.ModelId, - DateTime.UtcNow, incomingImage.Origin, - 0, 0, incomingImage.MaxUnauthorised, null, null, null, true, null, - incomingImage.Tags, incomingImage.String1, incomingImage.String2, incomingImage.String3, - incomingImage.Number1, incomingImage.Number2, incomingImage.Number3, - model.ImageOptimisationPolicies.First().Id, - model.ThumbnailPolicies.First().Id); - model.Images.Add(newImage); - return newImage; - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Controllers/ThumbnailPoliciesController.cs b/src/protagonist/DLCS.Mock/Controllers/ThumbnailPoliciesController.cs deleted file mode 100644 index 33d02a620..000000000 --- a/src/protagonist/DLCS.Mock/Controllers/ThumbnailPoliciesController.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Linq; -using DLCS.HydraModel; -using DLCS.Mock.ApiApp; -using Hydra.Collections; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace DLCS.Mock.Controllers; - -[ApiController] -public class ThumbnailPoliciesController : ControllerBase -{ - private readonly MockModel model; - - public ThumbnailPoliciesController(MockModel model) - { - this.model = model; - } - - [HttpGet] - [Route("/thumbnailPolicies")] - public HydraCollection Index() - { - var thumbnailPolicies = model.ThumbnailPolicies.ToArray(); - - return new HydraCollection - { - WithContext = true, - Members = thumbnailPolicies, - TotalItems = thumbnailPolicies.Length, - Id = Request.GetDisplayUrl() - }; - } - - - [HttpGet] - [Route("/thumbnailPolicies/{id}")] - public IActionResult Index(string id) - { - var tp = model.ThumbnailPolicies.SingleOrDefault(p => p.ModelId == id); - if (tp != null) - { - return Ok(tp); - } - return NotFound(); - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/DLCS.Mock.csproj b/src/protagonist/DLCS.Mock/DLCS.Mock.csproj deleted file mode 100644 index 5a9f470e0..000000000 --- a/src/protagonist/DLCS.Mock/DLCS.Mock.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - enable - - - - - - - - - - - - - - - - diff --git a/src/protagonist/DLCS.Mock/Program.cs b/src/protagonist/DLCS.Mock/Program.cs deleted file mode 100644 index 834923e46..000000000 --- a/src/protagonist/DLCS.Mock/Program.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace DLCS.Mock; - -public class Program -{ - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/Properties/launchSettings.json b/src/protagonist/DLCS.Mock/Properties/launchSettings.json deleted file mode 100644 index 8a6494481..000000000 --- a/src/protagonist/DLCS.Mock/Properties/launchSettings.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:8633", - "sslPort": 44388 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "DLCS.Mock": { - "commandName": "Project", - "dotnetRunMessages": "true", - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/src/protagonist/DLCS.Mock/Startup.cs b/src/protagonist/DLCS.Mock/Startup.cs deleted file mode 100644 index 04d39a3e2..000000000 --- a/src/protagonist/DLCS.Mock/Startup.cs +++ /dev/null @@ -1,53 +0,0 @@ -using DLCS.Mock.ApiApp; -using Hydra; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.OpenApi.Models; - -namespace DLCS.Mock; - -public class Startup -{ - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddSingleton(); - services.AddControllers(options => - { - options.Filters.Add(typeof(AddHydraApiHeaderFilter)); - }) - .AddNewtonsoftJson(options => - { - var jsonSettings = options.SerializerSettings; - jsonSettings.ApplyHydraSerializationSettings(); - }); - services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "DLCS.Mock", Version = "v1"}); }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseSwagger(); - app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DLCS.Mock v1")); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - app.UseRouting(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); - } -} \ No newline at end of file diff --git a/src/protagonist/DLCS.Mock/appsettings.json b/src/protagonist/DLCS.Mock/appsettings.json deleted file mode 100644 index d9d9a9bff..000000000 --- a/src/protagonist/DLCS.Mock/appsettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" -} diff --git a/src/protagonist/protagonist.sln b/src/protagonist/protagonist.sln index 608d61583..c796866dd 100644 --- a/src/protagonist/protagonist.sln +++ b/src/protagonist/protagonist.sln @@ -47,8 +47,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DLCS.HydraModel", "DLCS.Hyd EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hydra", "Hydra\Hydra.csproj", "{AD70A659-1EA7-4DCD-8FA6-265210E5CF25}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DLCS.Mock", "DLCS.Mock\DLCS.Mock.csproj", "{963A0ED4-2836-42F0-9254-E405626EA7CE}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DLCS.AWS", "DLCS.AWS\DLCS.AWS.csproj", "{5AE90CE9-26E2-4C4B-85F9-78BC4F406667}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DLCS.AWS.Tests", "DLCS.AWS.Tests\DLCS.AWS.Tests.csproj", "{1E5EB337-60AA-4D86-BFFC-30FB747F9B25}" @@ -157,10 +155,6 @@ Global {AD70A659-1EA7-4DCD-8FA6-265210E5CF25}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD70A659-1EA7-4DCD-8FA6-265210E5CF25}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD70A659-1EA7-4DCD-8FA6-265210E5CF25}.Release|Any CPU.Build.0 = Release|Any CPU - {963A0ED4-2836-42F0-9254-E405626EA7CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {963A0ED4-2836-42F0-9254-E405626EA7CE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {963A0ED4-2836-42F0-9254-E405626EA7CE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {963A0ED4-2836-42F0-9254-E405626EA7CE}.Release|Any CPU.Build.0 = Release|Any CPU {5AE90CE9-26E2-4C4B-85F9-78BC4F406667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5AE90CE9-26E2-4C4B-85F9-78BC4F406667}.Debug|Any CPU.Build.0 = Debug|Any CPU {5AE90CE9-26E2-4C4B-85F9-78BC4F406667}.Release|Any CPU.ActiveCfg = Release|Any CPU