Class: SMSCentre::API

Inherits:
Object
  • Object
show all
Defined in:
lib/sms_centre/api.rb

Instance Method Summary collapse

Constructor Details

#initialize(login, password) ⇒ API

Returns a new instance of API.



3
4
5
# File 'lib/sms_centre/api.rb', line 3

def initialize(, password)
  @provider = Provider.new(, password)
end

Instance Method Details

#balanceObject



7
8
9
10
11
12
13
14
15
# File 'lib/sms_centre/api.rb', line 7

def balance
  resp = @provider.request(path: '/sys/balance.php')
  
  if resp.key?("balance")
    resp["balance"]
  else
    raise ServerError.new("unexpected response: 'balance' key not found")
  end
end

#broadcast(phones, message, opts = {}) ⇒ Object



17
18
19
20
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
# File 'lib/sms_centre/api.rb', line 17

def broadcast(phones, message, opts = {})
  opts   = {path: '/sys/send.php'}.merge(opts)
  phones = [phones] if phones.kind_of? String

  if phones.length > SMSCentre.configuration.max_phones_per_request
    raise ClientError.new("too much phone numbers per request")
  end

  params = {
    phones: phones.join(','),
    mes:    message,
    err:    1, # Show errors for each phone
    cost:   3  # Return request cost and result balance
  }

  params.merge!(opts.delete(:params) || {})

  resp = @provider.request(opts.merge(params: params))

  if resp.key?("error_code")
    global_error = case resp["error_code"]
                   when ERROR_IMPOSSIBLE
                     MESSAGE_STATUS_ERROR_IMPOSSIBLE
                   when ERROR_PHONE_FORMAT
                     MESSAGE_STATUS_ERROR_PHONE_FORMAT
                   when ERROR_FORBIDDEN_MESSAGE
                     MESSAGE_STATUS_ERROR_FORBIDDEN_MESSAGE
                   when ERROR_BALANCE
                     MESSAGE_STATUS_ERROR_BALANCE
                   else
                     raise ClientError.new(resp['error_code'])
                   end

    errors = {}
    phones.each { |p| errors[p] = global_error }

    Result.new(errors, resp['id'])
  else
    Result.new(resp['errors'] || {}, resp['id'], cost: resp['cost'], balance: resp['balance'])
  end
end

#status(message_id, phone, opts = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sms_centre/api.rb', line 59

def status(message_id, phone, opts = {})
  opts   = {path: '/sys/status.php', all: 2}.merge(opts)
  params = {
    phone: phone,
    id:    message_id
  }

  params.merge!(opts.delete(:params) || {})

  resp = @provider.request(opts.merge(params: params))

  if resp.key?('error_code')
    raise ClientError.new(resp['error_code'])
  end

  Status.new(phone,  message_id, resp["status"],
    err:            resp["err"],
    last_date:      resp["last_date"],
    last_timestamp: resp["last_timestamp"],
  )
end