Skip to content

Commit

Permalink
Make audio_file#convert raise an exception on failure (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
chvp authored Oct 10, 2024
1 parent cc9633c commit 19d8a43
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
10 changes: 5 additions & 5 deletions app/models/audio_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#

class AudioFile < ApplicationRecord
class FailedTranscode < StandardError; end

belongs_to :location
belongs_to :codec
has_one :track, dependent: :nullify
Expand All @@ -37,7 +39,7 @@ def check_self

def convert(codec_conversion, out_file_name)
parameters = codec_conversion.ffmpeg_params.split
Open3.popen2(
_stdout, status = Open3.capture2(
'ffmpeg',
'-i', full_path,
'-f', codec_conversion.resulting_codec.extension,
Expand All @@ -46,10 +48,8 @@ def convert(codec_conversion, out_file_name)
'-map', 'a',
out_file_name,
err: [Rails.configuration.ffmpeg_log_location, 'a']
) do |_stdin, _stdout, _wait_thr|
# We call `Open3.popen2` with an empty block, so the process finishes before we return
# This returns `Process::Status`
end
)
raise FailedTranscode, "ffmpeg exited with #{status.to_i}" unless status.success?
end

def full_path
Expand Down
21 changes: 20 additions & 1 deletion test/models/audio_file_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@
require 'test_helper'

class AudioFileTest < ActiveSupport::TestCase
class ProcessStub
def initialize(exit_status)
@exit_status = exit_status
end

def success? = @exit_status.zero?
def to_i = @exit_status
end

def setup
location = Location.create(path: Rails.root.join('test/files'))
codec = Codec.create(extension: 'flac', mimetype: 'audio/flac')
Expand All @@ -26,10 +35,20 @@ def setup

path = TranscodedItem.path_for(codec_conversion, SecureRandom.uuid)

Open3.stubs(:popen2).once.with do |*args, **kwargs|
Open3.stubs(:capture2).once.returns(['', ProcessStub.new(0)]).with do |*args, **kwargs|
args.include?('ffmpeg') && args.include?(@audio_file.full_path) && args[-1] == path && kwargs.key?(:err)
end

@audio_file.convert(codec_conversion, path)
end

test 'convert should raise if underlying process fails' do
codec_conversion = create(:codec_conversion)

Open3.stubs(:capture2).once.returns(['', ProcessStub.new(9)])

assert_raises AudioFile::FailedTranscode do
@audio_file.convert(codec_conversion, TranscodedItem.path_for(codec_conversion, SecureRandom.uuid))
end
end
end

0 comments on commit 19d8a43

Please sign in to comment.