Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,27 +320,37 @@ ActionWebPush::Subscription.expired.destroy_all
Example JavaScript for subscription management:

```javascript
// This is only one implementation of this function, so you can override it if you wish
function arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}

// Register service worker and get subscription
navigator.serviceWorker.register('/sw.js').then(registration => {
navigator.serviceWorker.register('/service-worker.js').then(registration => {
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: '<%= ActionWebPush.config.vapid_public_key %>'
applicationServerKey: new Uint8Array(<%= Base64.urlsafe_decode64(ActionWebPush.config.vapid_public_key).bytes %>)
});
}).then(subscription => {
// Send subscription to your Rails app
fetch('/push_subscriptions', {
fetch('/awp/push/subscriptions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
},
body: JSON.stringify({
user_id: // pass user id here,
subscription: {
endpoint: subscription.endpoint,
keys: {
p256dh: arrayBufferToBase64(subscription.getKey('p256dh')),
auth: arrayBufferToBase64(subscription.getKey('auth'))
}
p256dh_key: arrayBufferToBase64(subscription.getKey('p256dh')),
auth_key: arrayBufferToBase64(subscription.getKey('auth'))
}
})
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module ActionWebPush
class SubscriptionsController < ActionController::Base
before_action :authenticate_user!, if: :respond_to_authenticate_user?
before_action :set_user
before_action :set_subscription, only: [:show, :destroy]
before_action :set_subscription, only: [ :show, :destroy ]

def index
@subscriptions = ActionWebPush::Subscription.for_user(@user)
Expand All @@ -18,7 +18,9 @@ def show
def create
@subscription = ActionWebPush::Subscription.find_or_create_subscription(
user: @user,
**subscription_params,
endpoint: subscription_params["endpoint"],
p256dh_key: subscription_params["p256dh_key"],
auth_key: subscription_params["auth_key"],
user_agent: request.user_agent
)

Expand Down Expand Up @@ -57,4 +59,4 @@ def respond_to_authenticate_user?
respond_to?(:authenticate_user!)
end
end
end
end
4 changes: 2 additions & 2 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

ActionWebPush::Engine.routes.draw do
resources :subscriptions, only: [:index, :show, :create, :destroy]
end
resources :subscriptions, only: [ :index, :show, :create, :destroy ]
end
6 changes: 3 additions & 3 deletions lib/actionwebpush/delivery_methods/web_push.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ def deliver!(notification, connection: nil)
urgency: notification.options[:urgency] || "high"
)

payload[:success] = response.success?
payload[:success] = response.kind_of? Net::HTTPSuccess
payload[:response_code] = response.code if response.respond_to?(:code)

response.success?
response.kind_of? Net::HTTPSuccess
end
rescue ::WebPush::ExpiredSubscription => e
context = {
Expand Down Expand Up @@ -71,4 +71,4 @@ def encoded_message(notification)
end
end
end
end
end
2 changes: 1 addition & 1 deletion lib/actionwebpush/instrumentation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ def self.publish(event_name, payload = {})
# action_web_push.subscription_created
# action_web_push.subscription_destroyed
end
end
end
4 changes: 2 additions & 2 deletions lib/actionwebpush/notification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def deliver(connection: nil)
if subscription
authorize_notification_sending!(
current_user: @current_user,
subscriptions: [subscription]
subscriptions: [ subscription ]
)
end
end
Expand Down Expand Up @@ -94,4 +94,4 @@ def encoded_message
JSON.generate(payload)
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,4 @@ def preserve_data?
end
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
require "rails/generators/base"

module ActionWebPush
module Generators
module Generators
class InstallGenerator < Rails::Generators::Base
include Rails::Generators::Migration

source_root File.expand_path("templates", __dir__)

def create_migration
def create_migration_web_push
migration_template(
"create_action_web_push_subscriptions.rb",
"db/migrate/create_action_web_push_subscriptions.rb",
Expand All @@ -20,7 +22,7 @@ def create_initializer
end

def mount_engine
route "mount ActionWebPush::Engine => '/push'"
route "mount ActionWebPush::Engine => '/push'", namespace: [ 'awp' ]
end

def show_readme
Expand All @@ -37,11 +39,16 @@ def show_readme

private

def self.next_migration_number(dirname)
next_migration_number = current_migration_number(dirname) + 1
ActiveRecord::Migration.next_migration_number(next_migration_number)
end

def migration_version
if Rails::VERSION::MAJOR >= 5
"[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
end
end
end
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ def change
t.index [:endpoint, :p256dh_key, :auth_key], name: "idx_action_web_push_subscription_keys"
end
end
end
end
8 changes: 4 additions & 4 deletions test/comprehensive_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ def test_web_push_delivery_with_mock

# Mock WebPush.payload_send to avoid actual network call (called twice)
mock_response = Minitest::Mock.new
mock_response.expect :success?, true
mock_response.expect :success?, true
mock_response.expect :kind_of?, true, [ Net::HTTPSuccess ]
mock_response.expect :kind_of?, true, [ Net::HTTPSuccess ]

::WebPush.stub :payload_send, -> (*args) { mock_response } do
::WebPush.stub :payload_send, ->(*args) { mock_response } do
result = web_push_method.deliver!(notification)
assert result, "Web push delivery should succeed"
end
Expand Down Expand Up @@ -150,4 +150,4 @@ def test_configuration_defaults
assert config.timeout > 0
assert config.max_retries >= 0
end
end
end
12 changes: 6 additions & 6 deletions test/delivery_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ def test_web_push_delivery_method

# Mock WebPush response (called twice - for payload and return)
mock_response = Minitest::Mock.new
mock_response.expect :success?, true
mock_response.expect :success?, true
mock_response.expect :kind_of?, true, [ Net::HTTPSuccess ]
mock_response.expect :kind_of?, true, [ Net::HTTPSuccess ]

::WebPush.stub :payload_send, -> (*args) { mock_response } do
::WebPush.stub :payload_send, ->(*args) { mock_response } do
result = web_push_method.deliver!(@notification)
assert result
end
Expand All @@ -86,7 +86,7 @@ def test_web_push_delivery_method_with_error
web_push_method = ActionWebPush::DeliveryMethods::WebPush.new

# Mock WebPush error
::WebPush.stub :payload_send, -> (*args) { raise ::WebPush::ResponseError.new("Test error") } do
::WebPush.stub :payload_send, ->(*args) { raise ::WebPush::ResponseError.new("Test error") } do
assert_raises(ActionWebPush::DeliveryError) do
web_push_method.deliver!(@notification)
end
Expand All @@ -99,7 +99,7 @@ def test_web_push_expired_subscription_handling
web_push_method = ActionWebPush::DeliveryMethods::WebPush.new

# Mock expired subscription error - simplified for testing
::WebPush.stub :payload_send, -> (*args) { raise StandardError.new("410 Gone") } do
::WebPush.stub :payload_send, ->(*args) { raise StandardError.new("410 Gone") } do
assert_raises(ActionWebPush::DeliveryError) do
web_push_method.deliver!(@notification)
end
Expand Down Expand Up @@ -139,4 +139,4 @@ def deliver!(notification, connection: nil)
assert result
assert_equal @notification, method.delivered_notification
end
end
end