request.rb 2.17 KB
# -*- encoding : utf-8 -*-
# == Schema Information
#
# Table name: v_libras_requests
#
#  id             :integer          not null, primary key
#  status         :string(255)
#  service_type   :string(255)
#  owner_id       :integer
#  params         :text
#  response       :text
#  created_at     :datetime
#  updated_at     :datetime
#  video_filename :string(255)
#

class VLibras::Request < ActiveRecord::Base
  serialize :params
  attr_accessor :files

  belongs_to :owner, :class => User

  has_one :video, :class => VLibras::Video, :dependent => :destroy

  validates :service_type,
            presence: true,
            inclusion: { in: %w(video-legenda video) }

  validates :status,
            presence: true,
            inclusion: { in: %w(created processing error success) }

  validate :match_files_with_service_type

  before_validation :default_values

  default_scope { order('created_at DESC') }

  def self.build_from_params(params, user)
    request = self.new

    request.service_type = params[:service]
    request.owner = user

    request.files = {}

    if params[:video]
      request.video_filename = params[:video].original_filename
      video = FileUploader.new
      video.cache!(params[:video])
      request.files.merge!(:video => video)
    end

    if params[:subtitle]
      subtitle = FileUploader.new
      subtitle.cache!(params[:subtitle])
      request.files.merge!(:subtitle => subtitle)
    end

    request.params = params[:params]

    request
  end

  def perform_request(files)
    logger.debug '[VLibras::Request] Starting request'
    self.update!(status: 'processing')

    ApiClient::Client.submit(self, files)

    # Warning: this code is also present on the controller, if there is an error
    files.values.each { |f| f.file.delete }

    logger.debug '[VLibras::Request] Request done'
  end

private
  def match_files_with_service_type
    return unless files

    if files[:video].nil?
      errors.add(:base, 'Você precisa enviar um vídeo.')
    end

    if (service_type == 'video-legenda') && files[:subtitle].nil?
      errors.add(:base, 'Você precisa enviar uma legenda.')
    end
  end

  def default_values
    self.status ||= 'created'
  end
end