用于 webpush 通知的 rake 任务

rake task for webpush notification

我在challenge_reminder.rake

task challenge_reminder: :environment do
  Challenge.unaccomplished.all.each do |challenge|
    if challenge.remind.include? Date::ABBR_DAYNAMES[Date.current.wday].downcase
        if challenge.mail == true # This Works
            UserMailer.challenge_reminder(challenge).deliver_now 
        end
        if challenge.push == true 
          # How to send webpush notification for challenge
        end 
    end      
  end 
end

如果用户手动点击按钮,可以收到推送通知...

<%= content_tag(:button, "Foo", class: "webpush-button") %>

<script>
  $('.webpush-button').on('click', (e) => {
    navigator.serviceWorker.ready
    .then((serviceWorkerRegistration) => {
      serviceWorkerRegistration.pushManager.getSubscription()
      .then((subscription) => {
        console.log('Almost there, Daddy!');
        $.post('/push', {
          subscription: subscription.toJSON(),
          message: 'You clicked a button!'
        });
      });
    });
  });
</script>

导致...

class PushNotificationsController < ApplicationController
  def push
    Webpush.payload_send(
      message: params[:message],
      endpoint: params[:subscription][:endpoint],
      p256dh: params[:subscription][:keys][:p256dh],
      auth: params[:subscription][:keys][:auth],
      vapid: {
        subject: "mailto:sender@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      }
    )
  end
end

如何调整 rake 任务的脚本代码?

我通过 serviceworker gem, webpush gem 和 VAPID 凭据实现了推送。

您应该将整个逻辑从 PushNotificationsController#push 移动到某些域逻辑或服务 - PushNotificationsService 可以从不同的地方使用:

class PushNotificationsService
  def self.call(params) 
    Webpush.payload_send(
      message: params[:message],
      endpoint: params[:subscription][:endpoint],
      p256dh: params[:subscription][:keys][:p256dh],
      auth: params[:subscription][:keys][:auth],
      vapid: {
        subject: "mailto:sender@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      } 
    )
  end
end

然后您可以从应用程序中的不同位置调用此服务,即。 PushNotificationsService.call(params)

希望对您有所帮助!