Skip to content
Snippets Groups Projects
download_all_controller.rb 3.55 KiB
class DownloadAllController < Hyrax::DownloadsController
  include HyraxHelper
  include DownloadHelper
  # include Hydra::Controller::DownloadBehavior
  include Hyrax::LocalFileDownloadsControllerBehavior

  # GET /download_all/1
  def show
    head :not_found unless work.present?
    respond_to do |format|
      format.zip {
        build_zip_file unless has_zip_file?
        return send_zip_file if has_zip_file?
        head :not_found
      }
      format.sh {
        has_shell_file? ? send_shell_file : (redirect_to :action => 'show')
      }
      format.html { build_download_file }
      format.any { head :unsupported_media_type }
    end
  end

  def build_download_file
    return redirect_to format: :zip if has_zip_file?
    return redirect_to format: :sh if has_shell_file?
    # Created id.txt file that store timestamp when we start download
    create_or_modify_ts_file
    #ToDo: Can we check for this faster than getting list from S3?
    list_of_objects, _total_size, format = objects_size_and_file_format
    if format == 'zip'
      build_zip_file(list_of_objects: list_of_objects)
      redirect_to format: :zip
    else
      # async job redirects to show
      build_shell_file
      flash[:alert] = I18n.t('hyrax.notifications.preparing_download.message')
      redirect_to main_app.polymorphic_path(work)
    end
  end

  def authorize_download!
    authorize! :download, params[:id]
  rescue CanCan::AccessDenied
    unauthorized_image = Rails.root.join("app", "assets", "images", "unauthorized.png")
    send_file unauthorized_image, status: :unauthorized
  end

  def button_ready
    render json: { is_ready: download_all_button_available?(params[:id]) }, status: 200
  end

  private

  def work
    @work ||= Hyrax.query_service.find_by(id: params[:id])
  end

  def file
    @file ||= if formats.include?(:zip)
                zip_file_path
              elsif formats.include?(:sh)
                shell_file_path
              else
                File.exist?(zip_file_path) ? zip_file_path : shell_file_path
              end
  end

  def send_zip_file
    return head :not_found unless has_zip_file?