From 3e0c12af918936eee86332b89ffb60ecb9caf23a Mon Sep 17 00:00:00 2001 From: Charlotte Van Petegem Date: Thu, 10 Oct 2024 22:31:03 +0200 Subject: [PATCH] Transcode to a temporary file which is only moved when finished --- app/jobs/create_transcoded_item_job.rb | 2 +- app/models/audio_file.rb | 8 ++++++++ test/jobs/create_transcoded_item_job_test.rb | 5 +++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/jobs/create_transcoded_item_job.rb b/app/jobs/create_transcoded_item_job.rb index ce7821d2..7f7cb4aa 100644 --- a/app/jobs/create_transcoded_item_job.rb +++ b/app/jobs/create_transcoded_item_job.rb @@ -8,7 +8,7 @@ def perform(audio_file, codec_conversion) uuid = TranscodedItem.uuid_for(codec_conversion) path = TranscodedItem.path_for(codec_conversion, uuid) FileUtils.mkdir_p Pathname.new(path).parent - audio_file.convert(codec_conversion, path) + audio_file.convert_and_move(codec_conversion, path) TranscodedItem.transaction do # Check that the transcoded item was not created while we were executing diff --git a/app/models/audio_file.rb b/app/models/audio_file.rb index 9e53a59d..607dba78 100644 --- a/app/models/audio_file.rb +++ b/app/models/audio_file.rb @@ -37,6 +37,14 @@ def check_self false end + def convert_and_move(codec_conversion, out_file_name) + tmp_path = File.join(Dir.tmpdir, "accentor_transcode-#{id}-#{codec_conversion.id}-#{SecureRandom.uuid}") + convert(codec_conversion, tmp_path) + FileUtils.mv tmp_path, out_file_name + ensure + FileUtils.rm_f tmp_path + end + def convert(codec_conversion, out_file_name) parameters = codec_conversion.ffmpeg_params.split _stdout, status = Open3.capture2( diff --git a/test/jobs/create_transcoded_item_job_test.rb b/test/jobs/create_transcoded_item_job_test.rb index c439f80f..7fb01d8f 100644 --- a/test/jobs/create_transcoded_item_job_test.rb +++ b/test/jobs/create_transcoded_item_job_test.rb @@ -34,11 +34,12 @@ class CreateTranscodedItemJobTest < ActiveJob::TestCase test 'should abort when TranscodedItem was created while converting' do audio_file = @audio_file codec_conversion = @codec_conversion - AudioFile.define_method :convert, lambda { |_codec_conversion, _out_file_name| + AudioFile.define_method :convert, lambda { |_codec_conversion, out_file_name| + FileUtils.touch out_file_name TranscodedItem.create!(audio_file:, codec_conversion:, uuid: '0000-0000-0000') } - FileUtils.stubs(:rm_f).once + FileUtils.stubs(:rm_f).twice CreateTranscodedItemJob.perform_now(@audio_file, @codec_conversion) end