Class: Webpush::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/webpush/request.rb

Overview

rubocop:disable Metrics/ClassLength

Instance Method Summary collapse

Constructor Details

#initialize(message: '', subscription:, vapid:, **options) ⇒ Request

Returns a new instance of Request.



13
14
15
16
17
18
19
# File 'lib/webpush/request.rb', line 13

def initialize(message: '', subscription:, vapid:, **options)
  endpoint = subscription.fetch(:endpoint)
  @endpoint = endpoint.gsub(GCM_URL, TEMP_GCM_URL)
  @payload = build_payload(message, subscription)
  @vapid_options = vapid
  @options = default_options.merge(options)
end

Instance Method Details

#bodyObject



70
71
72
# File 'lib/webpush/request.rb', line 70

def body
  @payload || ''
end

#build_vapid_headerObject

rubocop:enable Metrics/MethodLength



60
61
62
63
64
65
66
67
68
# File 'lib/webpush/request.rb', line 60

def build_vapid_header
  # https://tools.ietf.org/id/draft-ietf-webpush-vapid-03.html

  vapid_key = vapid_pem ? VapidKey.from_pem(vapid_pem) : VapidKey.from_keys(vapid_public_key, vapid_private_key)
  jwt = JWT.encode(jwt_payload, vapid_key.curve, 'ES256', jwt_header_fields)
  p256ecdsa = vapid_key.public_key_for_push_header

   "vapid t=#{jwt},k=#{p256ecdsa}"
end

#headersObject

rubocop:disable Metrics/MethodLength



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/webpush/request.rb', line 39

def headers
  headers = {}
  headers['Content-Type'] = 'application/octet-stream'
  headers['Ttl']          = ttl
  headers['Urgency']      = urgency

  if @payload
    headers['Content-Encoding'] = 'aes128gcm'
    headers["Content-Length"] = @payload.length.to_s
  end

  if api_key?
    headers['Authorization'] = "key=#{api_key}"
  elsif vapid?
    headers["Authorization"] = build_vapid_header
  end

  headers
end

#performObject

rubocop:disable Metrics/AbcSize



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/webpush/request.rb', line 22

def perform
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.ssl_timeout = @options[:ssl_timeout] unless @options[:ssl_timeout].nil?
  http.open_timeout = @options[:open_timeout] unless @options[:open_timeout].nil?
  http.read_timeout = @options[:read_timeout] unless @options[:read_timeout].nil?

  req = Net::HTTP::Post.new(uri.request_uri, headers)
  req.body = body
  resp = http.request(req)
  verify_response(resp)

  resp
end