forked from jeztek/imok_appengine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sms_android.py
145 lines (114 loc) · 4.47 KB
/
sms_android.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
try:
import json
except ImportError:
import django.utils.simplejson as json
from datastore import Post, SmsMessage, Phone, RegisteredEmail, ImokUser
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template, util
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import mail
import settings as s
from smsutils import sendSms
def secret_required(handler_method):
def check_secret(self, *args):
if self.request.get('secret', '') != s.GATEWAY_SECRET:
self.error(404)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("404 - Not Found\n")
return
handler_method(self, *args)
return check_secret
class IncomingHandler(webapp.RequestHandler):
@secret_required
def post(self):
self.response.headers['Content-Type'] = 'text/json'
phone = Phone.normalize_number(self.request.get('phone'))
message = self.request.get('message')
if not (message and phone):
result = { 'result': 'error',
'message': 'missing phone and/or message' }
self.response.out.write(json.dumps(result))
return
sms_message = SmsMessage(phone_number=phone,
message=message,
direction='incoming',
status='unclaimed')
objects = [ sms_message ]
phone_entity = Phone.all().filter('number =', phone).get()
if not phone_entity:
db.put(objects)
self.response.out.write(json.dumps({'result': 'ok'}))
return
post = Post.fromText(message)
post.unique_id = Post.gen_unique_key()
post.user = phone_entity.user
objects.append(post)
sms_message.status = 'queued'
db.put(objects)
imok_user = ImokUser.all().filter('account =', phone_entity.user).get()
email_query = RegisteredEmail.all().filter('userName =', phone_entity.user).order('emailAddress')
for email in email_query:
template_data = {
'message': post.message,
'link': post.permalink(self.request.host_url),
'unsubscribe_link': email.permalink(self.request.host_url),
'user': imok_user
}
body = template.render(s.template_path('email.txt'), template_data)
mail.send_mail(sender=s.MAILER_EMAIL,
to=email.emailAddress,
subject="IMOk status",
body=body)
sms_message.status = 'processed'
# Response_sms = SmsMessage(phone_number=phone,
# message="IMOk: Message received, %d contact(s) notified." % email_query.count(),
# direction="outgoing",
# status="queued")
sendSms(phone=phone_entity, message="IMOk: Message received, %d contact(s) notified." % email_query.count())
# db.put([ response_sms, sms_message ])
db.put([sms_message])
#self.response.out.write(message)
self.response.out.write(json.dumps({'result': 'ok'}))
class OutgoingHandler(webapp.RequestHandler):
@secret_required
def post(self):
self.response.headers['Content-Type'] = 'text/json'
# Handle any messages the phone sent
sent_messages_str = self.request.get('messages', '[]')
sent_messages = json.loads(sent_messages_str)
try:
messages = db.get(sent_messages)
def deliver(m):
m.status = 'delivered'
return m
map(deliver, messages)
db.put(messages)
except db.BadKeyError:
# TODO: Do something
pass
# Send them any new messages
messages = SmsMessage.all().filter('status =', 'queued').filter('direction =', 'outgoing').fetch(100)
def modify(m):
m.status = 'sent'
return { 'id': str(m.key()), 'message': m.message, 'phone': m.phone_number }
send_messages = map(modify, messages)
db.put(messages)
self.response.headers['Content-Type'] = 'text/json'
self.response.out.write(json.dumps({'result': 'ok', 'messages': send_messages}))
class StatusHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
if not user.is_current_user_admin():
self.redirect('/home')
def main():
application = webapp.WSGIApplication([
('/smsgateway/android/incoming', IncomingHandler),
('/smsgateway/android/outgoing', OutgoingHandler),
#('/smsgateway/status', StatusHandler),
], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()