Class: Rhoconnect::Fcm

Inherits:
Object
  • Object
show all
Defined in:
lib/rhoconnect/ping/fcm.rb

Defined Under Namespace

Classes: FCMPingError, InvalidPackageName, InvalidProjectId

Class Method Summary collapse

Class Method Details

.fcm_message(package_name, params) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rhoconnect/ping/fcm.rb', line 48

def self.fcm_message(package_name,params)
  params.reject! {|k,v| v.nil? || v.length == 0}
  data = {}
  data['do_sync'] = params['sources'] ? params['sources'].join(',') : ''
  data['alert'] = params['message'] if params['message']
  data['vibrate'] = params['vibrate'] if params['vibrate']
  data['sound'] = params['sound'] if params['sound']
  data['phone_id'] = params['phone_id'] if params['phone_id']

  android = {}
  android['collapse_key'] = (rand * 100000000).to_i.to_s
  android['priority'] = 'high'
  android['restricted_package_name'] = package_name
  android['data'] = data
  android['notification'] = {}
  # android['notification']['title'] = 'Test message'
  android['notification']['body'] = params['message']

  message = Google::Apis::Messages::Message.new(
    token: params['device_pin'].to_s,
    android: android
  )
  
  message
end

.ping(params) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rhoconnect/ping/fcm.rb', line 12

def self.ping(params)
  begin
    fcm_project_id = Rhoconnect.settings[:fcm_project_id]
    raise InvalidProjectId.new("Missing `:fcm_project_id:` option in settings/settings.yml") unless fcm_project_id

    package_name = Rhoconnect.settings[:package_name]
    raise InvalidPackageName.new("Missing `:package_name:` option in settings/settings.yml") unless package_name
    
    send_ping_to_device(fcm_project_id, package_name, params)
  rescue InvalidProjectId => error
    log error
    log error.backtrace.join("\n")
    raise error
  rescue InvalidPackageName => error
    log error
    log error.backtrace.join("\n")
    raise error
  rescue Exception => error
    log error
    log error.backtrace.join("\n")
    raise error
  end
end

.send_ping_to_device(project_id, package_name, params) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rhoconnect/ping/fcm.rb', line 36

def self.send_ping_to_device(project_id,package_name,params)

  scope = Google::Apis::Messages::AUTH_MESSAGES
  authorization = Google::Auth.get_application_default(scope)
  
  service = Google::Apis::Messages::MessagesService.new(project_id: project_id)
  service.authorization = authorization
  
  service.notify(fcm_message(package_name,params))

end