2022-09-11 11:12:42 -07:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Ajax::WebPushController < AjaxController
|
2022-12-24 08:41:21 -08:00
|
|
|
before_action :authenticate_user!
|
|
|
|
|
2022-09-11 11:12:42 -07:00
|
|
|
def key
|
|
|
|
certificate = Rpush::Webpush::App.find_by(name: "webpush").certificate
|
|
|
|
|
2022-10-20 10:02:12 -07:00
|
|
|
@response[:status] = :okay
|
|
|
|
@response[:success] = true
|
2022-09-11 11:12:42 -07:00
|
|
|
@response[:key] = JSON.parse(certificate)["public_key"]
|
|
|
|
end
|
|
|
|
|
|
|
|
def subscribe
|
|
|
|
WebPushSubscription.create!(
|
|
|
|
user: current_user,
|
|
|
|
subscription: params[:subscription]
|
|
|
|
)
|
|
|
|
|
|
|
|
@response[:status] = :okay
|
|
|
|
@response[:success] = true
|
2022-10-23 07:00:21 -07:00
|
|
|
@response[:message] = t(".subscription_count", count: current_user.web_push_subscriptions.count)
|
2022-09-11 11:12:42 -07:00
|
|
|
end
|
2022-10-21 13:37:52 -07:00
|
|
|
|
2022-12-25 15:30:06 -08:00
|
|
|
def unsubscribe # rubocop:disable Metrics/AbcSize
|
2022-10-21 13:37:52 -07:00
|
|
|
params.permit(:endpoint)
|
|
|
|
|
2022-12-24 08:41:21 -08:00
|
|
|
removed = if params.key?(:endpoint)
|
2022-12-25 15:30:06 -08:00
|
|
|
current_user.web_push_subscriptions.where("subscription ->> 'endpoint' = ?", params[:endpoint]).destroy_all
|
|
|
|
else
|
|
|
|
current_user.web_push_subscriptions.destroy_all
|
|
|
|
end
|
2022-10-21 13:37:52 -07:00
|
|
|
|
2022-10-23 07:00:21 -07:00
|
|
|
count = current_user.web_push_subscriptions.count
|
|
|
|
|
2022-12-24 08:41:21 -08:00
|
|
|
@response[:status] = removed.any? ? :okay : :err
|
|
|
|
@response[:success] = removed.any?
|
2022-10-23 07:00:21 -07:00
|
|
|
@response[:message] = t(".subscription_count", count:)
|
|
|
|
@response[:count] = count
|
2022-10-21 13:37:52 -07:00
|
|
|
end
|
2022-09-11 11:12:42 -07:00
|
|
|
end
|