The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

56 line
1.5 KiB

  1. # frozen_string_literal: true
  2. class Api::Web::PushSubscriptionsController < Api::BaseController
  3. respond_to :json
  4. before_action :require_user!
  5. protect_from_forgery with: :exception
  6. def create
  7. params.require(:subscription).require(:endpoint)
  8. params.require(:subscription).require(:keys).require([:auth, :p256dh])
  9. active_session = current_session
  10. unless active_session.web_push_subscription.nil?
  11. active_session.web_push_subscription.destroy!
  12. active_session.update!(web_push_subscription: nil)
  13. end
  14. # Mobile devices do not support regular notifications, so we enable push notifications by default
  15. alerts_enabled = active_session.detection.device.mobile? || active_session.detection.device.tablet?
  16. data = {
  17. alerts: {
  18. follow: alerts_enabled,
  19. favourite: alerts_enabled,
  20. reblog: alerts_enabled,
  21. mention: alerts_enabled,
  22. },
  23. }
  24. data.deep_merge!(params[:data]) if params[:data]
  25. web_subscription = ::Web::PushSubscription.create!(
  26. endpoint: params[:subscription][:endpoint],
  27. key_p256dh: params[:subscription][:keys][:p256dh],
  28. key_auth: params[:subscription][:keys][:auth],
  29. data: data
  30. )
  31. active_session.update!(web_push_subscription: web_subscription)
  32. render json: web_subscription.as_payload
  33. end
  34. def update
  35. params.require([:id, :data])
  36. web_subscription = ::Web::PushSubscription.find(params[:id])
  37. web_subscription.update!(data: params[:data])
  38. render json: web_subscription.as_payload
  39. end
  40. end