about summary refs log tree commit diff
path: root/app/controllers/api/web/push_subscriptions_controller.rb
blob: 68ccbd5e20db006f5a42db880aa08c0a415d8435 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# frozen_string_literal: true

class Api::Web::PushSubscriptionsController < Api::BaseController
  respond_to :json

  before_action :require_user!
  protect_from_forgery with: :exception

  def create
    params.require(:subscription).require(:endpoint)
    params.require(:subscription).require(:keys).require([:auth, :p256dh])

    active_session = current_session

    unless active_session.web_push_subscription.nil?
      active_session.web_push_subscription.destroy!
      active_session.update!(web_push_subscription: nil)
    end

    # Mobile devices do not support regular notifications, so we enable push notifications by default
    alerts_enabled = active_session.detection.device.mobile? || active_session.detection.device.tablet?

    data = {
      alerts: {
        follow: alerts_enabled,
        favourite: alerts_enabled,
        reblog: alerts_enabled,
        mention: alerts_enabled,
      },
    }

    data.deep_merge!(params[:data]) if params[:data]

    web_subscription = ::Web::PushSubscription.create!(
      endpoint: params[:subscription][:endpoint],
      key_p256dh: params[:subscription][:keys][:p256dh],
      key_auth: params[:subscription][:keys][:auth],
      data: data
    )

    active_session.update!(web_push_subscription: web_subscription)

    render json: web_subscription.as_payload
  end

  def update
    params.require([:id, :data])

    web_subscription = ::Web::PushSubscription.find(params[:id])

    web_subscription.update!(data: params[:data])

    render json: web_subscription.as_payload
  end
end