Class: Noticed::DeliveryMethods::Fcm

Inherits:
Noticed::DeliveryMethod show all
Defined in:
lib/noticed/delivery_methods/fcm.rb

Instance Attribute Summary

Attributes inherited from Noticed::DeliveryMethod

#config, #event, #notification

Instance Method Summary collapse

Methods inherited from Noticed::DeliveryMethod

#evaluate_option, #fetch_constant, #perform

Methods included from ApiClient

#post_request

Instance Method Details

#access_tokenObject



55
56
57
58
59
60
61
# File 'lib/noticed/delivery_methods/fcm.rb', line 55

def access_token
  @authorizer ||= (evaluate_option(:authorizer) || Google::Auth::ServiceAccountCredentials).make_creds(
    json_key_io: StringIO.new(credentials.to_json),
    scope: "https://www.googleapis.com/auth/firebase.messaging"
  )
  @authorizer.fetch_access_token!["access_token"]
end

#credentialsObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/noticed/delivery_methods/fcm.rb', line 35

def credentials
  @credentials ||= begin
    value = evaluate_option(:credentials)
    case value
    when Hash
      value
    when Pathname
      load_json(value)
    when String
      load_json(Rails.root.join(value))
    else
      raise ArgumentError, "FCM credentials must be a Hash, String, Pathname, or Symbol"
    end
  end
end

#deliverObject



8
9
10
11
12
# File 'lib/noticed/delivery_methods/fcm.rb', line 8

def deliver
  evaluate_option(:device_tokens).each do |device_token|
    send_notification device_token
  end
end

#format_notification(device_token) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/noticed/delivery_methods/fcm.rb', line 26

def format_notification(device_token)
  method = config[:json]
  if method.is_a?(Symbol) && event.respond_to?(method, true)
    event.send(method, device_token)
  else
    notification.instance_exec(device_token, &method)
  end
end

#load_json(path) ⇒ Object



51
52
53
# File 'lib/noticed/delivery_methods/fcm.rb', line 51

def load_json(path)
  JSON.parse(File.read(path), symbolize_names: true)
end

#send_notification(device_token) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/noticed/delivery_methods/fcm.rb', line 14

def send_notification(device_token)
  post_request("https://fcm.googleapis.com/v1/projects/#{credentials[:project_id]}/messages:send",
    headers: {authorization: "Bearer #{access_token}"},
    json: format_notification(device_token))
rescue Noticed::ResponseUnsuccessful => exception
  if exception.response.code == "404" && config[:invalid_token]
    notification.instance_exec(device_token, &config[:invalid_token])
  else
    raise
  end
end