Я добавляю функциональность уведомлений pu sh в мое приложение rails 6. Я использую ActionCable с адаптером asyn c в процессе разработки и перенаправляю в производство, чтобы успешно отправлять уведомления на рабочем столе, когда пользователь назначает задачу другому пользователю. Когда я использую свой телефон для того же, я не получаю уведомления на телефон (используя chrome на android, как в обычной, так и в установленной версии PWA). Если я назначу задачу с телефона пользователю на рабочем столе, он получит уведомление. Кажется, все работает хорошо, за исключением отображения уведомлений пользователям на мобильном телефоне.
connection.rb:
identified_by :current_user
def connect
self.current_user = find_verified_user
end
def session
cookies.encrypted[Rails.application.config.session_options[:key]]
end
protected
def find_verified_user
User.find_by(id: session["warden.user.user.key"][0][0])
end
messages_channel.rb:
class NotificationChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
канал уведомлений. js:
import consumer from "./consumer"
consumer.subscriptions.create("NotificationChannel", {
connected() {
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
if (Notification.permission === 'granted') {
var title = 'Push Notification'
var body = data
var options = { body: body }
new Notification(title, options)
}
}
});
task_controller.rb:
@house.users.each do |user|
NotificationChannel.broadcast_to(user, "#{current_user.name} challenged you with #{@task.name}")
end
работник службы:
var CACHE_VERSION = 'v1';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
'<%= asset_pack_path 'application.js' %>',
'<%= asset_pack_path 'application.css' %>',
]);
})
);
}
function onActivate(event) {
console.log('[Serviceworker]', "Activating!", event);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName.indexOf(CACHE_VERSION) !== 0;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
}
// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
return caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
console.log('[Serviceworker]', "Fetching offline content", event);
return caches.match('/offline.html');
}
})
})
);
}
self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
консольный журнал:
2020-04-13T14:14:00.223160+00:00 app[web.1]: I, [2020-04-13T14:14:00.223074 #4] INFO -- : [b4ebe1e2-f3df-485b-8c24-dc91656bb6db] Started GET "/cable" for 79.178.15.179 at 2020-04-13 14:14:00 +0000
2020-04-13T14:14:00.223561+00:00 app[web.1]: I, [2020-04-13T14:14:00.223509 #4] INFO -- : [b4ebe1e2-f3df-485b-8c24-dc91656bb6db] Started GET "/cable/" [WebSocket] for 79.178.15.179 at 2020-04-13 14:14:00 +0000
2020-04-13T14:14:00.223641+00:00 app[web.1]: I, [2020-04-13T14:14:00.223594 #4] INFO -- : [b4ebe1e2-f3df-485b-8c24-dc91656bb6db] Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
2020-04-13T14:14:00.231064+00:00 app[web.1]: D, [2020-04-13T14:14:00.230963 #4] DEBUG -- : User Load (4.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 80], ["LIMIT", 1]]
2020-04-13T14:14:00.231809+00:00 app[web.1]: I, [2020-04-13T14:14:00.231729 #4] INFO -- : Registered connection (Z2lkOi8vcGlua2FzL1VzZXIvODA)
2020-04-13T14:14:00.381473+00:00 app[web.1]: I, [2020-04-13T14:14:00.381364 #4] INFO -- : Finished "/cable/" [WebSocket] for 79.178.15.179 at 2020-04-13 14:14:00 +0000
2020-04-13T14:13:38.061012+00:00 app[web.1]: D, [2020-04-13T14:13:38.060929 #4] DEBUG -- : [b289eb0a-5982-406c-905a-9dc1ed6dafe8] [ActionCable] Broadcasting to notification:Z2lkOi8vcGlua2FzL1VzZXIvMjY: "notification body"