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',
        )
def push_to_android_devices(title_en,
                            title_pl,
                            message_en,
                            message_pl,
                            notification_type=NOTIFICATION_TYPE_BASIC):
    registration_ids = list(
        GCMDevice.objects.filter(active=True).values_list("registration_id",
                                                          flat=True))
    collapse_key = ''
    if notification_type is NOTIFICATION_TYPE_BASIC:
        collapse_key = 'basic'
    elif notification_type is NOTIFICATION_TYPE_ALERT:
        collapse_key = 'alert'
    elif notification_type is NOTIFICATION_TYPE_UPDATE:
        collapse_key = 'update'
    data = gcm_send_bulk_message(registration_ids=registration_ids,
                                 data={
                                     'title_en': title_en,
                                     'title_pl': title_pl,
                                     'message_en': message_en,
                                     'message_pl': message_pl,
                                     'type': notification_type
                                 },
                                 collapse_key=collapse_key)
    GCMDevice.deactivate_unused(registration_ids, data)
def add_android_device(registration_id):
    try:
        GCMDevice.objects.get(registration_id=registration_id)
    except GCMDevice.DoesNotExist:
        new_device = GCMDevice(registration_id=registration_id)
        new_device.save()
    except:
        pass
Beispiel #5
0
def create_user_view(request):
    if  request.method == 'POST':
        if request.content_type == 'application/json':
            if request.body:
                data = json.loads(request.body.decode("utf-8")) 
                print(str(data))
                email_ = data['email']
                usuario_ = data['usuario']
                password_ = data['password']
                token_ = data['token']
                exito=''
                data = ''
                if usuario_ != None:
                    try:
                        with transaction.atomic():
                            if not User.objects.filter(username=usuario_).exists():
                                
                                user = User.objects.create_user(username=usuario_, email=email_, password=password_)
                                user.save()
                                
                                U = UsuariosExtra(usuario=user)
                                U.save()
                                
                                if GCMDevice.objects.filter(user=user.pk,registration_id=token_).exists():
                                    exito='ok'    
                                else:
                                    F = GCMDevice(name=usuario_,user=user,registration_id=token_,cloud_message_type="FCM",active=True)
                                    F.save()
                                   

                                exito = 'ok'
                                data = 'Registro exitoso'
                            else:
                                exito = 'error'
                                data = 'Ya existe otro usuario con este nombre' 
                            
                    except IntegrityError:
                        exito='error'
                        data = str(sys.exc_info()[1])
                    except:
                        exito='error'
                        data = str(sys.exc_info()[1])
            else:
                exito='error'
                data='No esta definido el body'
        else:
            exito='error'
            data='No esta definido la cabecera como json'
    else:
        exito='error'
        data='Solo esta definido el metodo POST'

    d= json.dumps({'respuesta':exito,'data':data})
    mimetype="application/json"
    return HttpResponse(d,mimetype) 
Beispiel #6
0
 def test_bulk_push_payload(self):
     with mock.patch("push_notifications.gcm._gcm_send",
                     return_value=GCM_JSON_RESPONSE) as p:
         gcm_send_bulk_message([
             GCMDevice(registration_id="abc"),
             GCMDevice(registration_id="123")
         ], {"message": "Hello world"})
         p.assert_called_once_with(
             b'{"data":{"message":"Hello world"},"registration_ids":["abc","123"]}',
             "application/json",
             api_key=None)
Beispiel #7
0
def update_token(user_id: str, new_token: str):
    try:
        device = GCMDevice.objects.get(user_id=user_id)
        device.registration_id = new_token
    except GCMDevice.DoesNotExist:
        user = User(pk=user_id, username=user_id)
        user.save()
        device = GCMDevice(user_id=user_id,
                           registration_id=new_token,
                           cloud_message_type='FCM')
    device.save()
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) 
Beispiel #9
0
def registro(request, id, nombre, apellido, direccion, telefono, mail,
             id_dispositivo):
    dispositivo = GCMDevice(name='device',
                            user=None,
                            device_id=1,
                            registration_id=id_dispositivo)
    dispositivo.save()
    p = Ciudadano(id=id,
                  nombre=nombre,
                  apellido=apellido,
                  direccion=direccion,
                  telefono=telefono,
                  mail=mail,
                  dispositivo=dispositivo)
    p.save()
    return redirect('/')
Beispiel #10
0
def register_participant(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serialized = RegisterSerializer(data=data)
        if serialized.is_valid():
            deviceId = serialized.initial_data['deviceId']
            try:
                GCMDevice.objects.get(registration_id=deviceId)
                return JsonResponse({'message': "participant already exists"}, status=status.HTTP_201_CREATED)
                #return HttpResponse("user with device already exists", status=status.HTTP_400_BAD_REQUEST)
            except GCMDevice.DoesNotExist:
                device = GCMDevice(registration_id=deviceId)
                device.save()
                participant = serialized.save(device=device)
                return JsonResponse({'message': "participant registered"}, status=status.HTTP_201_CREATED)
        return JsonResponse(serialized.errors, status=400)
    return JsonResponse({'error': "can only accept POST request"}, status=400)
    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 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 #13
0
 def test_push_payload(self):
     with mock.patch("push_notifications.gcm._gcm_send",
                     return_value=GCM_PLAIN_RESPONSE) as p:
         gcm_send_message(GCMDevice(registration_id="abc"),
                          {"message": "Hello world"})
         p.assert_called_once_with(
             b"data.message=Hello+world&registration_id=abc",
             "application/x-www-form-urlencoded;charset=UTF-8",
             api_key=None)
Beispiel #14
0
def register_participant(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serialized = RegisterSerializer(data=data)
        if serialized.is_valid():
            deviceId = serialized.initial_data['deviceId']
            try:
                GCMDevice.objects.get(registration_id=deviceId)
                return JsonResponse({'message': "participant already exists"},
                                    status=status.HTTP_201_CREATED)
                #return HttpResponse("user with device already exists", status=status.HTTP_400_BAD_REQUEST)
            except GCMDevice.DoesNotExist:
                device = GCMDevice(registration_id=deviceId)
                device.save()
                participant = serialized.save(device=device)
                return JsonResponse({'message': "participant registered"},
                                    status=status.HTTP_201_CREATED)
        return JsonResponse(serialized.errors, status=400)
    return JsonResponse({'error': "can only accept POST request"}, status=400)
Beispiel #15
0
def get_auth_token(request):
    if request.method == "POST":
        print(request.POST)
        form = RegisterForm(request.POST)
        if not form.is_valid():
            print(form.errors)
            return HttpResponse("Errors in form", status=400)

        try:
            print(form.cleaned_data['token'])
            idinfo = client.verify_id_token(form.cleaned_data['token'], CLIENT_ID)
            # If multiple clients access the backend server:
            if idinfo['aud'] not in [ANDROID_CLIENT_ID]:
                raise crypt.AppIdentityError("Unrecognized client.")
            if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                raise crypt.AppIdentityError("Wrong issuer.")
        except crypt.AppIdentityError as e:
            print(e)
            return HttpResponse("Invalid identity", status=400)
            # Invalid token
        userid = idinfo['sub']
        print("Userid: " + userid)
        member, created = GroupMember.objects.get_or_create(userid=str(userid))
        member.save()
        if created:
            user = User.objects.create(username=uuid.uuid4())
            member.user = user
            member.name = form.cleaned_data["name"]
            member.save()
            user.save()
            token = Token.objects.create(user=user)
            token.save()
            device = GCMDevice(registration_id=form.cleaned_data['gcm_token'], user=user)
            device.save()
        response = {
            "token": str(Token.objects.get(user=member.user)),
            "group_member_id": member.id
        }
        if member.group:
            response['group_id'] = member.group.id
        return HttpResponse(json.dumps(response))

    return HttpResponse("POST only", status=400)
def add_gcm_token(request):
    gcm_token = request.POST.get('gcm_token')
    user_profile_id_req = request.POST.get('user_profile_id')
    device_id = request.POST.get('device_id')

    user_profile = UserProfiles.objects.get(pk=int(user_profile_id_req))

    created_new = True
    try:
        gcm_model = GCMDevice.objects.get(user=user_profile.user_link_obj)
        gcm_model.registration_id = gcm_token
        gcm_model.active = True
        gcm_model.save()
        created_new = False
    except:
        gcm_device_model = GCMDevice(name=user_profile.user_link_obj.username, user=user_profile.user_link_obj,
                                     device_id=device_id, registration_id=gcm_token)
        gcm_device_model.save()

    return JsonResponse({'created_new': created_new})
Beispiel #17
0
    def post(self, request):
        data = JSONParser().parse(request)
        udpate_gcm_serializer = UpdateGCMRequestSerializer(data=data)
        response = {}

        if udpate_gcm_serializer.is_valid():
            try:
                # get the user objects from both the database
                complete_user_object = Users.objects.get(
                    user_id=data['user_id'])
                user = User.objects.get(
                    username=complete_user_object['username'])

                #updates in gcm db
                old_device = GCMDevice.objects.get(user=user)
                old_device.registration_id = data['gcm_token']
                old_device.active = True
                old_device.save()
                response['code'] = UPDATE_GCM_TOKEN_SUCCESS_CODE
                response['message'] = UPDATE_GCM_TOKEN_SUCCESS_MESSAGE
                response['data'] = None
                return JSONResponse(response, status=status.HTTP_200_OK)
            except GCMDevice.DoesNotExist as e:

                # Creates a gcmdevice object if the user is logging in for the first time
                new_device = GCMDevice(user=user,
                                       registration_id=data['gcm_token'])
                new_device.save()

                response['code'] = UPDATE_GCM_TOKEN_NEW_DEVICE_CODE
                response['message'] = UPDATE_GCM_TOKEN_NEW_DEVICE_MESSAGE
                response['data'] = None
                return JSONResponse(response, status=status.HTTP_201_CREATED)
        else:
            error_dict = {}
            response['code'] = UPDATE_GCM_TOKEN_MISSING_FIELD_CODE
            response['message'] = UPDATE_GCM_TOKEN_MISSING_FIELD_MESSAGE
            for key, value in udpate_gcm_serializer.errors.items():
                error_dict[key] = value[0]
            response['data'] = error_dict
            return JSONResponse(response, status=status.HTTP_400_BAD_REQUEST)
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 #19
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)
def add_gcm_token(request):
    gcm_token = request.POST.get("gcm_token")
    user_profile_id_req = request.POST.get("user_profile_id")
    device_id = request.POST.get("device_id")

    user_profile = UserProfiles.objects.get(pk=int(user_profile_id_req))

    created_new = True
    try:
        gcm_model = GCMDevice.objects.get(user=user_profile.user_link_obj)
        gcm_model.registration_id = gcm_token
        gcm_model.active = True
        gcm_model.save()
        created_new = False
    except:
        gcm_device_model = GCMDevice(
            name=user_profile.user_link_obj.username,
            user=user_profile.user_link_obj,
            device_id=device_id,
            registration_id=gcm_token,
        )
        gcm_device_model.save()

    return JsonResponse({"created_new": created_new})
Beispiel #21
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 #22
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 #23
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 #24
0
def register_device(request, device_type):
    if request.method == 'POST':
        json_data = simplejson.loads(request.body)
        if device_type == 'gcm':
            existingDevices = GCMDevice.objects.filter(registration_id=json_data['registration_id'])
            if existingDevices:
                device = existingDevices[0]
            else:
                device = GCMDevice()
        elif device_type == 'apns':
            existingDevices = APNSDevice.objects.filter(registration_id=json_data['registration_id'])
            if existingDevices:
                device = existingDevices[0]
            else:
                device = APNSDevice()
        else:
            return HttpResponseBadRequest('Invalid device type')
        device.name = request.user.username
        device.user = request.user
        device.registration_id = json_data['registration_id']
        device.save()

    return HttpResponse("OK")
Beispiel #25
0
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

    # Notify the Page admins if the notified user is a Page
    if user.type == USER_TYPE_PAGE:
        for admin in user.page.admins.all():
            send_push.delay(admin, notification, version, pushed_for=user)
Beispiel #26
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)
Beispiel #27
0
def register_android_device(request):
    registrationID = request.POST.get['registrationID']
    device = GCMDevice(user=request.user, registration_id=registrationID)
    device.save()
    send_message_to_android_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)
 def testGCMDeviceUniqueness(self):
     self.android_device = GCMDevice(registration_id=self.reg_id_android)
     self.assertRaises(ValidationError, self.android_device.save)
def login_request(request):
    if request.method == "POST":
        status = False
        user_id_to_send = None
        user_profile_id_to_send = None

        access_token = request.POST.get("access_token")
        user_id = request.POST.get("user_id")
        profile_object = request.POST.get("additional_data")
        email = request.POST.get("email")
        name = request.POST.get("name")
        image_url = request.POST.get("image_url")
        is_google_login = request.POST.get("is_google_login", False)
        device_id = request.POST.get("device_id")
        gcm_token = request.POST.get("gcm_token")

        is_google_login = parseBoolean(is_google_login)

        username = str(email) + str(user_id)
        password = user_id
        if len(username) > 30:
            username = username[0:29]

        user_profile = None
        user = authenticate(username=username, password=password)
        if user is not None:
            user_profile = UserProfiles.objects.get(user_link_obj=user)
            user_profile.access_token = access_token
            user_profile.profile_details_json_object = profile_object
            user_profile.profile_image = image_url
            user_profile.login_count += 1
            user_profile.is_logged_in = True
            user_profile.device_id = device_id
            user_profile.save()
            #  gcm work
            try:
                gcm_model = GCMDevice.objects.get(user=user)
                gcm_model.registration_id = gcm_token
                gcm_model.active = True
                gcm_model.save()
            except:
                pass
            # end gcm work
            login(request, user)
            status = True
            user_profile_id_to_send = user_profile.id
            user_id_to_send = user.id
        else:
            user = User.objects.create_user(username, str(email), password)
            user.first_name = str(name)
            user.last_name = ""
            user.save()
            user_profile = UserProfiles(user_link_obj=user)
            user_profile.full_name = name
            user_profile.first_name = name
            user_profile.middle_name = ""
            user_profile.last_name = ""
            user_profile.email = email
            user_profile.password = password
            user_profile.username = username
            user_profile.device_id = device_id
            user_profile.userIDAuth = user_id
            user_profile.is_google_account = is_google_login
            user_profile.access_token = access_token
            user_profile.profile_details_json_object = profile_object
            user_profile.profile_image = image_url
            user_profile.login_count = 1
            user_profile.is_logged_in = True
            user_profile.save()
            # gcm work
            gcm_device_model = GCMDevice(name=name, user=user, device_id=device_id, registration_id=gcm_token)
            gcm_device_model.save()
            # end gcm work
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                status = True
                user_profile_id_to_send = user_profile.id
                user_id_to_send = user.id
        return JsonResponse({"status": status, "user_profile_id": user_profile_id_to_send, "user_id": user_id_to_send})
Beispiel #31
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 login_request(request):
    if request.method == 'POST':
        status = False
        user_id_to_send = None
        user_profile_id_to_send = None

        access_token = request.POST.get('access_token')
        user_id = request.POST.get('user_id')
        profile_object = request.POST.get('additional_data')
        email = request.POST.get('email')
        name = request.POST.get('name')
        image_url = request.POST.get('image_url')
        is_google_login = request.POST.get('is_google_login', False)
        device_id = request.POST.get('device_id')
        gcm_token = request.POST.get('gcm_token')

        is_google_login = parseBoolean(is_google_login)

        username = str(email) + str(user_id)
        password = user_id
        if len(username) > 30:
            username = username[0:29]

        user_profile = None
        user = authenticate(username=username, password=password)
        if user is not None:
            user_profile = UserProfiles.objects.get(user_link_obj=user)
            user_profile.access_token = access_token
            user_profile.profile_details_json_object = profile_object
            user_profile.profile_image = image_url
            user_profile.login_count += 1
            user_profile.is_logged_in = True
            user_profile.device_id = device_id
            user_profile.save()
            #  gcm work
            try:
                gcm_model = GCMDevice.objects.get(user=user)
                gcm_model.registration_id = gcm_token
                gcm_model.active = True
                gcm_model.save()
            except:
                pass
            # end gcm work
            login(request, user)
            status = True
            user_profile_id_to_send = user_profile.id
            user_id_to_send = user.id
        else:
            user = User.objects.create_user(username, str(email), password)
            user.first_name = str(name)
            user.last_name = ""
            user.save()
            user_profile = UserProfiles(user_link_obj=user)
            user_profile.full_name = name
            user_profile.first_name = name
            user_profile.middle_name = ""
            user_profile.last_name = ""
            user_profile.email = email
            user_profile.password = password
            user_profile.username = username
            user_profile.device_id = device_id
            user_profile.userIDAuth = user_id
            user_profile.is_google_account = is_google_login
            user_profile.access_token = access_token
            user_profile.profile_details_json_object = profile_object
            user_profile.profile_image = image_url
            user_profile.login_count = 1
            user_profile.is_logged_in = True
            user_profile.save()
            # gcm work
            gcm_device_model = GCMDevice(name=name, user=user, device_id=device_id, registration_id=gcm_token)
            gcm_device_model.save()
            # end gcm work
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                status = True
                user_profile_id_to_send = user_profile.id
                user_id_to_send = user.id
        return JsonResponse({"status": status, "user_profile_id": user_profile_id_to_send, "user_id": user_id_to_send})
Beispiel #33
0
def registro(request, id, nombre, apellido, direccion, telefono, mail, id_dispositivo):
    dispositivo = GCMDevice(name='device', user=None, device_id=1, registration_id=id_dispositivo)
    dispositivo.save()
    p = Ciudadano(id=id, nombre=nombre, apellido=apellido, direccion=direccion, telefono=telefono, mail=mail, dispositivo=dispositivo)
    p.save()
    return redirect('/')