74 lines
2.3 KiB
Ruby
74 lines
2.3 KiB
Ruby
module JamRuby
|
|
|
|
# describes what users have rights to which tracks
|
|
class JamTrackRight < ActiveRecord::Base
|
|
include JamRuby::S3ManagerMixin
|
|
attr_accessible :user, :jam_track, :user_id, :jam_track_id, :url, :md5, :length, :download_count
|
|
belongs_to :user, class_name: "JamRuby::User" # the owner, or purchaser of the jam_track
|
|
belongs_to :jam_track, class_name: "JamRuby::JamTrack"
|
|
|
|
validates :user, presence:true
|
|
validates :jam_track, presence:true
|
|
validate :verify_download_count
|
|
|
|
validates_uniqueness_of :user_id, scope: :jam_track_id
|
|
|
|
# Uploads the JKZ:
|
|
mount_uploader :url, JamTrackRightUploader
|
|
before_destroy :delete_s3_files
|
|
|
|
MAX_JAM_TRACK_DOWNLOADS = 1000
|
|
|
|
def store_dir
|
|
"#{jam_track.store_dir}/rights"
|
|
end
|
|
|
|
# create name of the file
|
|
def filename
|
|
"#{jam_track.name}.jkz"
|
|
end
|
|
|
|
def verify_download_count
|
|
if (self.download_count < 0 || self.download_count > MAX_JAM_TRACK_DOWNLOADS) && !@current_user.admin
|
|
errors.add(:download_count, "must be less than or equal to #{MAX_JAM_TRACK_DOWNLOADS}")
|
|
end
|
|
end
|
|
|
|
def self.ready_to_clean
|
|
JamTrackRight.where("downloaded_since_sign=? AND updated_at <= ?", true, 5.minutes.ago).limit(1000)
|
|
end
|
|
|
|
# creates a short-lived URL that has access to the object.
|
|
# the idea is that this is used when a user who has the rights to this tries to download this JamTrack
|
|
# we would verify their rights (can_download?), and generates a URL in response to the click so that they can download
|
|
# but the url is short lived enough so that it wouldn't be easily shared
|
|
def sign_url(expiration_time = 120)
|
|
s3_manager.sign_url(self[:url], {:expires => expiration_time, :secure => false})
|
|
end
|
|
|
|
def delete_s3_files
|
|
remove_url!
|
|
end
|
|
|
|
def enqueue
|
|
begin
|
|
Resque.enqueue(JamTracksBuilder, self.id)
|
|
rescue Exception => e
|
|
# implies redis is down. we don't update started_at by bailing out here
|
|
false
|
|
end
|
|
|
|
# avoid db validations
|
|
JamTrackRight.where(:id => self.id).update_all(:last_downloaded_at => Time.now)
|
|
|
|
true
|
|
end
|
|
|
|
def update_download_count(count=1)
|
|
self.download_count = self.download_count + count
|
|
self.last_downloaded_at = Time.now
|
|
end
|
|
|
|
end
|
|
end
|