def suggest(request): if request.data and request.GET: raise GenericAPIException( 400, 'Put all parameters either in the querystring or the HTTP request body.' ) serializer = SuggestSerializer(data=(request.data or request.GET)) if not serializer.is_valid(): raise GenericAPIException(400, serializer.errors) searcher = (es_utils.AnalyzerS().es( urls=settings.ES_URLS, timeout=settings.ES_TIMEOUT, use_ssl=settings.ES_USE_SSL, http_auth=settings.ES_HTTP_AUTH, connection_class=RequestsHttpConnection).indexes( es_utils.read_index('default'))) data = serializer.validated_data return Response({ 'questions': _question_suggestions(searcher, data['q'], data['locale'], data['product'], data['max_questions']), 'documents': _document_suggestions(searcher, data['q'], data['locale'], data['product'], data['max_documents']), })
def helpful(self, request, pk=None): question = self.get_object() if not question.editable: raise GenericAPIException(403, 'Question not editable') if question.has_voted(request): raise GenericAPIException(409, 'Cannot vote twice') QuestionVote(question=question, creator=request.user).save() num_votes = QuestionVote.objects.filter(question=question).count() return Response({'num_votes': num_votes})
def take(self, request, pk=None): question = self.get_object() field = serializers.BooleanField() force = field.to_internal_value(request.data.get('force', False)) try: question.take(request.user, force=force) except InvalidUserException: raise GenericAPIException(400, 'Question creator cannot take a question.') except AlreadyTakenException: raise GenericAPIException(409, 'Conflict: question is already taken.') return Response(status=204)
def delete_setting(self, request, user__username=None): profile = self.get_object() if 'name' not in request.data: raise GenericAPIException(400, {'name': 'This field is required'}) try: meta = (Setting.objects .get(user=profile.user, name=request.data['name'])) meta.delete() return Response(status=status.HTTP_204_NO_CONTENT) except Setting.DoesNotExist: raise GenericAPIException(404, {'detail': 'No matching user setting found.'})
def helpful(self, request, pk=None): answer = self.get_object() if not answer.question.editable: raise GenericAPIException(403, 'Answer not editable') if answer.has_voted(request): raise GenericAPIException(409, 'Cannot vote twice') AnswerVote(answer=answer, creator=request.user, helpful=True).save() num_helpful_votes = AnswerVote.objects.filter(answer=answer, helpful=True).count() num_unhelpful_votes = AnswerVote.objects.filter(answer=answer, helpful=False).count() return Response({ 'num_helpful_votes': num_helpful_votes, 'num_unhelpful_votes': num_unhelpful_votes, })
def ban(request): """Bans a twitter account from using the AoA tool.""" username = json.loads(request.body).get('username') if not username: raise GenericAPIException(status.HTTP_400_BAD_REQUEST, 'Username not provided.') username = username[1:] if username.startswith('@') else username account, created = TwitterAccount.objects.get_or_create( username=username, defaults={'banned': True}) if not created and account.banned: raise GenericAPIException(status.HTTP_409_CONFLICT, 'This account is already banned!') else: account.banned = True account.save() return Response({'success': 'Account banned successfully!'})
def ignore(request): """Ignores a twitter account from showing up in the AoA tool.""" username = json.loads(request.body).get('username') if not username: raise GenericAPIException(status.HTTP_400_BAD_REQUEST, 'Username not provided.') username = username[1:] if username.startswith('@') else username account, created = TwitterAccount.objects.get_or_create( username=username, defaults={'ignored': True}) if not created and account.ignored: raise GenericAPIException( status.HTTP_409_CONFLICT, 'This account is already in the ignore list!') else: account.ignored = True account.save() return Response({'success': 'Account is now being ignored!'})
def delete_metadata(self, request, pk=None): question = self.get_object() if 'name' not in request.data: return Response({'name': 'This field is required.'}, status=status.HTTP_400_BAD_REQUEST) try: meta = (QuestionMetaData.objects .get(question=question, name=request.data['name'])) meta.delete() return Response(status=status.HTTP_204_NO_CONTENT) except QuestionMetaData.DoesNotExist: raise GenericAPIException(404, 'No matching metadata object found.')
def set_setting(self, request, user__username=None): user = self.get_object().user request.data['user'] = user.pk try: setting = Setting.objects.get(user=user, name=request.data['name']) except Setting.DoesNotExist: setting = None serializer = UserSettingSerializer(instance=setting, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: raise GenericAPIException(400, serializer.errors)
def unban(request): """Unbans a twitter account from using the AoA tool.""" usernames = json.loads(request.body).get('usernames') if not usernames: raise GenericAPIException(status.HTTP_400_BAD_REQUEST, 'Usernames not provided.') accounts = TwitterAccount.objects.filter(username__in=usernames) for account in accounts: if account and account.banned: account.banned = False account.save() message = {'success': '{0} users unbanned successfully.' .format(len(accounts))} return Response(message)
def unignore(request): """Unignores a twitter account from showing up in the AoA tool.""" usernames = json.loads(request.body).get("usernames") if not usernames: raise GenericAPIException(status.HTTP_400_BAD_REQUEST, "Usernames not provided.") accounts = TwitterAccount.objects.filter(username__in=usernames) for account in accounts: if account and account.ignored: account.ignored = False account.save() message = { "success": "{0} users unignored successfully.".format(len(accounts)) } return Response(message)
def filter_metadata(self, queryset, value): try: value = json.loads(value) except ValueError: raise GenericAPIException(400, 'metadata must be valid JSON.') for name, values in value.items(): if not isinstance(values, list): values = [values] query = Q() for v in values: if v is None: query = query | ~Q(metadata_set__name=name) else: query = query | Q(metadata_set__name=name, metadata_set__value=v) queryset = queryset.filter(query) return queryset
def get_queryset(self): queryset = self.queryset queryset = queryset.filter(category__in=settings.IA_DEFAULT_CATEGORIES, current_revision__isnull=False) locale = self.get_locale() product = self.request.query_params.get('product') topic = self.request.query_params.get('topic') is_template = bool(self.request.query_params.get('is_template', False)) is_archived = bool(self.request.query_params.get('is_archived', False)) is_redirect = bool(self.request.query_params.get('is_redirect', False)) if locale is not None: queryset = queryset.filter(locale=locale) if product is not None: if locale == settings.WIKI_DEFAULT_LANGUAGE: queryset = queryset.filter(products__slug=product) else: # Localized articles inherit product from the parent. queryset = queryset.filter(parent__products__slug=product) if topic is not None: if locale == settings.WIKI_DEFAULT_LANGUAGE: queryset = queryset.filter(topics__slug=topic) else: # Localized articles inherit topic from the parent. queryset = queryset.filter(parent__topics__slug=topic) elif topic is not None: raise GenericAPIException(status.HTTP_400_BAD_REQUEST, 'topic requires product') queryset = queryset.filter(is_template=is_template) queryset = queryset.filter(is_archived=is_archived) redirect_filter = Q(html__startswith=REDIRECT_HTML) if is_redirect: queryset = queryset.filter(redirect_filter) else: queryset = queryset.filter(~redirect_filter) return queryset
def add_tags(self, request, pk=None): question = self.get_object() if 'tags' not in request.data: return Response({'tags': 'This field is required.'}, status=status.HTTP_400_BAD_REQUEST) tags = request.data['tags'] for tag in tags: try: add_existing_tag(tag, question.tags) except Tag.DoesNotExist: if request.user.has_perm('taggit.add_tag'): question.tags.add(tag) else: raise GenericAPIException(403, 'You are not authorized to create new tags.') data = [{'name': tag.name, 'slug': tag.slug} for tag in question.tags.all()] return Response(data)
def add_tags(self, request, pk=None): question = self.get_object() if "tags" not in request.data: return Response({"tags": "This field is required."}, status=status.HTTP_400_BAD_REQUEST) tags = request.data["tags"] for tag in tags: try: add_existing_tag(tag, question.tags) except Tag.DoesNotExist: if request.user.has_perm("taggit.add_tag"): question.tags.add(tag) else: raise GenericAPIException( 403, "You are not authorized to create new tags.") data = [{ "name": tag.name, "slug": tag.slug } for tag in question.tags.all()] return Response(data)