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.6 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. # domain :string
  16. #
  17. class Subscription < ApplicationRecord
  18. MIN_EXPIRATION = 1.day.to_i
  19. MAX_EXPIRATION = 30.days.to_i
  20. belongs_to :account, required: true
  21. validates :callback_url, presence: true
  22. validates :callback_url, uniqueness: { scope: :account_id }
  23. scope :confirmed, -> { where(confirmed: true) }
  24. scope :future_expiration, -> { where(arel_table[:expires_at].gt(Time.now.utc)) }
  25. scope :active, -> { confirmed.future_expiration }
  26. def lease_seconds=(value)
  27. self.expires_at = future_expiration(value)
  28. end
  29. def lease_seconds
  30. (expires_at - Time.now.utc).to_i
  31. end
  32. def expired?
  33. Time.now.utc > expires_at
  34. end
  35. before_validation :set_min_expiration
  36. private
  37. def future_expiration(value)
  38. Time.now.utc + future_offset(value).seconds
  39. end
  40. def future_offset(seconds)
  41. [
  42. [MIN_EXPIRATION, seconds.to_i].max,
  43. MAX_EXPIRATION,
  44. ].min
  45. end
  46. def set_min_expiration
  47. self.lease_seconds = 0 unless expires_at
  48. end
  49. end