Example #1
0
 def test_publish_should_fail_if_too_many_user_ids_passed(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with requests_mock.Mocker() as http_mock:
         http_mock.register_uri(
             requests_mock.ANY,
             requests_mock.ANY,
             status_code=200,
             json={
                 'publishId': '1234',
             },
         )
         with self.assertRaises(ValueError) as e:
             pn_client.publish_to_users(
                 user_ids=['user-' + str(i) for i in range(0, 1001)],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn(
             'Number of user ids (1001) exceeds maximum',
             str(e.exception),
         )
Example #2
0
 def test_publish_to_users_should_fail_if_body_not_dict(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with self.assertRaises(TypeError) as e:
         pn_client.publish_to_users(
             user_ids=['alice'],
             publish_body=False,
         )
     self.assertIn('publish_body must be a dictionary', str(e.exception))
Example #3
0
def pushNotifyUser(name, progress, work):
    from pusher_push_notifications import PushNotifications

    beams_client = PushNotifications(
        instance_id='a3c258e1-27c2-4053-88a1-6d644fbf78d5',
        secret_key=
        'E922B25E4167019F9CA1A482F9B1689A2E90E19FC4253BD184F545C76D15D78C',
    )
    response = beams_client.publish_to_users(user_ids=['user-0001'],
                                             publish_body={
                                                 'apns': {
                                                     'aps': {
                                                         'alert': 'Hello!'
                                                     }
                                                 },
                                                 'fcm': {
                                                     'notification': {
                                                         'title': 'Hello',
                                                         'body':
                                                         'Hello, World!'
                                                     }
                                                 }
                                             })

    print(response['publishId'])
Example #4
0
 def test_publish_to_users_should_fail_if_user_id_too_long(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with self.assertRaises(ValueError) as e:
         pn_client.publish_to_users(
             user_ids=['A'*165],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('longer than the maximum of 164 chars', str(e.exception))
Example #5
0
 def test_publish_to_users_should_fail_if_user_id_not_a_string(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with self.assertRaises(TypeError) as e:
         pn_client.publish_to_users(
             user_ids=[False],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('User id False is not a string', str(e.exception))
Example #6
0
 def test_publish_to_users_should_fail_if_no_users_passed(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with self.assertRaises(ValueError) as e:
         pn_client.publish_to_users(
             user_ids=[],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('must target at least one user', str(e.exception))
Example #7
0
 def test_publish_to_users_should_fail_if_user_ids_not_list(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with self.assertRaises(TypeError) as e:
         pn_client.publish_to_users(
             user_ids=False,
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('user_ids must be a list', str(e.exception))
Example #8
0
 def test_publish_to_users_should_handle_not_json_success(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with requests_mock.Mocker() as http_mock:
         http_mock.register_uri(
             requests_mock.ANY,
             requests_mock.ANY,
             status_code=200,
             text='<notjson></notjson>',
         )
         with self.assertRaises(PusherBadResponseError) as e:
             pn_client.publish_to_users(
                 user_ids=['alice'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('The server returned a malformed response', str(e.exception))
Example #9
0
 def test_publish_to_users_should_error_correctly_if_error_not_json(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with requests_mock.Mocker() as http_mock:
         http_mock.register_uri(
             requests_mock.ANY,
             requests_mock.ANY,
             status_code=500,
             text='<notjson></notjson>',
         )
         with self.assertRaises(PusherServerError) as e:
             pn_client.publish_to_users(
                 user_ids=['alice'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('Unknown error: no description', str(e.exception))
Example #10
0
 def test_publish_to_users_should_raise_on_http_404_error(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with requests_mock.Mocker() as http_mock:
         http_mock.register_uri(
             requests_mock.ANY,
             requests_mock.ANY,
             status_code=404,
             json={'error': 'Instance not found', 'description': 'blah'},
         )
         with self.assertRaises(PusherMissingInstanceError) as e:
             pn_client.publish_to_users(
                 user_ids=['alice'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('Instance not found: blah', str(e.exception))
Example #11
0
 def test_publish_to_users_should_succeed_if_1000_users_passed(self):
     pn_client = PushNotifications(
         'INSTANCE_ID',
         'SECRET_KEY'
     )
     with requests_mock.Mocker() as http_mock:
         http_mock.register_uri(
             requests_mock.ANY,
             requests_mock.ANY,
             status_code=200,
             json={
                 'publishId': '1234',
             },
         )
         pn_client.publish_to_users(
             user_ids=['user-' + str(i) for i in range(0, 1000)],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
Example #12
0
def add_visitor_entry(request):
    username = request.POST['username']
    password = request.POST['password']

    user = authenticate(request, username=username, password=password)

    if user is None:
        return JsonResponse([{'login_status': 0}], safe=False)

    if user.type != 'security':
        return JsonResponse([{'login_status': 1, 'authorization': 0}], safe=False)

    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    wing_id = request.POST['wing_id']
    apartment = request.POST['apartment']

    wing = Wing.objects.get(pk=int(wing_id))
    visitor_apartment = User.objects.get(wing=wing, apartment=apartment, township=user.township)

    visitor = Visitor.objects.create(first_name=first_name, last_name=last_name, apartment=visitor_apartment,
                           township=user.township, in_timestamp=timezone.now())

    beams_client = PushNotifications(instance_id=settings.BEAMS_INSTANCE_ID, secret_key=settings.BEAMS_SECRET_KEY)

    response = beams_client.publish_to_users(
        user_ids=[visitor_apartment.username],
        publish_body={
            'fcm': {
                'notification': {
                    'title': 'New visitor!',
                    'body': first_name + ' ' + last_name + ' is here to meet you',
                },
            },
        },
    )

    return JsonResponse([{'login_status': 1, 'request_status': 1, 'visitor_id': visitor.id}, {'visitor_id': visitor.id}], safe=False)
Example #13
0
class BeamsClient:
    beams_client: PushNotifications = None

    def __init__(self):
        self.beams_client = PushNotifications(
            instance_id=os.getenv("PUSHER_INSTANCE_ID"),
            secret_key=os.getenv("PUSHER_SECRET_KEY"),
        )

    def generate_token(self, user_id):
        try:
            beams_token = self.beams_client.generate_token(user_id)
            return beams_token
        except Exception as e:
            print("[GENTK ERROR]", e)
            return None

    def push_notification(self, notification, user_ids):
        try:
            response = self.beams_client.publish_to_users(
                user_ids=user_ids,
                publish_body={
                    "apns": {
                        "aps": {
                            "alert": notification
                        },
                        "data": notification["data"]
                    },
                    "fcm": notification,
                    "web": notification
                },
            )
            return response["publishId"]
        except Exception as e:
            print("[PUSHN ERROR]", e)
            return None
Example #14
0
    def test_publish_to_users_should_make_correct_http_request(self):
        pn_client = PushNotifications(
            'INSTANCE_ID',
            'SECRET_KEY'
        )
        with requests_mock.Mocker() as http_mock:
            http_mock.register_uri(
                requests_mock.ANY,
                requests_mock.ANY,
                status_code=200,
                json={
                    'publishId': '1234',
                },
            )
            response = pn_client.publish_to_users(
                user_ids=['alice'],
                publish_body={
                    'apns': {
                        'aps': {
                            'alert': 'Hello World!',
                        },
                    },
                },
            )
            req = http_mock.request_history[0]

        method = req.method
        path = req.path
        headers = dict(req._request.headers.lower_items())
        body = req.json()

        self.assertEqual(
            method,
            'POST',
        )
        self.assertEqual(
            path,
            '/publish_api/v1/instances/instance_id/publishes/users',
        )
        self.assertDictEqual(
            headers,
            {
                'content-type': 'application/json',
                'content-length': '64',
                'authorization': 'Bearer SECRET_KEY',
                'x-pusher-library': 'pusher-push-notifications-python 2.0.0',
                'host': 'instance_id.pushnotifications.pusher.com',
            },
        )
        self.assertDictEqual(
            body,
            {
                'users': ['alice'],
                'apns': {
                    'aps': {
                        'alert': 'Hello World!',
                    },
                },
            },
        )
        self.assertDictEqual(
            response,
            {
                'publishId': '1234',
            },
        )