Class: CallRecord::SwitchvoxImporterFile

Inherits:
Object
  • Object
show all
Defined in:
app/services/call_record/switchvox_importer_file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SwitchvoxImporterFile

Returns a new instance of SwitchvoxImporterFile.



7
8
9
10
11
# File 'app/services/call_record/switchvox_importer_file.rb', line 7

def initialize(options={})
  @options = options
  @logger = options[:logger] || Rails.logger
  @options[:remote_path] ||= Heatwave::Application.config.x.call_records_directory
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



5
6
7
# File 'app/services/call_record/switchvox_importer_file.rb', line 5

def logger
  @logger
end

Instance Method Details

#archive_file(file_name) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'app/services/call_record/switchvox_importer_file.rb', line 58

def archive_file(file_name)
  # year,month,day = file_name.split('-')
  archive_path = processed_folder.dup
  source_file_path = "#{remote_path}/#{file_name}"
  target_file_path = "#{remote_path}/#{archive_path}/#{file_name}"
  logger.info "Moving file from #{source_file_path} to #{target_file_path}"
  begin
    FileUtils.mv source_file_path, target_file_path, force: true
    logger.info "#{source_file_path} was moved to #{target_file_path}."
  rescue StandardError => exc
    logger.error "#{source_file_path} could not be moved #{exc.to_s}, target was #{target_file_path}"
  end
end

#attach_file_to_call_record(cr, local_file_path) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'app/services/call_record/switchvox_importer_file.rb', line 112

def attach_file_to_call_record(cr, local_file_path)
  return false unless local_file_path && cr
  return false if cr.upload # Already has a file

  au = Upload.uploadify( local_file_path, "call_record", cr )

  if au and !au.new_record? and au.attachment.present?
    logger.info " ** Audio record upload #{au.id} created"
    cr.update_attribute(:imported, true)
    return true
  else
    message = "!! Problem creating audio record for #{local_file_path}: #{au.errors_to_s}"
    logger.error message
    Mailer.admin_notification(message).deliver_now if (Rails.env.production? || Rails.env.staging?)
    return false
  end
end

#call_attributes(xml_doc) ⇒ Object

Retrieve all interesting attributes to a hash



142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'app/services/call_record/switchvox_importer_file.rb', line 142

def call_attributes(xml_doc)
  attributes = %w( recording_tag recorded_call_id recorder_cid recorded_cid
      recorder_account_id recorded_account_id from_account_id
      from_caller_id to_account_id to_caller_id duration date_created_ts
      date_created_secs )
  hsh = {}
  attributes.each do |attr_name|
    val = parse_node(xml_doc, attr_name)
    logger.debug " *** #{attr_name} -> #{val}"
    hsh[attr_name.to_sym] = val
  end
  hsh
end

#caller_id_parser(cid) {|origin_name, origin_number| ... } ⇒ Object

Yields:

  • (origin_name, origin_number)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'app/services/call_record/switchvox_importer_file.rb', line 254

def caller_id_parser(cid)
  return unless cid.present?
  expr = cid.match(/(.+)\<(\d+)\>/)
  if expr and expr.length == 3
    origin_name = expr[1].presence
    origin_number = expr[2]
  else
    # Just record the caller id as all letters in the name, all numbers in the number
    origin_name = cid.match(/[a-zA-Z\s]+/).to_s.presence
    origin_number = cid.match(/\d+/).to_s.presence
  end
  yield(origin_name, origin_number)

end

#convert_to_aac(local_file_path) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'app/services/call_record/switchvox_importer_file.rb', line 84

def convert_to_aac(local_file_path)
  require 'streamio-ffmpeg'
  base_dir = File.dirname(local_file_path)
  base_file_name = File.basename(local_file_path, File.extname(local_file_path))
  output_file_name = "#{base_dir}/#{base_file_name}.aac"
  audio = FFMPEG::Movie.new(local_file_path)

  # Skip empty or invalid audio files (Duration: N/A from PBX)
  if !audio.valid? || audio.duration.nil? || audio.duration.zero?
    logger.warn("Skipping invalid/empty WAV file", path: local_file_path, duration: audio.duration)
    return nil
  end

  audio.transcode(output_file_name, %w(-c:a aac -b:a 16k))
  output_file_name
end

#convert_to_oga(local_file_path) ⇒ Object

By far the best for compressing audio



102
103
104
105
106
107
108
109
110
# File 'app/services/call_record/switchvox_importer_file.rb', line 102

def convert_to_oga(local_file_path)
  require 'streamio-ffmpeg'
  base_dir = File.dirname(local_file_path)
  base_file_name = File.basename(local_file_path, File.extname(local_file_path))
  output_file_name = "#{base_dir}/#{base_file_name}.oga"
  audio = FFMPEG::Movie.new(local_file_path)
  audio.transcode(output_file_name, %w(-c:a libvorbis -b:a 8k))
  output_file_name
end

#error_folderObject



46
47
48
# File 'app/services/call_record/switchvox_importer_file.rb', line 46

def error_folder
  @options[:error_folder] || "errors/"
end

#get_file_listObject



54
55
56
# File 'app/services/call_record/switchvox_importer_file.rb', line 54

def get_file_list
  Dir["#{remote_path}/*.wav"].select{ |path| File.file?(path) }
end

#import_file(file_name) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
# File 'app/services/call_record/switchvox_importer_file.rb', line 156

def import_file(file_name)
  # The file name is an xml document per our pattern.  What is the base name?
  base_file_name = File.basename(file_name, '.wav')
  base_dir = File.dirname(file_name)
  xml_file_name = "#{base_file_name}.xml"
  recording_file_name = "#{base_file_name}.wav"
  xml_local_file_path = "#{base_dir}/#{base_file_name}.xml"
  recording_local_file_path = file_name
  converted_local_file_path = nil

  begin

    converted_local_file_path = convert_to_aac(recording_local_file_path)

    # Skip empty/invalid WAV files - just archive them without creating a call record
    if converted_local_file_path.nil?
      logger.info "Skipping empty/invalid recording: #{file_name}"
      archive_file "#{base_file_name}.wav"
      archive_file "#{base_file_name}.xml" if File.exist?(xml_local_file_path)
      return
    end

    raise "Could not process #{file_name} (converted #{converted_local_file_path})" unless File.exist?(converted_local_file_path)

    if File.exist?(xml_local_file_path)

      call_attrs = parse_xml_file(xml_local_file_path)
      logger.debug("Call attributes processed")

      switchvox_recorded_call_id = call_attrs[:recorded_call_id]
      # see if we have one already to update
      cr = CallRecord.where(switchvox_recorded_call_id: switchvox_recorded_call_id).first_or_initialize
      cr.recording_source = 'switchvox'

      cr.created_at = Time.zone.parse( call_attrs[:date_created_ts] )
      # Parse the caller id
      caller_id_parser( call_attrs[:from_caller_id] ) do |name, number|
        cr.origin_name = name
        cr.origin_number = number
      end
      # Parse the destination
      caller_id_parser( call_attrs[:to_caller_id] ) do |name, number|
        cr.destination_name = name
        cr.destination_number = number
      end
      cr.duration_secs = call_attrs[:duration]
      cr.reference1 = call_attrs[:recording_tag]
      cr.reference2 = base_file_name
      cr. = call_attrs[:from_account_id]
      cr. = call_attrs[:to_account_id]
      cr.switchvox_recorded_call_id = call_attrs[:recorded_call_id]
    else
      # Parse file name
      logger.info "No XML, using WAV filename information #{base_file_name}"
      cr = CallRecord.where(reference2: base_file_name).first_or_initialize
      cr.recording_source = 'switchvox'
      if cr.persisted?
        logger.info "CallRecord detected as previously imported: #{cr.id} for #{base_file_name}"
      else
        logger.info "Creating new call record for #{base_file_name}"
      end
      # Example string: 2018-01-08-09-46-37_+16305796221_829
      # 2018-01-08-09-52-07_829_809
      # 2018-01-08-10-02-04_852_17654526845
      parts = base_file_name.scan(/\A(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})_\+?(\d{3,})_\+?(\d{3,})\Z/)
      year,month,day,hour,minutes,seconds,from_caller_id,to_caller_id = *parts.flatten
      cr.origin_number = from_caller_id
      cr.destination_number = to_caller_id
    end

    cr.match_parties if cr.valid?

    if cr.destination_number.to_s.in?(CallRecord::VOICEMAIL_EXTENSIONS)
      cr.call_outcome = :voicemail
    end

    cr.save!
    logger.info "attaching local file: #{converted_local_file_path} to call record #{cr.id}"
    attach_file_to_call_record(cr, converted_local_file_path)

    # Queue transcription immediately for eligible calls (>= 30 seconds with audio)
    queue_transcription_if_eligible(cr)

    archive_file "#{base_file_name}.xml" if xml_local_file_path # only try this if we had an xml file
    archive_file "#{base_file_name}.wav"
    archive_file "#{base_file_name}.oga" if converted_local_file_path
  rescue StandardError => exc
    error_message = " !! Call Record failed to save for file #{file_name}, #{exc.to_s}"
    logger.error error_message
    ErrorReporting.error(exc, file_name: file_name)

    unprocessable_file "#{base_file_name}.wav"
    unprocessable_file "#{base_file_name}.xml" #if xml_local_file_path
    unprocessable_file "#{base_file_name}.oga" #if converted_local_file_path

  end
end

#import_new_records(limit = nil) ⇒ Object

Main entry point method



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/services/call_record/switchvox_importer_file.rb', line 14

def import_new_records(limit = nil)
  limit ||= @options[:limit]

  #list all files
  #recording-20120911_153955-8475502400-58204-8475407775-10238-LES.wav
  logger.info "Retrieving list of files to process"
  file_paths = get_file_list
  total_files = file_paths.length
  logger.info "Detected #{total_files} files/record(s) to process.  File limit set to #{limit}"

  file_paths.each_with_index do |file_name, i|
    break if limit.present? && i >= limit
    logger.info " - Processing record ##{i} / #{total_files} : #{file_name}"

    if Rails.env.development? || @options[:no_async].to_b || limit.to_i > 0 #Import right away
      import_file file_name
    else
      #Enqueue
      logger.info " - Enqueuing for processing #{file_name}"
      CallRecordImporterWorker.perform_async(file_name)
    end
  end
end

#parse_node(xml_doc, node_name) ⇒ Object

Simplify retrieval of attributes since we only have one in this file



137
138
139
# File 'app/services/call_record/switchvox_importer_file.rb', line 137

def parse_node(xml_doc, node_name)
  xml_doc.at_xpath("//#{node_name}").content.presence
end

#parse_xml_file(file_path) ⇒ Object

Parse a remote file using nokogiri and returns a nokogiri doc



131
132
133
134
# File 'app/services/call_record/switchvox_importer_file.rb', line 131

def parse_xml_file(file_path)
  xml_doc = Nokogiri::XML( File.read(file_path) )
  call_attributes(xml_doc)
end

#processed_folderObject



42
43
44
# File 'app/services/call_record/switchvox_importer_file.rb', line 42

def processed_folder
  @options[:processed_folder] || "processed/"
end

#queue_transcription_if_eligible(call_record) ⇒ Object

Queue transcription for calls that meet eligibility criteria:

  • Has an audio file attached (upload)
  • Duration >= minimum (30s standard, 5s for voicemails)
  • transcription_state is pending (default for new records)

The nightly DailyCallRecordTranscriptionWorker serves as a catch-up
for any records that might have been missed.



276
277
278
279
280
281
282
283
284
# File 'app/services/call_record/switchvox_importer_file.rb', line 276

def queue_transcription_if_eligible(call_record)
  return unless call_record.persisted?
  return unless call_record.upload.present?
  return unless call_record.duration_secs.to_i >= call_record.transcription_min_duration
  return unless call_record.transcription_state_pending?

  logger.info "Queueing transcription for CallRecord #{call_record.id}"
  CallRecordTranscriptionWorker.perform_async(call_record_id: call_record.id)
end

#remote_pathObject



38
39
40
# File 'app/services/call_record/switchvox_importer_file.rb', line 38

def remote_path
  @options[:remote_path]
end

#skip_download?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'app/services/call_record/switchvox_importer_file.rb', line 50

def skip_download?
  @options[:skip_download].nil? ? false : @options[:skip_download]
end

#unprocessable_file(file_name) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'app/services/call_record/switchvox_importer_file.rb', line 72

def unprocessable_file(file_name)
  source_file_path = "#{remote_path}/#{file_name}"
  target_file_path = "#{remote_path}/#{error_folder}#{file_name}"
  logger.info "Moving unprocessable file from #{source_file_path} to #{target_file_path}"
  begin
    FileUtils.mv source_file_path, target_file_path, force: true
    logger.info "#{source_file_path} was moved to #{target_file_path}"
  rescue StandardError => exc
    logger.error "#{source_file_path} could not be moved #{exc.to_s}, target was #{target_file_path}"
  end
end