Sha256: 6b9adfd4d93215b8afcf389af232276f3f6b800f69ff71005f156c39f7d6a100

Contents?: true

Size: 1.76 KB

Versions: 21

Compression:

Stored size: 1.76 KB

Contents

module Ddr
  class File < Valkyrie::Resource

    attribute :digest, Valkyrie::Types::Set.of(Ddr::Digest)
    attribute :file_identifier, Valkyrie::Types::ID
    attribute :media_type, Valkyrie::Types::Strict::String.optional
    attribute :original_filename, Valkyrie::Types::Strict::String

    DEFAULT_FILE_EXTENSION = 'bin'

    def content
      file.read
    end

    def file
      Ddr.storage_adapter.find_by(id: file_identifier)
    end

    def file_created_at
      ::File::Stat.new(Ddr.storage_adapter.file_path(file_identifier)).ctime
    end

    def file_path
      Ddr.storage_adapter.file_path(file_identifier)
    end

    def file_size
      file.size
    end

    # Return default file extension for file based on MIME type
    def default_file_extension
      mimetypes = MIME::Types[media_type]
      return mimetypes.first.extensions.first unless mimetypes.empty?
      case media_type
      when 'application/n-triples'
        'txt'
      else
        DEFAULT_FILE_EXTENSION
      end
    end

    def stored_checksums_valid?
      checksums = digest.each_with_object({}) { |dgst, memo| memo[dgst.type] = dgst.value }
      file.valid? digests: checksums
    end

    def validate_checksum!(checksum_value, checksum_type)
      raise Ddr::Error, I18n.t('ddr.checksum.validation.must_be_stored') unless file_identifier.present?
      raise Ddr::ChecksumInvalid, I18n.t('ddr.checksum.validation.internal_check_failed') unless stored_checksums_valid?
      if file.valid? digests: { checksum_type => checksum_value }
        I18n.t('ddr.checksum.validation.valid', type: checksum_type, value: checksum_value)
      else
        raise Ddr::ChecksumInvalid,
              I18n.t('ddr.checksum.validation.invalid', type: checksum_type, value: checksum_value)
      end
    end

  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
ddr-core-0.3.0 app/models/ddr/file.rb