闭社主体 forked from https://github.com/tootsuite/mastodon
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.

190 lines
6.1 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
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: web_push_subscriptions
  5. #
  6. # id :integer not null, primary key
  7. # endpoint :string not null
  8. # key_p256dh :string not null
  9. # key_auth :string not null
  10. # data :json
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. #
  14. class Web::PushSubscription < ApplicationRecord
  15. include RoutingHelper
  16. include StreamEntriesHelper
  17. include ActionView::Helpers::TranslationHelper
  18. include ActionView::Helpers::SanitizeHelper
  19. has_one :session_activation
  20. before_create :send_welcome_notification
  21. def push(notification)
  22. return unless pushable? notification
  23. name = display_name notification.from_account
  24. title = title_str(name, notification)
  25. body = body_str notification
  26. dir = dir_str body
  27. url = url_str notification
  28. image = image_str notification
  29. actions = actions_arr notification
  30. access_token = actions.empty? ? nil : find_or_create_access_token(notification).token
  31. nsfw = notification.target_status.nil? || notification.target_status.spoiler_text.empty? ? nil : notification.target_status.spoiler_text
  32. # TODO: Make sure that the payload does not exceed 4KB - Webpush::PayloadTooLarge
  33. # TODO: Queue the requests - Webpush::TooManyRequests
  34. Webpush.payload_send(
  35. message: JSON.generate(
  36. title: title,
  37. dir: dir,
  38. image: image,
  39. badge: full_asset_url('badge.png'),
  40. tag: notification.id,
  41. timestamp: notification.created_at,
  42. icon: notification.from_account.avatar_static_url,
  43. data: {
  44. content: decoder.decode(strip_tags(body)),
  45. nsfw: nsfw.nil? ? nil : decoder.decode(strip_tags(nsfw)),
  46. url: url,
  47. actions: actions,
  48. access_token: access_token,
  49. }
  50. ),
  51. endpoint: endpoint,
  52. p256dh: key_p256dh,
  53. auth: key_auth,
  54. vapid: {
  55. # subject: "mailto:#{Setting.site_contact_email}",
  56. private_key: Rails.configuration.x.vapid_private_key,
  57. public_key: Rails.configuration.x.vapid_public_key,
  58. },
  59. ttl: 40 * 60 * 60 # 48 hours
  60. )
  61. end
  62. def as_payload
  63. payload = {
  64. id: id,
  65. endpoint: endpoint,
  66. }
  67. payload[:alerts] = data['alerts'] if data && data.key?('alerts')
  68. payload
  69. end
  70. private
  71. def title_str(name, notification)
  72. case notification.type
  73. when :mention then translate('push_notifications.mention.title', name: name)
  74. when :follow then translate('push_notifications.follow.title', name: name)
  75. when :favourite then translate('push_notifications.favourite.title', name: name)
  76. when :reblog then translate('push_notifications.reblog.title', name: name)
  77. end
  78. end
  79. def body_str(notification)
  80. case notification.type
  81. when :mention then notification.target_status.text
  82. when :follow then notification.from_account.note
  83. when :favourite then notification.target_status.text
  84. when :reblog then notification.target_status.text
  85. end
  86. end
  87. def url_str(notification)
  88. case notification.type
  89. when :mention then web_url("statuses/#{notification.target_status.id}")
  90. when :follow then web_url("accounts/#{notification.from_account.id}")
  91. when :favourite then web_url("statuses/#{notification.target_status.id}")
  92. when :reblog then web_url("statuses/#{notification.target_status.id}")
  93. end
  94. end
  95. def actions_arr(notification)
  96. actions =
  97. case notification.type
  98. when :mention then [
  99. {
  100. title: translate('push_notifications.mention.action_favourite'),
  101. icon: full_asset_url('emoji/2764.png'),
  102. todo: 'request',
  103. method: 'POST',
  104. action: "/api/v1/statuses/#{notification.target_status.id}/favourite",
  105. },
  106. ]
  107. else []
  108. end
  109. should_hide = notification.type.equal?(:mention) && !notification.target_status.nil? && (notification.target_status.sensitive || !notification.target_status.spoiler_text.empty?)
  110. can_boost = notification.type.equal?(:mention) && !notification.target_status.nil? && !notification.target_status.hidden?
  111. if should_hide
  112. actions.insert(0, title: translate('push_notifications.mention.action_expand'), icon: full_asset_url('emoji/1f441.png'), todo: 'expand', action: 'expand')
  113. end
  114. if can_boost
  115. actions << { title: translate('push_notifications.mention.action_boost'), icon: full_asset_url('emoji/1f504.png'), todo: 'request', method: 'POST', action: "/api/v1/statuses/#{notification.target_status.id}/reblog" }
  116. end
  117. actions
  118. end
  119. def image_str(notification)
  120. return nil if notification.target_status.nil? || notification.target_status.media_attachments.empty?
  121. full_asset_url(notification.target_status.media_attachments.first.file.url(:small))
  122. end
  123. def dir_str(body)
  124. rtl?(body) ? 'rtl' : 'ltr'
  125. end
  126. def pushable?(notification)
  127. data && data.key?('alerts') && data['alerts'][notification.type.to_s]
  128. end
  129. def send_welcome_notification
  130. Webpush.payload_send(
  131. message: JSON.generate(
  132. title: translate('push_notifications.subscribed.title'),
  133. icon: full_asset_url('android-chrome-192x192.png'),
  134. badge: full_asset_url('badge.png'),
  135. data: {
  136. content: translate('push_notifications.subscribed.body'),
  137. actions: [],
  138. url: web_url('notifications'),
  139. }
  140. ),
  141. endpoint: endpoint,
  142. p256dh: key_p256dh,
  143. auth: key_auth,
  144. vapid: {
  145. # subject: "mailto:#{Setting.site_contact_email}",
  146. private_key: Rails.configuration.x.vapid_private_key,
  147. public_key: Rails.configuration.x.vapid_public_key,
  148. },
  149. ttl: 5 * 60 # 5 minutes
  150. )
  151. end
  152. def find_or_create_access_token(notification)
  153. Doorkeeper::AccessToken.find_or_create_for(
  154. Doorkeeper::Application.find_by(superapp: true),
  155. notification.account.user.id,
  156. Doorkeeper::OAuth::Scopes.from_string('read write follow'),
  157. Doorkeeper.configuration.access_token_expires_in,
  158. Doorkeeper.configuration.refresh_token_enabled?
  159. )
  160. end
  161. def decoder
  162. @decoder ||= HTMLEntities.new
  163. end
  164. end