def post(self, request): response_data = {} serializer = UsuarioEditSerializer(data=request.data) if serializer.is_valid(): serializer.save(rol=Rol(pk=2)) serializer.instance.set_password(serializer.instance.password) serializer.instance.save() token = Token.objects.get_or_create(user=serializer.instance) try: device = FCMDevice.objects.get( registration_id=serializer.instance.googleid) except FCMDevice.DoesNotExist: device = FCMDevice( registration_id=serializer.instance.googleid, name=serializer.instance.get_full_name(), user=serializer.instance) device.type = serializer.instance.procedencia device.save() return Response( { 'id': serializer.instance.pk, "token": str(token[0]) }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register_device(self, request): username = request.data['email'] device = request.data['device'] user = self.queryset.get(email = username) response = "" json_r = {} if not user is None: fcm_d = FCMDevice() fcm_d.name = "phone" fcm_d.registration_id = device fcm_d.type = 'android' fcm_d.user = user fcm_d.save() if not fcm_d.pk is None: FCMDevice.objects.filter(registration_id = device).exclude(pk = fcm_d.pk).update(active = False) json_r["message"] = "" json_r["type"] = "" json_r["title"] = "" json_r["success"] = True json_r["number"] = 1 json_r['extra'] = 0 response = json.dumps(json_r) return HttpResponse(response)
def post(self, request): serializer = UserRegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key fcm_token = json['fcm_token'] role = json['role'] device = FCMDevice() device.registration_id = fcm_token device.type = "Android" device.name = "Can be anything" device.user = user device.save() email = str(user) return Response( { "token": token.key, "role": role, "error": False }, status=status.HTTP_201_CREATED) else: data = {"error": True, "errors": serializer.errors} return Response(data, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data fcm_token = json['fcm_token'] user = json['id'] device = FCMDevice() device.registration_id = fcm_token device.type = "Android" device.name = "Can be anything" device.user = user device.save() return Response( { "token": token.key, "device_id": device.registration_id, "error": False }, status=status.HTTP_201_CREATED) else: data = {"error": True, "errors": serializer.errors} return Response(data, status=status.HTTP_400_BAD_REQUEST)
def groupLeave(userID, matchID): try: group = Match.objects.get(pk=matchID) leavingMember = Profile.objects.get(pk=userID) group.group_members.remove(leavingMember) groupList = group.group_members if groupList.exists(): group.save() for member in group.group_members.all(): #notify all group members they have a message print(member.id) userDevice = FCMDevice() userDevice.registration_id = member.deviceID userDevice.type = "Android" notificationMsg = leavingMember.name + " has left the Group " + group.group_name if member.notification: userDevice.send_message(title="Group Notification", body=notificationMsg) userDevice.send_message(data={ "title": "Group Notification", "body": notificationMsg }) else: group.delete() except ObjectDoesNotExist: pass
def register_device(self, request): json_data = request.data if request.data else json.loads(request.body.decode('utf-8')) username = json_data['email'] device = json_data['device'] user = self.queryset.get(email = username) response = "" json_r = {} if not user is None: fcm_d = FCMDevice() fcm_d.name = "phone" fcm_d.registration_id = device fcm_d.type = 'android' fcm_d.user = user fcm_d.save() if not fcm_d.pk is None: FCMDevice.objects.filter(registration_id = device).exclude(pk = fcm_d.pk).update(active = False) json_r["message"] = "" json_r["type"] = "" json_r["title"] = "" json_r["success"] = True json_r["number"] = 1 json_r['extra'] = 0 response = json.dumps(json_r) return HttpResponse(response)
def register_device(self, request): json_data = (request.data if request.data else json.loads( request.body.decode("utf-8"))) username = json_data["email"] device = json_data["device"] user = self.queryset.get(email=username) response = "" json_r = {} if not user is None: fcm_d = FCMDevice() fcm_d.name = "phone" fcm_d.registration_id = device fcm_d.type = "android" fcm_d.user = user fcm_d.save() if not fcm_d.pk is None: FCMDevice.objects.filter(registration_id=device).exclude( pk=fcm_d.pk).update(active=False) json_r["message"] = "" json_r["type"] = "" json_r["title"] = "" json_r["success"] = True json_r["number"] = 1 json_r["extra"] = 0 response = json.dumps(json_r) return HttpResponse(response)
def post(self, request): req_data = request.data user = request.user try: device = FCMDevice.objects.get(user=user) connection.close() return Response( {"message": "Device already registered for the user"}, status=status.HTTP_400_BAD_REQUEST, ) except: device = FCMDevice() device.device_id = req_data["device_id"] device.registration_id = req_data["registration_id"] device.type = "Android" device.user = request.user device.save() connection.close() return Response( { "message": "New Device Registered", "device_details": { "device_id": device.device_id, "registration_id": device.registration_id, "type": device.type, "user": device.user.id, }, }, status=status.HTTP_201_CREATED, )
def matchAccept(userid, match, acceptance): userProfile = Profile.objects.get(pk=userid) otherUser = match.returnOtherMatch(userProfile) if match.user1 == userProfile: match.user1accepted = acceptance match.user1HasMatched = True if match.user2HasMatched: if match.user2accepted: match.hasMatched = True # Notify User2 of a match; user2device = FCMDevice() user2device.registration_id = otherUser.deviceID user2device.type = "Android" notificationMsg = "A new match has been found for you!" if otherUser.notification: user2device.send_message(title="New Match!", body=notificationMsg) user2device.send_message(data={ "title": "New Match!", "body": notificationMsg }) else: match.user2accepted = acceptance match.user2HasMatched = True if match.user1HasMatched: if match.user1accepted: match.hasMatched = True # Notify user1 of a match; user1device = FCMDevice() user1device.registration_id = otherUser.deviceID user1device.type = "Android" notificationMsg = "A new match has been found for you!" if otherUser.notification: user1device.send_message(title="New Match!", body=notificationMsg) user1device.send_message(data={ "title": "New Match!", "body": notificationMsg }) match.save()
def createMessage(senderid, matchid, message, isGroup): retval = {} try: sender = Profile.objects.get(pk=senderid) match = Match.objects.get(pk=matchid) msg = Message(sender=sender, matchID=match, message=message) msg.save() if isGroup: group = groupMembers(matchid) for member in group: #notify all group members they have a message print(member.id) userDevice = FCMDevice() userDevice.registration_id = member.deviceID userDevice.type = "Android" notificationMsg = match.group_name + " has recieved a new message" if member.notification: userDevice.send_message(title="New Message", body=notificationMsg) userDevice.send_message(data={ "title": "New Message", "body": notificationMsg }) else: #notify user they have a message userDevice = FCMDevice() userDevice.registration_id = match.returnOtherMatch( sender).deviceID userDevice.type = "Android" notificationMsg = sender.name + " has sent you a message" if match.returnOtherMatch(sender).notification: userDevice.send_message(title="New Message", body=notificationMsg) userDevice.send_message(data={ "title": "New Message", "body": notificationMsg }) retval["id"] = msg.id except ObjectDoesNotExist: retval["id"] = -1 except MultipleObjectsReturned: retval["id"] = -2 return retval
def post(self, request): response_data = {} serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get('email') password = serializer.data.get('password') googleid = serializer.data.get('googleid') dispositivo = serializer.data.get('dispositivo') try: Cliente.objects.get(email=email) except Cliente.DoesNotExist: response_data['resultado'] = 0 response_data['error'] = "Usuario y/o contraseña incorrectos" return Response(response_data) user = authenticate(email=email, password=password) if user is not None: if user.estatus == False: response_data['resultado'] = 0 response_data[ 'error'] = "Tu usuario ha sido inhabilitado, contacta al administrador" return Response(response_data) token = Token.objects.get_or_create(user=user) else: response_data['resultado'] = 0 response_data['error'] = "Usuario y/o contraseña incorrectos" return Response(response_data) user.googleid = googleid user.dispositivo = dispositivo try: device = FCMDevice.objects.get(registration_id=googleid) device.user = user device.name = user.get_full_name() except FCMDevice.DoesNotExist: device = FCMDevice(registration_id=googleid, name=user.get_full_name(), user=user) device.type = dispositivo device.save() user.save() response_data['resultado'] = 1 response_data['token'] = str(token[0]) serializer = ClienteSerializer(user, many=False) response_data['cliente'] = serializer.data return Response(response_data, status=status.HTTP_200_OK)
def post(self, request): global device fcm = request.data.get("fcm_token") user = authenticate(email=request.data.get("email"), password=request.data.get("password")) if user is not None: ser = UserShortInfoSerializer(user) fb = User.objects.get(id=user.id) print(ser.data['id']) try: devices = FCMDevice.objects.get(user=ser.data['id']) except FCMDevice.DoesNotExist: devices = None if devices is None: device = FCMDevice() device.user = user device.registration_id = fcm device.type = "Android" device.name = "Can be anything" device.save() else: devices.registration_id = fcm devices.save() try: token = Token.objects.get(user_id=user.id) except: token = Token.objects.create(user=user) print(token.key) print(user) return Response({ "token": token.key, "device_id": device.registration_id, "error": False }) else: data = { "error": True, "msg": "User does not exist or password is wrong" } return Response(data, status=status.HTTP_401_UNAUTHORIZED)
def groupAdd(userMatchID, matchID, profile_id): group = Match.objects.get(pk=matchID) userMatch = Match.objects.get(pk=userMatchID) currUser = Profile.objects.get(pk=profile_id) newMember = userMatch.returnOtherMatch(currUser) if not group.group_members.all().filter(id=newMember.id).count(): group.group_members.add(newMember) userMatch.save() #notify group member userDevice = FCMDevice() userDevice.registration_id = newMember.deviceID userDevice.type = "Android" notificationMsg = currUser.name + " has added you into Group: " + group.group_name if newMember.notification: userDevice.send_message(title="Group Invite", body=notificationMsg) userDevice.send_message(data={ "title": "Group Invite", "body": notificationMsg })
def crud_device(request): """ CRUD Operation for FCM devices """ if request.method == 'POST': print('call crud') if request.user.is_authenticated: print('authen') try: req_data = json.loads(request.body.decode()) fcm_token = req_data['fcmtoken'] except (KeyError, ValueError): return HttpResponseBadRequest() device = FCMDevice() # registration_id is a mandatory field and should be the FCM token! device.registration_id = fcm_token # Fields below are not mandatory anymore device.name = request.user.name device.user = request.user # TODO check if this can always be web (or need something like "mobile") device.type = "web" device.save() return HttpResponse(status=status.HTTP_201_CREATED) else: return HttpResponse(status=status.HTTP_401_UNAUTHORIZED) elif request.method == 'DELETE': if request.user.is_authenticated: try: fcm_token = json.loads(request.body.decode())['fcmtoken'] except (KeyError, ValueError): return HttpResponseBadRequest() FCMDevice.objects.filter(registration_id=fcm_token).delete() return HttpResponse(status=status.HTTP_200_OK) else: return HttpResponse(status=status.HTTP_401_UNAUTHORIZED) else: return HttpResponseNotAllowed(['POST', 'DELETE'])
def post(self, request, **kwargs): ser = self.serializer_class(data=request.data, context={'request': request}) if ser.is_valid(): try: device = FCMDevice.objects.get( device_id=request.data['device']) device.registration_id = request.data['token'] device.save() return Response(True, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: fcm_device = FCMDevice() user_details: UserDetails = UserDetails.objects.get( user=request.user) fcm_device.name = user_details.username fcm_device.user = request.user fcm_device.device_id = request.data['device'] fcm_device.registration_id = request.data['token'] fcm_device.type = 'ios' if request.data[ 'platform'] == 2 else 'android' if request.data[ 'platform'] == 1 else 'web' fcm_device.save() return Response(True, status=status.HTTP_200_OK) return Response(False, status=status.HTTP_200_OK)
def post(self, request): response_data = {} serializer = LoginChoferSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get('email') password = serializer.data.get('password') googleid = serializer.data.get('googleid') placas = serializer.data.get('placas') dispositivo = serializer.data.get('dispositivo') try: c = Chofer.objects.get(email=email) cv = ChoferHasVehiculo.objects.filter(vehiculo__placa=placas, estatus=True) if c.estatus == False: response_data['resultado'] = 0 response_data[ 'error'] = "Tu usuario ha sido inhabilitado, contacta al administrador" return Response(response_data) if cv.exists(): response_data['resultado'] = 0 response_data[ 'error'] = "Este vehiculo ya esta en uso por alguien mas" return Response(response_data) cv = ChoferHasVehiculo.objects.filter(vehiculo__placa=placas, chofer=c) if not cv.exists(): response_data['resultado'] = 0 response_data['error'] = "No tienes ese coche" return Response(response_data) chofer_vehiculos_activos = ChoferHasVehiculo.objects.filter( chofer=c, estatus=True) if chofer_vehiculos_activos.exists(): response_data['resultado'] = 2 response_data[ 'error'] = "Ya tienes una sesión activa con otro vehículo" return Response(response_data) except Chofer.DoesNotExist: response_data['resultado'] = 0 response_data['error'] = "Usuario y/o contraseña incorrectos" return Response(response_data) user = authenticate(email=email, password=password) if user is not None: token = Token.objects.get_or_create(user=user) else: response_data['resultado'] = 0 response_data['error'] = "Usuario y/o contraseña incorrectos" return Response(response_data) user.googleid = googleid user.dispositivo = dispositivo try: device = FCMDevice.objects.get(registration_id=googleid) device.user = user device.name = user.get_full_name() except FCMDevice.DoesNotExist: device = FCMDevice(registration_id=googleid, name=user.get_full_name(), user=user) device.type = dispositivo device.save() user.save() cv = cv.first() cv.estatus = True cv.save() response_data['resultado'] = 1 response_data['token'] = str(token[0]) serializer = ChoferSerializer(c, many=False) response_data['usuario'] = serializer.data return Response(response_data)
def post(self, request): fcm = request.data.get("fcm_token") if fcm is None: return Response({ "Message": "Please provide a fcm token", "error": True }) email = None phone = None if 'email' in request.data: if request.data['email'] != "": email = request.data['email'] else: pass if 'phone' in request.data: if request.data['phone'] != "": phone = request.data['phone'] else: pass if email is None: if phone is None: return Response({ "Message": "Please enter email or phone no", "error": True }) # if email is not None: user = CustomAuthentication().authenticate( email=email, phone=phone, password=request.data.get("password")) # else: # user = CustomAuthentication().authenticate(email=email,phone=phone,password=request.data.get("password")) if user is not None: ser = UserDetailSerializer(user) fb = User.objects.get(id=user.id) fb.fcm_token = fcm fb.save() try: devices = FCMDevice.objects.get(user=ser.data['id']) except FCMDevice.DoesNotExist: devices = None if devices is None: device = FCMDevice() device.user = user device.registration_id = fcm device.type = "Android" device.name = "Can be anything" device.save() else: devices.registration_id = fcm devices.save() role = ser.data['role'] try: token = Token.objects.get(user_id=user.id) except: token = Token.objects.create(user=user) return Response({"token": token.key, "role": role, "error": False}) else: data = { "error": True, "msg": "User does not exist or password is wrong" } return Response(data, status=status.HTTP_401_UNAUTHORIZED)