Class: Tele42::SMS

Inherits:
Base
  • Object
show all
Defined in:
lib/tele42/sms.rb

Instance Method Summary collapse

Methods inherited from Base

#check_options, #connection, #faraday_options, #parse_options, #server_url

Constructor Details

#initialize(options) ⇒ SMS

Returns a new instance of SMS.



4
5
6
7
# File 'lib/tele42/sms.rb', line 4

def initialize(options)
  super(options)
  check_route
end

Instance Method Details

#check_from(from) ⇒ Object



79
80
81
82
83
# File 'lib/tele42/sms.rb', line 79

def check_from(from)
  unless from =~ /\A\d{1,15}\z/ || from =~ /\A[[:alnum:]]{1,11}\z/
    raise ::Tele42::InvalidFrom, 'invalid from format'
  end
end

#check_routeObject



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

def check_route
  raise ::Tele42::InvalidRoute, 'route should be set' if @route.nil? || @route.empty?
end

#default_paramsObject



13
14
15
# File 'lib/tele42/sms.rb', line 13

def default_params
  @default_params ||= super.merge('route' => @route)
end

#generate_message_for(type, message) ⇒ Object



60
61
62
63
64
65
# File 'lib/tele42/sms.rb', line 60

def generate_message_for(type, message)
  case type
  when :text
    generate_text_message(message)
  end
end

#generate_text_message(message) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/tele42/sms.rb', line 67

def generate_text_message(message)
  if @unicode
    if defined?(JRUBY_VERSION)
      message.each_byte.map { |b| sprintf('00%02X', b) }.join
    else
      ::Kconv.kconv(message, ::NKF::UTF16, ::NKF::UTF8).unpack('H*').first.upcase
    end
  else
    message.force_encoding('iso-8859-1')
  end
end

#parse_error(data) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/tele42/sms.rb', line 47

def parse_error(data)
  case data[1].to_i
  when 1
    raise ::Tele42::BadLoginDetails
  when 2
    raise ::Tele42::BadMessage
  when 3
    raise ::Tele42::BadNumber, "Bad to number #{data[2]}"
  when 4
    raise ::Tele42::NotEnoughCredits
  end
end

#parse_result(res) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/tele42/sms.rb', line 38

def parse_result(res)
  data = res.body.split(',')
  if data[0].to_i == 1
    data[1]
  else
    parse_error(data)
  end
end

#send_text(options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tele42/sms.rb', line 21

def send_text(options = {})
  from = options[:from]
  to = options[:to]
  message = options[:text]
  check_from(from)
  params = default_params.merge(
    'to' => to,
    'from' => from,
    'message' => generate_message_for(:text, message)
  )
  if @unicode
    params['coding'] = 'unicode'
  end
  res = connection.get('/api/current/send/message.php', params)
  parse_result(res)
end

#unicode!Object



17
18
19
# File 'lib/tele42/sms.rb', line 17

def unicode!
  @unicode = true
end