def process(self): message = self._data.get("message") if not message: return failure_response("Message is required", status.HTTP_400_BAD_REQUEST) receiving_user = User.objects.filter(id=self._receiving_user_id) if not receiving_user: return failure_response("Receiving user not found", status.HTTP_404_NOT_FOUND) receiving_user = receiving_user[0] if not receiving_user.person.fcm_registration_token: # Receiving user does not have notifications enabled, but message will still be delivered through Firebase return success_response(status=status.HTTP_200_OK) device = GCMDevice.objects.get( registration_id=receiving_user.person.fcm_registration_token) response = device.send_message( title=f"Chat from {self._user.first_name}", message=message, # Give APNS user id as thread id so iOS can collapse notifications thread_id=str(self._user.id), # Set the app to have a badge badge=1, ) if response.get("failure") == 1: return failure_response( f"Failed to send message, FCM Response: {response}", status.HTTP_502_BAD_GATEWAY, ) return success_response(status=status.HTTP_201_CREATED)
def process(self): # Verify that all required fields are provided name = self._data.get("name") if name is None: return failure_response("POST body is misformatted", status.HTTP_400_BAD_REQUEST) # Get optional fields subtitle = self._data.get("subtitle") img_url = self._data.get("img_url") # Check if a interest already exists with the given fields and return it if so interest = Interest.objects.filter(name=name, subtitle=subtitle, img_url=img_url) if interest: return success_response( self._serializer(interest[0]).data, status.HTTP_200_OK) # Create and return a new interest with the given fields interest = Interest.objects.create(name=name, subtitle=subtitle, img_url=img_url) interest.save() return success_response( self._serializer(interest).data, status.HTTP_201_CREATED)
def post(self, request): """Populates the database with the hardcoded data from the filenames in `request.body`.""" body = json.loads(request.body) filenames = body.get("filenames") if filenames is None: return failure_response( "POST body is misformatted", status.HTTP_400_BAD_REQUEST ) new_entries = 0 for filename in filenames: controller = self._filename_switch(filename) if controller: new_entries += self._parse_and_create(filename, controller) else: return failure_response( f"Invalid filename {filename}", status.HTTP_406_NOT_ACCEPTABLE ) if new_entries > 0: return success_response( f"Successfully created {new_entries} new entries", status.HTTP_201_CREATED, ) else: return success_response("No new changes", status.HTTP_200_OK)
def post(self, request, id): """Unblock user by id.""" if not User.objects.filter(id=id).exists(): return failure_response("User not found.", status.HTTP_404_NOT_FOUND) elif id == request.user.id: return failure_response("You cannot unblock yourself.", status.HTTP_403_FORBIDDEN) elif request.user.person.blocked_users.filter(id=id).exists(): request.user.person.blocked_users.remove(id) return success_response(status=status.HTTP_201_CREATED) else: # User is not blocked anyways return success_response(status=status.HTTP_200_OK)
def post(self, request): """Create multiple matches.""" try: data = json.loads(request.body) except json.JSONDecodeError: data = request.data match_ids_list = data.get("matches") cancel_previous = data.get("cancel_previous", False) if not match_ids_list: return failure_response("POST body is misformatted", status=status.HTTP_400_BAD_REQUEST) errors = [] for match_ids in match_ids_list: new_match_response = CreateMatchController( { "ids": match_ids, "cancel_previous": cancel_previous }, self.serializer_class, ).process() if new_match_response.status_code not in [ status.HTTP_201_CREATED, status.HTTP_200_OK, ]: errors.append(new_match_response) if errors: return failure_response( f"message: {len(errors)} matches failed to be created with the following errors: {errors}", status=status.HTTP_400_BAD_REQUEST, ) return success_response(status=status.HTTP_201_CREATED)
def process(self): """Returns the current access token or a new one if expired. If the user isn't authenticated yet, logs an existing user in or registers a new one.""" user = self._request.user status_code = status.HTTP_200_OK if self._data.get("username") and self._data.get("password"): user, status_code = self._authenticate(self._data.get("username"), self._data.get("password")) if user is None: return failure_response("Bad credentials provided.", status=status_code) elif not user.is_authenticated: token = self._data.get("id_token") token_info = self._get_token_info(token) if token_info is None: return failure_response("ID Token is not valid.", status.HTTP_401_UNAUTHORIZED) user, status_code = self._login(token_info) if user is None: return failure_response("ID Token is not valid.", status=status_code) access_token = self._issue_access_token(user) return success_response( self._serializer(user, context={ "access_token": access_token }).data, status=status_code, )
def get(self, request, id): """Get purpose by id.""" purpose = Purpose.objects.filter(id=id) if not purpose: return failure_response("Purpose does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(purpose[0]).data, status.HTTP_200_OK )
def get(self, request, id): """Get major by id.""" major = Major.objects.filter(id=id) if not major: return failure_response("Major does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(major[0]).data, status.HTTP_200_OK)
def process(self): # Verify that all required fields are provided name = self._data.get("name") if name is None: return failure_response( "POST body is misformatted", status.HTTP_400_BAD_REQUEST ) # Check if a major already exists with the given fields and return it if so major = Major.objects.filter(name=name) if major: return success_response(self._serializer(major[0]).data, status.HTTP_200_OK) # Create and return a new major with the given fields major = Major.objects.create(name=name) major.save() return success_response(self._serializer(major).data, status.HTTP_201_CREATED)
def get(self, request, id): """Get group by id.""" group = Group.objects.filter(id=id) if not group: return failure_response("Group does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(group[0]).data, status.HTTP_200_OK)
def get(self, request, id): """Get prompt by id.""" prompt = Prompt.objects.filter(id=id) if not prompt: return failure_response("Prompt does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(prompt[0]).data, status.HTTP_200_OK )
def get(self, request, id): """Get interest by id.""" interest = Interest.objects.filter(id=id) if not interest: return failure_response("Interest does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(interest[0]).data, status.HTTP_200_OK)
def delete(self, request, id): """Delete a match by id.""" match = Match.objects.filter(id=id) if not match: return failure_response("Match does not exist", status.HTTP_404_NOT_FOUND) match[0].delete() return success_response()
def delete(self, request, id, match_id): """Delete a survey by id.""" survey = Survey.objects.filter(id=id).exists() if not survey: return failure_response("Survey does not exist", status.HTTP_404_NOT_FOUND) Survey.objects.get(id=id).delete() return success_response(None, status.HTTP_200_OK)
def get(self, request, id, match_id): """Get survey by id.""" survey = Survey.objects.filter(id=id).exists() if not survey: return failure_response("Survey does not exist", status.HTTP_404_NOT_FOUND) return success_response( self.serializer_class(Survey.objects.get(id=id)).data, status.HTTP_200_OK)
def get(self, request, id): """Get user by id.""" if not User.objects.filter(id=id).exists(): return failure_response("User not found.", status.HTTP_404_NOT_FOUND) serialized_user = self.serializer_class( User.objects.get(id=id), context={"request_user": request.user}) # because we pass in the request, must make sure serializer is valid return success_response(serialized_user.data, status.HTTP_200_OK)
def get(self, request): """Get all of a user's matches, excluding blocked users.""" user = request.user blocked_ids = user.person.blocked_users.values_list("id", flat=True) matches = ( Match.objects.filter(Q(user_1=user) | Q(user_2=user)).exclude( Q(user_1_id__in=blocked_ids) | Q(user_2_id__in=blocked_ids)).order_by("-created_date")) return success_response(self.serializer_class(matches, many=True).data)
def post(self, request, id): """Cancel match by id.""" match = Match.objects.filter(id=id) if not match: return failure_response("Match does not exist.", status.HTTP_404_NOT_FOUND) match[0].status = match_status.CANCELED match[0].save() return success_response()
def get(self, request): """Run algorithm and return matches.""" return success_response( data=pear_algorithm( User.objects.filter( person__has_onboarded=True, person__is_paused=False, )), status=status.HTTP_201_CREATED, )
def get(self, request, id): """Get all matches for user by user id.""" user = User.objects.filter(id=id).exists() if not user: return failure_response("User not found.", status.HTTP_404_NOT_FOUND) user = User.objects.get(id=id) matches = Match.objects.filter(Q(user_1=user) | Q( user_2=user)).order_by("-created_date") return success_response( self.serializer_class(matches, many=True).data, status.HTTP_200_OK)
def get(self, request): """Get current match by user.""" match = Match.objects.filter( Q(user_1=request.user) | Q(user_2=request.user)).order_by("-created_date") if not match: return failure_response("Match does not exist", status.HTTP_404_NOT_FOUND) return success_response( MatchSerializer(match[0], user=request.user).data, status.HTTP_200_OK)
def post(self, request): body = json.loads(request.body) seconds = body.get("seconds") if seconds: start_countdown.delay(seconds) return success_response( f"Countdown started for {seconds} seconds", status.HTTP_200_OK ) return failure_response( "POST body is misformatted", status.HTTP_400_BAD_REQUEST )
def post(self, request): """Cancel current user's current match.""" match = Match.objects.filter( Q(user_1=request.user) | Q(user_2=request.user)).order_by("-created_date") if not match: return failure_response("Match does not exist", status.HTTP_404_NOT_FOUND) match = match[0] match.status = match_status.CANCELED match.save() return success_response()
def set_new_poll(request): title = request.GET.get("title", None) if title is None: response = failed_response('expected title value') else: try: poll = Poll(title=title) poll.save() response = success_response(poll_id=poll.poll_id) except Exception as e: response = failed_response(str(e)) return JsonResponse(response)
def set_new_choice(request, poll_id): description = request.GET.get("description", None) if description is None: response = failed_response('expected description value') else: try: choice = Choice(poll_id = poll_id, description = description) choice.save() response = success_response(choice_id=choice.choice_id) except Exception as e: response = failed_response(str(e)) return JsonResponse(response)
def get_poll_results(request, poll_id): votes = Vote.objects.select_related('poll').select_related('choice').select_related('user').filter(poll_id=poll_id) choices = Choice.objects.filter(poll_id=poll_id) results = { choice.choice_id:{**model_to_dict(choice),'number_of_vote':0} for choice in choices } for vote in votes: choice_id = vote.choice_id results[choice_id]['number_of_vote'] = results[choice_id]['number_of_vote'] + 1 response = success_response(results=list(results.values())) return JsonResponse(response)
def process(self): # Verify that all required fields are provided name = self._data.get("name") area = self._data.get("area") if name is None or area is None: return failure_response( "POST body is misformatted", status.HTTP_400_BAD_REQUEST ) # Check if a location already exists with the given fields and return it if so location = Location.objects.filter(name=name, area=area) if location: return success_response( self._serializer(location[0]).data, status.HTTP_200_OK ) # Create and return a new location with the given fields location = Location.objects.create(name=name, area=area) location.save() return success_response( self._serializer(location).data, status.HTTP_201_CREATED )
def process(self): # Verify that all required fields are provided name = self._data.get("question_name") if name is None: return failure_response("POST body is misformatted", status.HTTP_400_BAD_REQUEST) # Get label field label = self._data.get("question_placeholder") # Check if a prompt already exists with the given fields and return it if so prompt = Prompt.objects.filter(question_name=name, question_placeholder=label) if prompt: return success_response( self._serializer(prompt[0]).data, status.HTTP_200_OK) # Create and return a new prompt with the given fields prompt = Prompt.objects.create(question_name=name, question_placeholder=label) prompt.save() return success_response( self._serializer(prompt).data, status.HTTP_201_CREATED)
def get_poll_options(request, poll_id): try: poll = Poll.objects.get(poll_id=poll_id) choices = Choice.objects.filter(poll=poll) except Exception as e: response = failed_response(str(e)) return JsonResponse(response) data = {'poll': model_to_dict(poll), 'choices':[ model_to_dict(choice) for choice in choices ]} response = success_response(**data) return JsonResponse(response)
def process(self): # Get the model purpose = Purpose.objects.filter(id=self._id) if not purpose: return failure_response("Purpose does not exist", status.HTTP_404_NOT_FOUND) purpose = purpose[0] # Extract attributes name = self._data.get("name") # Modify new fields modify_attribute(purpose, "name", name) purpose.save() return success_response(self._serializer(purpose).data, status.HTTP_200_OK)