Class: Labimotion::Converter

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

Class Method Summary collapse

Class Method Details

.authObject



42
43
44
# File 'lib/labimotion/libs/converter.rb', line 42

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

.build_ds(att_id, ols) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/labimotion/libs/converter.rb', line 201

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
  )
end

.clean_dsr(att_id) ⇒ Object



271
272
273
# File 'lib/labimotion/libs/converter.rb', line 271

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

.client_idObject



34
35
36
# File 'lib/labimotion/libs/converter.rb', line 34

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

.collect_metadata(zip_file) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/labimotion/libs/converter.rb', line 72

def self.(zip_file) # 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

.create_profile(data) ⇒ Object



287
288
289
290
291
# File 'lib/labimotion/libs/converter.rb', line 287

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



305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/labimotion/libs/converter.rb', line 305

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



46
47
48
# File 'lib/labimotion/libs/converter.rb', line 46

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

.delete_profile(id) ⇒ Object



281
282
283
284
285
# File 'lib/labimotion/libs/converter.rb', line 281

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



30
31
32
# File 'lib/labimotion/libs/converter.rb', line 30

def self.extname
  '.jdx'
end

.fetch_dsr(att_id) ⇒ Object



267
268
269
# File 'lib/labimotion/libs/converter.rb', line 267

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

.fetch_optionsObject



275
276
277
278
279
# File 'lib/labimotion/libs/converter.rb', line 275

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



299
300
301
302
303
# File 'lib/labimotion/libs/converter.rb', line 299

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



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/labimotion/libs/converter.rb', line 188

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)
  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) ⇒ Object

rubocop: disable Metrics/PerceivedComplexity



94
95
96
97
98
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/labimotion/libs/converter.rb', line 94

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

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

    name = response&.headers && response&.headers['content-disposition']&.split('=')&.last
    filename = oat.filename
    name = "#{File.basename(filename, '.*')}.zip" if name.nil?

    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.attachment_attacher.attach(tmp_file)
    if att.valid? && Labimotion::IS_RAILS5 == false
      att.attachment_attacher.create_derivatives
      att.save!
    end
    if att.valid? && Labimotion::IS_RAILS5 == true
      att.save!
      primary_store = Rails.configuration.storage.primary_store
      att.update!(storage: primary_store)
    end

    Zip::File.open(tmp_file.path) do |zip_file|
      res = Labimotion::Converter.(zip_file) if name.split('.')&.last == 'zip'
      ols = res[:o] unless res&.dig(:o).nil?
      dsr.push(res[:d]) unless res&.dig(:d).nil?
    end

    dsr.flatten!
    if dsr.length.positive? && name.split('.')&.last == 'zip'
      Labimotion::Converter.ts('write', att.attachable_id, ols: ols, info: dsr)
    end
  rescue StandardError => e
    raise e
  ensure
    tmp_file&.close
  end
end

.header(opt = {}) ⇒ Object



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

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

.jcamp_converter(id) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/labimotion/libs/converter.rb', line 174

def self.jcamp_converter(id)
  resp = nil
  begin
    data = Labimotion::Converter.vor_conv(id)
    return if data.nil?

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

.loggerObject



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

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

.process(data) ⇒ Object



145
146
147
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
# File 'lib/labimotion/libs/converter.rb', line 145

def self.process(data)
  return if data[:a]&.attachable_type != 'Container'

  response = nil
  begin
    ofile = Rails.root.join(data[:f], data[:a].filename)
    FileUtils.cp(data[:a].store.path, 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)
    else
      Labimotion::Converter.logger.error ["Converter Response Error: id: [#{data[:a]&.id}], filename: [#{data[:a]&.filename}], response: #{response}"].join($INPUT_RECORD_SEPARATOR)
    end
    response
  rescue StandardError => e
    raise e
  ensure
    FileUtils.rm_f(ofile)
  end
end

.secret_keyObject



38
39
40
# File 'lib/labimotion/libs/converter.rb', line 38

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

.signature(jbody) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/labimotion/libs/converter.rb', line 50

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

.timeoutObject



26
27
28
# File 'lib/labimotion/libs/converter.rb', line 26

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

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



263
264
265
# File 'lib/labimotion/libs/converter.rb', line 263

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



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/labimotion/libs/converter.rb', line 225

def self.update_ds(dataset, dsr, current_user = nil) # rubocop: disable Metrics/PerceivedComplexity
  layers = dataset.properties['layers'] || {}
  new_prop = dataset.properties
  dsr.each do |ds|
    layer = layers[ds[:layer]]
    fields = layer['fields'].select{ |f| f['field'] == ds[:field] }
    fi = fields&.first
    idx = layer['fields'].find_index(fi)
    fi['value'] = ds[:value]
    fi['device'] = ds[:device] || ds[:value]
    new_prop['layers'][ds[:layer]]['fields'][idx] = fi
  end
  new_prop.dig('layers', 'general', 'fields')&.each_with_index do |fi, idx|
    if fi['field'] == 'creator' && current_user.present?
      fi['label'] = fi['label']
      fi['value'] = current_user.name
      fi['system'] = current_user.name
      new_prop['layers']['general']['fields'][idx] = fi
    end
  end
  element = Container.find(dataset.element_id)&.root_element
  element.present? && element&.class&.name == 'Sample' && new_prop.dig('layers', 'sample_details', 'fields')&.each_with_index do |fi, idx|
    if fi['field'] == 'id'
      fi['value'] = element.id
      fi['system'] = element.id
      new_prop['layers']['general']['fields'][idx] = fi
    end

    if fi['field'] == 'label'
      fi['value'] = element.short_label
      fi['system'] = element.short_label
      new_prop['layers']['general']['fields'][idx] = fi
    end
  end
  dataset.properties = new_prop
  dataset.save!
end

.update_profile(data) ⇒ Object



293
294
295
296
297
# File 'lib/labimotion/libs/converter.rb', line 293

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



21
22
23
24
# File 'lib/labimotion/libs/converter.rb', line 21

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

.vor_conv(id) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/labimotion/libs/converter.rb', line 62

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