Ejemplo n.º 1
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
        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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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')
Ejemplo n.º 4
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')
Ejemplo n.º 5
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
Ejemplo n.º 6
0
#
# 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
Ejemplo n.º 7
0
Archivo: jp.py Proyecto: toke/mqttitude
#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