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
|
|
|
|
|
2023-01-01 12:34:49 -08:00
|
|
|
def check
|
2023-01-04 03:32:16 -08:00
|
|
|
params.require(:endpoint)
|
2023-01-01 12:34:49 -08:00
|
|
|
|
2023-01-01 13:07:02 -08:00
|
|
|
found = current_user.web_push_subscriptions.where("subscription ->> 'endpoint' = ?", params[:endpoint]).first
|
2023-01-01 12:34:49 -08:00
|
|
|
|
|
|
|
@response[:status] = if found
|
|
|
|
if found.failures >= 3
|
|
|
|
:failed
|
|
|
|
else
|
|
|
|
:subscribed
|
|
|
|
end
|
|
|
|
else
|
|
|
|
:unsubscribed
|
|
|
|
end
|
|
|
|
@response[:success] = true
|
|
|
|
end
|
|
|
|
|
2022-09-11 11:12:42 -07:00
|
|
|
def subscribe
|
2023-01-04 03:32:16 -08:00
|
|
|
params.require(:subscription)
|
|
|
|
|
2022-09-11 11:12:42 -07:00
|
|
|
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
|
|
|
|
2023-10-15 01:21:46 -07:00
|
|
|
def unsubscribe
|
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
|