labimotion 2.2.0.rc21 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 006f7a0d5c1bc994e1ed1be862881e579b83a91844e176858571471a4225a6e5
4
- data.tar.gz: 9d40a31313cc7717bd0a9cb971e457bc6c2ad93a3818a3ad305dec05ad9bc406
3
+ metadata.gz: 5fc8d83e6c643b284cb25c8dc42610d4b42f3e0af1efb8b355f63bb6a4e8212f
4
+ data.tar.gz: f69aff320a11b70bde5e0e5c5d4f4d621795fa8c98e4dc1a318edc8599a8a21c
5
5
  SHA512:
6
- metadata.gz: 399cb835f06e3cc7e30a8c59f3e64ae7738da938a7bb4a68e3ffd9c331854e36c84743b90a07769407c910d2b49042996734d2572517932a97869a18f0e6174b
7
- data.tar.gz: 8ce94d81213aba4205aff04328c3eba89ca095b84301ddf7eee22497e0964635a0998735175f47fa00642f4d47d481e9ef0aa95bb1b04357705a1c1ad21c3c6b
6
+ metadata.gz: 5fec969db1fb1e89052a70d7076c6e6a149e7ce37dec8fe8d2809b9588930a277b2d99895c503a82e69504ea6c2cc8b889245ede972437a9f34d560e26b3c8ae
7
+ data.tar.gz: 9c45faf9b917299fae8fd27f24886388a4b829ed00309a540dc3b0cf2cb7078c2740bc327807bd1374c81902056c66fd0d1b5282e01c5f66a0d6cac3e4e3fb39
@@ -69,6 +69,25 @@ module Labimotion
69
69
  end
70
70
  end
71
71
 
72
+ namespace :create_dataset_klass do
73
+ desc 'create a new, inactive Generic Dataset Klass for an ontology term'
74
+ params do
75
+ requires :ols_term_id, type: String, desc: 'Ontology term ID, e.g. CHMO:0000656'
76
+ requires :label, type: String, desc: 'Label'
77
+ optional :desc, type: String, desc: 'Description; the label when left out'
78
+ end
79
+ post do
80
+ # Datasets are otherwise seeded, never created in the Designer; only the dataset
81
+ # designers that LABIMOTION_ADMIN names may add one.
82
+ authenticate_admin!('datasets')
83
+ error!('401 Unauthorized', 401) unless Labimotion::HubPush.allowed?(current_user)
84
+
85
+ klass = create_dataset_klass(params, current_user)
86
+ { mc: 'ss00', msg: "#{klass.label} was created, inactive.",
87
+ data: Labimotion::DatasetKlassEntity.represent(klass) }
88
+ end
89
+ end
90
+
72
91
  namespace :find_template do
73
92
  desc 'Find best matching template for given OLS term ID'
74
93
  params do
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Labimotion
4
+ ## HubPushAPI
5
+ # The Hub side of handing a dataset template to another Chemotion ELN (see
6
+ # Labimotion::HubPush). Declared under `generic_dataset` beside GenericDatasetAPI; Grape merges
7
+ # both into one route table.
8
+ class HubPushAPI < Grape::API
9
+ resource :generic_dataset do
10
+ namespace :hub_push do
11
+ desc 'whether the current user may create dataset templates and push them to another ELN ' \
12
+ '(LABIMOTION_ADMIN)'
13
+ get :permission do
14
+ { mc: 'ss00', allowed: Labimotion::HubPush.allowed?(current_user) }
15
+ end
16
+
17
+ desc 'have another Chemotion ELN import a dataset template of this Hub'
18
+ params do
19
+ requires :id, type: Integer, desc: 'Dataset Klass ID on this instance'
20
+ requires :url, type: String, desc: 'Base address of the target ELN'
21
+ requires :username, type: String, desc: 'Target ELN account (email or name abbreviation)'
22
+ requires :password, type: String, desc: 'Target ELN password; used once, never stored'
23
+ end
24
+ post do
25
+ error!('401 Unauthorized', 401) unless Labimotion::HubPush.allowed?(current_user)
26
+
27
+ klass = Labimotion::DatasetKlass.find_by(id: params[:id])
28
+ error!('This dataset template does not exist.', 404) if klass.nil?
29
+
30
+ result = Labimotion::HubPush.new(klass: klass, url: params[:url], username: params[:username],
31
+ password: params[:password]).call
32
+ Labimotion::HubPush.audit(current_user, klass, result)
33
+ { mc: 'ss00', msg: result[:message], data: result }
34
+ rescue Labimotion::HubPush::Error => e
35
+ error!(e.message, 422)
36
+ rescue StandardError => e
37
+ Labimotion.log_exception(e, current_user)
38
+ raise e
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -10,6 +10,7 @@ module Labimotion
10
10
  mount Labimotion::GenericDatasetAPI
11
11
  mount Labimotion::SegmentAPI
12
12
  mount Labimotion::LabimotionHubAPI
13
+ mount Labimotion::HubPushAPI
13
14
  mount Labimotion::StandardLayerAPI
14
15
  mount Labimotion::VocabularyAPI
15
16
  mount Labimotion::UserAPI
@@ -8,7 +8,9 @@ module Labimotion
8
8
  # Grape route and helper DSL blocks are necessarily large.
9
9
  KLASS_TYPES = Labimotion::TemplateDoiHelpers::KLASS_BY_TYPE.keys.freeze
10
10
  # Publication fields exposed on the public (anonymous) DOI endpoints.
11
- PUBLIC_PUBLICATION_KEYS = %w[title description authors contributor license].freeze
11
+ # `contributor` (singular) is kept for DOIs released before contributors
12
+ # became a list — their snapshot still carries it.
13
+ PUBLIC_PUBLICATION_KEYS = %w[title description authors contributors contributor references license].freeze
12
14
 
13
15
  helpers do
14
16
  def resolve_klass!(type, id)
@@ -10,7 +10,9 @@ module Labimotion
10
10
  KLASS_BY_TYPE = Labimotion::TemplateDoiHelpers::KLASS_BY_TYPE
11
11
  KLASS_TYPES = KLASS_BY_TYPE.keys.freeze
12
12
  # Publication fields exposed alongside a template / its released DOIs.
13
- PUBLICATION_KEYS = %w[title description authors contributor license].freeze
13
+ # `contributor` (singular) is kept for DOIs released before contributors
14
+ # became a list — their snapshot still carries it.
15
+ PUBLICATION_KEYS = %w[title description authors contributors contributor references license].freeze
14
16
  # type => [revision model, foreign key to the klass]
15
17
  REVISION_BY_TYPE = {
16
18
  'element' => [::Labimotion::ElementKlassesRevision, :element_klass_id],
@@ -49,6 +49,35 @@ module Labimotion
49
49
  raise e
50
50
  end
51
51
 
52
+ # A prefix, a colon and a local ID, as in CHMO:0000656 — the form the dataset picker
53
+ # matches klasses by.
54
+ OLS_TERM_ID = /\A[A-Za-z][A-Za-z0-9_]*:[A-Za-z0-9_.-]+\z/
55
+
56
+ # A new dataset klass starts inactive, so the Hub leaves it out of its list until someone
57
+ # activates it, with an empty template released as its first revision, the way a new
58
+ # element klass starts.
59
+ def create_dataset_klass(params, current_user)
60
+ term = params[:ols_term_id].to_s.strip
61
+ label = params[:label].to_s.strip
62
+ validate_new_dataset_klass!(term, label)
63
+
64
+ uuid = SecureRandom.uuid
65
+ template = { 'uuid' => uuid, 'layers' => {}, 'select_options' => {}, 'klass' => 'DatasetKlass',
66
+ 'pkg' => Labimotion::Utils.pkg(nil) }
67
+ klass = Labimotion::DatasetKlass.create!(
68
+ ols_term_id: term, label: label, desc: params[:desc].to_s.strip.presence || label,
69
+ properties_template: template, properties_release: template, uuid: uuid, released_at: DateTime.now,
70
+ is_active: false, place: (Labimotion::DatasetKlass.with_deleted.maximum(:place) || 0) + 10,
71
+ created_by: current_user.id
72
+ )
73
+ klass.reload
74
+ klass.create_klasses_revision(current_user)
75
+ klass
76
+ rescue StandardError => e
77
+ Labimotion.log_exception(e, current_user)
78
+ raise e
79
+ end
80
+
52
81
  def find_best_match_template(ols_term_id)
53
82
  result = Labimotion::TemplateMatcher.find_best_match(ols_term_id)
54
83
  if result[:template]
@@ -60,6 +89,15 @@ module Labimotion
60
89
 
61
90
  private
62
91
 
92
+ # Soft-deleted klasses still hold their term in the unique index, so they count.
93
+ def validate_new_dataset_klass!(term, label)
94
+ error!("'#{term}' is not an ontology term ID like CHMO:0000656.", 422) unless OLS_TERM_ID.match?(term)
95
+ error!('Enter a label.', 422) if label.empty?
96
+ return unless Labimotion::DatasetKlass.with_deleted.exists?(ols_term_id: term)
97
+
98
+ error!("A dataset template for #{term} already exists.", 422)
99
+ end
100
+
63
101
  def build_template_response(template, match_type, info_messages)
64
102
  response = {
65
103
  error: '',
@@ -15,8 +15,8 @@
15
15
  <% if creator['orcid'].present? %>
16
16
  <nameIdentifier schemeURI="https://orcid.org/" nameIdentifierScheme="ORCID"><%= creator['orcid'] %></nameIdentifier>
17
17
  <% end %>
18
- <% if creator['affiliation'].present? %>
19
- <affiliation><%= creator['affiliation'] %></affiliation>
18
+ <% if creator['affiliation'].present? || creator['ror'].present? %>
19
+ <affiliation<% if creator['ror'].present? %> affiliationIdentifier="<%= creator['ror'] %>" affiliationIdentifierScheme="ROR" schemeURI="https://ror.org"<% end %>><%= creator['affiliation'] %></affiliation>
20
20
  <% end %>
21
21
  </creator>
22
22
  <% end %>
@@ -29,18 +29,30 @@
29
29
  <subjects>
30
30
  <subject>Chemistry</subject>
31
31
  </subjects>
32
- <% if contributor %>
32
+ <% if contributors.any? %>
33
33
  <contributors>
34
- <contributor contributorType="Researcher">
34
+ <% contributors.each do |contributor| %>
35
+ <contributor contributorType="<%= contributor['contributorType'] %>">
35
36
  <contributorName nameType="Personal"><%= contributor['familyName'] %>, <%= contributor['givenName'] %></contributorName>
36
37
  <givenName><%= contributor['givenName'] %></givenName>
37
38
  <familyName><%= contributor['familyName'] %></familyName>
38
39
  <% if contributor['orcid'].present? %>
39
40
  <nameIdentifier schemeURI="https://orcid.org/" nameIdentifierScheme="ORCID"><%= contributor['orcid'] %></nameIdentifier>
40
41
  <% end %>
42
+ <% if contributor['affiliation'].present? || contributor['ror'].present? %>
43
+ <affiliation<% if contributor['ror'].present? %> affiliationIdentifier="<%= contributor['ror'] %>" affiliationIdentifierScheme="ROR" schemeURI="https://ror.org"<% end %>><%= contributor['affiliation'] %></affiliation>
44
+ <% end %>
41
45
  </contributor>
46
+ <% end %>
42
47
  </contributors>
43
48
  <% end %>
49
+ <% if references.any? %>
50
+ <relatedIdentifiers>
51
+ <% references.each do |reference| %>
52
+ <relatedIdentifier relatedIdentifierType="DOI" relationType="References">https://dx.doi.org/<%= reference['doi'] %></relatedIdentifier>
53
+ <% end %>
54
+ </relatedIdentifiers>
55
+ <% end %>
44
56
  <language>en</language>
45
57
  <resourceType resourceTypeGeneral="Model"><%= resource_label %></resourceType>
46
58
  <version><%= version %></version>
@@ -0,0 +1,247 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'openssl'
6
+ require 'uri'
7
+
8
+ module Labimotion
9
+ ## HubPush
10
+ # Hands a dataset template of this LabIMotion Hub to another Chemotion ELN that does not
11
+ # have it yet. The target needs nothing new: every step is a route it already serves
12
+ # (labimotion 2.3 included) —
13
+ # 1. POST public/token username + password -> JWT
14
+ # 2. GET generic_dataset/list_klass what the target holds for the term already
15
+ # 3. POST generic_dataset/create_repo_klass the target imports the template by identifier
16
+ # In step 3 the target downloads the template itself, from the Hub it is built against
17
+ # (Labimotion::TemplateHub::TARGET, www.chemotion-repository.net in production), so a push
18
+ # only lands when it is sent from that Hub. The Hub's fetch route serves a template by
19
+ # identifier whether or not it is active, so a template kept inactive here, and so left out
20
+ # of the Hub's list, can still be handed to the instances it is meant for.
21
+ class HubPush
22
+ ENV_KEY = 'LABIMOTION_ADMIN'
23
+ OPEN_TIMEOUT = 10
24
+ READ_TIMEOUT = 60
25
+
26
+ # A refusal the user can act on. Its message is shown to them as is, so it must never
27
+ # carry the password.
28
+ class Error < StandardError; end
29
+
30
+ # Who may create dataset templates and push them to another ELN: LABIMOTION_ADMIN, a comma-
31
+ # or space-separated list of the identifiers a user signs in with — an email (compared
32
+ # case-insensitively, the way Devise stores it) or a name abbreviation (compared exactly).
33
+ # Unset or empty means nobody.
34
+ def self.allowed?(user)
35
+ return false if user.nil?
36
+
37
+ email = user.respond_to?(:email) ? user.email.to_s.downcase : ''
38
+ abbreviation = user.respond_to?(:name_abbreviation) ? user.name_abbreviation.to_s : ''
39
+ admin_entries.any? do |entry|
40
+ entry.include?('@') ? entry.downcase == email : entry == abbreviation
41
+ end
42
+ end
43
+
44
+ # The split never yields an empty entry past the first, and that one is dropped, so an
45
+ # empty email or abbreviation can never match.
46
+ def self.admin_entries
47
+ ENV.fetch(ENV_KEY, '').split(/[\s,;]+/).reject(&:empty?)
48
+ end
49
+
50
+ # The target's base address: http(s) only, no credentials, query or fragment in it, and no
51
+ # trailing slash, so `<base>/api/v1/...` is what gets called. A path is kept for an ELN
52
+ # served below one (https://host/eln).
53
+ def self.base_uri(raw)
54
+ uri = URI.parse(raw.to_s.strip)
55
+ unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
56
+ raise Error, 'Enter the target ELN address, starting with http:// or https://.'
57
+ end
58
+ if uri.userinfo || uri.query || uri.fragment
59
+ raise Error, 'Enter only the address of the target ELN, without credentials, query or fragment.'
60
+ end
61
+
62
+ uri.path = uri.path.sub(%r{/+\z}, '')
63
+ uri
64
+ rescue URI::InvalidURIError
65
+ raise Error, 'The target ELN address is not a valid URL.'
66
+ end
67
+
68
+ # Who sent which template where, for the instance's own log: a push leaves the Hub under
69
+ # someone's name, so it is recorded. Never the credentials.
70
+ def self.audit(user, klass, result, logger: Labimotion.logger)
71
+ logger.info(
72
+ "[HubPush] user #{user&.id} pushed DatasetKlass #{klass.id} (#{klass.ols_term_id}, " \
73
+ "identifier #{klass.identifier}) to #{result[:target_url]}: #{result[:message]}"
74
+ )
75
+ end
76
+
77
+ attr_reader :klass, :base
78
+
79
+ def initialize(klass:, url:, username:, password:)
80
+ @klass = klass
81
+ @base = self.class.base_uri(url)
82
+ @username = username.to_s
83
+ @password = password.to_s
84
+ raise Error, 'Enter the username and password of the target ELN account.' if @username.empty? || @password.empty?
85
+ end
86
+
87
+ def call
88
+ ensure_pushable!
89
+ token = sign_in
90
+ ensure_target_free!(token)
91
+ message = import(token)
92
+ { target_url: base.to_s, label: klass.label, ols_term_id: klass.ols_term_id,
93
+ identifier: klass.identifier, version: klass.version, message: message }
94
+ end
95
+
96
+ private
97
+
98
+ def host
99
+ base.host
100
+ end
101
+
102
+ # The target receives what the Hub serves for the identifier: the released template. A
103
+ # template never released with any layer would arrive empty.
104
+ def ensure_pushable!
105
+ raise Error, "#{klass.label} has no identifier, so the target cannot import it." if klass.identifier.to_s.empty?
106
+
107
+ released = klass.properties_release
108
+ return if released.is_a?(Hash) && released['layers'].is_a?(Hash) && released['layers'].any?
109
+
110
+ raise Error, "#{klass.label} has no released template with layers yet; design and release it in the " \
111
+ 'Designer first.'
112
+ end
113
+
114
+ def sign_in
115
+ response = request(Net::HTTP::Post, 'public/token', body: { username: @username, password: @password })
116
+ raise Error, "#{host} rejected the username or password." if response.code == '401'
117
+
118
+ ensure_success!(response, 'sign in')
119
+ token = parse(response)['token']
120
+ raise Error, "#{host} did not return a sign-in token." if token.to_s.empty?
121
+
122
+ token
123
+ end
124
+
125
+ # create_repo_klass overwrites whatever the target holds for the term. That is wanted for
126
+ # an earlier push of this same template (same identifier: it is brought up to date) and
127
+ # for a never-released placeholder (what seeding leaves for each term); anything else is the
128
+ # target's own template, which a push must not replace.
129
+ def ensure_target_free!(token)
130
+ row = list_target_rows(token).find do |candidate|
131
+ candidate.is_a?(Hash) && candidate['ols_term_id'] == klass.ols_term_id
132
+ end
133
+ return if row.nil? || row['identifier'] == klass.identifier || row['released_at'].to_s.empty?
134
+
135
+ raise Error, "#{host} already has its own dataset template for #{klass.ols_term_id} " \
136
+ "(#{row['label']}); pushing would replace it, so nothing was sent."
137
+ end
138
+
139
+ # `list_klass` is the current route; a target older than it answers 404 and still serves
140
+ # the same list under `list_dataset_klass`, rooted at `klass`.
141
+ def list_target_rows(token)
142
+ response = request(Net::HTTP::Get, 'generic_dataset/list_klass', token: token)
143
+ response = request(Net::HTTP::Get, 'generic_dataset/list_dataset_klass', token: token) if response.code == '404'
144
+ ensure_success!(response, 'list its dataset templates')
145
+ listed = parse(response)
146
+ if listed.key?('mc') && listed['mc'] != 'ss00'
147
+ raise Error, "#{host} could not list its dataset templates: #{listed['msg']}"
148
+ end
149
+
150
+ Array(listed['data'] || listed['klass'])
151
+ end
152
+
153
+ # The target answers 201 either way and reports a failed download as `error`, which on a
154
+ # target that cannot reach this Hub is a bare Ruby message, so the likely cause is named.
155
+ def import(token)
156
+ response = request(Net::HTTP::Post, 'generic_dataset/create_repo_klass',
157
+ token: token, body: { identifier: klass.identifier })
158
+ # Since labimotion 2.4 the target lets only its dataset designers import.
159
+ if response.code == '401'
160
+ raise Error, "#{host} refused the import: the account needs the Dataset Designer right there."
161
+ end
162
+
163
+ ensure_success!(response, 'import the template')
164
+ imported = parse(response)
165
+ if imported['error'].to_s.empty? && imported['status'] == 'success'
166
+ return imported['message'].to_s.empty? ? "#{klass.label} was imported on #{host}." : imported['message']
167
+ end
168
+
169
+ raise Error, "#{host} could not download the template from its LabIMotion Hub " \
170
+ "(#{imported['error'] || imported['message']}). An ELN in production downloads from " \
171
+ 'www.chemotion-repository.net, one in development from http://localhost:3000/; the push ' \
172
+ 'must come from that instance, and the ELN must reach it. Its log/labimotion.log has the cause.'
173
+ end
174
+
175
+ def request(verb, path, body: nil, token: nil)
176
+ uri = base.dup
177
+ uri.path = "#{base.path}/api/v1/#{path}"
178
+ req = verb.new(uri)
179
+ req['Accept'] = 'application/json'
180
+ req['Authorization'] = "Bearer #{token}" if token
181
+ # create_repo_klass forwards its Origin to the Hub, which requires and logs one: the
182
+ # instance that downloads the template, the way its own browser would send it.
183
+ req['Origin'] = origin
184
+ if body
185
+ req['Content-Type'] = 'application/json'
186
+ req.body = body.to_json
187
+ end
188
+ # Net::HTTP does not follow redirects, which is wanted: a redirect would carry the
189
+ # credentials to wherever it points.
190
+ permitting_loads do
191
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
192
+ open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) do |http|
193
+ http.request(req)
194
+ end
195
+ end
196
+ rescue SocketError, SystemCallError, IOError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
197
+ raise Error, "Cannot reach #{host}: #{e.message}"
198
+ end
199
+
200
+ # The import makes the target call back into this instance, the Hub it downloads from.
201
+ # Without eager loading (development), a request that autoloads waits until no other
202
+ # request is running app code, and this one would sit waiting on the target, which waits
203
+ # on that request, until the target's 10 s timeout. Waiting on the network, it lets loads
204
+ # through, the way Rails asks of code that blocks on another thread.
205
+ def permitting_loads
206
+ interlock = ActiveSupport::Dependencies.interlock if defined?(ActiveSupport::Dependencies.interlock)
207
+ return yield unless interlock
208
+
209
+ # The cop's `&block` form is then flagged for anonymous forwarding, which Ruby 2.7 lacks.
210
+ interlock.permit_concurrent_loads { yield } # rubocop:disable Style/ExplicitBlockArgument
211
+ end
212
+
213
+ def origin
214
+ port = base.port == base.default_port ? '' : ":#{base.port}"
215
+ "#{base.scheme}://#{base.host}#{port}"
216
+ end
217
+
218
+ def ensure_success!(response, doing)
219
+ return if response.is_a?(Net::HTTPSuccess)
220
+
221
+ if response.is_a?(Net::HTTPRedirection)
222
+ raise Error, "#{host} redirected to #{response['location']}; enter that address as the target instead."
223
+ end
224
+
225
+ reason = refusal_text(response)
226
+ raise Error, "#{host} refused to #{doing} (HTTP #{response.code})#{reason.empty? ? '.' : ": #{reason}"}"
227
+ end
228
+
229
+ # The target's own sentence when it sent one: Grape's refusals carry `error`, the
230
+ # labimotion routes `msg`.
231
+ def refusal_text(response)
232
+ body = JSON.parse(response.body.to_s)
233
+ body.is_a?(Hash) ? (body['error'] || body['msg'] || body['message']).to_s : ''
234
+ rescue JSON::ParserError
235
+ ''
236
+ end
237
+
238
+ def parse(response)
239
+ parsed = JSON.parse(response.body.to_s)
240
+ raise JSON::ParserError, 'not an object' unless parsed.is_a?(Hash)
241
+
242
+ parsed
243
+ rescue JSON::ParserError
244
+ raise Error, "#{host} did not answer like a Chemotion ELN (HTTP #{response.code}); check the address."
245
+ end
246
+ end
247
+ end
@@ -76,30 +76,57 @@ module Labimotion
76
76
  end
77
77
 
78
78
  def creators
79
- Array(publication['authors']).filter_map do |author|
80
- next unless author.is_a?(Hash)
81
-
82
- given = author['givenName'].to_s.strip
83
- family = author['familyName'].to_s.strip
84
- next if given.empty? && family.empty?
79
+ Array(publication['authors']).filter_map { |author| person(author) }
80
+ end
85
81
 
86
- { 'givenName' => h(given), 'familyName' => h(family),
87
- 'orcid' => h(author['orcid'].to_s.strip), 'affiliation' => h(author['affiliation'].to_s.strip) }
82
+ # The people credited as DataCite contributors, each in their own role.
83
+ # Held apart from the creators — a contributor need not be one of the
84
+ # authors — and empty (no contributors block) until one is named; they are
85
+ # never inferred from whoever happens to be publishing. DOIs released
86
+ # before contributors became a list carry a single `contributor`.
87
+ def contributors
88
+ list = publication['contributors']
89
+ list = [publication['contributor']].compact unless list.is_a?(Array)
90
+ list.filter_map do |entry|
91
+ person(entry)&.merge('contributorType' => h(contributor_type(entry)))
88
92
  end
89
93
  end
90
94
 
91
- # The author picked from the author list, rendered as a DataCite
92
- # "Researcher" contributor. Nil (no contributors block) when none has been
93
- # picked — it is never inferred from whoever happens to be publishing.
94
- def contributor
95
- picked = publication['contributor']
96
- return nil unless picked.is_a?(Hash)
95
+ def contributor_type(entry)
96
+ type = entry['contributorType'].to_s.strip
97
+ types = TemplateDoiHelpers::CONTRIBUTOR_TYPES
98
+ types.include?(type) ? type : TemplateDoiHelpers::DEFAULT_CONTRIBUTOR_TYPE
99
+ end
97
100
 
98
- given = picked['givenName'].to_s.strip
99
- family = picked['familyName'].to_s.strip
101
+ # A creator or contributor, escaped for the template. Nameless entries are
102
+ # dropped: DataCite has nowhere to put an ORCID or affiliation on its own.
103
+ # `ror` is the resolver URI DataCite expects in affiliationIdentifier,
104
+ # rebuilt from the bare id that is stored.
105
+ def person(entry)
106
+ return nil unless entry.is_a?(Hash)
107
+
108
+ given = entry['givenName'].to_s.strip
109
+ family = entry['familyName'].to_s.strip
100
110
  return nil if given.empty? && family.empty?
101
111
 
102
- { 'givenName' => h(given), 'familyName' => h(family), 'orcid' => h(picked['orcid'].to_s.strip) }
112
+ ror = entry['ror_id'].to_s.strip
113
+ { 'givenName' => h(given), 'familyName' => h(family), 'orcid' => h(entry['orcid'].to_s.strip),
114
+ 'affiliation' => h(entry['affiliation'].to_s.strip),
115
+ 'ror' => ror.empty? ? '' : h("https://ror.org/#{ror}") }
116
+ end
117
+
118
+ # Works this template cites, published as DataCite relatedIdentifiers of
119
+ # relationType "References". Only the DOI travels — a relatedIdentifier
120
+ # carries no title — so entries without one are skipped.
121
+ def references
122
+ Array(publication['references']).filter_map do |reference|
123
+ next unless reference.is_a?(Hash)
124
+
125
+ doi = reference['doi'].to_s.strip
126
+ next if doi.empty?
127
+
128
+ { 'doi' => h(doi) }
129
+ end
103
130
  end
104
131
 
105
132
  # What this DOI renders: the snapshot taken when it was released, so every
@@ -86,13 +86,12 @@ module Labimotion
86
86
  end
87
87
 
88
88
  # Everything the publication form owns that DataCite needs, named so the
89
- # modal can say what is still missing. The contributor is one of the
90
- # authors and has to be picked in the form — a DOI is never released
91
- # crediting whoever happened to press the button.
89
+ # modal can say what is still missing. Contributors and references are
90
+ # optional: not every template credits a role beyond its authors, and not
91
+ # every template cites a work.
92
92
  def missing_metadata
93
93
  missing = %w[title description].reject { |key| publication[key].to_s.strip.present? }
94
94
  missing << 'authors' unless Array(publication['authors']).any? { |author| named?(author) }
95
- missing << 'contributor' unless named?(publication['contributor'])
96
95
  missing
97
96
  end
98
97
 
@@ -20,6 +20,24 @@ module Labimotion
20
20
  ::Labimotion::DatasetKlass => 'datasets'
21
21
  }.freeze
22
22
 
23
+ # Where the hub lives, most specific first. PUBLIC_URL is the instance's own
24
+ # public address (the host app's config/application.rb insists on it), so the
25
+ # link follows whichever instance is serving it rather than a hardcoded
26
+ # chemotion-repository.net. The DataCite-facing domains stay as fallbacks for
27
+ # deployments that only set those.
28
+ HOST_ENV_KEYS = %w[PUBLIC_URL REPO_HOST DOI_DOMAIN_TEST DOI_DOMAIN].freeze
29
+
30
+ # The DataCite kernel-4 contributorType vocabulary. A template DOI may name
31
+ # any number of contributors — including none — each credited in one of
32
+ # these roles. The list is closed: DataCite rejects anything else.
33
+ CONTRIBUTOR_TYPES = %w[
34
+ ContactPerson DataCollector DataCurator DataManager Distributor Editor
35
+ HostingInstitution Producer ProjectLeader ProjectManager ProjectMember
36
+ RegistrationAgency RegistrationAuthority RelatedPerson Researcher
37
+ ResearchGroup RightsHolder Sponsor Supervisor WorkPackageLeader Other
38
+ ].freeze
39
+ DEFAULT_CONTRIBUTOR_TYPE = 'Researcher'
40
+
23
41
  module_function
24
42
 
25
43
  # True once the template's latest DOI has been released (minted) and the
@@ -49,13 +67,17 @@ module Labimotion
49
67
  # Used as the DOI's DataCite landing page and surfaced in the UI.
50
68
  def template_url(record)
51
69
  type = klass_type_for(record)
52
- host = ENV['REPO_HOST'].presence || ENV['DOI_DOMAIN_TEST'].presence ||
53
- ENV['DOI_DOMAIN'].presence || 'https://www.chemotion-repository.net'
54
70
  record_id = record.try(:identifier).presence || record.try(:uuid).presence || record.id
55
71
  query = "type=finder&kind=#{type}&id=#{record_id}"
56
72
  version = record.try(:version)
57
73
  query += "&version=#{version}" if version.present?
58
- "#{host.chomp('/')}/home/genericHub?#{query}"
74
+ "#{public_host}/home/genericHub?#{query}"
75
+ end
76
+
77
+ # The instance serving the hub, without its trailing slash.
78
+ def public_host
79
+ host = HOST_ENV_KEYS.lazy.filter_map { |key| ENV[key].presence }.first
80
+ (host || 'http://localhost:3000').chomp('/')
59
81
  end
60
82
 
61
83
  # A user may manage a template's DOI iff they hold the LabIMotion
@@ -7,7 +7,12 @@ module Labimotion
7
7
  class UpdateTemplatePublicationMetadata
8
8
  include TemplateDoiHelpers
9
9
 
10
- ALLOWED_KEYS = %w[title description authors contributor license].freeze
10
+ ALLOWED_KEYS = %w[title description authors contributors references license].freeze
11
+ REFERENCE_KEYS = %w[doi title url].freeze
12
+ # Authors and contributors are the same shape: a DataCite personal name plus
13
+ # the identifiers that make it resolvable — ORCID for the person, ROR for
14
+ # their organisation. Contributors carry a contributorType on top.
15
+ PERSON_KEYS = %w[givenName familyName orcid affiliation affiliation_id ror_id].freeze
11
16
 
12
17
  attr_reader :record, :current_user, :publication, :error
13
18
 
@@ -39,42 +44,82 @@ module Labimotion
39
44
  def normalized_publication
40
45
  slice = publication.stringify_keys.slice(*ALLOWED_KEYS)
41
46
  slice['authors'] = Array(slice['authors']).filter_map { |a| normalize_author(a) }
42
- picked = picked_contributor(slice['authors'], slice['contributor'])
43
- picked ? slice['contributor'] = picked : slice.delete('contributor')
47
+ # Contributors are people in their own right — none of them need be one of
48
+ # the authors — so they are stored as given rather than matched back
49
+ # against the author list. There may be any number, including none.
50
+ slice['contributors'] = submitted_contributors.filter_map { |c| normalize_contributor(c) }
51
+ slice['references'] = Array(slice['references']).filter_map { |r| normalize_reference(r) }
44
52
  slice
45
53
  end
46
54
 
47
- # The contributor is one of the authors, so it is matched back against the
48
- # saved author list and stored as that author. Anything that matches none
49
- # of them — a stale pick whose author has since been removed, or a name
50
- # that was never on the list — is dropped.
51
- def picked_contributor(authors, contributor)
52
- picked = normalize_author(contributor)
53
- return nil if picked.nil?
55
+ # A single `contributor` is what the first version of the form sent; a
56
+ # template saved by it is read back into the list rather than dropped.
57
+ def submitted_contributors
58
+ given = publication.stringify_keys
59
+ given['contributors'].is_a?(Array) ? given['contributors'] : [given['contributor']].compact
60
+ end
61
+
62
+ # A person plus the DataCite role they are credited in. An unknown or
63
+ # missing role falls back to "Researcher" rather than failing the save —
64
+ # the vocabulary is closed, so anything else would be rejected at minting.
65
+ def normalize_contributor(contributor)
66
+ h = normalize_author(contributor)
67
+ return nil unless h
54
68
 
55
- authors.find { |author| same_person?(author, picked) }
69
+ type = contributor.stringify_keys['contributorType'].to_s.strip
70
+ known = TemplateDoiHelpers::CONTRIBUTOR_TYPES.include?(type)
71
+ h.merge('contributorType' => known ? type : TemplateDoiHelpers::DEFAULT_CONTRIBUTOR_TYPE)
56
72
  end
57
73
 
58
- # ORCID identifies a person when both sides carry one; otherwise fall back
59
- # to the name pair, which is what the editor matches on too.
60
- def same_person?(one, other)
61
- orcids = [one, other].map { |a| a['orcid'].to_s.strip }
62
- return orcids[0].casecmp?(orcids[1]) if orcids.all?(&:present?)
74
+ # A cited work, identified by its DOI. Anything without one is dropped: the
75
+ # DOI is what goes to DataCite as a relatedIdentifier, and a reference
76
+ # without it would be published as an empty relation.
77
+ def normalize_reference(reference)
78
+ return nil unless reference.is_a?(Hash)
79
+
80
+ h = reference.stringify_keys.slice(*REFERENCE_KEYS)
81
+ h['doi'] = sanitize_doi(h['doi'])
82
+ return nil if h['doi'].nil?
83
+
84
+ h.transform_values { |v| v.to_s.strip }
85
+ end
63
86
 
64
- %w[givenName familyName].all? do |key|
65
- one[key].to_s.strip.casecmp?(other[key].to_s.strip)
66
- end
87
+ # Accepts a bare DOI, a doi: prefix or a resolver URL, and keeps the bare
88
+ # "10.x/y" form. Nil for anything that is not a DOI.
89
+ def sanitize_doi(value)
90
+ match = value.to_s.strip.match(%r{(10\.\d{4,9}/\S+)\z})
91
+ match && match[1]
67
92
  end
68
93
 
69
94
  def normalize_author(author)
70
95
  return nil unless author.is_a?(Hash)
71
96
 
72
- h = author.stringify_keys.slice('givenName', 'familyName', 'orcid', 'affiliation', 'affiliation_id')
97
+ h = author.stringify_keys.slice(*PERSON_KEYS)
73
98
  return nil if h.values_at('givenName', 'familyName').all? { |v| v.to_s.strip.empty? }
74
99
 
100
+ ror = normalize_ror(h['ror_id']) || ror_for(h['affiliation_id'])
101
+ ror ? h['ror_id'] = ror : h.delete('ror_id')
75
102
  h
76
103
  end
77
104
 
105
+ # ROR IDs travel either bare ("05f950310") or as a resolver URL; DataCite
106
+ # wants the URI, so the bare form is what gets stored and the URI is built
107
+ # when the XML is rendered.
108
+ def normalize_ror(value)
109
+ value.to_s.strip.sub(%r{\Ahttps?://ror\.org/}i, '').presence
110
+ end
111
+
112
+ # The authoritative ROR for a picked affiliation. Whoever the editor picked
113
+ # came from an Affiliation record, so its id is the better source than
114
+ # anything retyped — and the current-user payload carries no ROR at all.
115
+ def ror_for(affiliation_id)
116
+ return nil if affiliation_id.blank? || !defined?(::Affiliation)
117
+
118
+ normalize_ror(::Affiliation.where(id: affiliation_id).pick(:ror_id))
119
+ rescue StandardError
120
+ nil
121
+ end
122
+
78
123
  def failure(message)
79
124
  @error = message
80
125
  self
@@ -2,5 +2,5 @@
2
2
 
3
3
  ## Labimotion Version
4
4
  module Labimotion
5
- VERSION = '2.2.0.rc21'
5
+ VERSION = '2.2.1'
6
6
  end
data/lib/labimotion.rb CHANGED
@@ -23,6 +23,7 @@ module Labimotion
23
23
  autoload :GenericDatasetAPI, 'labimotion/apis/generic_dataset_api'
24
24
  autoload :SegmentAPI, 'labimotion/apis/segment_api'
25
25
  autoload :LabimotionHubAPI, 'labimotion/apis/labimotion_hub_api'
26
+ autoload :HubPushAPI, 'labimotion/apis/hub_push_api'
26
27
  autoload :ConverterAPI, 'labimotion/apis/converter_api'
27
28
  autoload :ExporterAPI, 'labimotion/apis/exporter_api'
28
29
  autoload :StandardLayerAPI, 'labimotion/apis/standard_layer_api'
@@ -85,6 +86,7 @@ module Labimotion
85
86
  autoload :NmrMapper, 'labimotion/libs/nmr_mapper'
86
87
  autoload :NmrMapperRepo, 'labimotion/libs/nmr_mapper_repo' ## for Chemotion Repository
87
88
  autoload :TemplateHub, 'labimotion/libs/template_hub'
89
+ autoload :HubPush, 'labimotion/libs/hub_push'
88
90
  autoload :TemplateMatcher, 'labimotion/libs/template_matcher'
89
91
  autoload :ExportDataset, 'labimotion/libs/export_dataset'
90
92
  autoload :SampleAssociation, 'labimotion/libs/sample_association'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: labimotion
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.0.rc21
4
+ version: 2.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Chia-Lin Lin
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2026-07-28 00:00:00.000000000 Z
12
+ date: 2026-11-12 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: caxlsx
@@ -63,6 +63,7 @@ files:
63
63
  - lib/labimotion/apis/generic_dataset_api.rb
64
64
  - lib/labimotion/apis/generic_element_api.rb
65
65
  - lib/labimotion/apis/generic_klass_api.rb
66
+ - lib/labimotion/apis/hub_push_api.rb
66
67
  - lib/labimotion/apis/labimotion_api.rb
67
68
  - lib/labimotion/apis/labimotion_doi_api.rb
68
69
  - lib/labimotion/apis/labimotion_hub_api.rb
@@ -119,6 +120,7 @@ files:
119
120
  - lib/labimotion/libs/dataset_builder.rb
120
121
  - lib/labimotion/libs/export_dataset.rb
121
122
  - lib/labimotion/libs/export_element.rb
123
+ - lib/labimotion/libs/hub_push.rb
122
124
  - lib/labimotion/libs/nmr_mapper.rb
123
125
  - lib/labimotion/libs/properties_handler.rb
124
126
  - lib/labimotion/libs/sample_association.rb
@@ -206,9 +208,9 @@ required_ruby_version: !ruby/object:Gem::Requirement
206
208
  version: '3.4'
207
209
  required_rubygems_version: !ruby/object:Gem::Requirement
208
210
  requirements:
209
- - - ">"
211
+ - - ">="
210
212
  - !ruby/object:Gem::Version
211
- version: 1.3.1
213
+ version: '0'
212
214
  requirements: []
213
215
  rubygems_version: 3.1.6
214
216
  signing_key: