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.

62 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: subscriptions
  5. #
  6. # id :bigint(8) 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. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. # last_successful_delivery_at :datetime
  14. # domain :string
  15. # account_id :bigint(8) not null
  16. #
  17. class Subscription < ApplicationRecord
  18. MIN_EXPIRATION = 1.day.to_i
  19. MAX_EXPIRATION = 30.days.to_i
  20. belongs_to :account
  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 :expired, -> { where(arel_table[:expires_at].lt(Time.now.utc)) }
  26. scope :active, -> { confirmed.future_expiration }
  27. def lease_seconds=(value)
  28. self.expires_at = future_expiration(value)
  29. end
  30. def lease_seconds
  31. (expires_at - Time.now.utc).to_i
  32. end
  33. def expired?
  34. Time.now.utc > expires_at
  35. end
  36. before_validation :set_min_expiration
  37. private
  38. def future_expiration(value)
  39. Time.now.utc + future_offset(value).seconds
  40. end
  41. def future_offset(seconds)
  42. [
  43. [MIN_EXPIRATION, seconds.to_i].max,
  44. MAX_EXPIRATION,
  45. ].min
  46. end
  47. def set_min_expiration
  48. self.lease_seconds = 0 unless expires_at
  49. end
  50. end