Ejemplo n.º 1
0
    def test_sms_overrides(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            alert='top level alert',
            sms=ua.sms(
                alert='sms override alert',
                expiry='2018-04-01T12:00:00',
            )
        )
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload,
            {
                'audience': 'all',
                'device_types': ['sms'],
                'notification': {
                    'alert': 'top level alert',
                    'sms': {
                        'alert': 'sms override alert',
                        'expiry': '2018-04-01T12:00:00'
                    }
                }
            }
        )
Ejemplo n.º 2
0
 def test_all_device_types(self):
     self.assertEqual(
         ua.device_types(
             ua.all_
         ),
         'all'
     )
Ejemplo n.º 3
0
    def push(self, notification):

        if not config.get(config.SERVICES_ENABLED, 'off') == 'on':
            logger.info('notifications disabled: %s marked as pending' % notification.id)
            return

        push = self.airship.create_push()
        push.audience = self.make_tags(notification.tags)
        push.notification = ua.notification(ios=ua.ios(alert=notification.message, extra=notification.payload))
        push.device_types = ua.device_types('ios')

        if notification.scheduled_for:

            schedule = self.airship.create_scheduled_push()
            schedule.push = push
            schedule.name = notification.type

            if notification.scheduled_for_local:
                schedule.schedule = local_scheduled_time(notification.scheduled_for)
            else:
                schedule.schedule = ua.scheduled_time(notification.scheduled_for)

            logger.info("Sending scheduled push to Urban Airship")
            resp = schedule.send()

        else:
            logger.info("Sending push to Urban Airship")
            resp = push.send()

        notification.meta['ua_response'] = resp.payload
        notification.sent = True
 def test_multiple_device_types(self):
     cas = ua.CreateAndSendPush(
         self.airship,
         channels=self.test_sms_objs
     )
     with self.assertRaises(ValueError):
         cas.device_types = ua.device_types('sms', 'ios')
Ejemplo n.º 5
0
    def test_full_payload(self):
        p = ua.TemplatePush(None)
        p.audience = ua.ios_channel('b8f9b663-0a3b-cf45-587a-be880946e881')
        p.device_types = ua.device_types('ios')
        p.merge_data = ua.merge_data(
            template_id='ef34a8d9-0ad7-491c-86b0-aea74da15161',
            substitutions={
                'FIRST_NAME': 'Bob',
                'LAST_NAME': 'Smith',
                'TITLE': ''
            })

        self.assertEqual(
            p.payload, {
                'device_types': ['ios'],
                'merge_data': {
                    'template_id': 'ef34a8d9-0ad7-491c-86b0-aea74da15161',
                    'substitutions': {
                        'FIRST_NAME': 'Bob',
                        'LAST_NAME': 'Smith',
                        'TITLE': ''
                    }
                },
                'audience': {
                    'ios_channel': 'b8f9b663-0a3b-cf45-587a-be880946e881'
                }
            })
Ejemplo n.º 6
0
    def test_full_payload(self):
        p = ua.TemplatePush(None)
        p.audience = ua.ios_channel('b8f9b663-0a3b-cf45-587a-be880946e881')
        p.device_types = ua.device_types('ios')
        p.merge_data = ua.merge_data(
            template_id='ef34a8d9-0ad7-491c-86b0-aea74da15161',
            substitutions={
                'FIRST_NAME': 'Bob',
                'LAST_NAME': 'Smith',
                'TITLE': ''
            }
        )

        self.assertEqual(
            p.payload,
            {
                'device_types': ['ios'],
                'merge_data': {
                    'template_id': 'ef34a8d9-0ad7-491c-86b0-aea74da15161',
                    'substitutions': {
                        'FIRST_NAME': 'Bob',
                        'LAST_NAME': 'Smith',
                        'TITLE': ''
                    }
                },
                'audience': {
                    'ios_channel': 'b8f9b663-0a3b-cf45-587a-be880946e881'
                }
            }
        )
def create_notification(receiver, reporter, content_object, notification_type):
    # If the receiver of this notification is the same as the reporter or
    # if the user has blocked this type, then don't create
    if receiver == reporter or not NotificationSetting.objects.get(
            notification_type=notification_type, user=receiver).allow:
        return

    notification = Notification.objects.create(
        user=receiver,
        reporter=reporter,
        content_object=content_object,
        notification_type=notification_type)
    notification.save()

    if AirshipToken.objects.filter(user=receiver, expired=False).exists():
        try:
            device_tokens = list(
                AirshipToken.objects.filter(
                    user=receiver, expired=False).values_list('token',
                                                              flat=True))
            airship = urbanairship.Airship(settings.AIRSHIP_APP_KEY,
                                           settings.AIRSHIP_APP_MASTER_SECRET)

            for device_token in device_tokens:
                push = airship.create_push()
                push.audience = urbanairship.device_token(device_token)
                push.notification = urbanairship.notification(
                    ios=urbanairship.ios(alert=notification.push_message(),
                                         badge='+1'))
                push.device_types = urbanairship.device_types('ios')
                push.send()
        except urbanairship.AirshipFailure:
            pass
Ejemplo n.º 8
0
    def test_standard_ios_opts(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            alert='Top level alert',
            ios = ua.ios(
                alert='iOS override alert',
                sound='cat.caf',
            )
        )
        p.device_types = ua.device_types('ios')

        self.assertEqual(
            p.payload,
            {
                'audience': 'all',
                'device_types': ['ios'],
                'notification': {
                    'alert': 'Top level alert',
                    'ios': {
                        'alert': 'iOS override alert',
                        'sound': 'cat.caf'
                    }
                }
            }
        )
Ejemplo n.º 9
0
    def test_scheduled_template(self):
        with mock.patch.object(ua.Airship, '_request') as mock_request:
            response = requests.Response()
            response._content = json.dumps(
                {
                    'schedule_urls': [
                        'https://go.urbanairship.com/api/schedules/40fe5b31-8997-4819-9aeb-e6c4ae95e5d3'
                    ]
                }
            ).encode('utf-8')
            response.status_code = 202
            mock_request.return_value = response

            airship = ua.Airship(TEST_KEY, TEST_SECRET)
            sched = ua.ScheduledPush(airship)
            sched.schedule = ua.scheduled_time(datetime.datetime.now())

            template_push = airship.create_template_push()
            template_push.audience = ua.ios_channel('780ba0c5-45be-4f29-befa-39135cb05b59')
            template_push.device_types = ua.device_types('ios')
            template_push.merge_data = ua.merge_data(
                template_id='780ba0c5-45be-4f29-befa-39135cb05b59',
                substitutions={'key': 'value'}
            )

            sched.push = template_push
            sched.send()

            self.assertEqual(
                sched.url,
                'https://go.urbanairship.com/api/schedules/40fe5b31-8997-4819-9aeb-e6c4ae95e5d3'
            )
Ejemplo n.º 10
0
    def test_email_overrides(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            email=ua.email(message_type='transactional',
                           plaintext_body='hello',
                           reply_to='*****@*****.**',
                           sender_address='*****@*****.**',
                           sender_name='test_name',
                           subject='hi',
                           html_body='<html>so rich!</html>'))
        p.device_types = ua.device_types('email')

        self.assertEqual(
            p.payload, {
                'audience': 'all',
                'device_types': ['email'],
                'notification': {
                    'email': {
                        'message_type': 'transactional',
                        'plaintext_body': 'hello',
                        'reply_to': '*****@*****.**',
                        'sender_address': '*****@*****.**',
                        'sender_name': 'test_name',
                        'subject': 'hi',
                        'html_body': '<html>so rich!</html>'
                    }
                }
            })
Ejemplo n.º 11
0
    def test_email_overrides(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            email=ua.email(
                message_type='transactional',
                plaintext_body='hello',
                reply_to='*****@*****.**',
                sender_address='*****@*****.**',
                sender_name='test_name',
                subject='hi',
                html_body='<html>so rich!</html>'
            )
        )
        p.device_types = ua.device_types('email')

        self.assertEqual(
            p.payload,
            {
                'audience': 'all',
                'device_types': ['email'],
                'notification': {
                    'email': {
                        'message_type': 'transactional',
                        'plaintext_body': 'hello',
                        'reply_to': '*****@*****.**',
                        'sender_address': '*****@*****.**',
                        'sender_name': 'test_name',
                        'subject': 'hi',
                        'html_body': '<html>so rich!</html>'
                    }
                }
            }
        )
Ejemplo n.º 12
0
    def test_sms_overrides(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            alert='top level alert',
            sms = ua.sms(
                alert='sms override alert',
                expiry='2018-04-01T12:00:00',
            )
        )
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload,
            {
                'audience': 'all',
                'device_types': ['sms'],
                'notification': {
                    'alert': 'top level alert',
                    'sms': {
                        'alert': 'sms override alert',
                        'expiry': '2018-04-01T12:00:00'
                    }
                }
            }
        )
Ejemplo n.º 13
0
def create_notification(receiver, reporter, content_object, notification_type):
    # If the receiver of this notification is the same as the reporter or
    # if the user has blocked this type, then don't create
    if receiver == reporter or not NotificationSetting.objects.get(notification_type=notification_type, user=receiver).allow:
        return

    notification = Notification.objects.create(user=receiver,
                                               reporter=reporter,
                                               content_object=content_object,
                                               notification_type=notification_type)
    notification.save()

    if AirshipToken.objects.filter(user=receiver, expired=False).exists():
        try:
            device_tokens = list(AirshipToken.objects.filter(user=receiver, expired=False).values_list('token', flat=True))
            airship = urbanairship.Airship(settings.AIRSHIP_APP_KEY, settings.AIRSHIP_APP_MASTER_SECRET)

            for device_token in device_tokens:
                push = airship.create_push()
                push.audience = urbanairship.device_token(device_token)
                push.notification = urbanairship.notification(ios=urbanairship.ios(alert=notification.push_message(), badge='+1'))
                push.device_types = urbanairship.device_types('ios')
                push.send()
        except urbanairship.AirshipFailure:
            pass
Ejemplo n.º 14
0
    def push(self, notification):

        if not config.get(config.SERVICES_ENABLED, 'off') == 'on':
            logger.info('notifications disabled: %s marked as pending' %
                        notification.id)
            return

        push = self.airship.create_push()
        push.audience = self.make_tags(notification.tags)
        push.notification = ua.notification(
            ios=ua.ios(alert=notification.message, extra=notification.payload))
        push.device_types = ua.device_types('ios')

        if notification.scheduled_for:

            schedule = self.airship.create_scheduled_push()
            schedule.push = push
            schedule.name = notification.type

            if notification.scheduled_for_local:
                schedule.schedule = local_scheduled_time(
                    notification.scheduled_for)
            else:
                schedule.schedule = ua.scheduled_time(
                    notification.scheduled_for)

            logger.info("Sending scheduled push to Urban Airship")
            resp = schedule.send()

        else:
            logger.info("Sending push to Urban Airship")
            resp = push.send()

        notification.meta['ua_response'] = resp.payload
        notification.sent = True
Ejemplo n.º 15
0
    def test_standard_ios_opts(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            alert='Top level alert',
            ios=ua.ios(
                alert='iOS override alert',
                sound='cat.caf',
            )
        )
        p.device_types = ua.device_types('ios')

        self.assertEqual(
            p.payload,
            {
                'audience': 'all',
                'device_types': ['ios'],
                'notification': {
                    'alert': 'Top level alert',
                    'ios': {
                        'alert': 'iOS override alert',
                        'sound': 'cat.caf'
                    }
                }
            }
        )
Ejemplo n.º 16
0
    def test_scheduled_template(self):
        with mock.patch.object(ua.Airship, '_request') as mock_request:
            response = requests.Response()
            response._content = json.dumps({
                'schedule_urls': [
                    'https://go.urbanairship.com/api/schedules/40fe5b31-8997-4819-9aeb-e6c4ae95e5d3'
                ]
            }).encode('utf-8')
            response.status_code = 202
            mock_request.return_value = response

            airship = ua.Airship(TEST_KEY, TEST_SECRET)
            sched = ua.ScheduledPush(airship)
            sched.schedule = ua.scheduled_time(datetime.datetime.now())

            template_push = airship.create_template_push()
            template_push.audience = ua.ios_channel(
                '780ba0c5-45be-4f29-befa-39135cb05b59')
            template_push.device_types = ua.device_types('ios')
            template_push.merge_data = ua.merge_data(
                template_id='780ba0c5-45be-4f29-befa-39135cb05b59',
                substitutions={'key': 'value'})

            sched.push = template_push
            sched.send()

            self.assertEqual(
                sched.url,
                'https://go.urbanairship.com/api/schedules/40fe5b31-8997-4819-9aeb-e6c4ae95e5d3'
            )
Ejemplo n.º 17
0
    def test_email_missing_override(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(alert='no email to be found!')
        p.device_types = ua.device_types('email')

        with self.assertRaises(ValueError):
            p.send()
Ejemplo n.º 18
0
	def push_message_for_user(self, message, user, status):
		#self.airship.push({'aps': {'alert': message, 'badge':1, 'sound': 'default'},
		# 'status':status}, aliases=[user.username])

		push = self.airship.create_push()
		push.audience = ua.or_(ua.alias(user.username))
		push.notification = ua.notification(alert=message)
		push.device_types = ua.device_types('ios', 'android')
		push.send()
Ejemplo n.º 19
0
    def test_email_missing_override(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            alert='no email to be found!'
        )
        p.device_types = ua.device_types('email')

        with self.assertRaises(ValueError):
            p.send()
Ejemplo n.º 20
0
 def test_email_send(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_email_objs
     )
     cas.notification = ua.notification(
         email=ua.email(
             message_type='commercial',
             plaintext_body='this is an email',
             reply_to='*****@*****.**',
             sender_address='*****@*****.**',
             sender_name='test sender',
             subject='this is an email'
         )
     )
     cas.device_types = ua.device_types('email')
     cas.campaigns = ua.campaigns(
         categories=['email', 'fun']
     )
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59'
                     },
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59'
                     },
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59'
                     }
                 ]
             },
             'device_types': ['email'],
             'notification': {
                 'email': {
                     'subject': 'this is an email',
                     'plaintext_body': 'this is an email',
                     'message_type': 'commercial',
                     'sender_name': 'test sender',
                     'sender_address': '*****@*****.**',
                     'reply_to': '*****@*****.**'
                 }
             },
             'campaigns': {
                 'categories': ['email', 'fun']
             }
         }
     )
Ejemplo n.º 21
0
    def send(self, text, link, **kw):
        # Since the UA payloads we need contain much more data than just text
        # and link, we talk to the IMessage object instead.
        message = kw['message']

        now = datetime.now(pytz.UTC)
        to_push = []
        for push_message in message.render():
            # Check out
            # https://docs.urbanairship.com/api/ua/#push-object
            for device in push_message.get('device_types', []):
                application_credentials = self.credentials.get(
                    device, [None, None])

                push_message.setdefault('options',
                                        {}).setdefault('expiry',
                                                       self.expire_interval)
                # We transmit an absolute timestamp, not relative seconds, as a
                # safetybelt against (very) delayed pushes. The format must not
                # contain microseconds, so no `isoformat`.
                push_message['options']['expiry'] = (
                    now + timedelta(seconds=push_message['options']['expiry']))
                push_message['options']['expiry'] = push_message['options'][
                    'expiry'].strftime('%Y-%m-%dT%H:%M:%S')

                ua_push_object = urbanairship.Airship(
                    *application_credentials).create_push()
                ua_push_object.options = push_message['options']
                ua_push_object.audience = push_message['audience']
                ua_push_object.device_types = urbanairship.device_types(device)
                ua_push_object.notification = push_message['notification']
                to_push.append(ua_push_object)

        # Urban airship does support batch pushing, but
        # the python module does not
        # https://github.com/urbanairship/python-library/issues/34
        # Still we should not push each object directly after is
        # created, because otherwise the whole push process can fail with
        # a later object
        # Great validation would be a solution to this problem :)
        try:
            for ua_push_object in to_push:
                self.push(ua_push_object)
        except Exception:
            path = six.moves.urllib.parse.urlparse(link).path
            info = sys.exc_info()
            bugsnag.notify(
                info[2],
                traceback=info[2],
                context=path,
                severity='error',
                grouping_hash=message.config.get('payload_template'))
            raise
Ejemplo n.º 22
0
 def test_scheduled_send(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_sms_objs
     )
     cas.notification = ua.notification(
         alert='test sms'
     )
     cas.device_types = ua.device_types('sms')
     cas.campaigns = ua.campaigns(
         categories=['sms', 'offers']
     )
     schedule = ua.ScheduledPush(airship=self.airship)
     schedule.name = 'test schedule name'
     schedule.push = cas
     schedule.schedule = ua.scheduled_time(
         datetime.datetime(2025, 10, 8, 12, 15)
         )
     self.assertEqual(
         schedule.payload,
         {
             'schedule': {
                 'scheduled_time': '2025-10-08T12:15:00'
             },
             'name': 'test schedule name',
             'push': {
                 'audience': {
                     'create_and_send': [
                         {
                             'ua_msisdn': '15035556789',
                             'ua_sender': '12345',
                             'ua_opted_in': '2018-02-13T11:58:59'
                         },
                         {
                             'ua_msisdn': '15035556788',
                             'ua_sender': '12345',
                             'ua_opted_in': '2018-02-13T11:58:59'
                         },
                         {
                             'ua_msisdn': '15035556787',
                             'ua_sender': '12345',
                             'ua_opted_in': '2018-02-13T11:58:59'
                         },
                     ]
                 },
                 'notification': {'alert': 'test sms'},
                 'device_types': ['sms'],
                 'campaigns': {
                     'categories': ['sms', 'offers']
                 }
             }
         }
     )
Ejemplo n.º 23
0
class test_error_response(unittest.TestCase):
    test_channel = str(uuid.uuid4())
    airship = ua.Airship(TEST_KEY, TEST_SECRET)
    common_push = airship.create_push()
    common_push.device_types = ua.device_types('ios', 'android', 'amazon')
    common_push.audience = ua.channel(test_channel)
    common_push.notification = ua.notification(alert='testing')

    def test_unauthorized(self):
        with mock.patch.object(ua.Airship, '_request') as mock_request:
            response = requests.Response()
            response._content = json.dumps({
                'ok': False
            }).encode('utf-8')
            response.status_code = 401
            mock_request.return_value = response

            try:
                self.common_push.send()
            except Exception as e:
                self.assertIsInstance(ua.Unauthorized, e)

    def test_client_error(self):
        with mock.patch.object(ua.Airship, '_request') as mock_request:
            response = requests.Response()
            response._content = json.dumps({
                'ok': False
            }).encode('utf-8')
            response.status_code = 400
            mock_request.return_value = response

            try:
                r = self.common_push.send()
            except Exception as e:
                self.assertIsInstance(ua.AirshipFailure, e)
                self.assertEqual(r.status_code, 400)

    def test_server_error(self):
        with mock.patch.object(ua.Airship, '_request') as mock_request:
            response = requests.Response()
            response._content = json.dumps({
                'ok': False
            }).encode('utf-8')
            response.status_code = 500
            mock_request.return_value = response

            try:
                r = self.common_push.send()
            except Exception as e:
                self.assertIsInstance(ua.AirshipFailure, e)
                self.assertEqual(r.status_code, 500)
Ejemplo n.º 24
0
def send_push_notification(receiver, message):
    if AirshipToken.objects.filter(user=receiver, expired=False).exists():
        try:
            device_tokens = list(AirshipToken.objects.filter(user=receiver, expired=False).values_list('token', flat=True))
            airship = urbanairship.Airship(settings.AIRSHIP_APP_KEY, settings.AIRSHIP_APP_MASTER_SECRET)

            for device_token in device_tokens:
                push = airship.create_push()
                push.audience = urbanairship.device_token(device_token)
                push.notification = urbanairship.notification(ios=urbanairship.ios(alert=message, badge='+1'))
                push.device_types = urbanairship.device_types('ios')
                push.send()
        except urbanairship.AirshipFailure:
            pass
Ejemplo n.º 25
0
 def test_sms_inline_template(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_sms_objs
     )
     cas.notification = ua.notification(sms=ua.sms(
         template_alert=self.template_alert
     ))
     cas.device_types = ua.device_types('sms')
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_msisdn': '15035556789',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_msisdn': '15035556788',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_msisdn': '15035556787',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                 ]
             },
             'notification': {
                 'sms': {
                     'template': {
                         'fields': {
                             'alert': '{{name}} you are late for your {{event}}'
                         }
                     }
                 }
             },
             'device_types': ['sms']
         }
     )
Ejemplo n.º 26
0
    def test_email_missing_device_type(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            email=ua.email(message_type='transactional',
                           plaintext_body='hello',
                           reply_to='*****@*****.**',
                           sender_address='*****@*****.**',
                           sender_name='test_name',
                           subject='hi',
                           html_body='<html>so rich!</html>'))
        p.device_types = ua.device_types('ios')

        with self.assertRaises(ValueError):
            p.send()
Ejemplo n.º 27
0
    def pushNotification(self, resp, no_update_list):
        '''push notification'''
        resp.response.out.write("<br/>Start Pushing Notification <br/>")
        airship = ua.Airship('LTjlWamyTzyBHhVmzMLu_A','OB3h24o3RYOan5-JQWdVGQ')
        push = airship.create_push()
        push.device_types = ua.device_types('ios','android')
#        if len(no_update_list) == 0:
#            push.audience = ua.tag('260')
#            push.notification = ua.notification(alert="FAWN TESTING")
        for data in no_update_list:
            message = """%s is offline with FAWN for 2 hours.""" %(data[2])
            resp.response.out.write(message)
            push.audience = ua.tag(data[0])
            push.notification = ua.notification(alert = message)
            push.send()
Ejemplo n.º 28
0
    def test_mixed_platforms(self):
        email_channel = ua.Email(
            self.airship,
            address='*****@*****.**',
            commercial_opted_in=self.test_optin_datestring)
        mixed_channels = self.test_sms_objs
        mixed_channels.append(email_channel)

        cas = ua.CreateAndSendPush(
            self.airship,
            channels=mixed_channels
        )
        cas.device_types = ua.device_types('sms')
        cas.notification = ua.notification(alert='test sms')

        with self.assertRaises(TypeError):
            cas.payload
Ejemplo n.º 29
0
    def test_sms_push_to_sender(self):
        p = ua.Push(None)
        p.audience = ua.sms_sender('12345')
        p.notification = ua.notification(
            alert='sending sms to all with sender')
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload, {
                'audience': {
                    'sms_sender': '12345'
                },
                'device_types': ['sms'],
                'notification': {
                    'alert': 'sending sms to all with sender'
                }
            })
Ejemplo n.º 30
0
def create_notification(type, source_id, from_user, for_user, message=None):

        notification = Notification(type=type,
                                    source_id=source_id,
                                    from_user=from_user, for_user=for_user,
                                    message=message, seen=False, action_taken=False)

        notification.save()

        extra = {
            "id": notification.id,
            "type": notification.type
        }

        app_key = settings.UA['app_key']
        master_secret = settings.UA['master_secret']

        logger.debug("app_key")
        logger.debug(app_key)

        logger.debug("master_secret")
        logger.debug(master_secret)

        airship = ua.Airship(app_key, master_secret)
        devices = for_user.user_devices.all()
        for device in devices:
            logger.debug("push_token")
            logger.debug(device.push_token)
            if device.push_token:
                push = airship.create_push()
                if device.device_type == 'iOS':
                    push.audience = ua.device_token(device.push_token)
                elif device.device_type == 'Android':
                    push.audience = ua.apid(device.push_token)

                push.notification = ua.notification(ios=ua.ios(alert=message,
                                                               badge="+1",
                                                               extra=extra),
                                                    android=ua.android(alert=message,
                                                                       extra=extra))
                push.device_types = ua.device_types('ios', 'android', )
                logger.debug("push response")
                logger.debug(push.send())

        return notification
Ejemplo n.º 31
0
    def test_sms_without_optin(self):
        no_opt_in_sms = ua.Sms(
            airship=self.airship,
            sender=self.test_sms_sender,
            msisdn=self.test_sms_msisdns[0]
        )
        channels = self.test_sms_objs
        channels.append(no_opt_in_sms)

        cas = ua.CreateAndSendPush(
            self.airship,
            channels=channels
        )
        cas.device_types = ua.device_types('sms')
        cas.notification = ua.notification(alert='test sms')

        with self.assertRaises(ValueError):
            cas.payload
Ejemplo n.º 32
0
    def test_email_missing_device_type(self):
        p = ua.Push(None)
        p.audience = ua.all_
        p.notification = ua.notification(
            email=ua.email(
                message_type='transactional',
                plaintext_body='hello',
                reply_to='*****@*****.**',
                sender_address='*****@*****.**',
                sender_name='test_name',
                subject='hi',
                html_body='<html>so rich!</html>'
            )
        )
        p.device_types = ua.device_types('ios')

        with self.assertRaises(ValueError):
            p.send()
Ejemplo n.º 33
0
def publish(user, publication):
    """Send notifaction to followers on publication"""
    followers = user.followers.all()
    for follower in followers:
        airship = ua.Airship(settings.URBANAIRSHIP_KEY,
                             settings.URBANAIRSHIP_MASTER_SECRET)
        push = airship.create_push()
        push.notification = ua.notification(ios=ua.ios(
            alert="New publication from {}".format(user.username),
            badge='+1',
            extra={'url': publication.pk},
        ))
        push.device_types = ua.device_types('ios')
        devices = models.Device.objects.filter(profile=follower.profile)
        if devices.exists():
            device = devices[0]
            if device.chanid and device.chanid != "{}":
                push.audience = ua.ios_channel(device.chanid)
                push.send()
Ejemplo n.º 34
0
 def test_open_inline_template(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_open_channel_objs
     )
     cas.notification = ua.notification(open_platform={'foo': ua.open_platform(
         template_alert=self.template_alert
     )})
     cas.device_types = ua.device_types('open::foo')
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3907',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3908',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3909',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     }
                 ]
             },
             'notification': {
                 'open::foo': {
                     'template': {
                         'fields': {
                             'alert': '{{name}} you are late for your {{event}}'
                         }
                     }
                 }
             },
             'device_types': ['open::foo']
         }
     )
Ejemplo n.º 35
0
    def test_sms_push_to_sender(self):
        p = ua.Push(None)
        p.audience = ua.sms_sender('12345')
        p.notification = ua.notification(
            alert='sending sms to all with sender'
        )
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload,
            {
                'audience': {
                    'sms_sender': '12345'
                },
                'device_types': ['sms'],
                'notification': {
                    'alert': 'sending sms to all with sender'
                }
            }
        )
Ejemplo n.º 36
0
    def test_sms_push_to_id(self):
        p = ua.Push(None)
        p.audience = ua.sms_id('01230984567', '12345')
        p.notification = ua.notification(
            alert='send sms to id with sender and msisdn')
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload, {
                'audience': {
                    'sms_id': {
                        'sender': '12345',
                        'msisdn': '01230984567'
                    }
                },
                'device_types': ['sms'],
                'notification': {
                    'alert': 'send sms to id with sender and msisdn'
                }
            })
Ejemplo n.º 37
0
 def test_sms_send(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_sms_objs
     )
     cas.notification = ua.notification(
         alert='test sms'
     )
     cas.device_types = ua.device_types('sms')
     cas.campaigns = ua.campaigns(
         categories=['sms', 'offers']
     )
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_msisdn': '15035556789',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59'
                     },
                     {
                         'ua_msisdn': '15035556788',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59'
                     },
                     {
                         'ua_msisdn': '15035556787',
                         'ua_sender': '12345',
                         'ua_opted_in': '2018-02-13T11:58:59'
                     },
                 ]
             },
             'notification': {'alert': 'test sms'},
             'device_types': ['sms'],
             'campaigns': {
                 'categories': ['sms', 'offers']
             }
         }
     )
Ejemplo n.º 38
0
    def test_sms_push_to_id(self):
        p = ua.Push(None)
        p.audience = ua.sms_id('01230984567', '12345')
        p.notification = ua.notification(
            alert='send sms to id with sender and msisdn'
        )
        p.device_types = ua.device_types('sms')

        self.assertEqual(
            p.payload,
            {
                'audience': {
                    'sms_id': {
                        'sender': '12345',
                        'msisdn': '01230984567'
                    }
                },
                'device_types': ['sms'],
                'notification': {
                    'alert': 'send sms to id with sender and msisdn'
                }
            }
        )
Ejemplo n.º 39
0
 def test_open_channel_send(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_open_channel_objs,
     )
     cas.notification = ua.notification(
         alert='test open channel'
     )
     cas.device_types = ua.device_types('open::foo')
     cas.campaigns = ua.campaigns(
         categories=['foo', 'bar', 'baz']
     )
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3907'
                     },
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3908'
                     },
                     {
                         'ua_address': 'bfecbb67-5352-4582-a95d-24e4760a3909'
                     }
                 ]
             },
             'device_types': ['open::foo'],
             'notification': {
                 'alert': 'test open channel'
             },
             'campaigns': {
                 'categories': ['foo', 'bar', 'baz']
             }
         }
     )
Ejemplo n.º 40
0
def push_notification(devices: list, title: str, message: str, extra: dict):
    push = airship.create_push()
    push.device_types = ua.device_types(*DeviceType.choices_list())

    channels = [ua.android_channel(device.channel_id) for device in devices if device.device_type == 'android'] + \
               [ua.ios_channel(device.channel_id) for device in devices if device.device_type == 'ios']

    if len(channels) == 0:
        return

    push.audience = ua.and_(*channels)

    push.notification = ua.notification(
        alert=message,
        android=ua.android(alert=message,
                           title=title,
                           extra={'payload': json.dumps(extra)}),
        ios=ua.ios(alert=message,
                   title=title,
                   extra={'payload': json.dumps(extra)}))
    # print(push.payload)
    response = push.send()
    print(response.ok)
    return response
Ejemplo n.º 41
0
import urbanairship as ua

airship = ua.Airship(app_key, master_secret)
push = airship.create_push()
push.audience = ua.all_
push.notification = ua.notification(alert="Hello iOS! I am an API")
push.device_types = ua.device_types('ios')
push.send()
print("Sent notification to all iOS devices")
Ejemplo n.º 42
0
 def test_all_device_types(self):
     self.assertEqual(ua.device_types(ua.all_), 'all')
Ejemplo n.º 43
0
 def test_email_open_inline_template(self):
     cas = ua.CreateAndSendPush(
         airship=self.airship,
         channels=self.test_email_objs
     )
     cas.device_types = ua.device_types('email')
     cas.notification = ua.notification(
         email=ua.email(
             message_type='commercial',
             plaintext_body='{{name}} you are late for {{event}}',
             reply_to='*****@*****.**',
             sender_address='*****@*****.**',
             sender_name='test sender',
             subject='this is an email',
             variable_defaults=[
                 {
                     'key': 'name',
                     'default_value': 'hello'
                 },
                 {
                     'key': 'event',
                     'default_value': 'event'
                 }
             ]
         )
     )
     self.assertEqual(
         cas.payload,
         {
             'audience': {
                 'create_and_send': [
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     },
                     {
                         'ua_address': '*****@*****.**',
                         'ua_commercial_opted_in': '2018-02-13T11:58:59',
                         'name': 'bruce',
                         'event': 'zoom meeting'
                     }
                 ]
             },
             'device_types': ['email'],
             'notification': {
                 'email': {
                     'message_type': 'commercial',
                     'sender_name': 'test sender',
                     'sender_address': '*****@*****.**',
                     'reply_to': '*****@*****.**',
                     'template': {
                         'variable_defaults': [
                             {
                                 'key': 'name',
                                 'default_value': 'hello'
                             },
                             {
                                 'key': 'event',
                                 'default_value': 'event'
                             }
                         ],
                         'fields': {
                             'subject': 'this is an email',
                             'plaintext_body': '{{name}} you are late for {{event}}'
                         }
                     }
                 }
             }
         }
     )