2017-07-14 05:15:32 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Api::Web::PushSubscriptionsController < Api::BaseController
|
|
|
|
respond_to :json
|
|
|
|
|
|
|
|
before_action :require_user!
|
2018-01-15 14:51:23 +09:00
|
|
|
protect_from_forgery with: :exception
|
2017-07-14 05:15:32 +09:00
|
|
|
|
|
|
|
def create
|
|
|
|
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 06:27:23 +09: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,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2018-04-12 21:45:17 +09:00
|
|
|
data.deep_merge!(data_params) if params[:data]
|
2017-12-09 10:31:37 +09:00
|
|
|
|
2017-07-14 05:15:32 +09:00
|
|
|
web_subscription = ::Web::PushSubscription.create!(
|
2018-04-12 21:45:17 +09:00
|
|
|
endpoint: subscription_params[:endpoint],
|
|
|
|
key_p256dh: subscription_params[:keys][:p256dh],
|
|
|
|
key_auth: subscription_params[:keys][:auth],
|
2017-07-24 06:27:23 +09:00
|
|
|
data: data
|
2017-07-14 05:15:32 +09:00
|
|
|
)
|
|
|
|
|
|
|
|
active_session.update!(web_push_subscription: web_subscription)
|
|
|
|
|
|
|
|
render json: web_subscription.as_payload
|
|
|
|
end
|
|
|
|
|
|
|
|
def update
|
2018-04-12 21:45:17 +09:00
|
|
|
params.require([:id])
|
2017-07-14 05:15:32 +09:00
|
|
|
|
|
|
|
web_subscription = ::Web::PushSubscription.find(params[:id])
|
|
|
|
|
2018-04-12 21:45:17 +09:00
|
|
|
web_subscription.update!(data: data_params)
|
2017-07-14 05:15:32 +09:00
|
|
|
|
|
|
|
render json: web_subscription.as_payload
|
|
|
|
end
|
2018-04-12 21:45:17 +09:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def subscription_params
|
|
|
|
@subscription_params ||= params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
|
|
|
|
end
|
|
|
|
|
|
|
|
def data_params
|
|
|
|
@data_params ||= params.require(:data).permit(:alerts)
|
|
|
|
end
|
2017-07-14 05:15:32 +09:00
|
|
|
end
|