Beispiel #1
0
 def test_payload_with_payload_alert(self):
     payload = Payload(
         alert=self.payload_alert, badge=2, sound='chime',
         content_available=1, mutable_content=1,
         category='my_category', url_args='args', custom={'extra': 'something'}, thread_id=42)
     self.assertEqual(payload.dict(), {
         'aps': {
             'alert': {
                 'title': 'title',
                 'title-loc-key': 'loc_k',
                 'title-loc-args': 'loc_a',
                 'body': 'body',
                 'loc-key': 'body_loc_k',
                 'loc-args': 'body_loc_a',
                 'action-loc-key': 'ac_loc_k',
                 'action': 'send',
                 'launch-image': 'img'
             },
             'badge': 2,
             'sound': 'chime',
             'content-available': 1,
             'mutable-content': 1,
             'thread-id': 42,
             'category': 'my_category',
             'url-args': 'args',
         },
         'extra': 'something'
     })
Beispiel #2
0
def test_payload_with_payload_alert(payload_alert):
    payload = Payload(alert=payload_alert,
                      badge=2,
                      sound='chime',
                      content_available=True,
                      mutable_content=True,
                      category='my_category',
                      url_args='args',
                      custom={'extra': 'something'},
                      thread_id='42')
    assert payload.dict() == {
        'aps': {
            'alert': {
                'title': 'title',
                'title-loc-key': 'loc_k',
                'title-loc-args': ['loc_a'],
                'body': 'body',
                'loc-key': 'body_loc_k',
                'loc-args': ['body_loc_a'],
                'action-loc-key': 'ac_loc_k',
                'action': 'send',
                'launch-image': 'img'
            },
            'badge': 2,
            'sound': 'chime',
            'content-available': 1,
            'mutable-content': 1,
            'thread-id': '42',
            'category': 'my_category',
            'url-args': 'args',
        },
        'extra': 'something'
    }
    assert payload.push_type == 'alert'
Beispiel #3
0
 def send(self, token, message, count, isSilent):
     if isSilent:
         payload = Payload(content_available=True, badge=count)
     else:
         # TODO create custom sound (more so on client)
         payload = Payload(alert=message, sound="default", badge=count)
     topic = 'com.bfichter.KookMachine'
     self.client.send_notification(token, payload, topic)
     
Beispiel #4
0
	def create_payload(self, background=None, title="Title", body="Body", silent=True, badge=0): # pylint: disable=R0913
		"""
		Constructs APNS payload
		"""
		if silent:
			sound = None
		else:
			sound = "Default"
		if background is not None:
			data = {"Data": background}
			self.payload = Payload(content_available=True, custom=data)
		else:
			alert = PayloadAlert(title=title, body=body)
			self.payload = Payload(alert=alert, sound=sound, badge=badge)
Beispiel #5
0
    def send_ios(self, story, user, usersub):
        if not self.is_ios:
            return

        tokens = MUserNotificationTokens.get_tokens_for_user(self.user_id)
        # To update APNS:
        # 1. Create certificate signing requeswt in Keychain Access
        # 2. Upload to https://developer.apple.com/account/resources/certificates/list
        # 3. Download to secrets/certificates/ios/aps.cer
        # 4. Open in Keychain Access and export as aps.p12
        # 4. Export private key as aps_key.p12 WITH A PASSPHRASE (removed later)
        # 5. openssl pkcs12 -in aps.p12 -out aps.pem -nodes -clcerts -nokeys
        # 6. openssl pkcs12 -clcerts -nokeys -out aps.pem -in aps.p12
        # 7. cat aps.pem aps_key.noenc.pem > aps.p12.pem
        # 8. Verify: openssl s_client -connect gateway.push.apple.com:2195 -cert aps.p12.pem
        # 9. Deploy: aps -l work -t apns,repo,celery
        apns = APNsClient(
            '/srv/newsblur/config/certificates/aps.p12.pem', use_sandbox=tokens.use_sandbox
        )

        notification_title_only = is_true(user.profile.preference_value('notification_title_only'))
        title, subtitle, body = self.title_and_body(story, usersub, notification_title_only)
        image_url = None
        if len(story['image_urls']):
            image_url = story['image_urls'][0]
            # print image_url

        confirmed_ios_tokens = []
        for token in tokens.ios_tokens:
            logging.user(
                user,
                '~BMStory notification by iOS: ~FY~SB%s~SN~BM~FY/~SB%s'
                % (story['story_title'][:50], usersub.feed.feed_title[:50]),
            )
            payload = Payload(
                alert={'title': title, 'subtitle': subtitle, 'body': body},
                category="STORY_CATEGORY",
                mutable_content=True,
                custom={
                    'story_hash': story['story_hash'],
                    'story_feed_id': story['story_feed_id'],
                    'image_url': image_url,
                },
            )
            try:
                apns.send_notification(token, payload, topic="com.newsblur.NewsBlur")
            except (BadDeviceToken, Unregistered):
                logging.user(user, '~BMiOS token expired: ~FR~SB%s' % (token[:50]))
            else:
                confirmed_ios_tokens.append(token)
                if settings.DEBUG:
                    logging.user(
                        user,
                        '~BMiOS token good: ~FB~SB%s / %s'
                        % (token[:50], len(confirmed_ios_tokens)),
                    )

        if len(confirmed_ios_tokens) < len(tokens.ios_tokens):
            tokens.ios_tokens = confirmed_ios_tokens
            tokens.save()
Beispiel #6
0
    def _push(self, _apns, _body, _user_config):
        _ios_token = _user_config.get("device_ios_token")
        if _ios_token == None or len(_ios_token) == 0:
            return

        _user_language = _user_config.get("user_language") or "en_US"

        _title = push_title(_body.get("mt"), _body.get("ms"), _body.get("bo"),
                            _user_language)

        _sound = None
        if not _user_config.get("user_silence_notification"):
            _sound = "beep.wav"

        _count = _user_config.get("unacked_notification_count")
        _m = {"alert": _title, "sound": _sound, "badge": _count}

        from apns2.client import APNsClient
        from apns2.payload import Payload

        _dev = _user_config.get("is_development")
        _client = APNsClient(_apns.get("combination_pem"),
                             use_sandbox=False,
                             use_alternative_port=False)
        if _dev != None and _dev == True:
            _client = APNsClient(_apns.get("combination_pem"),
                                 use_sandbox=True,
                                 use_alternative_port=False)

        _payload = Payload(**_m)
        _client.send_notification(_ios_token, _payload)
        return
Beispiel #7
0
def test_alert(sandbox):
    f = open("imdemo.p12", "rb")
    p12 = f.read()
    f.close()
    token = "7b2a23d466cf2557fb4fa573e1cc5f63088cd060def124a9eca97ab251be08b5"
    alert = u"测试ios推送"
    badge = 1
    sound = "default"
    topic = "com.beetle.im.demo"
    print("p12", len(p12))

    extra = {"test": "hahah"}
    client = IOSPush.connect_apns_server(sandbox, p12, "")
    payload = Payload(alert=alert, sound=sound, badge=badge, custom=extra)

    try:
        client.send_notification(token, payload, topic)
        time.sleep(1)
    except OpenSSL.SSL.Error as e:
        err = e.message[0][2]
        print("certificate expired" in err)
        print("ssl exception:", e, type(e), dir(e), e.args, e.message)
        raise e
    except Exception as e:
        print("exception:", e, type(e), dir(e), e.args, e.message)
        raise e
Beispiel #8
0
    def push(cls,
             appid,
             token,
             alert,
             sound="default",
             badge=0,
             content_available=0,
             extra=None,
             collapse_id=None):
        topic = cls.get_bundle_id(appid)
        if not topic:
            logging.warn("appid:%s no bundle id", appid)
            return

        payload = Payload(alert=alert,
                          sound=sound,
                          badge=badge,
                          content_available=content_available,
                          custom=extra)
        client = cls.get_connection(appid)
        try:
            client.send_notification(token,
                                     payload,
                                     topic,
                                     collapse_id=collapse_id)
            logging.debug("send apns:%s %s %s success", token, alert, badge)
        except OpenSSL.SSL.Error as e:
            logging.warn("ssl exception:%s", str(e))
            cls.apns_manager.remove_apns_connection(appid)
        except Exception as e:
            logging.warn("send notification exception:%s %s", str(e), type(e))
            cls.apns_manager.remove_apns_connection(appid)
def send_Notification( message, key):

    token_hex = 'e4d3e8cb6e8c29d0dd6af4926e698c69632e2a8965cd17d66ed2d0cdd7869269'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    topic = 'ASU.SeatsFinderBot'
    client = APNsClient(key, use_sandbox=True, use_alternative_port=False)
    client.send_notification(token_hex, payload, topic)
Beispiel #10
0
def update_card():
    print('start update card')
    users = User.objects.all()
    for user in users:
        if user.card_drawer_of_next_day != '10102347454878415':
            user.update(card_drawer=None, draw_card_status='undraw')
        user.card_drawer = user.card_drawer_of_next_day
        user.card_drawer_of_next_day = None
        user.save()

    # send push notification
    print('send notification')
    try:
        user_list = User.objects.all()
        for user in user_list:
            if user.card_drawer != '10102347454878415':
                if user.device.ios != '':
                    custom_payload = {'type': 'card'}
                    payload = Payload(alert='已經有新的卡片囉!',
                                      sound="default",
                                      badge=1,
                                      custom=custom_payload)
                    client = APNsClient(APNS_CERT,
                                        use_sandbox=USE_SANDBOX,
                                        use_alternative_port=False)
                    client.send_notification(user.device.ios, payload,
                                             APNS_TOPIC)
        print('succeed')
    except Exception as e:
        print(e)
Beispiel #11
0
def test_send_notification_failure_410():
    with patch("apns2.credentials.CertificateCredentials.create_connection"
               ) as create_connection_mock:
        http_client_mock = MagicMock()
        http_client_mock.post.return_value = Response(status_code=410,
                                                      json={
                                                          "reason":
                                                          "BadDeviceToken",
                                                          "timestamp":
                                                          time.time()
                                                      })

        create_connection_mock.return_value = http_client_mock

        client = APNsClient(CertificateCredentials("test/mycert.pem"))

        exception_raised = False
        try:
            client.send_notification(
                token_hex=TOKEN,
                notification=Payload(alert="Test alert"),
                topic=TOPIC,
            )
        except BadDeviceToken:
            exception_raised = True

        http_client_mock.post.assert_called_once()
        assert exception_raised is True
    def send_Notification(self, message, key, device_id):

        token_hex = device_id
        payload = Payload(alert=message, sound="default", badge=1)
        topic = 'ASU.SeatsFinderBot'
        client = APNsClient(key, use_sandbox=False, use_alternative_port=False)
        client.send_notification(token_hex, payload, topic)
Beispiel #13
0
 def push(self, identifier: ID, message: str) -> bool:
     # 1. check
     tokens = self.delegate.device_tokens(identifier=identifier)
     if tokens is None:
         self.error('cannot get device token for user %s' % identifier)
         return False
     # 2. send
     badge = self.badge(identifier)
     payload = Payload(alert=message, badge=badge, sound='default')
     success = 0
     for token in tokens:
         self.debug('sending notification %s to user %s with token %s' % (message, identifier, token))
         # first try
         result = self.send_notification(token_hex=token, notification=payload)
         if result == -503:  # Service Unavailable
             # connection failed
             break
         elif result == -408:  # Request Timeout
             self.error('Broken pipe? try to reconnect again!')
             # reset APNs client
             self.client = None
             # try again
             result = self.send_notification(token_hex=token, notification=payload)
         if result == 200:  # OK
             success = success + 1
     if success > 0:
         self.info('sending notification success:%d badge=%d, %s' % (success, badge, identifier))
         return True
Beispiel #14
0
 def test_payload(self):
     payload = Payload(
         alert='my_alert', badge=2, sound='chime',
         content_available=1, mutable_content=3,
         category='my_category', url_args='args', custom={'extra': 'something'}, thread_id=42)
     self.assertEqual(payload.dict(), {
         'aps': {
             'alert': 'my_alert',
             'badge': 2,
             'sound': 'chime',
             'content-available': 1,
             'mutable-content': 1,
             'thread-id': 42,
             'category': 'my_category',
             'url-args': 'args'
         },
         'extra': 'something'
     })
Beispiel #15
0
def test_payload():
    payload = Payload(
        alert='my_alert', badge=2, sound='chime',
        content_available=True, mutable_content=True,
        category='my_category', url_args='args', custom={'extra': 'something'}, thread_id='42')
    assert payload.dict() == {
        'aps': {
            'alert': 'my_alert',
            'badge': 2,
            'sound': 'chime',
            'content-available': 1,
            'mutable-content': 1,
            'thread-id': '42',
            'category': 'my_category',
            'url-args': 'args'
        },
        'extra': 'something'
    }
Beispiel #16
0
def test_payload_with_background_push_type():
    payload = Payload(content_available=True,
                      mutable_content=True,
                      category='my_category',
                      url_args='args',
                      custom={'extra': 'something'},
                      thread_id='42')
    assert payload.dict() == {
        'aps': {
            'content-available': 1,
            'mutable-content': 1,
            'thread-id': '42',
            'category': 'my_category',
            'url-args': 'args',
        },
        'extra': 'something'
    }
    assert payload.push_type == 'background'
Beispiel #17
0
def send_apn(push_token: str):
    '''
    Sends an empty APN to the given device push_token
    '''
    payload = Payload()
    client = APNsClient(config.PASS_TYPE_CERTIFICATE_PATH,
                        use_sandbox=False,
                        use_alternative_port=False,
                        password=config.PEM_PASSWORD)
    client.send_notification(push_token, payload, config.PASS_TYPE_IDENTIFIER)
Beispiel #18
0
 def setUpClass(cls):
     # Ignore all log messages so that test output is not cluttered.
     logging.basicConfig(level=logging.CRITICAL)
     cls.tokens = ['%064x' % i for i in range(10000)]
     cls.payload = Payload(alert='Test alert')
     cls.notifications = [
         Notification(token=token, payload=cls.payload)
         for token in cls.tokens
     ]
     cls.topic = 'com.example.App'
Beispiel #19
0
 def sendMessages(self, apnTokens, message, custom):
     payload = Payload(alert=message,
                       sound="default",
                       custom=custom,
                       content_available=1)
     notifications = [
         Notification(token=token, payload=payload) for token in apnTokens
         if token != None
     ]
     self.client.send_notification_batch(notifications, self.topic)
Beispiel #20
0
    def send_message(self, message=None, **kwargs):
        """Send push message to registered devices."""
        from apns2.client import APNsClient
        from apns2.payload import Payload
        from apns2.errors import Unregistered

        apns = APNsClient(self.certificate,
                          use_sandbox=self.sandbox,
                          use_alternative_port=False)

        device_state = kwargs.get(ATTR_TARGET)
        message_data = kwargs.get(ATTR_DATA)

        if message_data is None:
            message_data = {}

        if isinstance(message, str):
            rendered_message = message
        elif isinstance(message, template_helper.Template):
            rendered_message = message.render()
        else:
            rendered_message = ""

        payload = Payload(
            alert=rendered_message,
            badge=message_data.get("badge"),
            sound=message_data.get("sound"),
            category=message_data.get("category"),
            custom=message_data.get("custom", {}),
            content_available=message_data.get("content_available", False),
        )

        device_update = False

        for push_id, device in self.devices.items():
            if not device.disabled:
                state = None
                if device.tracking_device_id is not None:
                    state = self.device_states.get(
                        device.full_tracking_device_id)

                if device_state is None or state == str(device_state):
                    try:
                        apns.send_notification(push_id,
                                               payload,
                                               topic=self.topic)
                    except Unregistered:
                        logging.error("Device %s has unregistered", push_id)
                        device_update = True
                        device.disable()

        if device_update:
            self.write_devices()

        return True
Beispiel #21
0
    def send_notification(self, userId, message="Hello World!"):

        token_hex = self.get_token(userId)
        payload = Payload(alert=message, sound="default", badge=1)
        print(payload.__dict__)
        topic = 'com.epage.QuietMind'

        self.client = APNsClient(DEV_CERT_FILE,
                                 use_sandbox=True,
                                 use_alternative_port=False)
        self.client.send_notification(token_hex, payload, topic)
Beispiel #22
0
def push(request):
    #fcm_device = GCMDevice.objects.create(registration_id="e--N1a4DuTg:APA91bGrwQnf8h5o3UHrVPx3PTkTVumOEfHP5dfAdvFDuBA2h6QZVG0MYuQtGRH21nvdnb44sThudENkAeEtrmBND3g1gv2A0IlLW4ZMsCGl_AsBDWCR4FJm6s57pf-PPz5BGTkIWCbw", cloud_message_type="FCM", user='******')
    #device = GCMDevice.objects.get(registration_id="e--N1a4DuTg:APA91bGrwQnf8h5o3UHrVPx3PTkTVumOEfHP5dfAdvFDuBA2h6QZVG0MYuQtGRH21nvdnb44sThudENkAeEtrmBND3g1gv2A0IlLW4ZMsCGl_AsBDWCR4FJm6s57pf-PPz5BGTkIWCbw")

    token_hex = '106ececed6c5985efb2afd75618a41120086e7e93488315dc03ccd9eff0be257'
    payload = Payload(alert="Hello World!", sound="default", badge=1)
    topic = 'com.example.App'
    client = APNsClient(
        'https://s3-us-west-1.amazonaws.com/blake-deets/aps_development.cer',
        use_sandbox=False,
        use_alternative_port=False)
    client.send_notification(token_hex, payload, topic)
Beispiel #23
0
def pushSecurityIOS(tokens, community, site):
    notification = {
        "loc-key": Msg_Type.IM,
        "command": Msg_Cmd.SECURITY,
        "device-system": community,
        "device-name": site
    }
    notifications = [
        Notification(token=token, payload=Payload(alert=notification))
        for token in tokens
    ]
    pushIOS(notifications)
Beispiel #24
0
def sendpushnotification(DeviceToken, OrderID, StoreID, dev_flag, Message):
    #send the push notification
    custom = {'launchURL': 'x-com.petco.wrapper.sim://launch'}
    payload = Payload(alert=Message,
                      sound="popcorn.wav",
                      badge=0,
                      custom=custom)
    topic = 'com.petco.notifications'
    IOS_Client = APNsClient('./Apple_Certificate/server1.pem',
                            use_sandbox=dev_flag,
                            use_alternative_port=False)
    IOS_Client.send_notification(DeviceToken, payload, topic)
    return True
Beispiel #25
0
    def send_ios(self, story, user, usersub):
        if not self.is_ios: return

        tokens = MUserNotificationTokens.get_tokens_for_user(self.user_id)
        apns = APNsClient('/srv/newsblur/config/certificates/aps.p12.pem',
                          use_sandbox=tokens.use_sandbox)

        notification_title_only = is_true(
            user.profile.preference_value('notification_title_only'))
        title, subtitle, body = self.title_and_body(story, usersub,
                                                    notification_title_only)
        image_url = None
        if len(story['image_urls']):
            image_url = story['image_urls'][0]
            # print image_url

        confirmed_ios_tokens = []
        for token in tokens.ios_tokens:
            logging.user(
                user, '~BMStory notification by iOS: ~FY~SB%s~SN~BM~FY/~SB%s' %
                (story['story_title'][:50], usersub.feed.feed_title[:50]))
            payload = Payload(alert={
                'title': title,
                'subtitle': subtitle,
                'body': body
            },
                              category="STORY_CATEGORY",
                              mutable_content=True,
                              custom={
                                  'story_hash': story['story_hash'],
                                  'story_feed_id': story['story_feed_id'],
                                  'image_url': image_url,
                              })
            try:
                apns.send_notification(token,
                                       payload,
                                       topic="com.newsblur.NewsBlur")
            except (BadDeviceToken, Unregistered):
                logging.user(user,
                             '~BMiOS token expired: ~FR~SB%s' % (token[:50]))
            else:
                confirmed_ios_tokens.append(token)
                if settings.DEBUG:
                    logging.user(
                        user, '~BMiOS token good: ~FB~SB%s / %s' %
                        (token[:50], len(confirmed_ios_tokens)))

        if len(confirmed_ios_tokens) < len(tokens.ios_tokens):
            tokens.ios_tokens = confirmed_ios_tokens
            tokens.save()
def send_apn_notification(message, endpoint):
    token = endpoint.device_token
    payload = Payload(alert=message, sound="default", badge=1)
    if settings.APNS_CERT_FILE:
        # allows for reuse of apns client and reuse of connections
        # TODO: handles errors by fcm client
        global apns_client
        if not apns_client:
            apns_client = APNsClient(settings.APNS_CERT_FILE,
                                     password=settings.APNS_CERT_PASSWORD,
                                     use_sandbox=settings.DEBUG,
                                     use_alternative_port=False)
        topic = settings.APNS_APP_BUNDLE_ID
        apns_client.send_notification(token, payload, topic)
Beispiel #27
0
    def voip_push(cls, appid, token, extra=None):
        topic = cls.get_bundle_id(appid)
        if not topic:
            logging.warn("appid:%s no bundle id", appid)
            return

        voip_topic = topic + ".voip"
        payload = Payload(custom=extra)
        client = cls.get_pushkit_connection(appid)
        try:
            client.send_notification(token, payload, voip_topic)
            logging.debug("send voip notification:%s success", token)
        except OpenSSL.SSL.Error, e:
            logging.warn("ssl exception:%s", str(e))
            cls.apns_manager.remove_apns_connection(appid)
    def send_push(self, title, body):
        connects = UserConnectionField.objects.find_type_connection_by_user(
            self.user, UserConnectionField.APNS_TYPE)

        client = APNsClient(settings.APNS_KEY_LOCATION,
                            use_sandbox=settings.APNS_SENDBOX,
                            use_alternative_port=False)

        payload = Payload(alert=PayloadAlert(title=title, body=body),
                          sound="default",
                          badge=1)
        for connect in connects:
            client.send_notification(token_hex=connect.value,
                                     notification=payload,
                                     topic=settings.APNS_BUNDLE_ID)
Beispiel #29
0
def push(category, title, body, device_token, params):
    payload = Payload(alert=PayloadAlert(title=None if title == '' else title,
                                         body=body),
                      sound='1107',
                      badge=int(params['badge']) if 'badge' in params else 0,
                      category=category,
                      mutable_content=True,
                      custom=params)
    client = APNsClient(CERT_PATH)

    try:
        client.send_notification(device_token, payload, 'me.fin.bark')
        return ''
    except APNsException as e:
        return str(e)
Beispiel #30
0
def test_send_notification_success():
    with patch("apns2.credentials.CertificateCredentials.create_connection"
               ) as create_connection_mock:
        http_client_mock = MagicMock()
        http_client_mock.post.return_value = Mock(status_code=200)

        create_connection_mock.return_value = http_client_mock

        client = APNsClient(CertificateCredentials("test/mycert.pem"))
        client.send_notification(
            token_hex=TOKEN,
            notification=Payload(alert="Test alert"),
            topic=TOPIC,
        )

        http_client_mock.post.assert_called_once()