Retrospring/app/controllers/ajax/web_push_controller.rb

42 lines
1.2 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
class Ajax::WebPushController < AjaxController
2022-12-24 08:41:21 -08:00
before_action :authenticate_user!
def key
certificate = Rpush::Webpush::App.find_by(name: "webpush").certificate
@response[:status] = :okay
@response[:success] = true
@response[:key] = JSON.parse(certificate)["public_key"]
end
def subscribe
WebPushSubscription.create!(
user: current_user,
subscription: params[:subscription]
)
@response[:status] = :okay
@response[:success] = true
@response[:message] = t(".subscription_count", count: current_user.web_push_subscriptions.count)
end
def unsubscribe # rubocop:disable Metrics/AbcSize
params.permit(:endpoint)
2022-12-24 08:41:21 -08:00
removed = if params.key?(:endpoint)
current_user.web_push_subscriptions.where("subscription ->> 'endpoint' = ?", params[:endpoint]).destroy_all
else
current_user.web_push_subscriptions.destroy_all
end
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?
@response[:message] = t(".subscription_count", count:)
@response[:count] = count
end
end