Class: Labimotion::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/labimotion/libs/converter.rb

Class Method Summary collapse

Class Method Details

.authObject



69
70
71
# File 'lib/labimotion/libs/converter.rb', line 69

def self.auth
  { username: client_id, password: secret_key }
end

.build_ds(att_id, ols) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/labimotion/libs/converter.rb', line 235

def self.build_ds(att_id, ols)
  cds = Container.find_by(id: att_id)
  dataset = Labimotion::Dataset.find_by(element_type: 'Container', element_id: cds.id)
  return dataset unless dataset.nil?

  klass = Labimotion::DatasetKlass.find_by(ols_term_id: ols)
  return if klass.nil?

  uuid = SecureRandom.uuid
  props = klass.properties_release
  props['uuid'] = uuid
  props['pkg'] = Labimotion::Utils.pkg(props['pkg'])
  props['klass'] = 'Dataset'
  Labimotion::Dataset.create!(
    uuid: uuid,
    dataset_klass_id: klass.id,
    element_type: 'Container',
    element_id: cds.id,
    properties: props,
    properties_release: klass.properties_release,
    klass_uuid: klass.uuid,
    metadata: klass.
  )
end

.clean_dsr(att_id) ⇒ Object



311
312
313
# File 'lib/labimotion/libs/converter.rb', line 311

def self.clean_dsr(att_id)
  Labimotion::Converter.ts('delete', att_id)
end

.client_idObject



61
62
63
# File 'lib/labimotion/libs/converter.rb', line 61

def self.client_id
  Rails.configuration.converter.profile || ''
end

.collect_metadata(zip_file, current_user = {}) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/labimotion/libs/converter.rb', line 126

def self.(zip_file, current_user = {}) # rubocop: disable Metrics/PerceivedComplexity
  dsr = []
  ols = nil
  zip_file.each do |entry|
    next unless entry.name == 'metadata/converter.json'

     = entry.get_input_stream.read.force_encoding('UTF-8')
    jdata = JSON.parse()

    ols = jdata['ols']
    matches = jdata['matches']
    matches&.each do |match|
      idf = match['identifier']
      idr = match['result']
      if idf&.class == Hash && idr&.class == Hash && !idf['outputLayer'].nil? && !idf['outputKey'].nil? && !idr['value'].nil? # rubocop:disable Layout/LineLength
        dsr.push(layer: idf['outputLayer'], field: idf['outputKey'], value: idr['value'])
      end
    end
  end
  { d: dsr, o: ols }
end

.collect_reaction_converter_metadata(oat, zip_file) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/labimotion/libs/converter.rb', line 99

def self.(oat, zip_file)
  zip_file.each do |entry|
    next unless entry.name == 'metadata/reaction_variation.json'

    # Create temp file
    tmp_file = Tempfile.new(['reaction_variation', '.json'])
    tmp_file.binmode

    # Write ZIP entry content into temp file
    entry.extract(tmp_file.path) { true }

    # Create attachment
    att = Attachment.create!(
      filename: 'reaction_variation.json',
      file_path: tmp_file.path,
      content_type: 'application/json',
      attachable_id: oat.attachable_id,
      attachable_type: 'Container',
      con_state: Labimotion::ConState::CONVERTED,
      created_by: oat.created_by,
      created_for: oat.created_for
    )

    att.save! if att.valid?
  end
end

.create_profile(data) ⇒ Object



327
328
329
330
331
# File 'lib/labimotion/libs/converter.rb', line 327

def self.create_profile(data)
  options = { basic_auth: auth, timeout: timeout, body: data.to_json, headers: { 'Content-Type' => 'application/json' } }
  response = HTTParty.post(uri('profiles'), options)
  response.parsed_response if response.code == 201
end

.create_tables(tmpfile) ⇒ Object



345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/labimotion/libs/converter.rb', line 345

def self.create_tables(tmpfile)
  res = {}
  File.open(tmpfile.path, 'r') do |file|
    body = { file: file }
    response = HTTParty.post(
      uri('tables'),
      basic_auth: auth,
      body: body,
      timeout: timeout,
    )
    res = response.parsed_response
  end
  res
end

.date_timeObject



73
74
75
# File 'lib/labimotion/libs/converter.rb', line 73

def self.date_time
  DateTime.now.strftime('%Q')
end

.delete_profile(id) ⇒ Object



321
322
323
324
325
# File 'lib/labimotion/libs/converter.rb', line 321

def self.delete_profile(id)
  options = { basic_auth: auth, timeout: timeout }
  response = HTTParty.delete("#{uri('profiles')}/#{id}", options)
  response.parsed_response if response.code == 200
end

.extnameObject



57
58
59
# File 'lib/labimotion/libs/converter.rb', line 57

def self.extname
  '.jdx'
end

.fetch_dsr(att_id) ⇒ Object



307
308
309
# File 'lib/labimotion/libs/converter.rb', line 307

def self.fetch_dsr(att_id)
  Labimotion::Converter.ts('read', att_id)
end

.fetch_optionsObject



315
316
317
318
319
# File 'lib/labimotion/libs/converter.rb', line 315

def self.fetch_options
  options = { basic_auth: auth, timeout: timeout }
  response = HTTParty.get(uri('options'), options)
  response.parsed_response if response.code == 200
end

.fetch_profilesObject



339
340
341
342
343
# File 'lib/labimotion/libs/converter.rb', line 339

def self.fetch_profiles
  options = { basic_auth: auth, timeout: timeout }
  response = HTTParty.get(uri('profiles'), options)
  response.parsed_response if response.code == 200
end

.generate_ds(att_id, current_user = {}) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/labimotion/libs/converter.rb', line 221

def self.generate_ds(att_id, current_user = {})
  dsr_info = Labimotion::Converter.fetch_dsr(att_id)
  begin
    return unless dsr_info && dsr_info[:info]&.length.positive?

    dataset = Labimotion::Converter.build_ds(att_id, dsr_info[:ols])
    Labimotion::Converter.update_ds(dataset, dsr_info[:info], current_user) if dataset.present?
  rescue StandardError => e
    Labimotion::Converter.logger.error ["Att ID: #{att_id}, OLS: #{dsr_info[:ols]}", "DSR: #{dsr_info[:info]}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR)
  ensure
    Labimotion::Converter.clean_dsr(att_id)
  end
end

.handle_response(oat, response, current_user = {}) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/labimotion/libs/converter.rb', line 148

def self.handle_response(oat, response, current_user = {}) # rubocop: disable Metrics/PerceivedComplexity
  dsr = []
  ols = nil

  begin
    tmp_file = Tempfile.new(encoding: 'ascii-8bit')
    tmp_file.write(response.parsed_response)
    tmp_file.rewind

    filename = oat.filename
    name = "#{File.basename(filename, '.*')}#{File.extname(filename) == '.zip' ? '.bagit.zip' : '.zip'}"
    att = Attachment.new(
      filename: name,
      file_path: tmp_file.path,
      ## content_type: file[:type],
      attachable_id: oat.attachable_id,
      attachable_type: 'Container',
      con_state: Labimotion::ConState::CONVERTED,
      created_by: oat.created_by,
      created_for: oat.created_for,
    )

    att.save! if att.valid?

    process_ds(att.id, current_user)
  rescue StandardError => e
    raise e
  ensure
    tmp_file&.close
  end
end

.header(opt = {}) ⇒ Object



85
86
87
# File 'lib/labimotion/libs/converter.rb', line 85

def self.header(opt = {})
  opt || {}
end

.jcamp_converter(id, current_user = {}) ⇒ Object



211
212
213
214
215
216
217
218
219
# File 'lib/labimotion/libs/converter.rb', line 211

def self.jcamp_converter(id, current_user = {})
  data = Labimotion::Converter.vor_conv(id)
  return if data.nil?

  Labimotion::Converter.process(data, current_user)
rescue StandardError => e
  Labimotion::Converter.logger.error ["jcamp_converter fail: #{id}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR)
  Labimotion::ConState::ERROR
end

.loggerObject



18
19
20
# File 'lib/labimotion/libs/converter.rb', line 18

def self.logger
  @@converter_logger ||= Logger.new(Rails.root.join('log/converter.log')) # rubocop:disable Style/ClassVars
end

.metadata(id, current_user) ⇒ Object



391
392
393
394
395
396
397
398
# File 'lib/labimotion/libs/converter.rb', line 391

def self.(id, current_user)
  att = Attachment.find(id)
  return if att.nil? || att.attachable_id.nil? || att.attachable_type != Labimotion::Prop::CONTAINER

  ds = Labimotion::Dataset.find_by(element_type: Labimotion::Prop::CONTAINER, element_id: att.attachable_id)
  att.update_column(:con_state, Labimotion::ConState::COMPLETED) if ds.present?
  process_ds(att.id, current_user) if ds.nil?
end

.process(data, current_user = {}) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/labimotion/libs/converter.rb', line 180

def self.process(data, current_user = {}) # rubocop: disable Metrics/PerceivedComplexity
  return data[:a].con_state if data[:a]&.attachable_type != 'Container'
  response = nil
  begin
    ofile = Rails.root.join(data[:f], data[:a].filename)
    FileUtils.cp(data[:a].attachment_url, ofile)

    File.open(ofile, 'r') do |f|
      body = { file: f }
      response = HTTParty.post(
        uri('conversions'),
        basic_auth: auth,
        body: body,
        timeout: timeout,
      )
    end
    if response.ok?
      Labimotion::Converter.handle_response(data[:a], response, current_user)
      Labimotion::ConState::PROCESSED
    else
      Labimotion::Converter.logger.error ["Converter Response Error: id: [#{data[:a]&.id}], filename: [#{data[:a]&.filename}], response: #{response}"].join($INPUT_RECORD_SEPARATOR)
      Labimotion::ConState::ERROR
    end
  rescue StandardError => e
    Labimotion::Converter.logger.error ["process fail: #{data[:a]&.id}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR)
    Labimotion::ConState::ERROR
  ensure
    FileUtils.rm_f(ofile)
  end
end

.process_ds(id, current_user = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/labimotion/libs/converter.rb', line 22

def self.process_ds(id, current_user = {})
  att = Attachment.find_by(id: id, con_state: Labimotion::ConState::CONVERTED)
  return if att.nil? || att.attachable_id.nil? || att.attachable_type != 'Container' || att.filename.split('.')&.last != 'zip'

  eln_ds = Container.find_by(id: att.attachable_id, container_type: 'dataset')
  return if eln_ds.nil? || eln_ds.parent.nil? || eln_ds.parent&.container_type != 'analysis'

  dsr = []
  ols = nil
  Zip::File.open(att.attachment_attacher.file.url) do |zip_file|
    if att.filename.split('.')&.last == 'zip'
      res = Labimotion::Converter.(zip_file, current_user)
      Labimotion::Converter.(att, zip_file)
    end
    ols = res[:o] unless res&.dig(:o).nil?
    dsr.push(res[:d]) unless res&.dig(:d).nil?
  end
  dsr.flatten!
  dataset = build_ds(att.attachable_id, ols)
  update_ds(dataset, dsr, current_user) if dataset.present?
  att.update_column(:con_state, Labimotion::ConState::COMPLETED)
rescue StandardError => e
  Labimotion::Converter.logger.error ["Att ID: #{att&.id}, OLS: #{ols}", "DSR: #{dsr}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR)
  raise e
end

.restore(profile_id, version, hard) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/labimotion/libs/converter.rb', line 375

def self.restore(profile_id, version, hard)
  body = { hard: hard }
  response = HTTParty.post(
    uri("profiles/restore/#{profile_id}/#{version}"),
    headers: {
      "Content-Type" => "application/json"
    },
    basic_auth: auth,
    body: body.to_json,
    timeout: timeout,
  )
  res = response.parsed_response

  res
end

.secret_keyObject



65
66
67
# File 'lib/labimotion/libs/converter.rb', line 65

def self.secret_key
  Rails.configuration.converter.secret_key || ''
end

.signature(jbody) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/labimotion/libs/converter.rb', line 77

def self.signature(jbody)
  md5 = Digest::MD5.new
  md5.update jbody
  mdhex = md5.hexdigest
  mdall = mdhex << secret_key
  @signature = Digest::SHA1.hexdigest mdall
end

.test_conversions(tmpfile, format) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/labimotion/libs/converter.rb', line 360

def self.test_conversions(tmpfile, format)
  res = {}
  File.open(tmpfile.path, 'r') do |file|
    body = { file: file, format: format }
    response = HTTParty.post(
      uri('conversions'),
      basic_auth: auth,
      body: body,
      timeout: timeout,
    )
    res = response.parsed_response
  end
  res
end

.timeoutObject



53
54
55
# File 'lib/labimotion/libs/converter.rb', line 53

def self.timeout
  Rails.configuration.try(:converter).try(:timeout) || 30
end

.ts(method, identifier, params = nil) ⇒ Object



303
304
305
# File 'lib/labimotion/libs/converter.rb', line 303

def self.ts(method, identifier, params = nil)
  Rails.cache.send(method, "#{Labimotion::Converter.new.class.name}#{identifier}", params)
end

.update_ds(dataset, dsr, current_user = nil) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/labimotion/libs/converter.rb', line 260

def self.update_ds(dataset, dsr, current_user = nil) # rubocop: disable Metrics/PerceivedComplexity
  layers = dataset.properties[Labimotion::Prop::LAYERS] || {}
  new_prop = dataset.properties

  container = dataset.element

  # Extract and update general description fields
  general_dsr = dsr.select { |ds| ds[:layer] == 'general' }
  if general_dsr.present?
    date = general_dsr.find { |ds| ds[:field] == 'date' }&.dig(:value)
    time = general_dsr.find { |ds| ds[:field] == 'time' }&.dig(:value)
    Labimotion::ConverterHelpers.update_general_description(container, current_user, date: date, time: time)
  else
    Labimotion::ConverterHelpers.update_general_description(container, current_user)
  end

  dsr.each do |ds|
    layer = layers[ds[:layer]]
    next if layer.blank? || layer[Labimotion::Prop::FIELDS].blank?
    is_unit = ds[:field].start_with?(Prop::CONVERTER_FIELD_UINT_PREFIX)
    next if is_unit && ds[:value].nil?

    field_name = ds[:field].delete_prefix(Prop::CONVERTER_FIELD_UINT_PREFIX)

    fields = layer[Labimotion::Prop::FIELDS].select{ |f| f['field'] == field_name }
    fi = fields&.first
    next if fi.blank?

    idx = layer[Labimotion::Prop::FIELDS].find_index(fi)
    if is_unit
      fi['value_system'] = ds[:value]
    else
      fi['value'] = ds[:value]
      fi['device'] = ds[:device] || ds[:value]
    end
    new_prop[Labimotion::Prop::LAYERS][ds[:layer]][Labimotion::Prop::FIELDS][idx] = fi
  end
  element = Container.find(dataset.element_id)&.root_element
  new_prop = Labimotion::VocabularyHandler.update_vocabularies(new_prop, current_user, element)
  dataset.properties = new_prop
  dataset.save!
end

.update_profile(data) ⇒ Object



333
334
335
336
337
# File 'lib/labimotion/libs/converter.rb', line 333

def self.update_profile(data)
  options = { basic_auth: auth, timeout: timeout, body: data.to_json, headers: { 'Content-Type' => 'application/json' } }
  response = HTTParty.put("#{uri('profiles')}/#{data[:id]}", options)
  response.parsed_response if response.code == 200
end

.uri(api_name) ⇒ Object



48
49
50
51
# File 'lib/labimotion/libs/converter.rb', line 48

def self.uri(api_name)
  url = Rails.configuration.converter.url
  "#{url}#{api_name}"
end

.vor_conv(id) ⇒ Object



89
90
91
92
93
94
95
96
97
# File 'lib/labimotion/libs/converter.rb', line 89

def self.vor_conv(id)
  conf = Rails.configuration.try(:converter).try(:url)
  oa = Attachment.find(id)
  folder = Rails.root.join('tmp/uploads/converter')
  FileUtils.mkdir_p(folder)
  return nil if conf.nil? || oa.nil?

  { a: oa, f: folder }
end