2017-07-05 07:06:29 -04:00
|
|
|
require "active_vault/site"
|
|
|
|
require "active_vault/filename"
|
2017-06-30 18:04:19 -04:00
|
|
|
|
2017-07-01 08:24:00 -04:00
|
|
|
# Schema: id, key, filename, content_type, metadata, byte_size, checksum, created_at
|
2017-07-05 07:06:29 -04:00
|
|
|
class ActiveVault::Blob < ActiveRecord::Base
|
2017-07-05 09:07:22 -04:00
|
|
|
self.table_name = "active_vault_blobs"
|
2017-06-30 13:12:58 -04:00
|
|
|
|
2017-06-30 18:02:30 -04:00
|
|
|
has_secure_token :key
|
2017-06-30 13:12:58 -04:00
|
|
|
store :metadata, coder: JSON
|
|
|
|
|
2017-06-30 18:04:19 -04:00
|
|
|
class_attribute :site
|
2017-06-30 13:12:58 -04:00
|
|
|
|
|
|
|
class << self
|
2017-07-04 10:05:06 -04:00
|
|
|
def build_after_upload(io:, filename:, content_type: nil, metadata: nil)
|
2017-06-30 13:12:58 -04:00
|
|
|
new.tap do |blob|
|
2017-07-04 12:43:56 -04:00
|
|
|
blob.filename = filename
|
2017-07-04 12:44:06 -04:00
|
|
|
blob.content_type = content_type
|
2017-07-05 09:18:42 -04:00
|
|
|
blob.metadata = metadata
|
2017-07-04 12:44:06 -04:00
|
|
|
|
2017-07-04 10:05:06 -04:00
|
|
|
blob.upload io
|
2017-06-30 13:12:58 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-07-04 10:05:06 -04:00
|
|
|
def create_after_upload!(io:, filename:, content_type: nil, metadata: nil)
|
|
|
|
build_after_upload(io: io, filename: filename, content_type: content_type, metadata: metadata).tap(&:save!)
|
2017-06-30 13:12:58 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-07-01 06:47:13 -04:00
|
|
|
# We can't wait until the record is first saved to have a key for it
|
|
|
|
def key
|
|
|
|
self[:key] ||= self.class.generate_unique_secure_token
|
|
|
|
end
|
2017-06-30 18:13:23 -04:00
|
|
|
|
2017-06-30 13:12:58 -04:00
|
|
|
def filename
|
2017-07-05 07:06:29 -04:00
|
|
|
ActiveVault::Filename.new(self[:filename])
|
2017-07-03 14:13:50 -04:00
|
|
|
end
|
2017-07-03 14:14:28 -04:00
|
|
|
|
2017-07-04 11:34:37 -04:00
|
|
|
def url(expires_in: 5.minutes, disposition: :inline)
|
|
|
|
site.url key, expires_in: expires_in, disposition: disposition, filename: filename
|
2017-06-30 13:12:58 -04:00
|
|
|
end
|
|
|
|
|
2017-06-30 18:13:23 -04:00
|
|
|
|
2017-07-04 10:05:06 -04:00
|
|
|
def upload(io)
|
|
|
|
site.upload(key, io)
|
2017-07-01 08:25:02 -04:00
|
|
|
|
|
|
|
self.checksum = site.checksum(key)
|
|
|
|
self.byte_size = site.byte_size(key)
|
2017-07-01 06:47:13 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def download
|
|
|
|
site.download key
|
|
|
|
end
|
|
|
|
|
|
|
|
|
2017-06-30 13:12:58 -04:00
|
|
|
def delete
|
2017-07-01 06:47:13 -04:00
|
|
|
site.delete key
|
2017-06-30 13:12:58 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def purge
|
|
|
|
delete
|
|
|
|
destroy
|
|
|
|
end
|
|
|
|
|
|
|
|
def purge_later
|
2017-07-05 07:06:29 -04:00
|
|
|
ActiveVault::PurgeJob.perform_later(self)
|
2017-06-30 13:12:58 -04:00
|
|
|
end
|
|
|
|
end
|