diff --git a/lib/travis/api/v3/models/broadcast.rb b/lib/travis/api/v3/models/broadcast.rb index 9c713d8e..d6cd95b6 100644 --- a/lib/travis/api/v3/models/broadcast.rb +++ b/lib/travis/api/v3/models/broadcast.rb @@ -1,5 +1,14 @@ module Travis::API::V3 class Models::Broadcast < Model + EXPIRY_TIME = 14.days + belongs_to :recipient, polymorphic: true + scope :active, -> { where('created_at >= ? AND (expired IS NULL OR expired <> ?)', EXPIRY_TIME.ago, true) } + scope :inactive, -> { where('created_at < ? OR (expired = ?)', EXPIRY_TIME.ago, true) } + + def active? + return false if expired? + created_at >= EXPIRY_TIME.ago + end end end diff --git a/lib/travis/api/v3/queries/broadcasts.rb b/lib/travis/api/v3/queries/broadcasts.rb index 04cac2ba..af2c43e2 100644 --- a/lib/travis/api/v3/queries/broadcasts.rb +++ b/lib/travis/api/v3/queries/broadcasts.rb @@ -1,13 +1,35 @@ module Travis::API::V3 class Queries::Broadcasts < Query + params :active, prefix: :broadcast + + def initialize(*) + super + self.active = "true".freeze if active.nil? + end + def for_user(user) - query = %( + all.where(<<-SQL, 'Organization'.freeze, user.organization_ids, 'User'.freeze, user.id, 'Repository'.freeze, user.repository_ids) recipient_type IS NULL OR recipient_type = ? AND recipient_id IN(?) OR recipient_type = ? AND recipient_id = ? OR recipient_type = ? AND recipient_id IN (?) - ) - Models::Broadcast.where(query, 'Organization', user.organization_ids, 'User', user.id, 'Repository', user.repository_ids) + SQL + end + + def all + @all ||= filter(Models::Broadcast) + end + + def filter(list) + active = list(self.active).map { |e| bool(e) } + + if active.include? true + list = list.active unless active.include? false + else + list = list.inactive + end + + list end end end