Class: SMS::Backend::Clickatell

Inherits:
Base show all
Defined in:
lib/rubysms/backend/clickatell.rb

Constant Summary collapse

PORT =
1280

Instance Attribute Summary

Attributes inherited from Thing

#label, #router

Instance Method Summary collapse

Methods inherited from Thing

#incoming, #outgoing, #stop

Constructor Details

#initialize(key, username, password) ⇒ Clickatell

just store the arguments until the backend is ready to be started



17
18
19
20
21
# File 'lib/rubysms/backend/clickatell.rb', line 17

def initialize(key, username, password)
	@username = username
	@password = password
	@key = key
end

Instance Method Details

#rack_app(env) ⇒ Object



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
79
80
81
82
83
84
85
86
87
# File 'lib/rubysms/backend/clickatell.rb', line 54

def rack_app(env)
	req = Rack::Request.new(env)
	post = req.GET
	
	# only a single (obscure) url is valid, which
	# must be entered into the clickatell admin
	return resp(404, "Not Found") unless\
		req.path_info == "/sms/receive"
	
	# check that the required parameters were
	# provided, and abort if any are missing
	return resp(500, "Missing Parameters") unless\
		post["from"] && post["timestamp"] && post["text"]
	
	begin
		# attempt to parse the timestamp
		# (it's a mySQL timestamp... ?!)
		time = Date.strptime(
			post["timestamp"],
			"%Y-%m-%d%H:%M:%S")
	
	# timestamp parsing fail
	rescue Exception => err
		log_exception err, "Invalid timestamp: #{post["timestamp"]}"
		return resp(500, "Invalid timestamp")
	end
	
	# everything looks fine, so notify rubysms of
	# the incoming message, and acknowledge clickatell
	router.incoming(
		SMS::Incoming.new(
			self, post["from"], time, post["text"]))
	resp(200, "Message Accepted")
end

#send_sms(msg) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubysms/backend/clickatell.rb', line 42

def send_sms(msg)
	begin
		@api.send_message(msg.phone_number, msg.text)
		super

	# sending failed, for some reason. i've
	# never seen this happen, so just log it
	rescue Clickatell::API::Error => err
		log_exception err, "Message sending FAILED"
	end
end

#startObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rubysms/backend/clickatell.rb', line 23

def start
	@api = ::Clickatell::API.authenticate(@key, @username, @password)
	balance = @api.
	
	# start a separate thread to receive
	# the incoming messages from clickatell
	@rack_thread = Thread.new do
		Rack::Handler::Mongrel.run(
			method(:rack_app), :Port=>PORT)
	end
	
	# nothing went wrong this time
	# so dump some useful info
	log [
		"Started #{label} Backend",
		"  Account balance: #{balance}"
	], :init
end