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



46
47
48
49
50
51
52
# File 'lib/noticed/delivery_methods/fcm.rb', line 46

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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/noticed/delivery_methods/fcm.rb', line 26

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

#load_json(path) ⇒ Object



42
43
44
# File 'lib/noticed/delivery_methods/fcm.rb', line 42

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: notification.instance_exec(device_token, &config[:json]))
rescue Noticed::ResponseUnsuccessful => exception
  if exception.response.code == "404" && config[:invalid_token]
    notification.instance_exec(device_token, &config[:invalid_token])
  else
    raise
  end
end