Sha256: ac38fbcf542d48192e660e8b8e6cdb99dcad0435f47aa9a2649cac9acfe85c2b

Contents?: true

Size: 1.82 KB

Versions: 15

Compression:

Stored size: 1.82 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

    def sha1
      digest.detect(&:sha1?)&.value
    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

15 entries across 15 versions & 1 rubygems

Version Path
ddr-core-1.17.0 app/models/ddr/file.rb
ddr-core-1.16.0 app/models/ddr/file.rb
ddr-core-1.15.0 app/models/ddr/file.rb
ddr-core-1.14.0 app/models/ddr/file.rb
ddr-core-1.13.2 app/models/ddr/file.rb
ddr-core-1.13.1 app/models/ddr/file.rb
ddr-core-1.13.0 app/models/ddr/file.rb
ddr-core-1.12.2 app/models/ddr/file.rb
ddr-core-1.12.1 app/models/ddr/file.rb
ddr-core-1.12.0 app/models/ddr/file.rb
ddr-core-1.11.0 app/models/ddr/file.rb
ddr-core-1.10.0 app/models/ddr/file.rb
ddr-core-1.9.0 app/models/ddr/file.rb
ddr-core-1.8.0 app/models/ddr/file.rb
ddr-core-1.7.0 app/models/ddr/file.rb