def push_apns(self): from people.models import Profile while True: push_apns = APNS.objects.filter(publish_date__lt=datetime.datetime.now(), is_pushed=False) if push_apns.count() > 0: print u'%s: %i ready.' % (datetime.datetime.now(), push_apns.count()) apns_send = APNs(use_sandbox=True, cert_file=settings.CERT_PEM, key_file=settings.KEY_PEM) profiles = Profile.objects.filter(deviceid__isnull=False).exclude(deviceid='').exclude(deviceid='faketoken').values('deviceid').distinct() for apns in push_apns: print u'%s: %s to be pushed.' % (datetime.datetime.now(), apns.content) payload = Payload(alert=apns.content, sound="default", badge=1, custom={}) i = 0 for profile in profiles: try: i += 1 if i % 50 == 0: apns_send = APNs(use_sandbox=True, cert_file=settings.CERT_PEM, key_file=settings.KEY_PEM) apns_send.gateway_server.send_notification(profile['deviceid'], payload) print u'%s: %s complete.' % (datetime.datetime.now(), profile['deviceid']) except: raise print u'%s: %s error.' % (datetime.datetime.now(), profile['deviceid']) print u'%s: %s completed' % (datetime.datetime.now(), apns.content) apns.is_pushed = True apns.save() else: print u'%s: no task. sleep....' % datetime.datetime.now() time.sleep(60)
def send(listtoken, dev): if dev == 1: print '--develop--' apns = APNs(use_sandbox=dev, cert_file='pem/cert.pem', key_file='pem/ck.pem') else: apns = APNs(use_sandbox=False, cert_file='pem/cert.pem', key_file='pem/key.pem') # attrs = ("alert", "badge", "sound", "custom") payload = Payload("You got your emails.", sound="default", badge=1, custom={"customdata": { "msgID": "51" }}) for i in range(0, len(listtoken)): print i print listtoken[i] try: apns.gateway_server.send_notification(listtoken[i], payload) except Exception, e: print e
def __init__(self, app=None, use_sandbox=True, cert_file=None, key_file=None): if app is not None: self.app = app self.init_app(self.app) else: self.app = None if cert_file is None or key_file is None: raise Exception('Must pass app or both cert_file and key_file') self.cert_file = cert_file self.key_file = key_file self.use_sandbox = use_sandbox APNs.__init__(self, use_sandbox=self.use_sandbox, cert_file=self.cert_file, key_file=self.key_file)
def send_notification_on_new_vote(usersecret): if not settings.PRODUCTION: apns = APNs(use_sandbox=True, cert_file='/home/ubuntu/apns/BackchannelCert.pem', key_file='/home/ubuntu/apns/BackchannelKey.pem') else: apns = APNs(use_sandbox=False, cert_file='/home/ubuntu/apns/BackchannelProdCert.pem', key_file='/home/ubuntu/apns/BackchannelProdKey.pem') owner = usersecret.secret.user if not owner.device_token or owner == usersecret.user: return payload = Payload(alert="A coworker just voted on your post.", sound="default", custom={'type': 'detail_view', 'sid': usersecret.secret.id}) apns.gateway_server.send_notification(owner.device_token, payload)
def send(self, push_id, push_token, push_type, raw_content): # create temp certificate cert_file_fd, cert_file = tempfile.mkstemp() cert_file_fp = os.fdopen(cert_file_fd, 'w') cert_file_fp.write(self.pem) cert_file_fp.close() apns = APNs( use_sandbox=True, cert_file=cert_file ) alert = raw_content.pop('alert', None) sound = raw_content.pop('sound', None) badge = raw_content.pop('badge', None) category = raw_content.pop('category', None) payload = Payload( alert=alert, sound=sound, badge=badge, category=category, custom={ 'id': push_id, 'content': raw_content, }, content_available=False if push_type == TYPE_NOTIFICATION else True ) try: async_send_task.delay(apns.gateway_server.send_notification, token_hex=push_token, payload=payload) finally: os.unlink(cert_file)
def sendNotificationForDiscussion(discussionname, coursename): global device_token apns = APNs(use_sandbox=True, cert_file=cert_file, key_file=key_file) alert = PayloadAlert(title=discussionname, body=("New Announcement in " + coursename)) payload = Payload(alert=alert) apns.gateway_server.send_notification(device_token, payload)
def send_applicable_pushes(self, pushes): payloads_and_tokens = [] # [(payload, token)] for push in pushes: for recip in push.recipients: if '.' in recip: token, service = recip.split('.', 1) if service == self.name: pl = Payload(alert=push.text, sound='default', badge=1) payloads_and_tokens.append((pl, token)) if len(payloads_and_tokens): prefix = 'dev' if self.is_sandbox() else 'prod' apns = APNs(use_sandbox=self.is_sandbox(), cert_file=prefix + '-cert.pem', key_file=prefix + '-key.pem', enhanced=True) frame = Frame() identifier = 1 expiry = time.time() + 3600 priority = 10 for payload, token in payloads_and_tokens: frame.add_item(token, payload, identifier, expiry, priority) apns.gateway_server.send_notification_multiple(frame) for (token, failed_time) in apns.feedback_server.items(): print failed_time print 'no f*****g feedback'
def push_update(modeladmin, request, queryset): for r in queryset.all(): # FIXME: use different certificates for different stores apns = APNs(use_sandbox=False, cert_file=settings.PASSBOOK_CERT, key_file=settings.PASSBOOK_CERT_KEY) apns.gateway_server.send_notification(r.push_token, Payload())
def send_apns(mess, token, custom): from apns import APNs, Payload pem_file = settings.home_dir + "apns_dev.pem" apns = APNs(use_sandbox=True, cert_file=pem_file, key_file=pem_file) payload = Payload(alert=mess, badge=1, sound='default', custom=custom) print(payload) apns.gateway_server.send_notification(token, payload)
def post(self): if not is_administrator(): self.abort(403) message = self.request.params["message"] use_sandbox = 'use_sandbox' in self.request.params certFile = 'RayvIosCerts.pem' logging.info("NotificationBroadcast with cert %s & sandbox %s" % (certFile, str(use_sandbox))) apns = APNs(use_sandbox=use_sandbox, cert_file=certFile) payload = Payload(alert=message, sound="default", badge=1, custom={}) count = 0 for registered_user in ndb_models.NotificationToken.query(): token = str(registered_user.token) hex_token = token.translate(None, '< >') try: apns.gateway_server.send_notification( hex_token, payload, expiry=(datetime.utcnow() + timedelta(300))) for (token_hex, fail_time) in apns.feedback_server.items(): logging.info(token_hex) logging.info(fail_time) count += 1 self.response.out.write('User %s<br>' % registered_user.userId) except: logging.warning( "NotificationBroadcast error for %d tok:%s" % (registered_user.userId, registered_user.token), exc_info=True) self.response.out.write('Sent %d messages, sandbox:%s' % (count, str(use_sandbox)))
def save(self, *args, **kwargs): super(EmergencySchedule, self).save(*args, **kwargs) if not self.is_booked: if self.dentist.dentistprofile.device_token: apns = APNs(use_sandbox=False, cert_file=settings.APN_CERT_LOCATION, key_file=settings.APN_KEY_LOCATION) # Send a notification token_hex = self.dentist.dentistprofile.device_token.all( )[0].token alert_message = 'Un RDV est disponible le %s a %s.' % ( self.date.strftime('%b %d,%Y'), self.time.strftime('%H:%M')) payload = Payload(alert=alert_message, sound="default", badge=1) frame = Frame() identifier = 1 expiry = time.time() + 3600 priority = 10 for patient in UserProfile.objects.filter( dentist=self.dentist): frame.add_item(patient.device_token.all()[0].token, payload, identifier, expiry, priority) notification = Notification(message=alert_message, user=patient.user) notification.save() apns.gateway_server.send_notification_multiple(frame)
def get_dev_apns(): """ http://stackoverflow.com/questions/1762555/creating-pem-file-for-apns Step 1: Create Certificate .pem from Certificate .p12 Command: openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12 Step 2: Create Key .pem from Key .p12 Command : openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12 Step 3: If you want to remove pass phrase asked in second step Command : openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem """ if not hasattr(threadlocal, "dev_apns"): settings = get_settings() cert_file = os.environ.get("APNS_CERT", settings.get("apns.dev.certificate")) key_file = os.environ.get("APNS_KEY", settings.get("apns.dev.key")) sandbox = True # other_helpers.boolify(os.environ.get("APNS_SANDBOX",settings.get("apns.sandbox"))) threadlocal.dev_apns = APNs(use_sandbox=sandbox, cert_file=cert_file, key_file=key_file, enhanced=True) def response_listener(error_response): log.debug("client get error-response: " + str(error_response)) threadlocal.dev_apns.gateway_server.register_response_listener( response_listener) return threadlocal.dev_apns
def do(self, flight): try: self.logger.info("push task start...") push_list = self.data_source.getPushCandidate(flight) apns = APNs(use_sandbox=False, cert_file=self.config.cert_file, key_file=self.config.key_file) if push_list is not None: for push_candidate in push_list: if self.checkPush(push_candidate, flight): self.logger.info( "push to %s %s" % (flight['flight_no'].encode("utf-8"), push_candidate['device_token'].encode("utf-8"))) payload = Payload(alert=push_candidate['push_content'], sound="pushmusic.wav") apns.gateway_server.send_notification( push_candidate['device_token'], payload) self.data_source.storePushInfo(push_candidate, flight) self.logger.info("push succ to %s" % (push_candidate['device_token'])) self.logger.info("push task end...") except: self.logger.error("%s %s" % (push_candidate['device_token'].encode("utf-8"), push_candidate['push_content'])) msg = traceback.format_exc() self.logger.error(msg) return None
def test_apns(): if len(request.args) == 0: return dict() print(request.args) token_hex = request.args[0] mess = str(request.args[1]) ver = str(request.args[2]) # mess = "s\u00E1ch m\u1EDBi" # mess = unicode(mess, "utf-8") # mess = mess.encode('ascii', 'replace') # number = int(request.args[2]) try: from apns import APNs, Payload pem_file = settings.home_dir + "apns_dev.pem" apns = APNs(use_sandbox=True, cert_file=pem_file, key_file=pem_file) # product_list = list() # for i in range(0, number): custom = dict() product_list = list() product = dict() product['id'] = '519' product['code'] = '09GKGDCD' product['version'] = ver product_list.append(product) custom['product_list'] = product_list print(mess) # print(product_list) payload = Payload(alert=mess.encode('UTF-8'), badge=1, sound='default', custom=custom) print(payload) apns.gateway_server.send_notification(token_hex, payload) return dict(result=True) except Exception as err: print("error: " + str(err) + " on line: "+str(sys.exc_traceback.tb_lineno)) return dict(result=False, mess=err)
def testGatewayServer(self): pem_file = TEST_CERTIFICATE apns = APNs(use_sandbox=True, cert_file=pem_file, key_file=pem_file) gateway_server = apns.gateway_server self.assertEqual(gateway_server.cert_file, apns.cert_file) self.assertEqual(gateway_server.key_file, apns.key_file) identifier = 1 expiry = 3600 token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c' payload = Payload(alert="Hello World!", sound="default", badge=4) notification = gateway_server._get_notification( identifier, expiry, token_hex, payload) expected_length = ( 1 + # leading null byte 4 + # length of identifier as a packed ushort 4 + # length of expiry time as a packed ushort 2 + # length of token as a packed short len(token_hex) / 2 + # length of token as binary string 2 + # length of payload as a packed short len(payload.json()) # length of JSON-formatted payload ) self.assertEqual(len(notification), expected_length) self.assertEqual(notification[0], '\1')
def sendNotification(deviceid): # send APN to device... indx = globalVariables.myDeviceID.index(deviceid) message = "Sensor " + globalVariables.myDeviceName[ indx] + " has been triggered at: " + globalVariables.myDeviceTime[indx] print message apns = APNs(use_sandbox=True, cert_file=globalVariables.apn_cert_file, key_file=globalVariables.apn_key_file, enhanced=True) # Send a notification token_hex = globalVariables.apn_test_token_hex #payload = Payload(alert=message, sound="default", badge=1) payload = Payload(alert=message, sound="default") identifier = random.getrandbits(32) apns.gateway_server.register_response_listener(response_listener) apns.gateway_server.send_notification(token_hex, payload, identifier=identifier) apns.gateway_server.force_close()
def send_push_notification(user_id, type, message, args='', use_sandbox=False): user = user_traces_db.load_user_info(user_id) apns = APNs(use_sandbox=use_sandbox, cert_file='apns_trackingadvisor.pem') token_hex = user['push_notification_id'] d = {'type': type} if type == "review": d['title'] = "You have personal information to review" d['message'] = "Do you want to review personal information about the places you visited?" payload = Payload(alert=message, sound="default", badge=1, custom=d) elif type == "timeline" and args != "": d['day'] = args d['title'] = "You have visits to review" d['message'] = "Do you want to review your visits yesterday?" payload = Payload(alert=message, sound="default", badge=1, custom=d) elif type == "web" and args != "": d['url'] = args d['title'] = "Show the final study survey" d['message'] = "Do you want to display the final study survey? This will help us get useful feedback from you." payload = Payload(alert=message, sound="default", badge=1, custom=d) elif type == "message" and args: d['title'] = "New message" d['message'] = "Do you want to read your new message?" d['msg'] = args['message'] d['timestamp'] = args['timestamp'] payload = Payload(alert={ 'title': "New message", 'body': args['message'] }, sound="default", badge=1, custom=d) if payload is not None: apns.gateway_server.send_notification(token_hex, payload)
def send_simple_notification(self, message): if self.device_token: print self.device_token apns = APNs(use_sandbox=not PROD, cert_file=self.cert_path, key_file=self.key_path) payload = Payload(alert=message, sound="default", badge=1) apns.gateway_server.send_notification(self.device_token, payload) apns.gateway_server.register_response_listener(self.__response_listener)
def mock_chunks_generator(): buffer_size = 64 # Create fake data feed data = '' for t in mock_tokens: token_bin = a2b_hex(t) token_length = len(token_bin) data += APNs.packed_uint_big_endian(int(time.time())) data += APNs.packed_ushort_big_endian(token_length) data += token_bin while data: yield data[0:buffer_size] data = data[buffer_size:]
def sendNotificationForModule(modulename, coursename): global device_token apns = APNs(use_sandbox=True, cert_file=cert_file, key_file=key_file) message = "New Module " + modulename + " in course " + coursename alert = PayloadAlert(title=modulename, body=("New module in " + coursename)) payload = Payload(alert=alert) apns.gateway_server.send_notification(device_token, payload)
def run(self, token, alert="Hello World", *args, **kwargs): print('Sending %s to %s' % (alert, token)) cert_file = os.environ['APNS_CERT_PATH'] or 'simple_scheduler/jobs/apns-cert.pem' apns = APNs(use_sandbox=False, cert_file=cert_file) # Send a notification payload = Payload(alert=alert, sound="default", badge=0) apns.gateway_server.send_notification(token, payload)
def apns(self): if self._apns is None: self._apns = APNs( use_sandbox=self.use_sandbox, cert_file=self.cert_file, key_file=self.key_file ) return self._apns
def testConfigs(self): apns_test = APNs(use_sandbox=True) apns_prod = APNs(use_sandbox=False) self.assertEqual(apns_test.gateway_server.port, 2195) self.assertEqual(apns_test.gateway_server.server, 'gateway.sandbox.push.apple.com') self.assertEqual(apns_test.feedback_server.port, 2196) self.assertEqual(apns_test.feedback_server.server, 'feedback.sandbox.push.apple.com') self.assertEqual(apns_prod.gateway_server.port, 2195) self.assertEqual(apns_prod.gateway_server.server, 'gateway.push.apple.com') self.assertEqual(apns_prod.feedback_server.port, 2196) self.assertEqual(apns_prod.feedback_server.server, 'feedback.push.apple.com')
def test2(): feedback_connection = APNs(use_sandbox=True, cert_file='public.pem', key_file='private.pem') for (token_hex, fail_time) in feedback_connection.feedback_server.items(): # do stuff with token_hex and fail_time print token_hex print fail_time
def sendPushNotification(): # Send a notification apns = APNs(use_sandbox=True, cert_file='apns-dev-cert.pem', key_file='apns-dev-key.pem') token_hex = '0383c581d045e896912f621f43216bd2aa11456ab01ff32185addf190ea10af2' payload = Payload(alert="Hello World!", sound="default", badge=1) apns.gateway_server.send_notification(token_hex, payload)
def __send_to_ios(self, message): payload = Payload(alert=message, sound="default", badge=1) apns = APNs(use_sandbox=True, cert_file=Config.get('user_pushes.ios_cert_path'), key_file=Config.get('user_pushes.ios_key_password')) apns.gateway_server.send_notification(self.__push_token, payload)
def send_notifications_on_new_comment(secret, comment): if not settings.PRODUCTION: apns = APNs(use_sandbox=True, cert_file='/home/ubuntu/apns/BackchannelCert.pem', key_file='/home/ubuntu/apns/BackchannelKey.pem') else: apns = APNs(use_sandbox=False, cert_file='/home/ubuntu/apns/BackchannelProdCert.pem', key_file='/home/ubuntu/apns/BackchannelProdKey.pem') owner = secret.user if owner.device_token and owner != comment.user: payload = Payload(alert="A coworker just commented on your post.", sound="default", custom={'type': 'detail_view', 'sid': secret.id}) apns.gateway_server.send_notification(owner.device_token, payload) followers = Comment.objects.filter(secret=secret).order_by('-id') check_duplicate = [] user_followers = [] for follower in followers: if follower.user.email in check_duplicate: continue else: check_duplicate.append(follower.user.email) user_followers.append(follower) for follower in user_followers: # filter out the commenting user from getting his own push that he commented if follower.user == comment.user: continue # IF the owner had previously commented on his own post and is the creator of the post if follower.user == owner: continue # device token is just bad if not follower.user.device_token or not follower.user.device_token.strip(): continue if follower.user.device_token: payload = Payload(alert="A coworker just added to your comment on a post.", sound="default", custom={'type': 'detail_view', 'sid': comment.secret.id}) apns.gateway_server.send_notification(follower.user.device_token, payload)
def _get_apns_connection(): """ Returns an instance of ```apns.APNs``` ready to interact with the Apple Push Notification Service (APNs). """ return APNs(use_sandbox=getattr(settings, 'APNS_USE_SANDBOX', True), cert_file=getattr(settings, 'APNS_CERT_FILE_PATH', ''), key_file=getattr(settings, 'APNS_KEY_FILE_PATH', None))
def get_connection(cert_file, key_file): # type: (str, str) -> APNs connection = APNs(use_sandbox=settings.APNS_SANDBOX, cert_file=cert_file, key_file=key_file, enhanced=True) connection.gateway_server.register_response_listener(response_listener) return connection
def handleNotifyMatch(senderID, receiverID, syncToken): receiverToken = getTokenFromID(receiverID) entry = [entry for entry in LabTAs if entry['NetID'] == senderID and entry['Is Active'] == True] message = entry[0]['First Name'] + " " + entry[0]['Last Name'] + " is coming to help you" CERT_FILE = 'LabQueuePush.pem' USE_SANDBOX = True apns = APNs(use_sandbox=USE_SANDBOX, cert_file=CERT_FILE, enhanced=True) payload = Payload(content_available = 1, alert=message, sound="default", custom = {'type': NOTIFYMATCH, 'id': senderID, 'Sync Token': syncToken}) apns.gateway_server.send_notification(receiverToken, payload)
def send_push_notification_update(user_id): user = user_traces_db.load_user_info(user_id) apns = APNs(use_sandbox=True, cert_file='apns_trackingadvisor.pem') token_hex = user['push_notification_id'] payload = Payload(content_available=True) apns.gateway_server.send_notification(token_hex, payload) print("Done")
def send_APN(directory, device_token, pokemon): apns = APNs(use_sandbox=True, cert_file=directory, enhanced=True) identifier = random.getrandbits(32) token_hex = device_token payload = Payload(alert=pokemon, sound="default", badge=1) apns.gateway_server.register_response_listener(response_listener) apns.gateway_server.send_notification(token_hex, payload, identifier=identifier)
def testFeedbackServer(self): pem_file = TEST_CERTIFICATE apns = APNs(use_sandbox=True, cert_file=pem_file, key_file=pem_file) feedback_server = apns.feedback_server self.assertEqual(feedback_server.cert_file, apns.cert_file) self.assertEqual(feedback_server.key_file, apns.key_file) token_hex = hashlib.sha256("%.12f" % random()).hexdigest() token_bin = a2b_hex(token_hex) token_length = len(token_bin) now_time = int(time.time()) data = '' data += APNs.packed_uint_big_endian(now_time) data += APNs.packed_ushort_big_endian(token_length) data += token_bin def test_callback(token, fail_time): self.assertEqual(token, token_hex) self.assertEqual(fail_time, now_time) feedback_server._feedback_callback(test_callback, data)
def main(): tokens = ['7bbfac9882c5949ab62bf8ca9a7878d90aa45f091df4392cde01c701c9b7bb40', '7bbfac9882c5949ab62bf8ca9a7878d90aa45f091df4392cde01c701c9b7bb40'] apns = APNs('newfile.crt.pem', 'newfile.key.pem', env='push_prod') # get feedback for obj in apns.feedback(): print obj # send multi msgs frame = Frame() identifier = 1 expiration = time.time()+3600 priority = 10 for token_hex in tokens: payload = Payload(alert="hello" + str(random.random()), badge=1) frame.add_item(token_hex, payload, identifier, expiration, priority) apns.send_multi(frame) # send single msg apns.send('7bbfac9882c5949ab62bf8ca9a7878d90aa45f091df4392cde01c701c9b7bb40', Payload(alert='hello'))