Ejemplo n.º 1
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'
Ejemplo n.º 2
0
class APNsMessage(object):
    def __init__(self,
                 user,
                 tokens,
                 alert=None,
                 badge=None,
                 sound=None,
                 category=None,
                 **kwargs):
        self.frame = Frame()
        self.tokens = tokens
        expiry = 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': user}
            identifier = generate_random_token(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)

    def get_frame(self):
        return self.frame
Ejemplo n.º 3
0
    def post(self):
        """
        post HTTP method

        Send apns notification for all data in the QuestionTimeNotification
        table.

        Returns:
            A 201 Created HTTP status code.
        """
        query = QuestionTimeNotification.query.all()
        print query
        if len(query) < 1:
            return "", 500
        else:
            payload = Payload(
                alert="Question time is currently live.",
                sound="default",
                category="QUESTION_TIME_CATEGORY",
                custom={
                    'link':
                    'http:/a-vide-link/playlist.m3u8'
                },
                badge=0)
            frame = Frame()
            identifer = 1
            expiry = time.time() + 3600
            priority = 10
            for item in query:
                token_hex = ''.join(item.tokenid)
                frame.add_item(token_hex, payload, identifer, expiry, priority)
            apns.gateway_server.send_notification_multiple(frame)
            return "", 204
Ejemplo n.º 4
0
class APNsMessage(object):
    def __init__(self,
                 user,
                 tokens,
                 alert=None,
                 badge=None,
                 sound=None,
                 category=None,
                 **kwargs):
        # type: (UserProfile, List[text_type], text_type, int, text_type, text_type, **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)

    def get_frame(self):
        # type: () -> Frame
        return self.frame
Ejemplo n.º 5
0
def test_add_frame_item_with_full_args():
    global has_called_check_method
    has_called_check_method = False

    # assert_called_once_with of Mock Class failes to compare Payload object.
    # So here created custom check method for parameter checking
    def check_add_item_args(token, payload, identifier, expiry, priority):
        eq_(token, dummy_token)
        eq_(payload.alert, 'Wow')
        eq_(payload.badge, 50)
        eq_(payload.sound, 'bell')
        eq_(payload.custom, {'foo': 'bar'})
        eq_(payload.content_available, True)
        eq_(identifier, 1)
        eq_(priority, 5)
        eq_(expiry, 0)

        global has_called_check_method
        has_called_check_method = True

    worker = SendWorkerThread(**dummy_setting)
    worker.count = 1
    frame = Frame()
    frame.add_item = check_add_item_args

    worker.add_frame_item(frame, 'myapp', dummy_token, {
        'alert': 'Wow',
        'badge': 50,
        'sound': 'bell',
        'custom': {'foo': 'bar'},
        'content_available': True,
    }, expiry=0, priority=5)
    ok_(has_called_check_method)
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
def apns_notification(tokens_hex, message):

    apns = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')

    """
    # Send a notification
    token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    apns.gateway_server.send_notification(token_hex, payload)
    """

    # Send multiple notifications in a single transmission
    # tokens_hex = []
    payload = Payload(alert=message, sound="default", badge=1)

    frame = Frame()
    identifier = 1
    expiry = time.time()+3600
    priority = 10

    for token in tokens_hex:
        frame.add_item(token, payload, identifier,
                       expiry, priority)

    apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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())
Ejemplo n.º 10
0
    def handle(self, *args, **options):

        while True:
            ApplePushNotification.objects.filter(state=ApplePushNotification.NEW).update(state=ApplePushNotification.PENDING)

            frame = Frame()
            identifier = 1
            expiry = time.time() + 3600
            priority = 10
            # retry_cnt = 10
            apns = APNs(use_sandbox=False, cert_file="onoo-production.pem", key_file="onoo-production-key.pem")
            # while retry_cnt > 0:
            try:
                cnt = 0
                for noti in ApplePushNotification.objects.filter(state=ApplePushNotification.PENDING):
                    cnt += 1
                    # apns.gateway_server.send_notification(noti.device_token, Payload(alert=noti.message, badge=noti.badge_count))
                    frame.add_item(noti.device_token, Payload(alert=noti.message, sound="default", badge=noti.badge_count), identifier, expiry, priority)
                if cnt > 0:
                    apns.gateway_server.send_notification_multiple(frame)
            except:
                import traceback
                traceback.print_exc()
                ApplePushNotification.objects.filter(state=ApplePushNotification.PENDING).update(state=ApplePushNotification.NEW)
                    # retry_cnt -= 1
                    # time.sleep(1)
            # for (token_hex, fail_time) in apns.feedback_server.items():
            #         # logging 하기 ...
            #         pass

            # ApplePushNotification.objects.filter(state=ApplePushNotification.PENDING).delete()
            ApplePushNotification.objects.filter(state=ApplePushNotification.PENDING).update(state=ApplePushNotification.DONE)

            time.sleep(1)
Ejemplo n.º 11
0
def test_add_frame_item():
    global has_called_check_method
    has_called_check_method = False

    # assert_called_once_with of Mock Class failes to compare Payload object.
    # So here created custom check method for parameter checking
    def check_add_item_args(token, payload, identifier, expiry, priority):
        default_expiry = int(time.time()) + (60 * 60)

        eq_(token, dummy_token)
        eq_(payload.alert, 'Hey')
        eq_(payload.badge, None)
        eq_(payload.sound, None)
        eq_(payload.custom, {})
        eq_(payload.content_available, False)
        eq_(identifier, 123)
        eq_(priority, 10, 'priority should set default value when skipped')
        eq_(expiry, default_expiry, 'expiry should set default value when skipped')

        global has_called_check_method
        has_called_check_method = True

    worker = SendWorkerThread(**dummy_setting)
    worker.count = 123
    frame = Frame()
    frame.add_item = check_add_item_args

    worker.add_frame_item(frame, 'myapp', dummy_token, {'alert': 'Hey'})
    ok_(has_called_check_method)
Ejemplo n.º 12
0
def test_add_frame_item():
    global has_called_check_method
    has_called_check_method = False

    # assert_called_once_with of Mock Class failes to compare Payload object.
    # So here created custom check method for parameter checking
    def check_add_item_args(token, payload, identifier, expiry, priority):
        default_expiry = int(time.time()) + (60 * 60)

        eq_(token, dummy_token)
        eq_(payload.alert, 'Hey')
        eq_(payload.badge, None)
        eq_(payload.sound, None)
        eq_(payload.custom, {})
        eq_(payload.content_available, False)
        eq_(identifier, 123)
        eq_(priority, 10, 'priority should set default value when skipped')
        eq_(expiry, default_expiry,
            'expiry should set default value when skipped')

        global has_called_check_method
        has_called_check_method = True

    worker = SendWorkerThread(**dummy_setting)
    worker.count = 123
    frame = Frame()
    frame.add_item = check_add_item_args

    worker.add_frame_item(frame, 'myapp', dummy_token, {'alert': 'Hey'})
    ok_(has_called_check_method)
Ejemplo n.º 13
0
def send(tokens, payload):
	frame = Frame()
	expiry = time.time() + config.expiry
	for token in tokens:
		identifier = random.getrandbits(32)
		frame.add_item(token, payload, identifier, expiry, config.priority)

	apns.gateway_server.register_response_listener(error_handler)
	apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 14
0
def sendNotification(token, message, timeout):
    apns = APNs(use_sandbox=False, cert_file="cert.pem", key_file="key.pem")
    frame = Frame()
    identifier = random.getrandbits(32)
    priority = 10
    payload = {"aps": {"alert": message, "sound": "default", "identifier": identifier}}
    # Payload(alert=message, sound="default", custom = {"identifier":identifier})
    frame.add_item(token, payload, identifier, timeout, priority)
    apns.gateway_server.send_notification_multiple(frame)
    return identifier
Ejemplo n.º 15
0
 def send_notification_with_payload(self, message, payload_dict):
     if self.device_token_list:
         apns = APNs(use_sandbox=True, cert_file=self.cert_path, key_file=self.key_path)
         frame = Frame()
         identifier = 1
         expiry = time.time() + 3600
         priority = 10
         payload = Payload(alert=message, sound="default", badge=1, custom=payload_dict)
         for device_token in self.device_token_list:
             frame.add_item(device_token, payload, identifier, expiry, priority)
         apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 16
0
def apns_send(tokens, alert, message):
    apns = APNs(cert_file='cert.pem', key_file='key.pem')
    payload = Payload(alert=alert, custom=message)
    frame = Frame()
    identifier = 1
    expiry = time.time()+3600
    priority = 10
    [frame.add_item(token, payload, identifier, expiry, priority) for token in tokens if len(token) > 10]
    try:
        apns.gateway_server.send_notification_multiple(frame)
    except:
        pass
Ejemplo n.º 17
0
def send_notification(state):
    device_tokens = DeviceToken.objects.values_list('token', flat=True)
    payload = get_payload(state)

    apns = APNs(cert_file=config('CERT_PEM'), key_file=config('KEY_PEM'), enhanced=True)
    frame = Frame()

    for index, token in enumerate(device_tokens):
        identifier = index + 1
        expiry = time.time() + 3600
        priority = 10
        frame.add_item(token, payload, identifier, expiry, priority)

    apns.gateway_server.send_notification_multiple(frame)
    def get_frame(self, message, device_tokens):
        frame = Frame()
        identifier = random.getrandbits(32)
        payload = Payload(alert=message)

        for token in device_tokens:
            frame.add_item(
                token,
                payload,
                identifier,
                self.IOS_EXPIRY_SECONDS,
                self.IOS_PRIORITY
            )

        return frame
Ejemplo n.º 19
0
def send_push_background(tokens, text, badge, data, content_available):
  apns = APNs(use_sandbox=False, cert_file='static/JukeboxBetaPush.pem', key_file='static/JukeboxBetaPush.pem')
  frame = Frame()
  identifier = 1
  expiry = time.time()+3600
  priority = 10
  for device_token in tokens:
    sound = None
    if text:
      sound = "default"
    if not data:
      data = {}
    payload = Payload(alert=text, sound=sound, badge=badge, custom=data, content_available=content_available)
    frame.add_item(device_token, payload, identifier, expiry, priority)
  apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 20
0
    def send_notifications_apns(self, device_tokens, payload, priority=10, 
        identifier=None, expiry=None):

        if not device_tokens:
            raise ValueError("No device tokens specified, should be a list")
        
        apns = APNs(use_sandbox=self.use_sandbox, cert_file=self.current_cert_file)

        # Send multiple notifications in a single transmission
        frame = Frame()
        
        for device_token in device_tokens:
            frame.add_item(device_token, payload, identifier, expiry, priority)
        
        return apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 21
0
def push_notification_multi_raw_apple(apns, tokens_hex, payload=None, payloads=None):
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10
    if payload:
        for token in tokens_hex:
            frame.add_item(token, Payload(**payload), identifier, expiry, priority)
    else:
        for token, payload in tokens_hex, payloads:
            frame.add_item(token, Payload(**payload), identifier, expiry, priority)
    apns.gateway_server.send_notification_multiple(frame)
    # Get feedback messages
    for (token_hex, fail_time) in apns.feedback_server.items():
        # do stuff with token_hex and fail_time
        pass
Ejemplo n.º 22
0
def massNotification(tokens, message):
    apns = APNs(use_sandbox=True,
                cert_file='certificates/certificate.pem',
                key_file='certificates/npkey.pem')
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10
    payload = Payload(alert=message,
                      sound="default",
                      badge=1,
                      mutable_content=True)
    for i in tokens:
        frame.add_item(i, payload, identifier, expiry, priority)
    apns.gateway_server.send_notification_multiple(frame)
    return "Success"
Ejemplo n.º 23
0
def send_message_ios(tokens, alert_message, link_url):
    cert = '/home/webuser/webapps/tigaserver/CertificatMosquito_prod.pem'
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10
    apns = APNs(use_sandbox=True, cert_file=cert)
    for single_token in tokens:
        try:
            unread_notifications = get_pending_messages(single_token)
        except:
            unread_notifications = 0
        payload = Payload(alert=alert_message,
                          sound="default",
                          badge=unread_notifications)
        frame.add_item(single_token, payload, identifier, expiry, priority)
    apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 24
0
def update_wallets_states(force_update=False):
    wallets = get_wallets_from_db()
    addresses = [wallet['address'] for wallet in wallets]
    address_to_device_token = {
        wallet['address']: wallet['device_token']
        for wallet in wallets
    }
    device_token_to_address = {
        wallet['device_token']: wallet['address']
        for wallet in wallets
    }
    addresses_unspent_outputs = return_unspent_outputs(addresses)
    frame = Frame()
    frame_empty = True
    expiry = time.time() + config.EXPIRY
    priority = config.PRIORITY
    for address, utxos in addresses_unspent_outputs.items():
        previous_state_of_address = redis.get(address)
        current_state_of_address = gen_hash_for_dict(utxos)
        print(address, previous_state_of_address, current_state_of_address)
        if force_update or (current_state_of_address !=
                            previous_state_of_address):
            print('Sending...')
            for unspent_output in addresses_unspent_outputs[address]:
                frame_empty = False
                payload = Payload(alert=None,
                                  sound=None,
                                  custom={'data': json.dumps(unspent_output)},
                                  badge=1,
                                  content_available=not force_update)
                frame.add_item(token_hex=address_to_device_token[address],
                               payload=payload,
                               identifier=1,
                               expiry=expiry,
                               priority=priority)
        redis.set(address, current_state_of_address)

    if not frame_empty:
        try:
            config.apns.gateway_server.send_notification_multiple(frame)
        except requests.exceptions.SSLError as e:
            print(e)
            time.sleep(1)
            config.apns = create_apn_service(cert_file=config.CERT_FILE,
                                             key_file=config.KEY_FILE)
Ejemplo n.º 25
0
def send_multi_apn(message, devs, pub=None):
    frame = Frame()
    identifier = 1
    expiry = time.time()+(60*60*24) # 1 day expire time
    priority = 10
    send = []
    unsend = []
    
    for dev in devs:
        payload = craft_apn_payload(message, dev, pub=pub)
        if payload:
            frame.add_item(dev.apns_token, payload, identifier, expiry, priority)
            send.append(dev.name)
        else:
            unsend.append(dev.name)

    apns.gateway_server.send_notification_multiple(frame)
    return (send, unsend)
Ejemplo n.º 26
0
    def testFrame(self):

        identifier = 1
        expiry = 3600
        token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c'
        payload = Payload(alert="Hello World!", sound="default", badge=4)
        priority = 10

        frame = Frame()
        frame.add_item(token_hex, payload, identifier, expiry, priority)

        f = (
            '\x02\x00\x00\x00t\x01\x00 \xb5\xbb\x9d\x80\x14\xa0\xf9\xb1\xd6\x1e!'
            '\xe7\x96\xd7\x8d\xcc\xdf\x13R\xf2<\xd3(\x12\xf4\x85\x0b\x87\x8a\xe4\x94L'
            '\x02\x00<{"aps":{"sound":"default","badge":4,"alert":"Hello World!"}}'
            '\x03\x00\x04\x00\x00\x00\x01\x04\x00\x04\x00\x00\x0e\x10\x05\x00\x01\n'
        )
        self.assertEqual(f, str(frame))
Ejemplo n.º 27
0
def send_push_notification(message,
                           sound_type="default",
                           cert_file_path='/home/ubuntu/pemfiles/cert.pem',
                           key_file_path='/home/ubuntu/pemfiles/comb.pem'):

    apns = APNs(use_sandbox=True, cert_file=cert_file_path)
    #key_file=key_file_path)

    # Dummy hex
    token_hex = '7ffdd1583899067942754f9afe2a575aa64f5ab3147834b9250a837f538f3097'
    payload = Payload(alert=message, sound=sound_type, badge=1)
    apns.gateway_server.send_notification(token_hex, payload)
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10
    frame.add_item(token_hex, payload, identifier, expiry, priority)
    apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 28
0
    def testFrame(self):

        identifier = 1
        expiry = 3600
        token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c'
        payload = Payload(alert="Hello World!",
                          sound="default",
                          badge=4)
        priority = 10

        frame = Frame()
        frame.add_item(token_hex, payload, identifier, expiry, priority)

        f = ('\x02\x00\x00\x00t\x01\x00 \xb5\xbb\x9d\x80\x14\xa0\xf9\xb1\xd6\x1e!'
             '\xe7\x96\xd7\x8d\xcc\xdf\x13R\xf2<\xd3(\x12\xf4\x85\x0b\x87\x8a\xe4\x94L'
             '\x02\x00<{"aps":{"sound":"default","badge":4,"alert":"Hello World!"}}'
             '\x03\x00\x04\x00\x00\x00\x01\x04\x00\x04\x00\x00\x0e\x10\x05\x00\x01\n')
        self.assertEqual(f, str(frame))
Ejemplo n.º 29
0
 def send_expert_requests(self, user, approx_call_time, price_per_min,
                          max_wait, experts):
     frame = Frame()
     for expert in experts:
         frame = self.add_expert_request(
             user, approx_call_time, price_per_min, max_wait, expert, frame
         )
     if frame.notification_data:
         self.send_notifications(frame)
Ejemplo n.º 30
0
class APNsMessage(object):
    def __init__(self, user, tokens, alert=None, badge=None, sound=None, category=None, **kwargs):
        # type: (UserProfile, List[text_type], text_type, int, text_type, text_type, **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)

    def get_frame(self):
        # type: () -> Frame
        return self.frame
Ejemplo n.º 31
0
class APNsMessage(object):
    def __init__(self, user, tokens, alert=None, badge=None, sound=None,
            category=None, **kwargs):
        self.frame = Frame()
        self.tokens = tokens
        expiry = 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': user}
            identifier = generate_random_token(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)

    def get_frame(self):
        return self.frame
Ejemplo n.º 32
0
 def handle(self, *args, **options):
     data = ({
         "token": "5283dfd6fa2a59389452daf5e7c8079e02cb1b16d2f1419dd540b5218057d58d",
         "alert": {
             "loc-key": "Update 해주세요".decode('utf8'),
             "loc-args": ["Jenna", "Frank"],
             "action-loc-key": "Okay"
         },
     },)
     frame = Frame()
     identifier = 1
     expiry = time.time() + 3600
     priority = 10
     apns = APNs(use_sandbox=False, cert_file="onoo-production.pem", key_file="onoo-production-key.pem")
     for noti in data:
         frame.add_item(noti['token'], Payload(alert=noti['alert'],
         custom={"need_update": True, "update_url": "itms-services://?action=download-manifest&url=https://ios-beta-deploy.b4sunset.net/kIgGzS2BEm50TbASqOA7.inst"}
         ), identifier, expiry, priority)
     apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 33
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, custom=push.custom)
                     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')
         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)
Ejemplo n.º 34
0
def do_send_sms(sendDeviceStringList):
    apns = APNs(use_sandbox=APNS_USE_SANDBOX, cert_file=APNS_CERT_FILE, key_file=APNS_KEY_FILE)
    frame = Frame()
    identifier = 1
    expiry = time.time()+3600*4
    priority = 10

    for info in sendDeviceStringList:
        device_id = info['device_id']
        alert = info['alert']
        badge = info['badge']
        payload = Payload(alert=alert, sound="default", badge=badge)
        frame.add_item(device_id, payload, identifier, expiry, priority)

    # DO SEND!
    t1 = time.time()
    apns.gateway_server.send_notification_multiple(frame)
    t2 = time.time()
    print "Sending %s notifications, using seconds = %s" %(len(sendDeviceStringList),int(t2-t1))
Ejemplo n.º 35
0
def sendNotification(token, message, timeout):
    apns = APNs(use_sandbox=False, cert_file='cert.pem', key_file='key.pem')
    frame = Frame()
    identifier = random.getrandbits(32)
    priority = 10
    payload = {
        "aps": {
            "alert": message,
            "sound": "default",
            "identifier": identifier
        }
    }
    #Payload(alert=message, sound="default", custom = {"identifier":identifier})
    frame.add_item(token, payload, identifier, timeout, priority)
    apns.gateway_server.send_notification_multiple(frame)
    return identifier


#there'll be more stuff here, I promise
Ejemplo n.º 36
0
    def send_batch(self):
        if len(self.queue) > 0:
            self.log.debug('Apns batch size: {0}'.format(len(self.queue)))
            frame = Frame()
            while len(self.queue) > 0:
                notification = self.queue.pop()

                notification['status'] = const.NOTIFICATION_SUCCESS
                self.sent_queue[notification['sending_id']] = notification

                data = self.create_message(notification)
                if data:
                    frame.add_item(token_hex=data['token'],
                                   payload=data['payload'],
                                   identifier=data['identifier'],
                                   expiry=data['expiry'],
                                   priority=data['priority'])

            # batch (frame) prepared, send it
            self.apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 37
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)
Ejemplo n.º 38
0
def send_push_background(tokens, text, badge, data, content_available):
    apns = APNs(use_sandbox=False,
                cert_file='static/JukeboxBetaPush.pem',
                key_file='static/JukeboxBetaPush.pem')
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10
    for device_token in tokens:
        sound = None
        if text:
            sound = "default"
        if not data:
            data = {}
        payload = Payload(alert=text,
                          sound=sound,
                          badge=badge,
                          custom=data,
                          content_available=content_available)
        frame.add_item(device_token, payload, identifier, expiry, priority)
    apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 39
0
def do_send_sms(sendDeviceStringList):
    apns = APNs(use_sandbox=APNS_USE_SANDBOX,
                cert_file=APNS_CERT_FILE,
                key_file=APNS_KEY_FILE)
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600 * 4
    priority = 10

    for info in sendDeviceStringList:
        device_id = info['device_id']
        alert = info['alert']
        badge = info['badge']
        payload = Payload(alert=alert, sound="default", badge=badge)
        frame.add_item(device_id, payload, identifier, expiry, priority)

    # DO SEND!
    t1 = time.time()
    apns.gateway_server.send_notification_multiple(frame)
    t2 = time.time()
    print "Sending %s notifications, using seconds = %s" % (
        len(sendDeviceStringList), int(t2 - t1))
Ejemplo n.º 40
0
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'))
Ejemplo n.º 41
0
def test_add_frame_item_with_full_args():
    global has_called_check_method
    has_called_check_method = False

    # assert_called_once_with of Mock Class failes to compare Payload object.
    # So here created custom check method for parameter checking
    def check_add_item_args(token, payload, identifier, expiry, priority):
        eq_(token, dummy_token)
        eq_(payload.alert, 'Wow')
        eq_(payload.badge, 50)
        eq_(payload.sound, 'bell')
        eq_(payload.custom, {'foo': 'bar'})
        eq_(payload.content_available, True)
        eq_(identifier, 1)
        eq_(priority, 5)
        eq_(expiry, 0)

        global has_called_check_method
        has_called_check_method = True

    worker = SendWorkerThread(**dummy_setting)
    worker.count = 1
    frame = Frame()
    frame.add_item = check_add_item_args

    worker.add_frame_item(frame,
                          'myapp',
                          dummy_token, {
                              'alert': 'Wow',
                              'badge': 50,
                              'sound': 'bell',
                              'custom': {
                                  'foo': 'bar'
                              },
                              'content_available': True,
                          },
                          expiry=0,
                          priority=5)
    ok_(has_called_check_method)
Ejemplo n.º 42
0
    def send_batch(self):
        if len(self.queue) > 0:
            self.log.debug('Apns batch size: {0}'.format(len(self.queue)))
            frame = Frame()
            while len(self.queue) > 0:
                notification = self.queue.pop()

                notification['status'] = const.NOTIFICATION_SUCCESS
                self.sent_queue[notification['sending_id']] = notification

                data = self.prepare_data(notification)
                if data:
                    frame.add_item(
                        token_hex=data['token'],
                        payload=data['payload'],
                        identifier=data['identifier'],
                        expiry=data['expiry'],
                        priority=data['priority']
                    )

            # batch (frame) prepared, send it
            self.apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 43
0
def execute(device_token_lists, notification):
    if notification.is_production:
        pem_file_name = ProductFileModel.objects.all()[0].production_file_name
        apns = APNs(use_sandbox=False,
                    cert_file=PEM_FILE_DIR + pem_file_name,
                    enhanced=True)
    else:
        pem_file_name = DevelopFileModel.objects.all()[0].development_file_name
        apns = APNs(use_sandbox=True,
                    cert_file=PEM_FILE_DIR + pem_file_name,
                    enhanced=True)

    token_hex = []
    for token in device_token_lists:
        token_hex.append(token)

    json_data = ''
    if notification.json != '':
        json_data = json.loads(notification.json)

    payload = Payload(alert=notification.message,
                      sound=notification.sound,
                      badge=notification.badge,
                      custom=json_data)

    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10

    for token in token_hex:
        frame.add_item(token, payload, identifier, expiry, priority)

    apns.gateway_server.send_notification_multiple(frame)

    notification.is_sent = True
    notification.status = 1
    notification.save()
Ejemplo n.º 44
0
    def post(self):
        """
        post HTTP method

        Send apns notification for given devices in 'Follower' table
        associated with bill argument.

        HTTP args:
            bill -- The name of the bill

        Returns:
            A 201 Created HTTP status code.
        """
        args = parser.parse_args()
        billname = args['bill']
        query = Follower.query.filter_by(billname=billname).all()
        print query
        if len(query) < 1:
            return "", 500
        else:
            payload = Payload(
                alert=billname + " is currently live.",
                sound="default",
                category="BILLS_CATEGORY",
                custom={
                    'link':
                    'http:/a-vide-link/playlist.m3u8'
                },
                badge=0)
            frame = Frame()
            identifer = 1
            expiry = time.time() + 3600
            priority = 10
            for item in query:
                token_hex = ''.join(item.tokenid)
                frame.add_item(token_hex, payload, identifer, expiry, priority)
            apns.gateway_server.send_notification_multiple(frame)
            return "", 204
Ejemplo n.º 45
0
def apns_notification(tokens_hex, message):

    apns = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')
    """
    # Send a notification
    token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    apns.gateway_server.send_notification(token_hex, payload)
    """

    # Send multiple notifications in a single transmission
    # tokens_hex = []
    payload = Payload(alert=message, sound="default", badge=1)

    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10

    for token in tokens_hex:
        frame.add_item(token, payload, identifier, expiry, priority)

    apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 46
0
def send_message(users, cert_file, key_file, sandbox=False, **data):
    if not isinstance(users, list):
        users = [users]

    messaging_ids = [user.messaging_id for user in users \
                        if user.messaging_id is not None]

    if not messaging_ids:
        logging.debug('No messaging ids founds')
        return

    logging.debug('Using messaging sandbox: %s' % sandbox)

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

    payload = Payload(**data)

    if len(users) == 1:
        logging.debug('Sending message to: %s' % messaging_ids[0])
        apns.gateway_server.send_notification(messaging_ids[0], payload)
    else:
        # Send multiple notifications in a single transmission
        frame = Frame()
        # used for reporting errors (in send_notification_multiple())
        identifier = 1
        # APNs stores notification until this time
        expiry = time.time() + 3600
        # 10=send immediately, 5=send at time that conserves device power
        priority = 10
        for messaging_id in messaging_ids:
            frame.add_item(messaging_id, payload, identifier, expiry, priority)
        logging.debug('Sending message to multiple users')
        apns.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 47
0
 def __init__(self, user, tokens, alert=None, badge=None, sound=None,
         category=None, **kwargs):
     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)
Ejemplo n.º 48
0
def test_frame_content():
    worker = SendWorkerThread(**dummy_setting)
    frame = Frame()
    ok_(len(frame.frame_data) == 0)
    worker.add_frame_item(frame,
                          'myapp',
                          dummy_token, {'alert': 'hello'},
                          expiry=None,
                          priority=10)

    hex_frame = b2a_hex(str(frame.frame_data))
    # Notification command
    eq_('02', hex_frame[0:2])
    # Frame length
    eq_('00000051', hex_frame[2:10])
    # Item ID:1 Device Token
    eq_('01', hex_frame[10:12])
    # Token Length
    eq_('0020', hex_frame[12:16])
    # Token
    eq_(dummy_token, hex_frame[16:80])
Ejemplo n.º 49
0
	def make_push(self, request, queryset):
		from apns import APNs, Frame, Payload
		import time
		wrapper = {}
		frames = {}
		for msg in queryset:
			if msg.sent:
				continue
			if msg.device.development:
				pem = msg.app.cert_dev
			else:
				pem = msg.app.cert_dist
			key = "%d_%d" % (msg.app.pk, msg.device.development)
			if not wrapper.has_key(key):
				wrapper[key] = APNs(cert_file="/var/www/cert/%s" % pem, use_sandbox=msg.device.development)
				frames[key] = Frame()
			#wrapper = APNSNotificationWrapper("/home/mrgaolei/%s" % pem, msg.device.development)
			custom = {}

			# property
			for ppt in msg.property_set.all():
				custom[ppt.argkey] = ppt.argvalue

			payload = Payload(alert = msg.alert, sound = msg.sound, badge = int(msg.badge), custom = custom, category = msg.category)
			frames[key].add_item(msg.device.devtoken, payload, msg.pk, time.time()+3600, 10)
			
			# property
			# for ppt in msg.property_set.all():
				#message.appendProperty(APNSProperty(str(ppt.argkey), str(ppt.argvalue)))
				#message.appendProperty(APNSProperty(ppt.argkey.encode( "UTF-8" ), ppt.argvalue.encode( "UTF-8" )))

			#wrapper[key].append(message)
			#if wrapper.notify():
			msg.sent = True
			msg.save()
		keys = wrapper.keys()
		for key in keys:
			wrapper[key].gateway_server.send_notification_multiple(frames[key])
Ejemplo n.º 50
0
    def main(self):
        frame = Frame()
        try:
            item_count = 0
            while item_count < 500:
                if item_count == 0:
                    # First time
                    # Wait here by blocking get
                    item = self.task_queue.get(True, self.TASK_QUEUE_TIMEOUT)
                else:
                    item = self.task_queue.get(False)
                item_count += 1

                self.count += 1
                self.store_item(self.count, item)
                self.add_frame_item(frame, **item)
        except Queue.Empty:
            if item_count == 0:
                raise QueueWaitTimeout()

        if len(frame.frame_data) > 0:
            self.send(frame)
            self.check_error()
def process():

    # Defines a function to translate the notification type into a string
    def getNotificationTitle(type, sender):
        type_r = ""
        if type == string_constants.kServerNotificationsTypeConnectionsRequest:
            type_r = string_constants.kServerNotificationsTypeConnectionsRequestTitle % (sender)
        elif type == string_constants.kServerNotificationsTypeConnectionsRequestConfirmation:
            type_r = string_constants.kServerNotificationsTypeConnectionsRequestConfirmationTitle % (sender)
        elif type == string_constants.kServerNotificationsTypeNewVideo:
            type_r = string_constants.kServerNotificationsTypeNewVideoTitle % (sender)
        return type_r

    if len(sys.argv) > 1:
        a = sys.argv[1]
        b = sys.argv[2]
        c = sys.argv[3]
        d = sys.argv[4]
        database.createDatabase(a, b)
        sandbox = False
    else:
        database.createDatabase()
        c = "certs/apns-dev-cert.pem"
        d = "certs/apns-dev-key-noenc.pem"
        sandbox = True

    # database.createDatabase()
    session = database.DBSession()

    pendingNotifications = (
        session.query(NotificationModel)
        .filter(NotificationModel.notification_sent == 0)
        .order_by(desc(NotificationModel.notification_date))
        .all()
    )

    if len(pendingNotifications) < 1:
        return

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

    # Send multiple notifications in a single transmission
    frame = Frame()
    identifier = 1
    expiry = time.time() + 3600
    priority = 10

    for notification in pendingNotifications:
        _payload = notification.notification_payload
        display_name = _payload[string_constants.kServerNotificationsUser_NameKey]
        _payload[string_constants.kServerNotificationsUser_NameKey] = None
        if _payload is None:
            _payload = {}
        token_hex = notification.registered_notification_user_model.registered_user_token
        if token_hex is not None:
            payload = Payload(
                alert=getNotificationTitle(
                    notification.notification_payload[string_constants.kServerNotificationsType], display_name
                ),
                sound="default",
                badge=1,
                custom=_payload,
            )

            frame.add_item(token_hex, payload, identifier, expiry, priority)
        session.query(NotificationModel).filter(
            NotificationModel.notification_id == notification.notification_id
        ).update({"notification_sent": 1})

    apns.gateway_server.send_notification_multiple(frame)

    # Get feedback messages
    for (token_hex, fail_time) in apns.feedback_server.items():
        print token_hex
        print fail_time

    # Remove all pending notifications that were just sent and close the DB session
    session.commit()
    session.close()
Ejemplo n.º 52
0
try:
    cnx = mysql.connector.connect(user="******",
                                  password="******",
                                  host="Med65",
                                  port=65002,
                                  db="rehabtracker")

except mysql.connector.Error as err:
    print(err)
else:
    cursor = cnx.cursor(buffered=True)
    cursor.execute(
        "SELECT pmkPushID, fnkPatientID, fnkMessageID FROM tblPush WHERE fldDelivered != 1"
    )
    notifications = cursor.fetchall()
    frame = Frame()
    for push_ID, patient_ID, message_ID in notifications:
        cursor.execute("SELECT UDID FROM tblPatient WHERE pmkPatientID=%s;",
                       (patient_ID, ))
        token_hex = cursor.fetchall()[0][0]
        if token_hex:
            print("{}, {}\n".format(patient_ID, token_hex))
            cursor.execute(
                "SELECT fldMessageString FROM tblNotifications WHERE pmkMessageID=%s;",
                (message_ID, ))
            message = cursor.fetchall()[0][0]
            payload = Payload(alert=message, sound="default", badge=1)
            identifier = random.getrandbits(32)
            priority = 10
            expiry = time.time() + 86400
            frame.add_item(token_hex, payload, identifier, expiry, priority)
Ejemplo n.º 53
0
import time
import os
from apns import APNs, Frame, Payload

cert_file = os.environ.get('APNS_PUBLIC_PEM')
key_file = os.environ.get('APNS_PUBLIC_PEM')

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

# Send a notification
token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert='Hello World!', sound='default', badge=3)
apns.gateway_server.send_notification(token_hex, payload)

# Send multiple notifications in a signle transmission
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
frame.add_item('b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87',
		payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)

Ejemplo n.º 54
0
import requests
from apns import APNs, Payload, Frame
import json
import random
import time

r = requests.get(
    'https://rehabtracker.med.uvm.edu/Restful/getPushNotifications.php')
noteList = json.loads(r.text)
apns = APNs(use_sandbox=False,
            cert_file='rehabDepCer.pem',
            key_file='rehabDepKey.pem',
            enhanced=True)
delivered = []
frame = Frame()
for note in noteList:
    payload = Payload(alert=note['Message'], sound="default", badge=0)
    identifier = random.getrandbits(32)
    priority = 10
    expiry = time.time() + 86400
    print(note['UDID'])
    frame.add_item(note['UDID'], payload, identifier, expiry, priority)
    delivered.append(note['pmkPushID'])
apns.gateway_server.send_notification_multiple(frame)
postJson = json.dumps({"pushed": delivered})
POST = requests.post(
    'https://rehabtracker.med.uvm.edu/Restful/getPushNotifications.php',
    data=postJson)
print(POST.status_code)
Ejemplo n.º 55
0
#coding:utf-8
'''
Created on 2015-5-10

@author: hack
'''
from apns import APNs, Frame
from apns import Payload
apns_handler = APNs(use_sandbox=True, cert_file='push_dev2.pem', enhanced=True)
device_token ='8690afe1f1f1067b3f45e0a26a3af4eef5391449e8d07073a83220462bf061be'


payload = Payload('hello', badge=1)

apns_handler.gateway_server.send_notification(device_token, payload)

frame = Frame()
frame.add_item(device_token, payload, 1, 1, 1)
apns_handler.gateway_server.send_notification_multiple(frame)
Ejemplo n.º 56
0
'''
Created on 2016年7月8日

@author: qiu
'''
import time
from apns import APNs, Frame, Payload

apns = APNs(use_sandbox=True, cert_file='new.pem')

# Send a notification
token_hex1 = 'e1c04c5c5a02ff26e23251c1acfe6d38e8d4d3f5ba2dc68d2a932d50d20d791a'
token_hex2 = 'ead30cb88a39b2f9e612212c1ecf34f415e826fb8192a61581d4a282bca77a0b'
token_hex3 = '0c7cd6cd7a2d328083d687440f12598656ff75e6e0a5ccbb3c369f30008d0955'
payload = Payload(alert="Hello World!", sound="default", badge=1)
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
frame.add_item(token_hex1, payload, identifier, expiry, priority)
frame.add_item(token_hex2, payload, identifier, expiry, priority)
frame.add_item(token_hex3, payload, identifier, expiry, priority)
# New APNS connection
feedback_connection = APNs(
    use_sandbox=True, key_file='private.pem', cert_file='public.pem')

# Get feedback messages.
for (token_hex, fail_time) in feedback_connection.feedback_server.items():
    # do stuff with token_hex and fail_time
    print token_hex, fail_time
Ejemplo n.º 57
0
import time
from apns import APNs, Frame, Payload

print("start")
apns = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')
print("apns")
# Send a notification
# 这个是ios设备的 device token
token_hex = 'f73ac698f7492cb4d2f0b7d53dc540e76155b18703b2b7c3f0a369413bc4f3ac'
payload = Payload(alert="Hello World!", sound="default", badge=1)
print("before gateway")
apns.gateway_server.send_notification(token_hex, payload)

print("发送了==============================")
# Send multiple notifications in a single transmission
frame = Frame()
identifier = 1
expiry = time.time() + 3600
priority = 10
frame.add_item('b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87',
               payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)