Class: GcmSendDownstream

Inherits:
Object
  • Object
show all
Defined in:
lib/gcm-send-downstream.rb

Instance Method Summary collapse

Constructor Details

#initialize(auth_key, app_title) ⇒ GcmSendDownstream

Returns a new instance of GcmSendDownstream.



13
14
15
16
17
18
19
# File 'lib/gcm-send-downstream.rb', line 13

def initialize(auth_key, app_title)

  # GCM API KEY : https://developers.google.com/cloud-messaging/
  @auth_key = auth_key
  @app_title = app_title

end

Instance Method Details

#send_message(registration_ids, message, silent = false, silent_data = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
73
74
75
76
77
78
# File 'lib/gcm-send-downstream.rb', line 21

def send_message(registration_ids, message, silent = false, silent_data = nil)

  unless silent

    params = {

      'notification' => {'title' => @app_title,
                         'body' => message},
      'data' => {'title' => @app_title,
      'message' => message},
      'registration_ids' => registration_ids

    }.to_json

  else

    params = {

      'data' => silent_data,
      'registration_ids' => registration_ids,
      'content_available' => true

    }.to_json

  end

  uri = URI.parse("https://gcm-http.googleapis.com")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
 
  request = Net::HTTP::Post.new("/gcm/send")
  request.add_field("Authorization", "key=#{@auth_key}")
  request.add_field("Content-Type", "application/json")
  request.body = params
  response= http.request(request)

  # Json Parse
  begin

    results = JSON.parse(response.body)

  rescue JSON::ParserError => e

    str_error =  "JSON Parse Error (#{e})"
    yield false, str_error
    return

  end

  gcm_results = results["results"]
 
  gcm_results.each_with_index do |gcm_result, index|
 
    yield true, gcm_result

  end 

end