[英]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)
希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.