Class: CallRecordSwitchvoxImporterFile
- Inherits:
-
Object
- Object
- CallRecordSwitchvoxImporterFile
- Defined in:
- app/services/call_record_switchvox_importer_file.rb
Overview
Service object: switchvox importer file.
Instance Attribute Summary collapse
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
Instance Method Summary collapse
-
#archive_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) ⇒ Object
Move the source .wav/.xml and the converted audio into processed/ after a successful import.
- #archive_file(file_name) ⇒ Object
- #attach_file_to_call_record(cr, local_file_path) ⇒ Object
-
#call_attributes(xml_doc) ⇒ Object
Retrieve all interesting attributes to a hash.
- #caller_id_parser(cid) {|origin_name, origin_number| ... } ⇒ Object
- #convert_to_aac(local_file_path) ⇒ Object
-
#convert_to_oga(local_file_path) ⇒ Object
By far the best for compressing audio.
- #error_folder ⇒ Object
- #get_file_list ⇒ Object
- #import_file(file_name) ⇒ Object
-
#import_new_records(limit = nil) ⇒ Object
Main entry point method.
-
#initialize(options = {}) ⇒ CallRecordSwitchvoxImporterFile
constructor
A new instance of CallRecordSwitchvoxImporterFile.
-
#parse_node(xml_doc, node_name) ⇒ Object
Simplify retrieval of attributes since we only have one in this file.
-
#parse_xml_file(file_path) ⇒ Object
Parse a remote file using nokogiri and returns a nokogiri doc.
- #processed_folder ⇒ Object
-
#quarantine_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) ⇒ Object
Move the same artifacts into errors/ when the import fails.
-
#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).
- #remote_path ⇒ Object
- #skip_download? ⇒ Boolean
- #unprocessable_file(file_name) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ CallRecordSwitchvoxImporterFile
Returns a new instance of CallRecordSwitchvoxImporterFile.
9 10 11 12 13 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 9 def initialize( = {}) @options = @logger = [:logger] || Rails.logger @options[:remote_path] ||= Heatwave::Application.config.x.call_records_directory end |
Instance Attribute Details
#logger ⇒ Object (readonly)
Returns the value of attribute logger.
7 8 9 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 7 def logger @logger end |
Instance Method Details
#archive_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) ⇒ Object
Move the source .wav/.xml and the converted audio into processed/ after a successful
import. The converted file is referenced by its REAL name (File.basename), so the
extension can never drift again: a hardcoded ".oga" here (a leftover from
convert_to_oga) once silently orphaned every converted .aac in the source dir.
265 266 267 268 269 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 265 def archive_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) archive_file "#{base_file_name}.xml" if File.exist?(xml_local_file_path) archive_file "#{base_file_name}.wav" archive_file File.basename(converted_local_file_path) if converted_local_file_path end |
#archive_file(file_name) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 61 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 => e logger.error "#{source_file_path} could not be moved #{e}, target was #{target_file_path}" end end |
#attach_file_to_call_record(cr, local_file_path) ⇒ Object
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 130 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 && !au.new_record? && au..present? logger.info " ** Audio record upload #{au.id} created" cr.update_attribute!(:imported, true) true else = "!! Problem creating audio record for #{local_file_path}: #{au.errors_to_s}" logger.error Mailer.admin_notification().deliver_now if Rails.env.production? || Rails.env.staging? false end end |
#call_attributes(xml_doc) ⇒ Object
Retrieve all interesting attributes to a hash
160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 160 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
278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 278 def caller_id_parser(cid) return if cid.blank? expr = cid.match(/(.+)<(\d+)>/) if expr && (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
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 87 def convert_to_aac(local_file_path) require 'streamio-ffmpeg' # A recording can vanish before conversion (already archived by a prior run, # or the R2 download was skipped/cleaned up). FFMPEG::Movie.new would then # raise Errno::ENOENT and crash the import (AppSignal #5976). Treat a missing # file like an empty/invalid one — import_file already archives + returns on nil. unless local_file_path && File.exist?(local_file_path) logger.warn('Skipping conversion — recording file missing', path: local_file_path) return nil end 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 rescue Errno::ENOENT => e # Safety net for the check-then-open race: the file can still vanish between # the File.exist? guard above and FFMPEG opening it (a concurrent importer run # archives it). Treat it like a missing file — skip, don't crash (#5976). logger.warn('Skipping conversion — recording file vanished mid-convert', path: local_file_path, error: e.) nil end |
#convert_to_oga(local_file_path) ⇒ Object
By far the best for compressing audio
120 121 122 123 124 125 126 127 128 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 120 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_folder ⇒ Object
49 50 51 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 49 def error_folder @options[:error_folder] || "errors/" end |
#get_file_list ⇒ Object
57 58 59 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 57 def get_file_list Dir["#{remote_path}/*.wav"].select { |path| File.file?(path) } end |
#import_file(file_name) ⇒ Object
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 253 254 255 256 257 258 259 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 174 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_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_artifacts(base_file_name, xml_local_file_path, nil) 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.switchvox_from_account_id = call_attrs[:from_account_id] cr.switchvox_to_account_id = 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/) _, _, _, _, _, _, 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? cr.call_outcome = :voicemail if cr.destination_number.to_s.in?(CallRecord::VOICEMAIL_EXTENSIONS) 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_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) rescue StandardError => e = " !! Call Record failed to save for file #{file_name}, #{e}" logger.error ErrorReporting.error(e, file_name: file_name) quarantine_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) end end |
#import_new_records(limit = nil) ⇒ Object
Main entry point method
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 16 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
155 156 157 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 155 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
149 150 151 152 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 149 def parse_xml_file(file_path) xml_doc = Nokogiri::XML(File.read(file_path)) call_attributes(xml_doc) end |
#processed_folder ⇒ Object
45 46 47 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 45 def processed_folder @options[:processed_folder] || "processed/" end |
#quarantine_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) ⇒ Object
Move the same artifacts into errors/ when the import fails.
272 273 274 275 276 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 272 def quarantine_artifacts(base_file_name, xml_local_file_path, converted_local_file_path) unprocessable_file "#{base_file_name}.wav" unprocessable_file "#{base_file_name}.xml" if File.exist?(xml_local_file_path) unprocessable_file File.basename(converted_local_file_path) if converted_local_file_path 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.
300 301 302 303 304 305 306 307 308 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 300 def queue_transcription_if_eligible(call_record) return unless call_record.persisted? return if call_record.upload.blank? 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_path ⇒ Object
41 42 43 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 41 def remote_path @options[:remote_path] end |
#skip_download? ⇒ Boolean
53 54 55 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 53 def skip_download? @options[:skip_download].nil? ? false : @options[:skip_download] end |
#unprocessable_file(file_name) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 |
# File 'app/services/call_record_switchvox_importer_file.rb', line 75 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 => e logger.error "#{source_file_path} could not be moved #{e}, target was #{target_file_path}" end end |