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.

161 lines
4.8 KiB

Web Push Notifications (#3243) * feat: Register push subscription * feat: Notify when mentioned * feat: Boost, favourite, reply, follow, follow request * feat: Notification interaction * feat: Handle change of public key * feat: Unsubscribe if things go wrong * feat: Do not send normal notifications if push is enabled * feat: Focus client if open * refactor: Move push logic to WebPushSubscription * feat: Better title and body * feat: Localize messages * chore: Fix lint errors * feat: Settings * refactor: Lazy load * fix: Check if push settings exist * feat: Device-based preferences * refactor: Simplify logic * refactor: Pull request feedback * refactor: Pull request feedback * refactor: Create /api/web/push_subscriptions endpoint * feat: Spec PushSubscriptionController * refactor: WebPushSubscription => Web::PushSubscription * feat: Spec Web::PushSubscription * feat: Display first media attachment * feat: Support direction * fix: Stuff broken while rebasing * refactor: Integration with session activations * refactor: Cleanup * refactor: Simplify implementation * feat: Set VAPID keys via environment * chore: Comments * fix: Crash when no alerts * fix: Set VAPID keys in testing environment * fix: Follow link * feat: Notification actions * fix: Delete previous subscription * chore: Temporary logs * refactor: Move migration to a later date * fix: Fetch the correct session activation and misc bugs * refactor: Move migration to a later date * fix: Remove follow request (no notifications) * feat: Send administrator contact to push service * feat: Set time-to-live * fix: Do not show sensitive images * fix: Reducer crash in error handling * feat: Add badge * chore: Fix lint error * fix: Checkbox label overlap * fix: Check for payload support * fix: Rename action "type" (crash in latest Chrome) * feat: Action to expand notification * fix: Lint errors * fix: Unescape notification body * fix: Do not allow boosting if the status is hidden * feat: Add VAPID keys to the production sample environment * fix: Strip HTML tags from status * refactor: Better error messages * refactor: Handle browser not implementing the VAPID protocol (Samsung Internet) * fix: Error when target_status is nil * fix: Handle lack of image * fix: Delete reference to invalid subscriptions * feat: Better error handling * fix: Unescape HTML characters after tags are striped * refactor: Simpify code * fix: Modify to work with #4091 * Sort strings alphabetically * i18n: Updated Polish translation it annoys me that it's not fully localized :P * refactor: Use current_session in PushSubscriptionController * fix: Rebase mistake * fix: Set cacheName to mastodon * refactor: Pull request feedback * refactor: Remove logging statements * chore(yarn): Fix conflicts with master * chore(yarn): Copy latest from master * chore(yarn): Readd offline-plugin * refactor: Use save! and update! * refactor: Send notifications async * fix: Allow retry when push fails * fix: Save track for failed pushes * fix: Minify sw.js * fix: Remove account_id from fabricator
6 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: users
  5. #
  6. # id :integer not null, primary key
  7. # email :string default(""), not null
  8. # account_id :integer not null
  9. # created_at :datetime not null
  10. # updated_at :datetime not null
  11. # encrypted_password :string default(""), not null
  12. # reset_password_token :string
  13. # reset_password_sent_at :datetime
  14. # remember_created_at :datetime
  15. # sign_in_count :integer default(0), not null
  16. # current_sign_in_at :datetime
  17. # last_sign_in_at :datetime
  18. # current_sign_in_ip :inet
  19. # last_sign_in_ip :inet
  20. # admin :boolean default(FALSE), not null
  21. # confirmation_token :string
  22. # confirmed_at :datetime
  23. # confirmation_sent_at :datetime
  24. # unconfirmed_email :string
  25. # locale :string
  26. # encrypted_otp_secret :string
  27. # encrypted_otp_secret_iv :string
  28. # encrypted_otp_secret_salt :string
  29. # consumed_timestep :integer
  30. # otp_required_for_login :boolean default(FALSE), not null
  31. # last_emailed_at :datetime
  32. # otp_backup_codes :string is an Array
  33. # filtered_languages :string default([]), not null, is an Array
  34. #
  35. class User < ApplicationRecord
  36. include Settings::Extend
  37. ACTIVE_DURATION = 14.days
  38. devise :registerable, :recoverable,
  39. :rememberable, :trackable, :validatable, :confirmable,
  40. :two_factor_authenticatable, :two_factor_backupable,
  41. otp_secret_encryption_key: ENV['OTP_SECRET'],
  42. otp_number_of_backup_codes: 10
  43. belongs_to :account, inverse_of: :user, required: true
  44. accepts_nested_attributes_for :account
  45. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  46. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  47. validates_with BlacklistedEmailValidator, if: :email_changed?
  48. scope :recent, -> { order(id: :desc) }
  49. scope :admins, -> { where(admin: true) }
  50. scope :confirmed, -> { where.not(confirmed_at: nil) }
  51. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  52. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended: false }) }
  53. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  54. scope :with_recent_ip_address, ->(value) { where(arel_table[:current_sign_in_ip].eq(value).or(arel_table[:last_sign_in_ip].eq(value))) }
  55. before_validation :sanitize_languages
  56. # This avoids a deprecation warning from Rails 5.1
  57. # It seems possible that a future release of devise-two-factor will
  58. # handle this itself, and this can be removed from our User class.
  59. attribute :otp_secret
  60. has_many :session_activations, dependent: :destroy
  61. def confirmed?
  62. confirmed_at.present?
  63. end
  64. def disable_two_factor!
  65. self.otp_required_for_login = false
  66. otp_backup_codes&.clear
  67. save!
  68. end
  69. def setting_default_privacy
  70. settings.default_privacy || (account.locked? ? 'private' : 'public')
  71. end
  72. def setting_default_sensitive
  73. settings.default_sensitive
  74. end
  75. def setting_unfollow_modal
  76. settings.unfollow_modal
  77. end
  78. def setting_boost_modal
  79. settings.boost_modal
  80. end
  81. def setting_delete_modal
  82. settings.delete_modal
  83. end
  84. def setting_auto_play_gif
  85. settings.auto_play_gif
  86. end
  87. def setting_reduce_motion
  88. settings.reduce_motion
  89. end
  90. def setting_system_font_ui
  91. settings.system_font_ui
  92. end
  93. def setting_noindex
  94. settings.noindex
  95. end
  96. def setting_theme
  97. settings.theme
  98. end
  99. def token_for_app(a)
  100. return nil if a.nil? || a.owner != self
  101. Doorkeeper::AccessToken
  102. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  103. t.scopes = a.scopes
  104. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  105. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  106. end
  107. end
  108. def activate_session(request)
  109. session_activations.activate(session_id: SecureRandom.hex,
  110. user_agent: request.user_agent,
  111. ip: request.remote_ip).session_id
  112. end
  113. def exclusive_session(id)
  114. session_activations.exclusive(id)
  115. end
  116. def session_active?(id)
  117. session_activations.active? id
  118. end
  119. def web_push_subscription(session)
  120. session.web_push_subscription.nil? ? nil : session.web_push_subscription.as_payload
  121. end
  122. protected
  123. def send_devise_notification(notification, *args)
  124. devise_mailer.send(notification, self, *args).deliver_later
  125. end
  126. private
  127. def sanitize_languages
  128. filtered_languages.reject!(&:blank?)
  129. end
  130. end