Created
January 7, 2013 14:49
-
-
Save neilxp/4475485 to your computer and use it in GitHub Desktop.
Python program for sending message to iOS via APN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python2.7 | |
import socket | |
import ssl | |
import json | |
import struct | |
import argparse | |
APNS_HOST = ( 'gateway.sandbox.push.apple.com', 2195 ) | |
class Payload: | |
PAYLOAD = '{"aps":{${MESSAGE}${BADGE}${SOUND}}}' | |
def __init__(self): | |
pass | |
def set_message(self, msg): | |
if msg is None: | |
self.PAYLOAD = self.PAYLOAD.replace('${MESSAGE}', '') | |
else: | |
self.PAYLOAD = self.PAYLOAD.replace('${MESSAGE}', '"alert":"%s",' % msg) | |
def set_badge(self, num): | |
if num is None: | |
self.PAYLOAD = self.PAYLOAD.replace('${BADGE}', '') | |
else: | |
self.PAYLOAD = self.PAYLOAD.replace('${BADGE}', '"badge":%s,' % num) | |
def set_sound(self, sound): | |
if sound is None: | |
self.PAYLOAD = self.PAYLOAD.replace('${SOUND}', '') | |
else: | |
self.PAYLOAD = self.PAYLOAD.replace('${SOUND}', '"sound":"%s",' % sound) | |
def toString(self): | |
return (self.PAYLOAD.replace('${MESSAGE}','').replace('${BADGE}','').replace('${SOUND}','')) | |
def connectAPNS(host, cert): | |
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = cert ) | |
ssl_sock.connect( APNS_HOST ) | |
return ssl_sock | |
def sendNotification(sslSock, device, message, badge, sound): | |
payload = Payload() | |
payload.set_message(message) | |
payload.set_badge(badge) | |
payload.set_sound(sound) | |
payloadAsStr = payload.toString() | |
format = '!BH32sH%ds' % len(payloadAsStr) | |
binaryDeviceToken = device.replace(' ','').decode('hex') | |
binaryNotification = struct.pack( format, 0, 32, binaryDeviceToken, len(payloadAsStr), payloadAsStr ) | |
print ("sending payload: ["+payloadAsStr+"] as binary to device: ["+device+"]") | |
sslSock.write(binaryNotification) | |
def printUsageAndExit(): | |
print("msg2ios - Version 0.1\nmsg2IOS.py -d <device> -m <message> -s[plays sound] -b <badgeint> -c <certBundlePath>") | |
exit(1) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-d', '--device') | |
parser.add_argument('-m', '--message') | |
parser.add_argument('-s', '--sound') | |
parser.add_argument('-b', '--badge') | |
parser.add_argument('-c', '--cert') | |
args = parser.parse_args() | |
if (args.device is None) or ((args.message is None) and (args.sound is None) and (args.badge is None)) or (args.cert is None): | |
printUsageAndExit() | |
sslSock = connectAPNS(APNS_HOST, args.cert) | |
sendNotification(sslSock, args.device, args.message, args.badge, args.sound) | |
sslSock.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment