diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..875f551323e15092ecf59ce40d12e3e1206d8f3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,276 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Database connection for t4 class generation from database +**/*.generated.cs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user +Resharper + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +#cake +tools/* +!tools/packages.config +dist/ + +#linq2db +src/.tools/ + +# Dotnet Tool Manifest +.config/* diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..555722dfd87d8e199bea6bda9b054ad45e674748 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,24 @@ +include: + - project: coscine/tools/gitlab-ci-templates + file: + - /dotnet.yml + +stages: + - build + - test + - publish + +variables: + DOTNET_MAIN_PROJECT_FOLDER: PIDMigrator + +build-branch: + extends: .build-branch + +test: + extends: .test + +publish-gitlab-release: + extends: .publish-gitlab-release + +publish: + extends: .publish-artifact-release diff --git a/GitVersion.yml b/GitVersion.yml new file mode 100644 index 0000000000000000000000000000000000000000..1bdc0fe219f5f35d8a024a66d9fd715f44539640 --- /dev/null +++ b/GitVersion.yml @@ -0,0 +1,7 @@ +mode: ContinuousDeployment +next-version: 1.0.0 +major-version-bump-message: 'Breaking:' +minor-version-bump-message: '(Update|New):' +patch-version-bump-message: 'Fix:' +no-bump-message: '.*' +commit-message-incrementing: Enabled \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d5fdbb17f8bd9bcbd119191c248a3bebaddc9133 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 RWTH Aachen University + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 3b9d9b6fb55700b87de155d23f2de7b70d33f1fc..88160fb34f629bd33369835a65638e9b6cdf2bcd 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,3 @@ # PID Record Migrator - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://git.rwth-aachen.de/coscine/backend/scripts/pid-record-migrator.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://git.rwth-aachen.de/coscine/backend/scripts/pid-record-migrator/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +This repository migrates all existing PIDs to a FAIR Digital Object. diff --git a/nunit3-junit.xslt b/nunit3-junit.xslt new file mode 100644 index 0000000000000000000000000000000000000000..bf69bdb1d2cd6fc2fdbeb915b4eb6732f720848e --- /dev/null +++ b/nunit3-junit.xslt @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Taken from: https://github.com/nunit/nunit-transforms/tree/master/nunit3-junit +--> +<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> + <xsl:output method="xml" indent="yes"/> + + <xsl:template match="/test-run"> + <testsuites tests="{@testcasecount}" failures="{@failed}" disabled="{@skipped}" time="{@duration}"> + <xsl:apply-templates/> + </testsuites> + </xsl:template> + + <xsl:template match="test-suite"> + <xsl:if test="test-case"> + <testsuite tests="{@testcasecount}" time="{@duration}" errors="{@testcasecount - @passed - @skipped - @failed}" failures="{@failed}" skipped="{@skipped}" timestamp="{@start-time}"> + <xsl:attribute name="name"> + <xsl:for-each select="ancestor-or-self::test-suite/@name"> + <xsl:value-of select="concat(., '.')"/> + </xsl:for-each> + </xsl:attribute> + <xsl:apply-templates select="test-case"/> + </testsuite> + <xsl:apply-templates select="test-suite"/> + </xsl:if> + <xsl:if test="not(test-case)"> + <xsl:apply-templates/> + </xsl:if> + </xsl:template> + + <xsl:template match="test-case"> + <testcase name="{@name}" assertions="{@asserts}" time="{@duration}" status="{@result}" classname="{@classname}"> + <xsl:if test="@runstate = 'Skipped' or @runstate = 'Ignored'"> + <skipped/> + </xsl:if> + + <xsl:apply-templates/> + </testcase> + </xsl:template> + + <xsl:template match="command-line"/> + <xsl:template match="settings"/> + + <xsl:template match="output"> + <system-out> + <xsl:value-of select="."/> + </system-out> + </xsl:template> + + <xsl:template match="stack-trace"> + </xsl:template> + + <xsl:template match="test-case/failure"> + <failure message="{./message}"> + <xsl:value-of select="./stack-trace"/> + </failure> + </xsl:template> + + <xsl:template match="test-suite/failure"/> + + <xsl:template match="test-case/reason"> + <skipped message="{./message}"/> + </xsl:template> + + <xsl:template match="test-case/assertions"> + </xsl:template> + + <xsl:template match="test-suite/reason"/> + + <xsl:template match="properties"/> +</xsl:stylesheet> \ No newline at end of file diff --git a/src/.config/dotnet-tools.json b/src/.config/dotnet-tools.json new file mode 100644 index 0000000000000000000000000000000000000000..6528a5153127b51ab8ecd2460e6c473ad2e545cf --- /dev/null +++ b/src/.config/dotnet-tools.json @@ -0,0 +1,12 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "0.27.2", + "commands": [ + "dotnet-csharpier" + ] + } + } +} \ No newline at end of file diff --git a/src/PID Record Migrator.sln b/src/PID Record Migrator.sln new file mode 100644 index 0000000000000000000000000000000000000000..b0da10380e17c006d183fe1bd5f97838e7ff28e6 --- /dev/null +++ b/src/PID Record Migrator.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33627.172 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PID Record Migrator", "PID Record Migrator\PID Record Migrator.csproj", "{447E2FF2-D92C-4661-A6DE-C4283970A7A6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {447E2FF2-D92C-4661-A6DE-C4283970A7A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {447E2FF2-D92C-4661-A6DE-C4283970A7A6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {447E2FF2-D92C-4661-A6DE-C4283970A7A6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {447E2FF2-D92C-4661-A6DE-C4283970A7A6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8297B36D-812B-4125-8F78-80B13A69331F} + EndGlobalSection +EndGlobal diff --git a/src/PID Record Migrator/PID Record Migrator.csproj b/src/PID Record Migrator/PID Record Migrator.csproj new file mode 100644 index 0000000000000000000000000000000000000000..297b88b02b06b15a2c0d6f204028d7de2b10595e --- /dev/null +++ b/src/PID Record Migrator/PID Record Migrator.csproj @@ -0,0 +1,19 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net8.0</TargetFramework> + <RootNamespace>PID_Record_Migrator</RootNamespace> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Coscine.ApiClient" Version="1.5.0-alpha0002" /> + <PackageReference Include="Coscine.ApiClient.Core" Version="1.5.0-alpha0002" /> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" /> + <PackageReference Include="Winton.Extensions.Configuration.Consul" Version="3.4.0" /> + </ItemGroup> + +</Project> diff --git a/src/PID Record Migrator/PidHandles.cs b/src/PID Record Migrator/PidHandles.cs new file mode 100644 index 0000000000000000000000000000000000000000..dd428953b04693f1052eeaed00533496bb729a10 --- /dev/null +++ b/src/PID Record Migrator/PidHandles.cs @@ -0,0 +1,39 @@ +namespace Coscine.Api.Core.Shared; + +/// <summary> +/// Contains Handles relevant to the Coscine PID Record. +/// All values are entries in the DTR:https://dtr-test.pidconsortium.eu/#objects/21.T11148/8882327b7c25331e3cdd +/// </summary> +public static class PidHandles +{ // The general handle of the Kernel Information Profile type + public static readonly string KernelInformationProfileHandle = "21.T11148/076759916209e5d62bd5"; + + // The handle of the Coscine Kernel Information Profile type + public static readonly string CoscineKernelInformationProfileHandle = "21.T11148/8882327b7c25331e3cdd"; + + // The handle of the date created type + public static readonly string DateCreatedHandle = "21.T11148/aafd5fb4c7222e2d950a"; + + // The handle of the digital object location type + public static readonly string DigitalObjectLocationHandle = "21.T11148/b8457812905b83046284"; + + // The handle of the digital object type + public static readonly string DigitalObjectTypeHandle = "21.T11148/1c699a5d1b4ad3ba4956"; + + // The handle of the digital object value: resource + // DTR entry: https://dtr-test.pidconsortium.eu/#objects/21.T11148/12aad485b74d04f584c1 + public static readonly string DigitalObjectTypeResourceHandle = "21.T11148/12aad485b74d04f584c1"; + + // The handle of the digital object value: project + // DTR entry: https://dtr-test.pidconsortium.eu/#objects/21.T11148/0f13b0a83bd926fe269f + public static readonly string DigitalObjectTypeProjectHandle = "21.T11148/0f13b0a83bd926fe269f"; + + // The handle of the license type + public static readonly string LicenseHandle = "21.T11148/2f314c8fe5fb6a0063a8"; + + // The handle of the contact type + public static readonly string ContactHandle = "21.T11148/1a73af9e7ae00182733b"; + + // The handle of the topic type + public static readonly string TopicHandle = "21.T11148/b415e16fbe4ca40f2270"; +} \ No newline at end of file diff --git a/src/PID Record Migrator/Program.cs b/src/PID Record Migrator/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..3d702cb98993a3ea367beaaccab9dbd1b2124bbe --- /dev/null +++ b/src/PID Record Migrator/Program.cs @@ -0,0 +1,382 @@ +using System.Web; +using Coscine.Api.Core.Shared; +using Coscine.ApiClient; +using Coscine.ApiClient.Core.Api; +using Coscine.ApiClient.Core.Client; +using Coscine.ApiClient.Core.Model; +using Microsoft.Extensions.Configuration; +using Winton.Extensions.Configuration.Consul; + +var _dummyMode = true; +_dummyMode = !(args.Length > 0 && args[0] == "--noDryRun"); + +// Console text output +Console.Write($"{new string('=', 80)}\n PID Record Migrator"); + +if (_dummyMode) +{ + Console.Write(" : DUMMY MODE"); +} +Console.WriteLine($"\n{new string('-', 80)}"); + +var configBuilder = new ConfigurationBuilder(); + +// Define the Consul URL +var consulUrl = Environment.GetEnvironmentVariable("CONSUL_URL") ?? "http://localhost:8500"; + +// Remove the default sources +configBuilder.Sources.Clear(); + +var configuration = configBuilder + .AddConsul( + "coscine/Coscine.Api/appsettings", + options => + { + options.ConsulConfigurationOptions = cco => cco.Address = new Uri(consulUrl); + options.Optional = true; + options.ReloadOnChange = true; + options.PollWaitTime = TimeSpan.FromSeconds(5); + options.OnLoadException = exceptionContext => exceptionContext.Ignore = true; + } + ) + .Build(); + +var apiConfiguration = new Configuration() +{ + BasePath = "http://localhost:7206/coscine", + ApiKeyPrefix = { { "Authorization", "Bearer" } }, + ApiKey = + { + { + "Authorization", + ApiConfigurationUtil.GenerateAdminToken(ApiConfigurationUtil.RetrieveJwtConfiguration()) + } + }, +}; + +var pidApi = new PidApi(apiConfiguration); + +Console.WriteLine($"- Collecting Coscine data ..."); + +var pids = await RequestUtil.WrapPagedRequest<PidDtoPagedResponse, PidDto>( + (currentPage) => + pidApi.GetPidsAsync( + includeProjects: true, + includeResources: true, + includeDeleted: false, + pageNumber: currentPage, + pageSize: 250 + ) +); +var proxyUrlString = + configuration.GetSection("ConnectionConfiguration").GetSection("ProxyUrl").Value + ?? throw new Exception("ConnectionConfiguration:ProxyUrl is not defined in the configuration!"); +var digitalObjectLocationUrlString = + configuration.GetSection("PidConfiguration").GetSection("digitalObjectLocationUrl").Value + ?? throw new Exception( + "PidConfiguration:DigitalObjectLocationUrl is not defined in the configuration!" + ); + +Console.WriteLine($"- Search yielded {pids.Count()} PID(s)"); + +var handleApi = new HandleApi(apiConfiguration); +var resourceApi = new ResourceApi(apiConfiguration); +var projectApi = new ProjectApi(apiConfiguration); +int updatedPidCount = 0; + +Console.WriteLine($"- Iterating through {pids.Count()} PID(s) ..."); +foreach (var pid in pids) +{ + // Check if there's an entry in the handle service + try + { + Console.WriteLine("- Find the PID in the handle service ..."); + var handle = (await handleApi.GetHandleAsync(pid.Prefix, pid.Suffix)).Data; + } + catch (Exception e) + { + Console.WriteLine( + $"└ The following PID: {pid.Suffix} could not be found in the handle service.\n {e.Message}\n" + ); + continue; + } + // Only update when PIDs are available + if (!_dummyMode) + { + Console.WriteLine($"- Updating Coscine PID ..."); + + try + { + // Check if project or resource + if (pid.Type.ToString()?.Equals("resource", StringComparison.OrdinalIgnoreCase) == true) + { + try + { + // Generate the PID record + var resourceHandleValues = await GenerateResourceHandleValuesAsync( + pid.Prefix, + Guid.Parse(pid.Suffix) + ); + // Send the update with the request content + await handleApi.UpdateHandleAsync( + pid.Prefix, + pid.Suffix, + new HandleForUpdateDto { Values = resourceHandleValues.ToList() } + ); + updatedPidCount++; + } + catch (Exception e) + { + Console.WriteLine( + $"└ Updating the following PID: {pid.Suffix} FAILED.\n {e.Message}\n" + ); + } + } + if (pid.Type.ToString()?.Equals("project", StringComparison.OrdinalIgnoreCase) == true) + { + try + { + // Generate the PID record + var projectHandleValues = await GenerateProjectHandleValuesAsync( + pid.Prefix, + Guid.Parse(pid.Suffix) + ); + // Send the update with the request content + await handleApi.UpdateHandleAsync( + pid.Prefix, + pid.Suffix, + new HandleForUpdateDto { Values = projectHandleValues.ToList() } + ); + updatedPidCount++; + } + catch (Exception e) + { + Console.WriteLine( + $"└ Updating the following PID: {pid.Suffix} FAILED.\n {e.Message}\n" + ); + } + } + } + catch (Exception e) + { + Console.WriteLine( + $"└ Updating the following PID: {pid.Suffix} FAILED.\n {e.Message}\n" + ); + Console.WriteLine($"└ Migration FAILED. {e.Message}"); + return; + } + } +} +Console.WriteLine($"Updated {updatedPidCount} Coscine PIDs\n"); +Console.WriteLine($"Finished"); + +async Task<IEnumerable<HandleValueForUpdateDto>> GenerateProjectHandleValuesAsync( + string prefix, + Guid suffix +) +{ + var handles = new List<HandleValueForUpdateDto>(); + + // Use the configuration to build necessary URLs and prefixes + var pid = $"{prefix.Trim('/')}/{suffix}"; + var baseUri = new Uri(proxyUrlString, UriKind.Absolute); + var digitalObjectLocationUri = new Uri(digitalObjectLocationUrlString, UriKind.Absolute); + var projectDto = (await projectApi.GetProjectAsync(suffix.ToString())).Data; + var isProjectPublic = + projectDto?.Visibility?.DisplayName.Equals("public", StringComparison.OrdinalIgnoreCase) + ?? false; + + var idx = 1; + + // Create the URL handle value + handles.Add( + new() + { + Idx = idx++, + Type = "URL", + ParsedData = new Uri(baseUri, $"/pid/?pid={HttpUtility.UrlEncode(pid)}") + } + ); + + // Create the kernel information profile handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.KernelInformationProfileHandle, + ParsedData = PidHandles.CoscineKernelInformationProfileHandle + } + ); + + // Create the date created handle value + if (projectDto.CreationDate is not null && isProjectPublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DateCreatedHandle, + ParsedData = projectDto.CreationDate + } + ); + } + + // Create the digital object location handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DigitalObjectLocationHandle, + ParsedData = new Uri( + digitalObjectLocationUri, + $"/coscine/api/v2/projects/{projectDto.Id}" + ) + } + ); + + // Create the digital object type handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DigitalObjectTypeHandle, + ParsedData = PidHandles.DigitalObjectTypeProjectHandle + } + ); + + // Create the topic (discipline) handle value + var disciplines = projectDto.Disciplines.Where(pd => pd.DisplayNameEn is not null).ToList(); + if (disciplines.Count != 0 && isProjectPublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.TopicHandle, + // NOTE: Consider adding all disciplines as a comma-separated string + ParsedData = disciplines[0].DisplayNameEn ?? string.Empty + } + ); + } + + // Create the contact (organizations) handle value + if (projectDto.Organizations.Count != 0 && isProjectPublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.ContactHandle, + // NOTE: Consider adding all institutes as a comma-separated string + ParsedData = projectDto.Organizations[0].Uri + } + ); + } + + return handles; +} + +async Task<IEnumerable<HandleValueForUpdateDto>> GenerateResourceHandleValuesAsync( + string prefix, + Guid suffix +) +{ + var handles = new List<HandleValueForUpdateDto>(); + + // Use the configuration to build necessary URLs and prefixes + var pid = $"{prefix.Trim('/')}/{suffix}"; + var baseUri = new Uri(proxyUrlString, UriKind.Absolute); + var digitalObjectLocationUri = new Uri(digitalObjectLocationUrlString, UriKind.Absolute); + var resourceDto = (await resourceApi.GetResourceAsync(suffix)).Data; + var isResourcePublic = + resourceDto?.Visibility?.DisplayName.Equals("public", StringComparison.OrdinalIgnoreCase) + ?? false; + + var idx = 1; + + // Create the URL handle value + handles.Add( + new() + { + Idx = idx++, + Type = "URL", + ParsedData = new Uri(baseUri, $"/pid/?pid={HttpUtility.UrlEncode(pid)}") + } + ); + + // Create the kernel information profile handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.KernelInformationProfileHandle, + ParsedData = PidHandles.CoscineKernelInformationProfileHandle + } + ); + + // Create the date created handle value + if (resourceDto.DateCreated is not null && isResourcePublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DateCreatedHandle, + ParsedData = resourceDto.DateCreated + } + ); + } + + // Create the digital object location handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DigitalObjectLocationHandle, + ParsedData = new Uri( + digitalObjectLocationUri, + $"/coscine/api/v2/resources/{resourceDto.Id}" + ) + } + ); + + // Create the digital object type handle value + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.DigitalObjectTypeHandle, + ParsedData = PidHandles.DigitalObjectTypeResourceHandle + } + ); + + // Create the topic (discipline) handle value + var disciplines = resourceDto.Disciplines.Where(rd => rd.DisplayNameEn is not null).ToList(); + if (disciplines.Count != 0 && isResourcePublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.TopicHandle, + // NOTE: Consider adding all disciplines as a comma-separated string + ParsedData = disciplines[0].DisplayNameEn ?? string.Empty + } + ); + } + + // Create the license handle value + if (resourceDto.License?.Url is not null && isResourcePublic) + { + handles.Add( + new() + { + Idx = idx++, + Type = PidHandles.LicenseHandle, + ParsedData = resourceDto.License.Url + } + ); + } + + return handles; +} diff --git a/src/PID Record Migrator/Properties/launchSettings.json b/src/PID Record Migrator/Properties/launchSettings.json new file mode 100644 index 0000000000000000000000000000000000000000..ff8537ba3652d766fccd0603b40c1bba98d1cdbd --- /dev/null +++ b/src/PID Record Migrator/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "PID Record Migrator": { + "commandName": "Project", + "commandLineArgs": "--noDryRun" + } + } +} \ No newline at end of file