2019-09-19 22:12:15 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Api
|
|
|
|
module V1
|
|
|
|
class AssetsController < BaseController
|
|
|
|
before_action :load_team, :load_project, :load_experiment, :load_task, :load_protocol, :load_step
|
|
|
|
before_action :load_asset, only: :show
|
2020-07-24 20:56:42 +08:00
|
|
|
before_action :check_upload_type, only: :create
|
2019-09-19 22:12:15 +08:00
|
|
|
|
|
|
|
def index
|
|
|
|
attachments = @step.assets
|
|
|
|
.page(params.dig(:page, :number))
|
|
|
|
.per(params.dig(:page, :size))
|
|
|
|
|
|
|
|
render jsonapi: attachments, each_serializer: AssetSerializer
|
|
|
|
end
|
|
|
|
|
|
|
|
def show
|
|
|
|
render jsonapi: @asset, serializer: AssetSerializer
|
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
raise PermissionError.new(Asset, :create) unless can_manage_protocol_in_module?(@protocol)
|
|
|
|
|
2020-07-24 20:56:42 +08:00
|
|
|
if @form_multipart_upload
|
2020-09-25 14:38:38 +08:00
|
|
|
asset = @step.assets.new(asset_params.merge({ team_id: @team.id }))
|
2020-07-24 20:56:42 +08:00
|
|
|
else
|
2021-01-28 21:43:45 +08:00
|
|
|
blob = ActiveStorage::Blob.create_and_upload!(
|
2020-07-24 20:56:42 +08:00
|
|
|
io: StringIO.new(Base64.decode64(asset_params[:file_data])),
|
|
|
|
filename: asset_params[:file_name],
|
2020-07-25 17:41:26 +08:00
|
|
|
content_type: asset_params[:file_type]
|
2020-07-24 20:56:42 +08:00
|
|
|
)
|
2020-09-25 14:38:38 +08:00
|
|
|
asset = @step.assets.new(file: blob, team: @team)
|
2020-07-24 20:56:42 +08:00
|
|
|
end
|
2019-09-19 22:12:15 +08:00
|
|
|
|
2020-07-24 20:56:42 +08:00
|
|
|
asset.save!(context: :on_api_upload)
|
2019-10-01 18:50:54 +08:00
|
|
|
asset.post_process_file
|
2019-09-19 22:12:15 +08:00
|
|
|
|
|
|
|
render jsonapi: asset,
|
|
|
|
serializer: AssetSerializer,
|
|
|
|
status: :created
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def asset_params
|
|
|
|
raise TypeError unless params.require(:data).require(:type) == 'attachments'
|
|
|
|
|
2020-07-24 20:56:42 +08:00
|
|
|
return params.require(:data).require(:attributes).permit(:file) if @form_multipart_upload
|
|
|
|
|
2020-07-25 17:41:26 +08:00
|
|
|
attr_list = %i(file_data file_type file_name)
|
2019-09-19 22:12:15 +08:00
|
|
|
params.require(:data).require(:attributes).require(attr_list)
|
|
|
|
params.require(:data).require(:attributes).permit(attr_list)
|
|
|
|
end
|
|
|
|
|
|
|
|
def load_asset
|
|
|
|
@asset = @step.assets.find(params.require(:id))
|
2019-10-01 18:50:54 +08:00
|
|
|
raise PermissionError.new(Asset, :read) unless can_read_protocol_in_module?(@asset.step.protocol)
|
2019-09-19 22:12:15 +08:00
|
|
|
end
|
2020-07-24 20:56:42 +08:00
|
|
|
|
|
|
|
def check_upload_type
|
2020-07-25 17:41:26 +08:00
|
|
|
@form_multipart_upload = true if params.dig(:data, :attributes, :file)
|
2020-07-24 20:56:42 +08:00
|
|
|
end
|
2019-09-19 22:12:15 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|