1
0
puyopuyotetr.is/app/models/web/push_subscription.rb
Yamagishi Kazutoshi 9613a53cb3 Update dependencies for Ruby (2018-04-23) (#7237)
* Update annotate to version 2.7.3

* Update aws-sdk-s3 to version 1.9.2

* Update browser to version 2.5.3

* Update capistrano to version 3.10.2

* Update domain_name to version 0.5.20180417

* Update http to version 3.2.0

* Update lograge to version 0.10.0

* Update oj to version 3.5.1

* Update parallel_tests to version 2.21.3

* Update puma to version 3.11.4

* Update rubocop to version 0.55.0

* Update scss_lint to version 0.57.0

* Update simplecov to version 0.16.1

* Update tty-command to version 0.8.0

* Update tty-prompt to version 0.16.0

* Update pkg-config to version 1.3.0

* Update fog-local to version 0.5.0

* Update fog-openstack to version 0.1.25

* Update devise-two-factor to version 3.0.3

* bundle update
2018-04-23 11:29:17 +02:00

75 lines
2.1 KiB
Ruby

# frozen_string_literal: true
# == Schema Information
#
# Table name: web_push_subscriptions
#
# id :bigint(8) not null, primary key
# endpoint :string not null
# key_p256dh :string not null
# key_auth :string not null
# data :json
# created_at :datetime not null
# updated_at :datetime not null
#
require 'webpush'
class Web::PushSubscription < ApplicationRecord
has_one :session_activation
def push(notification)
I18n.with_locale(session_activation.user.locale || I18n.default_locale) do
push_payload(message_from(notification), 48.hours.seconds)
end
end
def pushable?(notification)
data&.key?('alerts') && data['alerts'][notification.type.to_s]
end
def as_payload
payload = { id: id, endpoint: endpoint }
payload[:alerts] = data['alerts'] if data&.key?('alerts')
payload
end
def access_token
find_or_create_access_token.token
end
private
def push_payload(message, ttl = 5.minutes.seconds)
# TODO: Make sure that the payload does not
# exceed 4KB - Webpush::PayloadTooLarge
Webpush.payload_send(
message: Oj.dump(message),
endpoint: endpoint,
p256dh: key_p256dh,
auth: key_auth,
ttl: ttl,
vapid: {
subject: "mailto:#{::Setting.site_contact_email}",
private_key: Rails.configuration.x.vapid_private_key,
public_key: Rails.configuration.x.vapid_public_key,
}
)
end
def message_from(notification)
serializable_resource = ActiveModelSerializers::SerializableResource.new(notification, serializer: Web::NotificationSerializer, scope: self, scope_name: :current_push_subscription)
serializable_resource.as_json
end
def find_or_create_access_token
Doorkeeper::AccessToken.find_or_create_for(
Doorkeeper::Application.find_by(superapp: true),
session_activation.user_id,
Doorkeeper::OAuth::Scopes.from_string('read write follow'),
Doorkeeper.configuration.access_token_expires_in,
Doorkeeper.configuration.refresh_token_enabled?
)
end
end