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.

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