def send_notification_to_user(user, payload, ttl=0): # Get all the push_info of the user errors = [] push_infos = user.webpush_info.select_related("subscription") for push_info in push_infos: try: _send_notification(push_info.subscription, payload, ttl) except WebPushException as ex: errors.append(dict(subscription=push_info.subscription, exception=ex)) if errors: raise WebPushException("Push failed.")
def test_exception(self): from requests import Response exp = WebPushException("foo") assert ("{}".format(exp) == "WebPushException: foo") # Really should try to load the response to verify, but this mock # covers what we need. response = Mock(spec=Response) response.text = ('{"code": 401, "errno": 109, "error": ' '"Unauthorized", "more_info": "http://' 'autopush.readthedocs.io/en/latest/htt' 'p.html#error-codes", "message": "Requ' 'est did not validate missing authoriz' 'ation header"}') response.json.return_value = json.loads(response.text) response.status_code = 401 response.reason = "Unauthorized" exp = WebPushException("foo", response) assert "{}".format(exp) == "WebPushException: foo, Response {}".format( response.text) assert '{}'.format(exp.response), '<Response [401]>' assert exp.response.json().get('errno') == 109 exp = WebPushException("foo", [1, 2, 3]) assert '{}'.format(exp) == "WebPushException: foo, Response [1, 2, 3]"
def send_notification_to_group(group_name, payload, ttl=0): from .models import Group # Get all the subscription related to the group errors = [] push_infos = Group.objects.get(name=group_name).webpush_info.select_related("subscription") for push_info in push_infos: try: _send_notification(push_info.subscription, payload, ttl) except WebPushException as ex: errors.append(dict(subscription=push_info.subscription, exception=ex)) if errors: raise WebPushException("Push failed.")
def SendNotification(request): try: user_obj = request.user if not request.user.is_authenticated(): user_obj = User.objects.get(username='******') pushinfo_objs = user_obj.pushinfo.select_related("subscription") errors = [] for pushinfo_obj in pushinfo_objs: try: subscription_data = model_to_dict(pushinfo_obj.subscription, exclude=['browser', 'id']) print subscription_data endpoint = subscription_data['endpoint'] p256dh = subscription_data['p256dh'] auth = subscription_data['auth'] final_subscription_data = { 'endpoint': endpoint, 'keys': {'auth': auth, 'p256dh': p256dh} } vapid_data = {} vapid_settings = getattr(settings, 'VAPID_SETTINGS', {}) vapid_private_key = vapid_settings.get('VAPID_PRIVATE_KEY') vapid_admin_email = vapid_settings.get('VAPID_ADMIN_EMAIL') if vapid_private_key: vapid_data = { 'vapid_private_key': vapid_private_key, 'vapid_claims': {"sub": "mailto:{}".format(vapid_admin_email)} } payload = {'head': 'Web Push Example', 'body': 'Hell Yeah! Notification Works!'} req = webpush(subscription_info=final_subscription_data, data=json.dumps(payload), ttl=0, **vapid_data) except WebPushException as ex: errors.append(dict(subscription=pushinfo_obj.subscription, exception=ex)) if errors: raise WebPushException("Push failed.", extra=errors) return JsonResponse(status=200, data={"message": "Web push successful"}) except TypeError: return JsonResponse(status=500, data={"message": "An error occurred"})
def test_push_if_timeout(self, member): sub = PushSubscription.objects.create( user=member.member, community=member.community, endpoint="http://xyz.com", auth="auth", p256dh="xxx", ) payload = {"head": "hello", "body": "testing"} e = WebPushException("BOOM", response=mock.Mock(status_code=410)) with mock.patch("localhub.notifications.models.webpush", side_effect=e): assert not sub.push(payload) assert not PushSubscription.objects.exists()