def test_publish_to_interests_should_fail_if_too_many_interests_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_interests(
                 interests=['interest-' + str(i) for i in range(0, 101)],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('Number of interests (101) exceeds maximum',
                       str(e.exception))
 def test_publish_to_interests_should_fail_if_body_not_dict(self):
     pn_client = PushNotifications('INSTANCE_ID', 'SECRET_KEY')
     with self.assertRaises(TypeError) as e:
         pn_client.publish_to_interests(
             interests=['donuts'],
             publish_body=False,
         )
     self.assertIn('publish_body must be a dictionary', str(e.exception))
 def test_publish_to_interests_should_fail_if_no_interests_passed(self):
     pn_client = PushNotifications('INSTANCE_ID', 'SECRET_KEY')
     with self.assertRaises(ValueError) as e:
         pn_client.publish_to_interests(
             interests=[],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('must target at least one interest', str(e.exception))
 def test_publish_to_interests_should_fail_if_interest_not_a_string(self):
     pn_client = PushNotifications('INSTANCE_ID', 'SECRET_KEY')
     with self.assertRaises(TypeError) as e:
         pn_client.publish_to_interests(
             interests=[False],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('Interest False is not a string', str(e.exception))
 def test_publish_to_interests_should_fail_if_interest_too_long(self):
     pn_client = PushNotifications('INSTANCE_ID', 'SECRET_KEY')
     with self.assertRaises(ValueError) as e:
         pn_client.publish_to_interests(
             interests=['A' * 200],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
     self.assertIn('longer than the maximum of 164 chars', str(e.exception))
Exemple #6
0
def push_notify(name,progress,work):
    from pusher_push_notifications import PushNotifications

    beams_client = PushNotifications(
        instance_id='068acacc-d54f-4853-ab93-a2ffbb3b4f89',
        secret_key='2965ADD942C08D08770BD5767E0D2949C0A467B1002DE65179D539F4302759DE',
    )
    response = beams_client.publish_to_interests(
        interests=['hello'],
        publish_body={
            'apns': {
                'aps': {
                    'alert': 'Report created!'
                }
            },
            'fcm': {
                'notification': {
                    'title': str(name),
                    'body': "Progress :" + str(progress) + "work :"+ str(work)
                }
            }
        }
    )

    print(response['publishId'])
def send_push(name, time):

    beams_client = PushNotifications(
        instance_id='97bc1b7f-aa2a-4760-af68-3052371c6dbd',
        secret_key=
        '17482EE2588EE046FBA7E20949EBB4CE00AA2325E6FCDDCD3E34202E0A79A5CB',
    )

    response = beams_client.publish_to_interests(
        interests=['hello'],
        publish_body={
            'apns': {
                'aps': {
                    'alert': 'Hello!'
                }
            },
            'fcm': {
                'notification': {
                    'title': 'New access request',
                    'body': name + " has been requested to open at " + time
                }
            }
        })

    print(response['publishId'])
def add_complaint(request):
    username = request.POST['username']
    password = request.POST['password']

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

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

    title = request.POST['title']
    description = request.POST['description']
    # num_photos = request.POST['num_photos']

    complaint = Complaint.objects.create(resident=user, township=user.township, title=title, description=description,
                                         timestamp=timezone.now(), resolved=False)

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

    response = beams_client.publish_to_interests(
        interests=[str(user.township_id) + '-admins'],
        publish_body={
            'fcm': {
                'notification': {
                    'title': 'New complaint!',
                    'body': user.first_name + ': ' + title,
                },
            },
        },
    )

    return JsonResponse([{'login_status': 1, 'request_status': 1}, {'complaint_id': complaint.id}], safe=False)
Exemple #9
0
def push_not():

    beams_client = PushNotifications(
        instance_id='661a95d4-7499-47b3-9e3f-5a03827fad36',
        secret_key='3300D2F6DE32046A00577E121354FAC46421E5922AFC2E6116D86E3E8BACD5C8',
    )

    response = beams_client.publish_to_interests(
    interests=['hello'],
    publish_body={
        'apns': {
            'aps': {
                'alert': 'Hello!'
            }
        },
        'fcm': {
            'notification': {
                'title': 'Hello',
                'body': 'Hello, World!'
            }
        }
    }
)

    print(response['publishId'])
Exemple #10
0
def send_notification(title, message, topic="notifications"):
    beams_client = PushNotifications(
        instance_id=local_settings.instance_id,
        secret_key=local_settings.secret_key,
    )
    try:
        response = beams_client.publish_to_interests(interests=[topic],
                                                     publish_body={
                                                         'apns': {
                                                             'aps': {
                                                                 'alert': title
                                                             }
                                                         },
                                                         'fcm': {
                                                             'notification': {
                                                                 'title':
                                                                 title,
                                                                 'body':
                                                                 message
                                                             }
                                                         }
                                                     })
        print(response['publishId'])
    except Exception as e:
        print(e)
Exemple #11
0
def push_notify(request):
    from pusher_push_notifications import PushNotifications

    beams_client = PushNotifications(
        instance_id='422713b7-8870-499a-8534-5553787dc86c',
         secret_key='6DACD3113B8FF98826AB73E91EB1BF4EADC216BBB8567B562A065F4BD1E71C60',
    )
    response = beams_client.publish_to_interests(
    interests=['hello'],
    publish_body={
        'apns': {
            'aps': {
                'alert': 'Notification form Dashboard!'
            }
        },
        'fcm': {
            'notification': {
                'title': 'Notification from Dashboard!',
                'body': 'Notification from Dashboard!'
            }
        }
    }
    )

    return HttpResponse('Notification Sent')
Exemple #12
0
def push_notify(request):
    from pusher_push_notifications import PushNotifications
    print("Push notify called!")
    beams_client = PushNotifications(
        instance_id='422713b7-8870-499a-8534-5553787dc86c',
        secret_key=
        '6DACD3113B8FF98826AB73E91EB1BF4EADC216BBB8567B562A065F4BD1E71C60',
    )
    print([request.POST.get("interest", "null")])
    response = beams_client.publish_to_interests(
        interests=list([request.POST.get("interest", "null")]),
        # interests=['hello'],
        publish_body={
            'apns': {
                'aps': {
                    'alert': 'Notification form Dashboard!'
                }
            },
            'fcm': {
                'notification': {
                    'title':
                    str(request.POST.get("username", "not found")),
                    'body':
                    str("Alert: " + request.POST.get("age", "null") +
                        " years old.")
                }
            }
        })
    return HttpResponse("Pass!")
def add_notice(request):
    username = request.POST['username']
    password = request.POST['password']

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

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

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

    title = request.POST['title']
    description = request.POST['description']
    num_wings = request.POST['num_wings']
    notice = Notice.objects.create(title=title, description=description, timestamp=timezone.now(), posted_by=user,
                                   township=user.township)

    beams_interests = [str(user.township_id) + '-admins']

    for i in range(int(num_wings)):
        wing = Wing.objects.get(pk=request.GET['wing_' + str(i) + '_id'])
        beams_interests.append(str(user.township_id) + '-' + str(wing.id) + '-residents')
        notice.wings.add(wing)

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

    response = beams_client.publish_to_interests(
        interests=beams_interests,
        publish_body={
            'fcm': {
                'notification': {
                    'title': 'New notice!',
                    'body': title + ': ' + description,
                },
            },
        },
    )

    def generate_dict(notice):
        data_dict = {}
        data_dict['notice_id'] = notice.id
        data_dict['posted_by_first_name'] = notice.posted_by.first_name
        data_dict['posted_by_last_name'] = notice.posted_by.last_name
        data_dict['posted_by_designation'] = notice.posted_by.designation
        data_dict['timestamp'] = notice.timestamp
        data_dict['title'] = notice.title
        data_dict['description'] = notice.description
        # data_dict['wings'] = [{'wing_id': wing.id, 'wing_name': wing.name} for wing in wings]
        return data_dict

    wings = notice.wings.all()

    return JsonResponse(
        [{'login_status': 1, 'request_status': 1}, generate_dict(notice), [{'wing_id': wing.id} for wing in wings]],
        safe=False)
 def test_publish_to_interests_should_succeed_if_100_interests_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_interests(
             interests=['interest-' + str(i) for i in range(0, 100)],
             publish_body={
                 'apns': {
                     'aps': {
                         'alert': 'Hello World!',
                     },
                 },
             },
         )
 def test_publish_to_interests_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_interests(
                 interests=['donuts'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('The server returned a malformed response',
                       str(e.exception))
 def test_publish_to_interests_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_interests(
                 interests=['donuts'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('Unknown error: no description', str(e.exception))
Exemple #17
0
class PusherBeamsClient:
    def __init__(self):
        (
            pusher_beams_instance_id,
            pusher_beams_secret_key,
        ) = load_pusher_beams_config()

        self.pusher_beams_client = PushNotifications(
            instance_id=pusher_beams_instance_id,
            secret_key=pusher_beams_secret_key,
        )

    def send_new_class_notification(self, title: str, body: str):
        interests = ["nueva-clase"]
        publish_body = {
            "apns": {
                "aps": {
                    "alert": {
                        "title": title,
                        "body": body,
                    },
                },
            },
            "fcm": {
                "notification": {
                    "title": title,
                    "body": body,
                },
            },
            "web": {
                "notification": {
                    "title": title,
                    "body": body,
                },
            },
        }
        self.pusher_beams_client.publish_to_interests(interests, publish_body)
 def test_publish_to_interests_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_interests(
                 interests=['donuts'],
                 publish_body={
                     'apns': {
                         'aps': {
                             'alert': 'Hello World!',
                         },
                     },
                 },
             )
         self.assertIn('Instance not found: blah', str(e.exception))
def lambda_handler(event, context):
    beams_client = PushNotifications(
        instance_id='YOUR_INSTANCE_ID',
        secret_key='YOUR_SECRET_KEY',
    )

    response = beams_client.publish_to_interests(
        interests=['hello'],
        publish_body={
            'fcm': {
                'notification': {
                    'title': event['title'],
                    'body': event['message'],
                },
            },
        },
    )
    print(response['publishId'])
Exemple #20
0
def notify(name):
    pn_client = PushNotifications(
        instance_id='d565ede4-c39f-4978-8d91-2b249efd7eee',
        secret_key=
        'ACD47A2B2F277C3EFE35FC53535019E716E43CF0085F18A1FFC24C893FC7F943',
    )
    response = pn_client.publish_to_interests(interests=['51403072'],
                                              publish_body={
                                                  'apns': {
                                                      'aps': {
                                                          'alert': 'Hello!'
                                                      }
                                                  },
                                                  'fcm': {
                                                      "data": {
                                                          "body":
                                                          "Xin chao " + name,
                                                          "title":
                                                          "Hello+" + name
                                                      }
                                                  }
                                              })
Exemple #21
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
    except ValueError:
        pass
    title = req_body.get('title')
    message = req_body.get('message')
    beams_client = PushNotifications(
        instance_id='YOUR_INSTANCE_ID',
        secret_key='YOUR_SECRET_KEY',
    )
    response = beams_client.publish_to_interests(interests=['hello'],
                                                 publish_body={
                                                     'fcm': {
                                                         'notification': {
                                                             'title': title,
                                                             'body': message,
                                                         },
                                                     },
                                                 })
    return func.HttpResponse(f"Sent message {title}, {message}")
Exemple #22
0
def push_notify(post,c_id):
    print("hello")
    from pusher_push_notifications import PushNotifications

    beams_client = PushNotifications(
        instance_id='e5e2e6cd-9f3b-449e-a850-3931a46fedc0',
        secret_key='6F61EE51B348051B01FF3C05DB4ED0009322EFBC70A0592CE89E422F21750255',
    )

    response = beams_client.publish_to_interests(
        interests=[c_id],
        publish_body={
            'apns': {
                'aps': {
                    'alert': 'Message from '+ str(post.instructor)
                }
            },
            'fcm': {
                'notification': {
                    'title': c_id,
                    'body': post.body
                },
                'data': {
                    'title' : c_id,
                    'notifId' : post.id,
                    'date': post.date,
                    'body': post.body,
                    'course': c_id
                }  
            },
            'android':{
                'priority':post.priority
            }
        }
    )

    print(response['publishId'])
Exemple #23
0
    def sendNotification(self, email):
        beams_client = PushNotifications(
            instance_id='7032df3e-e5a8-494e-9fc5-3b9f05a68e3c',
            secret_key=
            '8AC9B8AABB93DFE452B2EFC2714FCF923841B6740F97207F4512F240264FF493',
        )

        response = beams_client.publish_to_interests(
            interests=[email.replace('.', '')],
            publish_body={
                'apns': {
                    'aps': {
                        'alert': {
                            'title':
                            'choose2reuse',
                            'body':
                            'One of your containers has been verified as returned!',
                        },
                    },
                },
                'fcm': {
                    'notification': {
                        'title':
                        'choose2reuse',
                        'body':
                        'One of your containers has been verified as returned!',
                    },
                },
                'web': {
                    'notification': {
                        'title': 'Hello',
                        'body': 'Hello, world!',
                    },
                },
            },
        )
        print('success', response['publishId'])
    def test_publish_to_interests_should_fail_if_interest_contains_invalid_chars(
            self):
        pn_client = PushNotifications('INSTANCE_ID', 'SECRET_KEY')
        with self.assertRaises(ValueError) as e:
            pn_client.publish_to_interests(
                interests=['bad:interest'],
                publish_body={
                    'apns': {
                        'aps': {
                            'alert': 'Hello World!',
                        },
                    },
                },
            )
        self.assertIn('"bad:interest" contains a forbidden character',
                      str(e.exception))

        with self.assertRaises(ValueError) as e:
            pn_client.publish_to_interests(
                interests=['bad|interest'],
                publish_body={
                    'apns': {
                        'aps': {
                            'alert': 'Hello World!',
                        },
                    },
                },
            )
        self.assertIn('"bad|interest" contains a forbidden character',
                      str(e.exception))

        with self.assertRaises(ValueError) as e:
            pn_client.publish_to_interests(
                interests=['bad(interest)'],
                publish_body={
                    'apns': {
                        'aps': {
                            'alert': 'Hello World!',
                        },
                    },
                },
            )
        self.assertIn('"bad(interest)" contains a forbidden character',
                      str(e.exception))
Exemple #25
0
def pushNotifyAll(request, title, bodymsg):
    from pusher_push_notifications import PushNotifications

    beams_client = PushNotifications(
        instance_id='a3c258e1-27c2-4053-88a1-6d644fbf78d5',
        secret_key=
        'E922B25E4167019F9CA1A482F9B1689A2E90E19FC4253BD184F545C76D15D78C',
    )
    response = beams_client.publish_to_interests(interests=['hello'],
                                                 publish_body={
                                                     'apns': {
                                                         'aps': {
                                                             'alert': 'alert'
                                                         }
                                                     },
                                                     'fcm': {
                                                         'notification': {
                                                             'title': title,
                                                             'body': bodymsg
                                                         }
                                                     }
                                                 })

    return HttpResponse("push msg")
def notify(name,code, time, image_path, hour, minute, seconds, day, month, year):
    service = google_drive.get_service()

    image_id = google_drive.upload_file(name+"_"+code+"_"+time,image_path,service) 
    pn_client = PushNotifications(
        instance_id='d565ede4-c39f-4978-8d91-2b249efd7eee',
        secret_key='ACD47A2B2F277C3EFE35FC53535019E716E43CF0085F18A1FFC24C893FC7F943',
    )
    print("Push a message to {}".format(code))
    response = pn_client.publish_to_interests(
        interests=[code],
        publish_body={
            'apns': {
                'aps': {
                    'alert': 'Hello!'
                }
            },
            'fcm': {
                
                "data": {
                    "body":"Em "+name +" đã có mặt tại trường lúc: ",
                    "title":"Xin chào phụ huynh em "+name,
                    "image_id": image_id,
                    "time": time,
                    "code": code,
                    "name": name,
                    "day": day,
                    "month": month,
                    "year": year,
                    "hour": hour,
                    "minute": minute,
                    "seconds": seconds
                }
            }
        }
    )
Exemple #27
0
for b in need_to_be_messaged:
    response = beams_client.publish_to_interests(
        interests=[b],
        publish_body={
            'apns': {
                'aps': {
                    'alert': {
                        'title':
                        'choose2reuse',
                        'body':
                        'You have a container that has been checked out for over 48 hours, please consider returning it!',
                    },
                },
            },
            'fcm': {
                'notification': {
                    'title':
                    'choose2reuse',
                    'body':
                    'You have a container that has been checked out for over 48 hours, please consider returning it!',
                },
            },
            'web': {
                'notification': {
                    'title': 'Hello',
                    'body': 'Hello, world!',
                },
            },
        },
    )
    print(response['publishId'])
    def test_publish_to_interests_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_interests(
                interests=['donuts'],
                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/interests',
        )
        self.assertDictEqual(
            headers,
            {
                'content-type': 'application/json',
                'content-length': '69',
                'authorization': 'Bearer SECRET_KEY',
                'x-pusher-library': 'pusher-push-notifications-python 2.0.1',
                'host': 'instance_id.pushnotifications.pusher.com',
            },
        )
        self.assertDictEqual(
            body,
            {
                'interests': ['donuts'],
                'apns': {
                    'aps': {
                        'alert': 'Hello World!',
                    },
                },
            },
        )
        self.assertDictEqual(
            response,
            {
                'publishId': '1234',
            },
        )
Exemple #29
0
    instance_id='4eacff80-61d8-48d7-ba72-9e7aede4119c',
    secret_key=
    '4A9C78664B4FCC25397DD2F780028D9967F69BA4229736B49420727081646EFC',
)
response = beams_client.publish_to_interests(
    interests=['hello'],
    publish_body={
        'apns': {
            'aps': {
                'alert': {
                    'title': 'Hello',
                    'body': 'Hello, world!',
                },
            },
        },
        'fcm': {
            'notification': {
                'title': 'Hello',
                'body': 'Hello, world!',
            },
        },
        'web': {
            'notification': {
                'title': 'Hello',
                'body': 'Hello, world!',
            },
        },
    },
)

print(response['publishId'])