Class: C2dm::Connection

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username, password, source) ⇒ Connection

Returns a new instance of Connection.



11
12
13
14
15
16
17
# File 'lib/connection.rb', line 11

def initialize(username, password, source)
  @username = username
  @password = password
  @source   = source

  authenticate!
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



9
10
11
# File 'lib/connection.rb', line 9

def access_token
  @access_token
end

#passwordObject

Returns the value of attribute password.



9
10
11
# File 'lib/connection.rb', line 9

def password
  @password
end

#sourceObject

Returns the value of attribute source.



9
10
11
# File 'lib/connection.rb', line 9

def source
  @source
end

#timeoutObject

Returns the value of attribute timeout.



9
10
11
# File 'lib/connection.rb', line 9

def timeout
  @timeout
end

#usernameObject

Returns the value of attribute username.



9
10
11
# File 'lib/connection.rb', line 9

def username
  @username
end

Instance Method Details

#authenticate!Object



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
# File 'lib/connection.rb', line 23

def authenticate!
  auth_options = {
    'accountType' => 'HOSTED_OR_GOOGLE',
    'service'     => 'ac2dm',
    'Email'       => self.username,
    'Passwd'      => self.password,
    'source'      => self.source
  }
  post_body = build_post_body(auth_options)

  params = {
    :body    => post_body,
    :headers => {
      'Content-type'   => 'application/x-www-form-urlencoded',
      'Content-length' => post_body.length.to_s
    }
  }

  response = self.class.post(C2dm.auth_url, params)

  # check for authentication failures
  raise response.parsed_response if response['Error=']

  @auth_token = response.body.split("\n")[2].gsub('Auth=', '')
end

#authenticated?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/connection.rb', line 19

def authenticated?
  !@auth_token.nil?
end

#send_notification(options) ⇒ Object

{

:registration_id => "...",
:data => {
  :some_message => "Hi!", 
  :another_message => 7
}
:collapse_key => "optional collapse_key string"

}



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/connection.rb', line 57

def send_notification(options)
  options[:collapse_key] ||= 'foo'
  post_body = build_post_body(options)

  params = {
    :body    => post_body,
    :headers => {
      'Authorization'  => "GoogleLogin auth=#{@auth_token}",
      'Content-type'   => 'application/x-www-form-urlencoded',
      'Content-length' => "#{post_body.length}"
    }
  }

  self.class.post(C2dm.push_url, params)
end