Beispiel #1
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
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 #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 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 #6
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 #7
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 #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")
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 #10
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 #11
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 #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.')})
Beispiel #13
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")
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)