push_subscriptions_controller.rb 1.8 KB

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