Sha256: 648438ee9ba57627f7c02c3bb547b30d72599a7fa5f87c626e35456ffeb0ad2e

Contents?: true

Size: 1.77 KB

Versions: 5

Compression:

Stored size: 1.77 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.preferred_extension 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

5 entries across 5 versions & 1 rubygems

Version Path
ddr-core-1.6.6 app/models/ddr/file.rb
ddr-core-1.6.5 app/models/ddr/file.rb
ddr-core-1.6.4 app/models/ddr/file.rb
ddr-core-1.6.3 app/models/ddr/file.rb
ddr-core-1.6.2 app/models/ddr/file.rb