logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

push_subscription.rb (2115B)


  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. class Web::PushSubscription < ApplicationRecord
  16. has_one :session_activation
  17. def push(notification)
  18. I18n.with_locale(session_activation.user.locale || I18n.default_locale) do
  19. push_payload(message_from(notification), 48.hours.seconds)
  20. end
  21. end
  22. def pushable?(notification)
  23. data&.key?('alerts') && data['alerts'][notification.type.to_s]
  24. end
  25. def as_payload
  26. payload = { id: id, endpoint: endpoint }
  27. payload[:alerts] = data['alerts'] if data&.key?('alerts')
  28. payload
  29. end
  30. def access_token
  31. find_or_create_access_token.token
  32. end
  33. private
  34. def push_payload(message, ttl = 5.minutes.seconds)
  35. # TODO: Make sure that the payload does not
  36. # exceed 4KB - Webpush::PayloadTooLarge
  37. Webpush.payload_send(
  38. message: Oj.dump(message),
  39. endpoint: endpoint,
  40. p256dh: key_p256dh,
  41. auth: key_auth,
  42. ttl: ttl,
  43. vapid: {
  44. subject: "mailto:#{::Setting.site_contact_email}",
  45. private_key: Rails.configuration.x.vapid_private_key,
  46. public_key: Rails.configuration.x.vapid_public_key,
  47. }
  48. )
  49. end
  50. def message_from(notification)
  51. serializable_resource = ActiveModelSerializers::SerializableResource.new(notification, serializer: Web::NotificationSerializer, scope: self, scope_name: :current_push_subscription)
  52. serializable_resource.as_json
  53. end
  54. def find_or_create_access_token
  55. Doorkeeper::AccessToken.find_or_create_for(
  56. Doorkeeper::Application.find_by(superapp: true),
  57. session_activation.user_id,
  58. Doorkeeper::OAuth::Scopes.from_string('read write follow'),
  59. Doorkeeper.configuration.access_token_expires_in,
  60. Doorkeeper.configuration.refresh_token_enabled?
  61. )
  62. end
  63. end