2017-07-14 06:15:32 +10:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Api::Web::PushSubscriptionsController < Api::BaseController
|
|
|
|
respond_to :json
|
|
|
|
|
|
|
|
before_action :require_user!
|
2018-01-15 16:51:23 +11:00
|
|
|
protect_from_forgery with: :exception
|
2017-07-14 06:15:32 +10:00
|
|
|
|
|
|
|
def create
|
2017-07-24 07:27:23 +10:00
|
|
|
params.require(:subscription).require(:endpoint)
|
|
|
|
params.require(:subscription).require(:keys).require([:auth, :p256dh])
|
2017-07-14 06:15:32 +10:00
|
|
|
|
|
|
|
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
|
|
|
|
|
2017-07-24 07:27:23 +10:00
|
|
|
# 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,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2017-12-09 12:31:37 +11:00
|
|
|
data.deep_merge!(params[:data]) if params[:data]
|
|
|
|
|
2017-07-14 06:15:32 +10:00
|
|
|
web_subscription = ::Web::PushSubscription.create!(
|
2017-07-24 07:27:23 +10:00
|
|
|
endpoint: params[:subscription][:endpoint],
|
|
|
|
key_p256dh: params[:subscription][:keys][:p256dh],
|
|
|
|
key_auth: params[:subscription][:keys][:auth],
|
|
|
|
data: data
|
2017-07-14 06:15:32 +10:00
|
|
|
)
|
|
|
|
|
|
|
|
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
|