Class: MxitApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/mxit_api/client.rb

Constant Summary collapse

MXIT_AUTH_BASE_URI =
'https://auth.mxit.com'
MXIT_AUTH_TOKEN_URI =
MXIT_AUTH_BASE_URI + '/token'
MXIT_AUTH_CODE_URI =
MXIT_AUTH_BASE_URI + '/authorize'
MXIT_API_URI =
'http://api.mxit.com'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_name, client_id, client_secret) ⇒ Client

Returns a new instance of Client.



16
17
18
19
20
# File 'lib/mxit_api/client.rb', line 16

def initialize(app_name, client_id, client_secret)
  @app_name = app_name
  @client_id = client_id
  @client_secret = client_secret
end

Instance Attribute Details

#app_nameObject

Returns the value of attribute app_name.



13
14
15
# File 'lib/mxit_api/client.rb', line 13

def app_name
  @app_name
end

#auth_tokenObject

Returns the value of attribute auth_token.



14
15
16
# File 'lib/mxit_api/client.rb', line 14

def auth_token
  @auth_token
end

#client_idObject

Returns the value of attribute client_id.



13
14
15
# File 'lib/mxit_api/client.rb', line 13

def client_id
  @client_id
end

#client_secretObject

Returns the value of attribute client_secret.



13
14
15
# File 'lib/mxit_api/client.rb', line 13

def client_secret
  @client_secret
end

Instance Method Details

#batch_notify_users(mxit_ids, message, contains_markup, options = { spool: true, spool_timeout: 60*60*24*7 }) ⇒ Object

When the Mxit API returns 400::Bad Request due to a non-existent Mxit ID in the batch the rest of the IDs still receive the message.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/mxit_api/client.rb', line 203

def batch_notify_users(mxit_ids, message, contains_markup, options={ spool: true,
  spool_timeout: 60*60*24*7 })

  Rails.logger.info('Requesting MXit API auth...')
  request_app_auth(["message/send"])
  Rails.logger.info('Finished MXit API auth.')

  batch_size = 50
  Rails.logger.info('Starting to notify users in batches of ' + batch_size.to_s + '...')
  i = 0
  while i < mxit_ids.count
    current_batch = mxit_ids[i, batch_size]
    i += current_batch.count 

    to = current_batch.join(',')
    begin
      send_message(@app_name, to, message, contains_markup, options)
    rescue Exception => exception
      Rails.logger.error("The following batch caused an exception during send message:" +
        "\n\t#{to}")
      Rails.logger.error(exception.message)
    end

    Rails.logger.info("Total users notified: " + i.to_s)
  end
  Rails.logger.info('Finished notifying!')
end

#get_contact_list(filter, options = { skip: nil, count: nil, auth_token: nil }) ⇒ Object

The following filter parameters are available (only one can be specified at a time):

@All - Return all roster entries
@Friends - Return only friends
@Apps - Return only applications
@Invites  - Return all entries that is in an invite state
@Connections  - Return all entries that has been accepted
@Rejected - Return all entries that has been rejected
@Pending - Return all entries that is waiting to be accepted by the other party
@Deleted - Return all entries that was deleted
@Blocked - Return all entries that was blocked


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/mxit_api/client.rb', line 158

def get_contact_list(filter, options={ skip: nil, count: nil, auth_token: nil })
  auth_token = options[:auth_token] || @auth_token
  check_auth_token(auth_token, ["graph/read"])

  response = http_client(MXIT_API_URI + "/user/socialgraph/contactlist") do |http, path|

    parameters = { :filter => filter }
    # skip and count are optional
    parameters[:skip] = options[:skip] if options[:skip]
    parameters[:count] = options[:count] if options[:count]

    request = Net::HTTP::Get.new(path + "?#{URI.encode_www_form(parameters)}")
    set_api_headers(request, auth_token.access_token)

    http.request(request)
  end

  handle_response(response)
end

#recommend_app(callback_url, from_user_id, to_user_id, message, options = { auth_token: nil }) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/mxit_api/client.rb', line 178

def recommend_app(callback_url, from_user_id, to_user_id, message, options={ auth_token: nil })
  auth_token = options[:auth_token] || @auth_token
  check_auth_token(auth_token, ["contact/recommend"])

  response = http_client(MXIT_API_URI + "/user/recommend") do |http, path|

    request = Net::HTTP::Post.new(path)
    set_api_headers(request, auth_token.access_token)

    request.body = {
      "Application" => @app_name,
      "CallbackUrl" => callback_url,
      "FromUserId" => from_user_id,
      "ToUserId" => to_user_id,
      "Message" => message
    }.to_json

    http.request(request)
  end

  handle_response(response)
end

#refresh_token(auth_token) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/mxit_api/client.rb', line 93

def refresh_token(auth_token)
  if auth_token.refresh_token.nil?
    raise MxitApi::Exception.new("The provided auth token doesn't have a refresh token.")
  end

  response = http_client(MXIT_AUTH_TOKEN_URI) do |http, path|

    request = new_post_request(path, {
      "grant_type" => "refresh_token",
      "refresh_token" => auth_token.refresh_token
    })

    http.request(request)
  end

  handle_response(response)
end

#request_app_auth(scopes) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mxit_api/client.rb', line 22

def request_app_auth(scopes)
  if scopes.empty?
    raise MxitApi::Exception.new("No scopes were provided.")
  end

  response = http_client(MXIT_AUTH_TOKEN_URI) do |http, path|

    request = new_post_request(path, {
      "grant_type" => "client_credentials",
      "scope" => scopes.join(" ")
    })

    http.request(request)
  end

  @auth_token = AuthToken.new(handle_response(response))
end

#request_user_auth(code, redirect_uri) ⇒ Object

NOTE: ‘user_code_request_uri` must be used before `request_user_auth` because it provides the `code` argument. `redirect_uri` must match the one used in the `user_code_request_uri` call



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mxit_api/client.rb', line 65

def request_user_auth(code, redirect_uri)
  response = http_client(MXIT_AUTH_TOKEN_URI) do |http, path|

    request = new_post_request(path, {
      "grant_type" => "authorization_code",
      "code" => code,
      "redirect_uri" => redirect_uri
    })

    http.request(request)
  end

  @auth_token = AuthToken.new(handle_response(response))
end

#revoke_token(auth_token) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/mxit_api/client.rb', line 80

def revoke_token(auth_token)
  response = http_client(MXIT_AUTH_BASE_URI + "/revoke") do |http, path|

    request = new_post_request(path, {
      "token" => auth_token.access_token
    })

    http.request(request)
  end

  handle_response(response)
end

#send_message(from, to, body, contains_markup, options = { spool: true, spool_timeout: 60*60*24*7, auth_token: nil }) ⇒ Object

When sending as the app the ‘message/send` scope is required otherwise `message/user`



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/mxit_api/client.rb', line 114

def send_message(from, to, body, contains_markup, options={ spool: true,
  spool_timeout: 60*60*24*7, auth_token: nil })

  auth_token = options[:auth_token] || @auth_token

  if from == @app_name
    check_auth_token(auth_token, ["message/send"])
  else
    check_auth_token(auth_token, ["message/user"])
  end

  response = http_client(MXIT_API_URI + "/message/send/") do |http, path|

    request = Net::HTTP::Post.new(path)
    set_api_headers(request, auth_token.access_token)

    spool = options[:spool].nil? ? true : options[:spool]
    spool_timeout = options[:spool_timeout] || 60*60*24*7

    request.body = {
      "Body" => body,
      "ContainsMarkup" => contains_markup,
      "From" => from,
      "To" => to,
      "Spool" => spool,
      "SpoolTimeOut" => spool_timeout
    }.to_json

    http.request(request)
  end

  handle_response(response)
end

#user_code_request_uri(redirect_uri, state, scopes) ⇒ Object

The user’s response to the authorisation code request will be redirected to ‘redirect_uri`. If the request was successful there will be a `code` request parameter; otherwise `error`.

redirect_uri - absolute URI to which the user will be redirected after authorisation state - passed back to ‘redirect_uri` as a request parameter scopes - list of scopes to which access is required



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mxit_api/client.rb', line 46

def user_code_request_uri(redirect_uri, state, scopes)
  if scopes.empty?
    raise MxitApi::Exception.new("No scopes were provided.")
  end

  # build parameters
  parameters = {
    :response_type => "code",
    :client_id => @client_id,
    :redirect_uri => redirect_uri,
    :state => state,
    :scope => scopes.join(' ')
  }

  path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}"
end