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.

363 lines
11 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
7 years ago
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
7 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: users
  5. #
  6. # id :bigint(8) not null, primary key
  7. # email :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # encrypted_password :string default(""), not null
  11. # reset_password_token :string
  12. # reset_password_sent_at :datetime
  13. # remember_created_at :datetime
  14. # sign_in_count :integer default(0), not null
  15. # current_sign_in_at :datetime
  16. # last_sign_in_at :datetime
  17. # current_sign_in_ip :inet
  18. # last_sign_in_ip :inet
  19. # admin :boolean default(FALSE), not null
  20. # confirmation_token :string
  21. # confirmed_at :datetime
  22. # confirmation_sent_at :datetime
  23. # unconfirmed_email :string
  24. # locale :string
  25. # encrypted_otp_secret :string
  26. # encrypted_otp_secret_iv :string
  27. # encrypted_otp_secret_salt :string
  28. # consumed_timestep :integer
  29. # otp_required_for_login :boolean default(FALSE), not null
  30. # last_emailed_at :datetime
  31. # otp_backup_codes :string is an Array
  32. # filtered_languages :string default([]), not null, is an Array
  33. # account_id :bigint(8) not null
  34. # disabled :boolean default(FALSE), not null
  35. # moderator :boolean default(FALSE), not null
  36. # invite_id :bigint(8)
  37. # remember_token :string
  38. # chosen_languages :string is an Array
  39. # created_by_application_id :bigint(8)
  40. # approved :boolean default(TRUE), not null
  41. #
  42. class User < ApplicationRecord
  43. include Settings::Extend
  44. include UserRoles
  45. # The home and list feeds will be stored in Redis for this amount
  46. # of time, and status fan-out to followers will include only people
  47. # within this time frame. Lowering the duration may improve performance
  48. # if lots of people sign up, but not a lot of them check their feed
  49. # every day. Raising the duration reduces the amount of expensive
  50. # RegenerationWorker jobs that need to be run when those people come
  51. # to check their feed
  52. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  53. devise :two_factor_authenticatable,
  54. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  55. devise :two_factor_backupable,
  56. otp_number_of_backup_codes: 10
  57. devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
  58. :confirmable
  59. include Omniauthable
  60. include PamAuthenticable
  61. include LdapAuthenticable
  62. belongs_to :account, inverse_of: :user
  63. belongs_to :invite, counter_cache: :uses, optional: true
  64. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  65. accepts_nested_attributes_for :account
  66. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  67. has_many :backups, inverse_of: :user
  68. has_many :invites, inverse_of: :user
  69. has_many :markers, inverse_of: :user, dependent: :destroy
  70. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  71. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
  72. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  73. validates_with BlacklistedEmailValidator, on: :create
  74. validates_with EmailMxValidator, if: :validate_email_dns?
  75. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  76. scope :recent, -> { order(id: :desc) }
  77. scope :pending, -> { where(approved: false) }
  78. scope :approved, -> { where(approved: true) }
  79. scope :confirmed, -> { where.not(confirmed_at: nil) }
  80. scope :enabled, -> { where(disabled: false) }
  81. scope :disabled, -> { where(disabled: true) }
  82. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  83. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  84. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  85. scope :matches_ip, ->(value) { left_joins(:session_activations).where('users.current_sign_in_ip <<= ?', value).or(left_joins(:session_activations).where('users.last_sign_in_ip <<= ?', value)).or(left_joins(:session_activations).where('session_activations.ip <<= ?', value)) }
  86. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  87. before_validation :sanitize_languages
  88. before_create :set_approved
  89. # This avoids a deprecation warning from Rails 5.1
  90. # It seems possible that a future release of devise-two-factor will
  91. # handle this itself, and this can be removed from our User class.
  92. attribute :otp_secret
  93. has_many :session_activations, dependent: :destroy
  94. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  95. :reduce_motion, :system_font_ui, :noindex, :theme, :display_media, :hide_network,
  96. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  97. :advanced_layout, :use_blurhash, :use_pending_items, :trends, :crop_images,
  98. to: :settings, prefix: :setting, allow_nil: false
  99. attr_reader :invite_code
  100. attr_writer :external
  101. def confirmed?
  102. confirmed_at.present?
  103. end
  104. def invited?
  105. invite_id.present?
  106. end
  107. def valid_invitation?
  108. invite_id.present? && invite.valid_for_use?
  109. end
  110. def disable!
  111. update!(disabled: true)
  112. end
  113. def enable!
  114. update!(disabled: false)
  115. end
  116. def confirm
  117. new_user = !confirmed?
  118. self.approved = true if open_registrations?
  119. super
  120. if new_user && approved?
  121. prepare_new_user!
  122. elsif new_user
  123. notify_staff_about_pending_account!
  124. end
  125. end
  126. def confirm!
  127. new_user = !confirmed?
  128. self.approved = true if open_registrations?
  129. skip_confirmation!
  130. save!
  131. prepare_new_user! if new_user && approved?
  132. end
  133. def pending?
  134. !approved?
  135. end
  136. def active_for_authentication?
  137. true
  138. end
  139. def functional?
  140. confirmed? && approved? && !disabled? && !account.suspended? && account.moved_to_account_id.nil?
  141. end
  142. def unconfirmed_or_pending?
  143. !(confirmed? && approved?)
  144. end
  145. def inactive_message
  146. !approved? ? :pending : super
  147. end
  148. def approve!
  149. return if approved?
  150. update!(approved: true)
  151. prepare_new_user!
  152. end
  153. def update_tracked_fields!(request)
  154. super
  155. prepare_returning_user!
  156. end
  157. def disable_two_factor!
  158. self.otp_required_for_login = false
  159. otp_backup_codes&.clear
  160. save!
  161. end
  162. def setting_default_privacy
  163. settings.default_privacy || (account.locked? ? 'private' : 'public')
  164. end
  165. def allows_digest_emails?
  166. settings.notification_emails['digest']
  167. end
  168. def allows_report_emails?
  169. settings.notification_emails['report']
  170. end
  171. def allows_pending_account_emails?
  172. settings.notification_emails['pending_account']
  173. end
  174. def allows_trending_tag_emails?
  175. settings.notification_emails['trending_tag']
  176. end
  177. def hides_network?
  178. @hides_network ||= settings.hide_network
  179. end
  180. def aggregates_reblogs?
  181. @aggregates_reblogs ||= settings.aggregate_reblogs
  182. end
  183. def shows_application?
  184. @shows_application ||= settings.show_application
  185. end
  186. def token_for_app(a)
  187. return nil if a.nil? || a.owner != self
  188. Doorkeeper::AccessToken
  189. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  190. t.scopes = a.scopes
  191. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  192. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  193. end
  194. end
  195. def activate_session(request)
  196. session_activations.activate(session_id: SecureRandom.hex,
  197. user_agent: request.user_agent,
  198. ip: request.remote_ip).session_id
  199. end
  200. def clear_other_sessions(id)
  201. session_activations.exclusive(id)
  202. end
  203. def session_active?(id)
  204. session_activations.active? id
  205. end
  206. def web_push_subscription(session)
  207. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  208. end
  209. def invite_code=(code)
  210. self.invite = Invite.find_by(code: code) if code.present?
  211. @invite_code = code
  212. end
  213. def password_required?
  214. return false if external?
  215. super
  216. end
  217. def send_reset_password_instructions
  218. return false if encrypted_password.blank?
  219. super
  220. end
  221. def reset_password!(new_password, new_password_confirmation)
  222. return false if encrypted_password.blank?
  223. super
  224. end
  225. def show_all_media?
  226. setting_display_media == 'show_all'
  227. end
  228. def hide_all_media?
  229. setting_display_media == 'hide_all'
  230. end
  231. def recent_ips
  232. @recent_ips ||= begin
  233. arr = []
  234. session_activations.each do |session_activation|
  235. arr << [session_activation.updated_at, session_activation.ip]
  236. end
  237. arr << [current_sign_in_at, current_sign_in_ip] if current_sign_in_ip.present?
  238. arr << [last_sign_in_at, last_sign_in_ip] if last_sign_in_ip.present?
  239. arr.sort_by { |pair| pair.first || Time.now.utc }.uniq(&:last).reverse!
  240. end
  241. end
  242. protected
  243. def send_devise_notification(notification, *args)
  244. devise_mailer.send(notification, self, *args).deliver_later
  245. end
  246. private
  247. def set_approved
  248. self.approved = open_registrations? || valid_invitation? || external?
  249. end
  250. def open_registrations?
  251. Setting.registrations_mode == 'open'
  252. end
  253. def external?
  254. !!@external
  255. end
  256. def sanitize_languages
  257. return if chosen_languages.nil?
  258. chosen_languages.reject!(&:blank?)
  259. self.chosen_languages = nil if chosen_languages.empty?
  260. end
  261. def prepare_new_user!
  262. BootstrapTimelineWorker.perform_async(account_id)
  263. ActivityTracker.increment('activity:accounts:local')
  264. UserMailer.welcome(self).deliver_later
  265. end
  266. def prepare_returning_user!
  267. ActivityTracker.record('activity:logins', id)
  268. regenerate_feed! if needs_feed_update?
  269. end
  270. def notify_staff_about_pending_account!
  271. User.staff.includes(:account).each do |u|
  272. next unless u.allows_pending_account_emails?
  273. AdminMailer.new_pending_account(u.account, self).deliver_later
  274. end
  275. end
  276. def regenerate_feed!
  277. return unless Redis.current.setnx("account:#{account_id}:regeneration", true)
  278. Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  279. RegenerationWorker.perform_async(account_id)
  280. end
  281. def needs_feed_update?
  282. last_sign_in_at < ACTIVE_DURATION.ago
  283. end
  284. def validate_email_dns?
  285. email_changed? && !(Rails.env.test? || Rails.env.development?)
  286. end
  287. end