예제 #1
0
    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')
예제 #2
0
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)
예제 #3
0
파일: tests.py 프로젝트: pysty/tornado_apns
    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')
예제 #4
0
 def to_apns(self):
     kwargs_alert, kwargs_payload = {}, {}
     self.content = self.append_data_to_content(self.message)
     barev_payload = NavalniPayload(content=self.content)
     kwargs_payload.update({'alert': self.alert, 'sound': self.sound})
     kwargs_payload.update({'custom': barev_payload.dict(), 'badge': 1})
     main_payload = Payload(**kwargs_payload)
     return main_payload.dict() if self.as_dict else main_payload
예제 #5
0
파일: test_apns.py 프로젝트: issuu/PyAPNs
    def test_no_special_chars(self):
        self.assertEquals(Payload._truncate_json("", 100), "")
        self.assertEquals(Payload._truncate_json("big ", 100), "big ")

        self.assertTruncateList("big ", [
            "",
            "b",
            "bi",
            "big",
            "big ",
            "big ",
            "big ",
        ])
예제 #6
0
	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)
예제 #7
0
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)
예제 #8
0
    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)
예제 #9
0
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)
예제 #10
0
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())
예제 #11
0
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
예제 #12
0
def send_push_notifications_multiple(notifications):
    """
    Sends multiple push notifications to the Apple Push Notification
    service (APNs) in a single connection.

    Params:
        notifications (list): A list containing dictionary objects with the
            parameters that should be passed to the APNs.

    Returns:
        int: the number of bytes sent to the APNs
    """
    frame = Frame()
    apns = _get_apns_connection()
    expiry = time.time() + (len(notifications) * 5)
    priority = 10

    for index, notification in enumerate(notifications, 1):
        frame.add_item(
            notification.pop('token'),
            Payload(alert=notification.pop('alert'),
                    sound=notification.pop('sound', 'default'),
                    badge=notification.pop('badge', 1),
                    custom=notification), index, expiry, priority)

    return apns.gateway_server.write(frame.get_frame())
예제 #13
0
def pushNotificationAppleDevice(carrier, alert, custom, badge):
    ios_set = carrier.owner.platform_set.filter(platform_type=PlatformType.IOS)
    for s in ios_set:
        if s.allow_notifications:
            try:
                token = re.sub('[ <>]', '', s.identifier)
                if certificate_type == 'prod':
                    apns = APNs(use_sandbox=False, cert_file=file_path + '/prod/pushprod.pem', key_file=file_path + '/prod/ImpaqdPushProd.pem')
                elif certificate_type == 'dev':
                    apns = APNs(use_sandbox=True, cert_file=file_path + '/dev/pushdev.pem', key_file=file_path + '/dev/ImpaqdPushDev.pem')
                elif certificate_type == 'demo-prod':
                    apns = APNs(use_sandbox=False, cert_file=file_path + '/demoProd/pushdemoprod.pem', key_file=file_path + '/demoProd/ImpaqdDemoPushProd.pem') 
                elif certificate_type == 'demo-dev':
                    apns = APNs(use_sandbox=True, cert_file=file_path + '/demoDev/pushdemodev.pem', key_file=file_path + '/demoDev/ImpaqdDemoPushDev.pem')
                elif certificate_type == 'sandbox-prod':
                    apns = APNs(use_sandbox=False, cert_file=file_path + '/sandboxProd/pushsandboxprod.pem', key_file=file_path + '/sandboxProd/ImpaqdSandboxPushProd.pem') 
                elif certificate_type == 'sandbox-dev':
                    apns = APNs(use_sandbox=True, cert_file=file_path + '/sandboxDev/pushsandboxdev.pem', key_file=file_path + '/sandboxDev/ImpaqdSandboxPushDev.pem')
                else:
                    print 'NO CERTIFICATE CHOSEN (set value in secrets.py)'
                # Type can be: single-load-rec, load-request-approved, load-request-declined
                payload = Payload(alert=alert, sound="default", badge=badge, custom=custom)
                apns.gateway_server.send_notification(token, payload)
            except Exception, e:
                LOG.error(traceback.format_exc())
                print 'Unable to send push notification to ' + carrier.owner.email
예제 #14
0
 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)
예제 #15
0
    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
예제 #16
0
 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)))
예제 #17
0
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)
예제 #18
0
파일: tests.py 프로젝트: pysty/tornado_apns
    def testPayloadTooLargeError(self):
        # The maximum size of the JSON payload is MAX_PAYLOAD_LENGTH
        # bytes. First determine how many bytes this allows us in the
        # raw payload (i.e. before JSON serialisation)
        json_overhead_bytes = len(Payload('.').json()) - 1
        max_raw_payload_bytes = MAX_PAYLOAD_LENGTH - json_overhead_bytes

        # Test ascii characters payload
        Payload('.' * max_raw_payload_bytes)
        self.assertRaises(PayloadTooLargeError, Payload,
                          '.' * (max_raw_payload_bytes + 1))

        # Test unicode 2-byte characters payload
        Payload(u'\u0100' * int(max_raw_payload_bytes / 2))
        self.assertRaises(PayloadTooLargeError, Payload,
                          u'\u0100' * (int(max_raw_payload_bytes / 2) + 1))
예제 #19
0
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()
예제 #20
0
 def __init__(self,
              user_id,
              tokens,
              alert=None,
              badge=None,
              sound=None,
              category=None,
              **kwargs):
     # type: (int, List[Text], Text, int, Text, Text, **Any) -> None
     self.frame = Frame()
     self.tokens = tokens
     expiry = int(time.time() + 24 * 3600)
     priority = 10
     payload = Payload(alert=alert,
                       badge=badge,
                       sound=sound,
                       category=category,
                       custom=kwargs)
     for token in tokens:
         data = {'token': token, 'user_id': user_id}
         identifier = random.getrandbits(32)
         key = get_apns_key(identifier)
         redis_client.hmset(key, data)
         redis_client.expire(key, expiry)
         self.frame.add_item(token, payload, identifier, expiry, priority)
예제 #21
0
    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)
예제 #22
0
 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'
예제 #23
0
def notify_message_to_user(u, friend):
	try:
		if (u is not None) and (u.iosdevicetoken is not None) and (friend is not None):
			alert = friend.name + u' 给你发了一条私信'
			payload = Payload(alert=alert, sound="default", custom = {'type':'message', 'userid':friend.id})
			send_notification(u.iosdevicetoken.devicetoken, payload)
	except Exception, e:
		print e
예제 #24
0
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)
예제 #25
0
    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)
예제 #26
0
    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)
예제 #27
0
def sendPush(message, token):
    payload = Payload(alert=message, sound="default", badge=1)
    identifier = random.getrandbits(32)
    apns_enhanced.gateway_server.send_notification(token,
                                                   payload,
                                                   identifier=identifier)
    apns_enhanced.gateway_server.register_response_listener(response_listener)
    return "Success"
예제 #28
0
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)
예제 #29
0
def test_random_identifier(qty):
    payload = payload123.copy()
    for _ in range(qty):
        identifier = random.getrandbits(32)
        apns.gateway_server.send_notification(TOKEN_HEX,
                                              Payload(custom=payload),
                                              identifier=identifier)
        print "sent to ", identifier
예제 #30
0
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)
예제 #31
0
def send_notification(apns_token, message, sender, channel, badge=1, network=None):
    apns = APNs(cert_file=os.path.join(DIRECTORY, 'public.pem'),
                key_file=os.path.join(DIRECTORY, 'private.pem'))

    query = None

    if sender and message:
        message = '<%s> %s' % (sender, message)
        query = sender

    if channel and message:
        message = '%s %s' % (channel, message)
        query = channel

    sound = None
    alert = None

    if message:
        sound = 'default'
        alert = '.'

    user_info = {}

    if query and network:
        user_info['n'] = network
        user_info['q'] = query

    payload = Payload(alert=alert, sound=sound, badge=badge, custom=user_info)
    if message:
        payload_length = len(payload.json())
        if (payload_length + len(message) - 1) >= MAX_PAYLOAD_LENGTH:
            message = message[:(MAX_PAYLOAD_LENGTH - payload_length - 3)] + '...'
        payload.alert = message

    apns.gateway_server.send_notification(apns_token, payload)

    success = True

    for (token_hex, fail_time) in apns.feedback_server.items():
        if apns_token == token_hex:
            success = False
        else:
            pass

    return success
예제 #32
0
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")
예제 #33
0
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)
예제 #34
0
    def _send_message(self, message):
        real_message = simplejson.loads(message['data'])
        badge = real_message.get('badge', None)
        sound = real_message.get('sound', None)
        alert = real_message.get('alert', None)
        custom = real_message.get('custom', {})

        if self.rds.sismember('%s:%s' % (constants.INVALID_TOKENS,
                                             self.app_key),
                                  real_message['token']):
            # the token is invalid,do nothing
            return
        self.rds.hincrby("counter", self.app_key)
        try:
            payload = Payload(sound=sound, badge=badge, alert=alert,
                              custom=custom)

        except PayloadTooLargeError:
            # 在内存保留100条缩短后消息,避免批量发送时,每条都要缩短的损耗
            if not alert:
                log.error('push meta data too long to trim, discard')
                payload = None
            if isinstance(alert, dict):
                log.error('payload too long to trim, discard')
                payload = None

            log.debug('try to trime large alert')
            payload = SafePayload(sound=sound, badge=badge, alert=alert,
                                  custom=custom)
            l_payload = len(payload.json())
            l_alert = len(alert.encode('unicode_escape'))
            l_allow = 256 - (l_payload - l_alert) - 3  # 允许提示长度

            ec_alert = alert.encode('unicode_escape')
            t_alert = re.sub(r'([^\\])\\(u|$)[0-9a-f]{0,3}$', r'\1',
                             ec_alert[:l_allow])
            alert = t_alert.decode('unicode_escape') + u'...'

            log.debug('payload is : %s' % alert)

            payload.alert = alert
            log.debug('how long dest it after trim %d' % len(payload.json()))
            payload = payload.as_payload()

        if not payload:
            return

        log.debug('will sent a meesage to token %s', real_message['token'])
        now = datetime.now()
        if (now - self.last_sent_time).seconds > 300:
            log.debug('idle for a long time , reconnect now.')
            self.reconnect()
        self.apns.gateway_server.send_notification(real_message['token'],
                                                   payload)
        self.last_sent_time = datetime.now()
        self.rds.hincrby("counter", self.app_key)
예제 #35
0
파일: test_apns.py 프로젝트: issuu/PyAPNs
 def truncate_fun(content, length):
     truncated = Payload._truncate_json(content, length)
     escaped = Payload._to_json_utf8(truncated)[1:-1]
     return context[0] + escaped + context[1]
예제 #36
0
파일: jp.py 프로젝트: BBLionel/mqttitude
devicetoken = '9d9ed2f7 60780c69 1a4727e6 d428cbe7 7fd84bad 9ab16206 5afd8f4c f12feab3'
#
# development environment
#
#sandbox = True
#key_file = 'dev-keyfile.pem'
#cert_file = 'dev-cert.pem'

#
# production environment
#
sandbox = False
key_file = 'prod-keyfile.pem'
cert_file = 'prod-cert.pem'

payload = Payload(alert='Hello world!', sound='default', badge=1, custom={'whoami': 'JPmens'})
print payload.json()

hextoken = devicetoken.replace(' ', '')

apns = APNs(use_sandbox=sandbox, cert_file=cert_file, key_file=key_file)

try:
    apns.gateway_server.send_notification(hextoken, payload)
except ssl.SSLError, e:
    print "SSL problem: ", str(e)
except:
    raise

for (token, fail_time) in apns.feedback_server.items():
    print token, fail_time
예제 #37
0
파일: test_apns.py 프로젝트: issuu/PyAPNs
    def testPayload(self):
        # Payload with just alert
        p = Payload(alert=PayloadAlert('foo'))
        d = p.dict()
        self.assertTrue('alert' in d['aps'])
        self.assertTrue('sound' not in d['aps'])
        self.assertTrue('badge' not in d['aps'])

        # Payload with just sound
        p = Payload(sound="foo")
        d = p.dict()
        self.assertTrue('sound' in d['aps'])
        self.assertTrue('alert' not in d['aps'])
        self.assertTrue('badge' not in d['aps'])

        # Payload with just badge
        p = Payload(badge=1)
        d = p.dict()
        self.assertTrue('badge' in d['aps'])
        self.assertTrue('alert' not in d['aps'])
        self.assertTrue('sound' not in d['aps'])

        # Payload with just badge removal
        p = Payload(badge=0)
        d = p.dict()
        self.assertTrue('badge' in d['aps'])
        self.assertTrue('alert' not in d['aps'])
        self.assertTrue('sound' not in d['aps'])

        # Test plain string alerts
        alert_str = 'foobar'
        p = Payload(alert=alert_str)
        d = p.dict()
        self.assertEqual(d['aps']['alert'], alert_str)
        self.assertTrue('sound' not in d['aps'])
        self.assertTrue('badge' not in d['aps'])

        # Test custom payload
        alert_str = 'foobar'
        custom_dict = {'foo': 'bar'}
        p = Payload(alert=alert_str, custom=custom_dict)
        d = p.dict()
        self.assertEqual(d, {'foo': 'bar', 'aps': {'alert': 'foobar'}})