Skip to content

Instantly share code, notes, and snippets.

@crusadergo
Created August 21, 2018 07:58
Show Gist options
  • Save crusadergo/f2a954e6d57939c9af7d7d5619b6700d to your computer and use it in GitHub Desktop.
Save crusadergo/f2a954e6d57939c9af7d7d5619b6700d to your computer and use it in GitHub Desktop.
module Api
module V1
class AudiosController < ApplicationController
def create
return render json: { error: 'File format error.' } unless file_exist? && mp3_exist?
return render json: { error: 'Request format error.' } unless artist_exist? && song_exist?
audio = Audio.new audio_params
audio.save!
original_path = audio_path 'original', audio
clone_path = audio_path '128kbps', audio
save_original original_path
save_clone original_path, clone_path
render json: { track_id: audio.id }
end
protected
# Saving the original into a separate folder
def save_original original_path
File.open(original_path, 'wb') { |f| f.write(params[:file].read) }
end
# Saving the clone with a lower bitrate into a separate folder
def save_clone original_path, clone_path
`avconv -i #{ original_path } -c:a libmp3lame -b:a 128k #{ clone_path }`
end
# Generates a path for saving files
def audio_path additional_path, audio
File.join 'public', 'audio', additional_path, audio.id.to_s +
'_' + audio.artist.gsub(' ', '_') +
'_' + audio.song.gsub(' ', '_') + '.mp3'
end
# Checks file existance in the request
def file_exist?
params[:file]
end
# Checks mp3 extension existance in the request
def mp3_exist?
params[:file].original_filename.split('.').last == 'mp3'
end
# Checks artist existance in the request
def artist_exist?
params[:artist]
end
# Checks song existance in the request
def song_exist?
params[:song]
end
private
# Permitted attributes
def audio_params
params.permit(:file, :artist, :song)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment