You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.5 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: subscriptions
  5. #
  6. # id :integer not null, primary key
  7. # callback_url :string default(""), not null
  8. # secret :string
  9. # expires_at :datetime
  10. # confirmed :boolean default(FALSE), not null
  11. # account_id :integer not null
  12. # created_at :datetime not null
  13. # updated_at :datetime not null
  14. # last_successful_delivery_at :datetime
  15. #
  16. class Subscription < ApplicationRecord
  17. MIN_EXPIRATION = 7.days.seconds.to_i
  18. MAX_EXPIRATION = 30.days.seconds.to_i
  19. belongs_to :account, required: true
  20. validates :callback_url, presence: true
  21. validates :callback_url, uniqueness: { scope: :account_id }
  22. scope :confirmed, -> { where(confirmed: true) }
  23. scope :future_expiration, -> { where(arel_table[:expires_at].gt(Time.now.utc)) }
  24. scope :active, -> { confirmed.future_expiration }
  25. def lease_seconds=(value)
  26. self.expires_at = future_expiration(value)
  27. end
  28. def lease_seconds
  29. (expires_at - Time.now.utc).to_i
  30. end
  31. def expired?
  32. Time.now.utc > expires_at
  33. end
  34. before_validation :set_min_expiration
  35. private
  36. def future_expiration(value)
  37. Time.now.utc + future_offset(value).seconds
  38. end
  39. def future_offset(seconds)
  40. [
  41. [MIN_EXPIRATION, seconds.to_i].max,
  42. MAX_EXPIRATION,
  43. ].min
  44. end
  45. def set_min_expiration
  46. self.lease_seconds = 0 unless expires_at
  47. end
  48. end