class TestSending(unittest.TestCase):
    reg_id_android = settings.TEST_ID_ANDROID
    reg_id_ios = settings.TEST_ID_APPLE

    def setUp(self):
        GCMDevice.objects.filter(registration_id=self.reg_id_android).delete()
        APNSDevice.objects.filter(registration_id=self.reg_id_ios).delete()

        self.android_device = GCMDevice(registration_id=self.reg_id_android)
        self.android_device.save()
        self.ios_device = APNSDevice(registration_id=self.reg_id_ios)
        self.ios_device.save()

    def testGCMDeviceSend(self):
        self.assertRaises(
            HTTPError,
            GCMDevice.objects.filter(registration_id=self.reg_id_android).send_message,
            'test_message',
        )

    def testAPNSDeviceSend(self):
        self.assertRaises(
            SSLError,
            APNSDevice.objects.filter(registration_id=self.reg_id_ios).send_message,
            'test_message',
        )
Beispiel #2
0
 def create_session(self, service, registration_id, device_name):
     try:
         if service == 'android':
             DeviceSession.objects.get(
                 gcm_device__registration_id=registration_id).delete()
         else:
             DeviceSession.objects.get(
                 apns_device__registration_id=registration_id).delete()
     except:
         pass
     session = DeviceSession()
     session.service = 'AN' if service == 'android' else 'IO'
     if service == 'android':
         gcm_device = GCMDevice(registration_id=registration_id,
                                user=self,
                                name=device_name)
         gcm_device.save()
         session.gcm_device = gcm_device
     else:
         apns_device = APNSDevice(registration_id=registration_id,
                                  user=self,
                                  name=device_name)
         apns_device.save()
         session.apns_device = apns_device
     session.save()
     return session
Beispiel #3
0
def register_push_notification_id(request):
	"""
	If the device didn't have the push notification id ready
	when registering then 
	"""
	if request.method == 'POST':
		json_data = json.loads(request.body)

		try:
			device_id = json_data['device_id']
			push_notification_id = json_data['push_notification_id']
		except KeyError:
			print "Error: A posted question did not have a JSON object with the required properties"
		else:
			
			try:
				push_device = APNSDevice.objects.get(registration_id=push_notification_id)
			except APNSDevice.DoesNotExist:
				push_device = APNSDevice(registration_id=push_notification_id, device_id=device_id)
				push_device.save()
			
			# print "Pushing the message"
			# push_device.send_message("F**k yeah, we got push!")
			
			# See if the device id already exists
			# device = Device.objects.filter( device_id=device_id )
			
			return HttpResponse(json.dumps({ 'valid_id' : True }), content_type="application/json")
def add_ios_device(device_token):
    try:
        APNSDevice.objects.get(registration_id=device_token)
    except APNSDevice.DoesNotExist:
        new_device = APNSDevice(registration_id=device_token)
        new_device.save()
    except:
        pass
Beispiel #5
0
def send_push(request):
    one_day_ago = datetime.datetime.today() - datetime.timedelta(days=1)
    new_concerts = YupeConcerts.objects.using('epidemy_legacy').filter(creation_date__gte=one_day_ago)
    for concert in new_concerts:
        center_point = city_coordinates(concert.title)
        fans_for_notifications = Fan.objects.filter(fan_point__dwithin=(center_point, 1.4))
        for fan in fans_for_notifications:
            device = APNSDevice(registration_id=fan.device_token)
            concert_date = concert.date.strftime('%d.%m.%Y')
            message_for_notification = 'Уже {} концерт группы "Эпидемия" в городе {}.'.format(concert_date,
                                                                                              concert.title)
            device.send_message(message_for_notification)
Beispiel #6
0
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        access_token = request.headers.get('Authorization', None)
        payload = jwt.decode(access_token, SECRET_KEY, algorithm='HS256')
        user_pk = SignUpModel.objects.get(id=payload['id']).pk

        if APNSDevice.objects.filter(user_id=user_pk).exists():
            return JsonResponse({'message': '해당 사용자가 이미 있습니다.'}, status=400)
        else:
            device = APNSDevice(user_id=user_pk,
                                registration_id=data['device_token'])
            device.save()
            return HttpResponse(status=200)
Beispiel #7
0
def register_device_token(request, token):
    """
    Adds a new APNS device with the token as the registration ID.
    :param request: HTTPRequest
    :param token: Device Token
    :return: HTTPResponse
    """
    try:
        device = APNSDevice(registration_id=token)
        device.save()
    except IntegrityError:
        return HttpResponseBadRequest()

    return HttpResponse(device.registration_id)
Beispiel #8
0
def register_push_notifications(request, username):
    try:
        profile = Profile.objects.get(username=username)
        props = json.loads(request.body.decode("utf-8"))
        missing = missing_props(props, ["token"])
        if missing: 
            return JsonResponse({"error": "missing properties: {}".format(", ".join(missing))}, status=400)
        profile.device_token = props["token"]
        phone = APNSDevice(registration_id=props['token'])
        phone.save()
        profile.save()
        return JsonResponse(profile.status_json())
    except Profile.DoesNotExist:
        return err("no such user")
Beispiel #9
0
def register_push_notifications(request, username):
    try:
        profile = Profile.objects.get(username=username)
        props = json.loads(request.body.decode("utf-8"))
        missing = missing_props(props, ["token"])
        if missing:
            return JsonResponse(
                {"error": "missing properties: {}".format(", ".join(missing))},
                status=400)
        profile.device_token = props["token"]
        phone = APNSDevice(registration_id=props['token'])
        phone.save()
        profile.save()
        return JsonResponse(profile.status_json())
    except Profile.DoesNotExist:
        return err("no such user")
Beispiel #10
0
def login(request):
    if request.method == 'POST':

        try:
            user = User.objects.get(email=request.DATA["email"])
        except:
            try:
                temp_user = tempUser.objects.get(email=request.DATA["email"])
            except:
                return Response(status=status.HTTP_404_NOT_FOUND)
            return Response(status=status.HTTP_409_CONFLICT)

        try:
            profile = Profile.objects.get(username=user.email)
            usercredit = UserCredit.objects.get(user_id=user.id)
            credit = usercredit.credit
        except:
            credit = 0

        response_data = {}
        response_data['id'] = user.id
        response_data['authToken'] = profile.authToken
        response_data['usercredit'] = credit

        if check_password(request.DATA["password"], user.password):
            if request.DATA["deviceType"] == "Android":
                gcm_id = request.DATA["deviceID"]
                new_device = GCMDevice(user=user, registration_id=gcm_id)
                #check if gcm_id already exists . If so then delete the old device and create new .
                try:
                    old_device = GCMDevice.objects.get(registration_id=gcm_id)
                except:
                    new_device.save()
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json")
                old_device.delete()
                new_device.save()
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")

            elif request.DATA["deviceType"] == "ios":
                apns_id = request.DATA["deviceID"]
                new_device = APNSDevice(user=user, registration_id=apns_id)
                #check if gcm_id already exists . If so then delete the old device and create new .
                try:
                    old_device = APNSDevice.objects.get(
                        registration_id=apns_id)
                except:
                    new_device.save()
                    return HttpResponse(json.dumps(response_data),
                                        content_type="application/json")
                old_device.delete()
                new_device.save()
                return HttpResponse(json.dumps(response_data),
                                    content_type="application/json")
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")

        return Response(status=status.HTTP_401_UNAUTHORIZED)
    def setUp(self):
        GCMDevice.objects.filter(registration_id=self.reg_id_android).delete()
        APNSDevice.objects.filter(registration_id=self.reg_id_ios).delete()

        self.android_device = GCMDevice(registration_id=self.reg_id_android)
        self.android_device.save()
        self.ios_device = APNSDevice(registration_id=self.reg_id_ios)
        self.ios_device.save()
Beispiel #12
0
def connect_device(request):
    try:
        user = request.user

        if not request.user.anonymously:
            user_agent = request.META.get("HTTP_USER_AGENT", "")
            device_uid = request.data.get("device_uid", "")

            if not device_uid:
                error = {
                    "code": 400,
                    "message": _("The device_uid field is required."),
                    "fields": "device_uid"
                }
                return Response(error, status=400)

            if user_agent:
                if 'ios' in user_agent.lower():
                    try:
                        device = APNSDevice.objects.get(
                            registration_id=device_uid)
                        device.user = user
                        device.save()

                    except APNSDevice.DoesNotExist, e:
                        device = APNSDevice(user=user,
                                            name=user.email,
                                            registration_id=device_uid)
                        device.save()
                else:
                    try:
                        device = GCMDevice.objects.get(
                            registration_id=device_uid,
                            cloud_message_type="FCM")
                        device.user = user
                        device.save()

                    except GCMDevice.DoesNotExist, e:
                        device = GCMDevice(user=user,
                                           name=user.email,
                                           registration_id=device_uid,
                                           cloud_message_type="FCM")
                        device.save()
            return Response({'message': _('Connect device successful.')})
class TestModels(unittest.TestCase):
    reg_id_android = settings.TEST_ID_ANDROID
    reg_id_ios = settings.TEST_ID_APPLE

    def setUp(self):
        GCMDevice.objects.filter(registration_id=self.reg_id_android).delete()
        APNSDevice.objects.filter(registration_id=self.reg_id_ios).delete()

        self.android_device = GCMDevice(registration_id=self.reg_id_android)
        self.android_device.save()
        self.ios_device = APNSDevice(registration_id=self.reg_id_ios)
        self.ios_device.save()

    def testGCMDevice(self):
        self.assertEqual(GCMDevice.objects.filter(registration_id=self.reg_id_android).count(), 1)

    def testAPNSDevice(self):
        self.assertEqual(APNSDevice.objects.filter(registration_id=self.reg_id_ios).count(), 1)

    def testGCMDeviceUniqueness(self):
        self.android_device = GCMDevice(registration_id=self.reg_id_android)
        self.assertRaises(ValidationError, self.android_device.save)
Beispiel #14
0
def update_regid(request):

    service = request.POST.get('service', '')
    previous = request.POST.get('previous' '')
    new = request.POST.get('new' '')

    if service == '' or previous == '' or new == '':
        return HttpResponse(status=404)

    if previous == new:
        return HttpResponse(status=400)

    try:
        if service == 'android':
            previous_device = GCMDevice.objects.get(registration_id=previous)
            device_name = previous_device.name
            session = DeviceSession.objects.get(gcm_device=previous_device)
            session.gcm_device.delete()
            gcm_device = GCMDevice(registration_id=new,
                                   user=session.get_user(),
                                   name=device_name)
            gcm_device.save()
            session.gcm_device = gcm_device
        else:
            previous_device = APNSDevice.objects.get(registration_id=previous)
            device_name = previous_device.name
            session = DeviceSession.objects.get(apns_device=previous_device)
            session.apns_device.delete()
            apns_device = APNSDevice(registration_id=new,
                                     user=session.get_user(),
                                     name=device_name)
            apns_device.save()
            session.apns_device = apns_device
        session.save()
    except ObjectDoesNotExist:
        pass

    return HttpResponse(status=200)
Beispiel #15
0
    def update_push_tokens(self, push_tokens_data, api_version):
        if 'apns' in push_tokens_data:
            apns_token = push_tokens_data.get('apns')
            # Delete user devices
            self.delete_apns_devices()
            if apns_token is not None:
                # Delete devices with same apns_token
                APNSDevice.objects.filter(registration_id=apns_token).delete()
                # Create new device for user with apns_token
                apns_device = APNSDevice(registration_id=apns_token, user=self)
                apns_device.api_version = api_version
                apns_device.save()

        if 'gcm' in push_tokens_data:
            gcm_token = push_tokens_data.get('gcm')
            # Delete user devices
            self.delete_gcm_devices()
            if gcm_token is not None:
                # Delete devices with same gcm_token
                GCMDevice.objects.filter(registration_id=gcm_token).delete()
                # Create new gcm device for user with gcm_token
                gcm_device = GCMDevice(registration_id=gcm_token, user=self)
                gcm_device.api_version = api_version
                gcm_device.save()
Beispiel #16
0
    def Register(regid, uuid, name, platform):
        existingDevice = None
        if platform == 'android':
            existingDevice = GCMDevice.objects.filter(registration_id=regid)
        else:
            existingDevice = APNSDevice.objects.filter(registration_id=regid)
        if len(existingDevice) > 0:
            return False

        newDevice = None
        if platform == 'android':
            newDevice = GCMDevice()
        else:
            newDevice = APNSDevice()

        try:
            newDevice.registration_id = regid
            newDevice.device_id = uuid
            newDevice.name = name
            newDevice.save()
            return True
        except Exception, e:
            print e
            return False
Beispiel #17
0
class Command(BaseCommand):
    help = "Create plenty of segments and subscribers for benchmarking"

    def add_arguments(self, parser):
        parser.add_argument(
            "-q",
            "--quantity",
            dest="quantity",
            default=100_000,
            type=int,
            help="The number of subscribers to create",
        )
        parser.add_argument(
            "-b",
            "--batch_size",
            dest="batch_size",
            default=1000,
            type=int,
            help="The batch size for the subscriber creation",
        )

    def handle(self, *args, quantity=100_000, batch_size=1000, **options):
        (segment, created) = Segment.objects.get_or_create(id="fake_emails")
        subscribers = Subscriber.objects.filter(email__startswith="fake_email")

        if subscribers.exists():
            self.stdout.write(
                f"Deleting {subscribers.count()} existing fake subscribers.")
            subscribers.delete()

        self.stdout.write(
            f"Creating {quantity} subscriber objects with batch size {batch_size}."
        )

        batch_size = min(batch_size, quantity)
        objs = (Subscriber(
            email="fake_email" + str(i) + "@example.com",
            subscriber_status=BaseSubscriber.STATUS_SUBSCRIBED,
        ) for i in range(quantity))

        with tqdm(total=quantity) as progress_bar:
            while True:
                batch = list(islice(objs, batch_size))
                if not batch:
                    break
                Subscriber.objects.bulk_create(batch, batch_size)
                progress_bar.update(batch_size)

        self.stdout.write(
            f"Creating {quantity} segment subscriptions with batch size {batch_size}."
        )
        Relation = Subscriber.segments.through
        Relation.objects.filter(segment=segment).delete()
        objs = (Relation(segment=segment, subscriber=subscriber)
                for subscriber in subscribers.all())
        with tqdm(total=quantity) as progress_bar:
            while True:
                batch = list(islice(objs, batch_size))
                if not batch:
                    break
                Relation.objects.bulk_create(batch, batch_size)
                progress_bar.update(batch_size)

        if app_settings.CAMPAIGN_TYPE_PUSH in settings.NUNTIUS_ENABLED_CAMPAIGN_TYPES:
            try:
                from push_notifications.models import APNSDevice, GCMDevice
            except ImportError:
                pass
            else:
                self.stdout.write(
                    f"Creating {quantity} APNS devices with batch size {batch_size}."
                )
                APNSDevice.objects.filter(
                    registration_id__in=subscribers.values_list("email",
                                                                flat=True))
                objs = (APNSDevice(
                    name="",
                    active=True,
                    device_id=uuid.uuid4(),
                    registration_id=subscriber.email,
                ) for subscriber in subscribers.all())
                with tqdm(total=quantity) as progress_bar:
                    while True:
                        batch = list(islice(objs, batch_size))
                        if not batch:
                            break
                        APNSDevice.objects.bulk_create(batch, batch_size)
                        progress_bar.update(batch_size)

                self.stdout.write(
                    f"Creating {quantity} GCM devices with batch size {batch_size}."
                )
                GCMDevice.objects.filter(
                    registration_id__in=subscribers.values_list("email",
                                                                flat=True))
                objs = (GCMDevice(
                    name="",
                    active=True,
                    device_id=hex(subscriber.id),
                    registration_id=subscriber.email,
                ) for subscriber in subscribers.all())
                with tqdm(total=quantity) as progress_bar:
                    while True:
                        batch = list(islice(objs, batch_size))
                        if not batch:
                            break
                        GCMDevice.objects.bulk_create(batch, batch_size)
                        progress_bar.update(batch_size)
def register(request):
    logging.warn('register')
    os_type = get_request_var(request, 'os')
    username = get_request_var(request, 'username')
    registration_id = get_request_var(request, 'registration_id')

    if not username:
        response_dict = error_dict()
        response_dict['error_code'] = 100
        response_dict['error_msg'] = 'Missing username'
        return render_json(request, response_dict)

    if not registration_id:
        response_dict = error_dict()
        response_dict['error_code'] = 200
        response_dict['error_msg'] = 'Missing registration_id'
        return render_json(request, response_dict)

    if not os_type:
        response_dict = error_dict()
        response_dict['error_code'] = 300
        response_dict['error_msg'] = 'Missing os_type'
        return render_json(request, response_dict)

    logging.warn('fetching user')
    user = User.objects.get(username=username)
    if not user:
        response_dict = error_dict()
        response_dict['error_code'] = 400
        response_dict['error_msg'] = 'No user'
        return render_json(request, response_dict)

    if os_type == 'a':
        apns_device = None
        try:
            apns_device = APNSDevice.objects.get(user=user)
            logging.warn('apns device already registered')
        except:
            logging.exception('error getting apns device')
            logging.warn('no existing apns device')

        if apns_device:
            if registration_id != apns_device.registration_id:
                logging.warn('updating apns device with new registration_id')
                apns_device.registration_id = registration_id
                apns_device.save()
        else:
            logging.warn('creating apns device')
            try:
                apns_device = APNSDevice()
                apns_device.user = user
                apns_device.name = user.first_name
                apns_device.registration_id = registration_id
                apns_device.save()
            except:
                logging.exception('error creating apns device')
                response_dict = error_dict()
                response_dict['error_code'] = 500
                response_dict['error_msg'] = 'Error creating apns device'
                return render_json(request, response_dict)
    elif os_type == 'g':
        gcm_device = None
        try:
            gcm_device = GCMDevice.objects.get(user=user)
            logging.warn('gcm device already registered')
        except:
            logging.exception('error getting gcm device')
            logging.warn('no existing gcm device')

        if gcm_device:
            if registration_id != gcm_device.registration_id:
                logging.warn('updating gcm device with new registration_id')
                gcm_device.registration_id = registration_id
                gcm_device.save()
        else:
            logging.warn('creating gcm device')
            try:
                gcm_device = GCMDevice()
                gcm_device.user = user
                gcm_device.name = user.first_name
                gcm_device.registration_id = registration_id
                gcm_device.save()
            except:
                logging.exception('error creating gcm device')
                response_dict = error_dict()
                response_dict['error_code'] = 500
                response_dict['error_msg'] = 'Error creating gcm device'
                return render_json(request, response_dict)
    else:
        response_dict = error_dict()
        response_dict['error_code'] = 600
        response_dict['error_msg'] = 'Unrecognized os_type'
        return render_json(request, response_dict)

    logging.warn('registration done')
    response_dict = success_dict()
    return render_json(request, response_dict)
Beispiel #19
0
def register_apple_device(request):
    registrationID = request.POST.get['registrationID']
    device = APNSDevice(user=request.user, registration_id=registrationID)
    device.save()
    send_message_to_apple_device(request.user, "You have been registered")
Beispiel #20
0
from django_rq import job
from push_notifications.apns import APNSError
from push_notifications.gcm import GCMError
from push_notifications.models import APNSDevice, GCMDevice
from rest_framework.settings import api_settings

from common.constants import (DEVICE_ANDROID, DEVICE_IOS, NotificationType,
                              NOTIFICATION_TYPE_BROADCAST, USER_TYPE_PAGE,
                              NOTIFICATION_TYPE_INCOMING_VIDEO_CALL)
from shoutit.api.serializers import serialize_attached_object
from ..models import User, PushBroadcast, Device
from ..utils import debug_logger, error_logger, UserIds

_apns_devices = GenericRelation('shoutit.Device',
                                related_query_name='apns_devices')
APNSDevice.add_to_class('devices', _apns_devices)

_gcm_devices = GenericRelation('shoutit.Device',
                               related_query_name='gcm_devices')
GCMDevice.add_to_class('devices', _gcm_devices)


@job(settings.RQ_QUEUE_PUSH)
def send_push(user,
              notification,
              version,
              pushed_for=None,
              serializing_options=None):
    from shoutit.controllers.notifications_controller import get_total_unread_count
    from shoutit.controllers import pusher_controller