import tornado.ioloop
import tornado.web
import anydbm
import time
import urllib
import urllib2
from datetime import datetime
#to store the Keys from the phone
#written when the phone sends in http://xxxxxx/reg/?name=xxx&id=xxxx
client_db = 'gcm_client.db'
#enter your APK key here, the one i used is the key for browser app,
#but i think the key for server will be ok as well
API_KEY = ''
#don't modify this...
GCM_URL = 'https://android.googleapis.com/gcm/send'
class gcmDefault(tornado.web.RequestHandler):
def get(self):
curr_args = self.request.arguments
self.write("OK")
self.finish()
class gcmReg(tornado.web.RequestHandler):
def get(self):
curr_args = self.request.arguments
if (len(curr_args) == 3):
device_password = curr_args['device_password']
name = curr_args['name'][0]
dev_id = curr_args['id'][0]
db = anydbm.open(client_db,'c')
db[name] = dev_id
db.close()
print "name:%s / id:%s" % (name,dev_id)
raise tornado.web.HTTPError(200)
class gcmPush(tornado.web.RequestHandler):
def get(self):
curr_args = self.request.arguments
if (len(curr_args) == 1):
message = curr_args['message'][0]
db = anydbm.open(client_db,'c')
for k,v in db.iteritems():
json_data = { "registration_id": v, "data" : {
"message": message,
},
}
# Plaintext request
result = self.Push(k,v,json_data)
if not(result == ''):
print "PUSH to %s\r\nMessage:%s\r\nStatus:%s" % (k,message,result)
else:
print "Error: Not Found/No Response\r\nID:%s" % v
db.close()
self.finish()
def Push(self, name, regid, json_data):
global API_KEY,GCM_URL
myKey = "key=" + API_KEY
### Get regids
registration_data = {
"registration_ids": [regid],
}
headers = {'Content-Type': 'application/json', 'Authorization': myKey}
data = urllib.urlencode(json_data)
req = urllib2.Request(GCM_URL, data)
req.add_header("Authorization", myKey)
f = urllib2.urlopen(req)
response = f.read()
f.close()
return response
application = tornado.web.Application([
(r"/",gcmDefault),
(r"/reg/", gcmReg),
(r"/push/", gcmPush)
])
if __name__ == "__main__":
curr_time = datetime.now()
print 'pyGCM (1.0.0). (%s).' % curr_time
print ''
#change here for the port used
application.listen(8001)
tornado.ioloop.IOLoop.instance().start()