Esempio n. 1
0
 def response_or_404(self, query_result, many=False):
     response = Response()
     if query_result is None:
         response.status_code = 404
     else:
         response.data = self.serializer_class(query_result, many=many)
     return response
Esempio n. 2
0
def exception_handler(exc, context):
    response = rest_exception_handler(exc, context)

    if response is None:
        if hasattr(exc, "name") and callable(exc.name):
            name = exc.name()
        else:
            name = exc.__class__.__name__

        response = {
            "detail": str(exc),
            "name": name
        }

        if settings.DEBUG:
            import traceback

            response['traceback'] = traceback.format_tb(exc.__traceback__)

        response = Response(response)
    else:
        response.data["name"] = exc.__class__.__name__

    response.status_code = 500

    return response
Esempio n. 3
0
    def post(self, request):
        print
        "creating a goddamned user"
        print
        request.DATA
        print
        dir(request)
        username = request.DATA.get('username', '')
        password = request.DATA.get('password', '')
        email = request.DATA.get('email', '')
        print
        username
        user = User.objects.create_user(username, email, password)
        user = authenticate(username=username, password=password)
        cl = Client.objects.create(user=user, name=username,
                                   redirect_uri="http://localhost/",
                                   client_type=2
        )

        token = AccessToken.objects.create(user=user, client=cl,
                                           expires=datetime.date(year=2015, month=1, day=2)
        )
        if self.request.accepted_renderer.format == 'json':
            response = Response({'access_token': token.token})
            response.status_code = status.HTTP_201_CREATED
            return response
        login(request, user)
        return redirect('/users/' + str(user.id))
Esempio n. 4
0
    def get(self, request, *args, **kw):
        ip = args[0]
        details_request = IPDetails(ip, *args, **kw)
        result = DetailsSerializer(details_request)
        response = Response(result.data, status=status.HTTP_200_OK)

        visit = Visit()
        visit.endpoint = '/api/details/' + ip
        visit.timestamp = get_epoch_timestamp()
        visit.address = get_ip(request)

        cookie = request.COOKIES.get("alienvaultid", None)
        if cookie is None:
            ck_val = create_random_string()
            # set this cookie to expire in one year
            response.set_cookie('alienvaultid', ck_val, max_age=31536000)
            visitor = Visitor()
            visitor.alienvaultid = ck_val
            visitor.save()
        else:
            visitor = Visitor.objects.get(alienvaultid=cookie)

        visit.visitor_id = visitor.id
        visit.save()
        return response
Esempio n. 5
0
    def test_should_return_response_from_cache_if_it_is_in_it(self):
        def key_func(**kwargs):
            return 'cache_response_key'

        class TestView(views.APIView):
            @cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response(u'Response from method 4')

        view_instance = TestView()
        view_instance.headers = {}
        cached_response = Response(u'Cached response from method 4')
        view_instance.finalize_response(request=self.request, response=cached_response)
        cached_response.render()
        response_dict = (
            cached_response.rendered_content,
            cached_response.status_code,
            cached_response._headers
        )
        self.cache.set('cache_response_key', response_dict)

        response = view_instance.dispatch(request=self.request)
        self.assertEqual(
            response.content.decode('utf-8'),
            u'"Cached response from method 4"')
    def get(self, request, offset=0, limit=10, orderBy='id', order='asc', filterOn=None, filterValue=None,format=None):
        if offset is None:
            offset = 0
        if limit is None:
            limit = 10
        if orderBy == None:
            orderBy = 'id'
        if order == 'desc':
            orderBy = '-' + orderBy

        try:
            if filterOn is None or filterValue is None:
                users = Users.objects.all().order_by(orderBy)[offset:limit]
                count = Users.objects.all()[offset:limit].count()
            else:    
                users = Users.objects.all().filter(**{ filterOn: filterValue }).order_by(orderBy)[offset:limit]
                count = Users.objects.all().filter(**{ filterOn: filterValue })[offset:limit].count()
            total_count = Users.objects.count()
            serializer = UserDetailListViewSerializer(users, many=True)
            response = Response()
            response['count'] = count
            response['total_count'] = total_count
            response.data = serializer.data
            response.status = status.HTTP_200_OK 
            return response
        except Users.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST) 
Esempio n. 7
0
    def get_response(self):
        serializer_class = self.get_response_serializer()

        if getattr(settings, 'REST_USE_JWT', False):
            data = {
                'user': self.user,
                'token': self.token
            }
            serializer = serializer_class(instance=data,
                                          context={'request': self.request})
        else:
            serializer = serializer_class(instance=self.token,
                                          context={'request': self.request})

        response = Response(serializer.data, status=status.HTTP_200_OK)
        if getattr(settings, 'REST_USE_JWT', False):
            from rest_framework_jwt.settings import api_settings as jwt_settings
            if jwt_settings.JWT_AUTH_COOKIE:
                from datetime import datetime
                expiration = (datetime.utcnow() + jwt_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(jwt_settings.JWT_AUTH_COOKIE,
                                    self.token,
                                    expires=expiration,
                                    httponly=True)
        return response
Esempio n. 8
0
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            response.data = {
                'token': token,
                'user':{
                    'alias': user.alias,
                    'email': user.email
                }
            }
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 9
0
    def post(self, request, assembly, format=None):
        respmsg = "inicio"
        try:
            api = get_api_obj(assembly)

            api.ignore_admin_user = "******"
            api.social_ideation_source = request.data['source'] # indicates the name of the providerId (e.g., social_ideation_facebook)
            api.social_ideation_source_url = request.data['source_url'] # source to the original post
            api.social_ideation_user_source_url = request.data['user_url'] # link to the user
            api.social_ideation_user_source_id = request.data['user_external_id'] # email or id of the user in the source social network
            api.social_ideation_user_name = request.data['user_name'] # the name of the author in the social network
            api.assembly_id = assembly.appcivist_id
            new_obj_raw = getattr(api, self.api_method)(**self.api_method_params)
            new_obj_id = find_obj_id(new_obj_raw)
            new_obj= self.create_obj(new_obj_id, assembly, new_obj_raw)
            serializer = self.serializer_class(new_obj)
            if self.filters:
                new_obj.sync = True
                new_obj.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        except Exception as e:
            resp = Response(status=status.HTTP_400_BAD_REQUEST)
            resp.content = e
            return resp
Esempio n. 10
0
def custom_exception_handler(exc):
    """
    Formats REST exceptions like:
    {
        "error": "error_code",
        "error_description": "description of the error",
    }
    :param exc: Exception
    :return: Response
    """
    response = exception_handler(exc)

    if not response:
        # Unhandled exceptions (500 internal server errors)
        response = Response(data={
            'error': 'server_error',
            'error_description': unicode(exc),
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return response

    if hasattr(exc, 'default_error'):
        response.data['error'] = exc.default_error
    else:
        response.data['error'] = 'api_error'

    if hasattr(exc, 'default_detail'):
        response.data['error_description'] = exc.default_detail
    elif 'detail' in response.data:
        response.data['error_description'] = response.data['details']

    if 'detail' in response.data:
        del response.data['detail']

    return response
Esempio n. 11
0
def datal_exception_handler(exception, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exception, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status'] = response.status_code
        if not 'description' in response.data:
            response.data['description'] = ''
            if 'detail' in response.data:
                response.data['description'] =  response.data.pop('detail')
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = 'api-error'
    elif isinstance(exception, DATALException):
        set_rollback()
        response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.data['status'] = exception.status_code
        response.data['description'] =  exception.description % {}
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = exception.tipo
    elif not settings.DEBUG:
        logger = logging.getLogger(__name__)
        trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
        logger.error('[UnexpectedCatchError] %s. %s %s' % (
                str(exception), repr(exception), trace))
        set_rollback()
        response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.data['status'] = response.status_code
        response.data['description'] = str(exception)
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = 'unexpected-error'

    return response
    def create(self, request):
        """Override request to handle kicking off celery task"""

        indicators_config = OTIIndicatorsConfig.objects.all()[0]
        failures = []
        for attr in ['poverty_line', 'nearby_buffer_distance_m',
                     'max_commute_time_s', 'avg_fare', 'arrive_by_time_s']:
            if not indicators_config.__getattribute__(attr) > 0:
                failures.append(attr)
        if not valid_sample_periods():
            failures.append('sample_periods')
        try:
            with connection.cursor() as c:
                c.execute('''SELECT COUNT(*) FROM planet_osm_line''')
        except ProgrammingError:
            failures.append('osm_data')

        if len(failures) > 0:
            response = Response({'error': 'Invalid configuration',
                                 'items': failures})
            response.status_code = status.HTTP_400_BAD_REQUEST
            return response

        response = super(IndicatorJobViewSet, self).create(request)
        if response.status_code == status.HTTP_201_CREATED:
            start_indicator_calculation.apply_async(args=[self.object.id], queue='indicators')
        return response
Esempio n. 13
0
 def get(self, request, *args, **kwargs):
     contextdata = {
         "@context": getHydraVocab()
     }
     response = Response(data=contextdata)
     if request.accepted_media_type != "text/html":
         response.content_type = "application/ld+json"
     return response
Esempio n. 14
0
 def get(self, request, doc=None):
     if doc.endswith('.js'):
         doc = doc.replace(".js", "-js")
     version = MarkdownType.get_default()
     response = Response({})
     response['Location'] = "/%s/docs/%s" % (version.name, doc)
     response.status_code = status.HTTP_302_FOUND
     return response
Esempio n. 15
0
 def handle_exception(self, exc):
     # REST API drops the string attached to Django's PermissionDenied
     # exception, and replaces it with a generic "Permission Denied"
     if isinstance(exc, DjangoPermissionDenied):
         response=Response({'detail': {"error": "PermissionDenied", "specific_error": str(exc), "fields": {}}}, status=status.HTTP_403_FORBIDDEN)
         response.exception=True
         return response
     else:
         return super(XOSListCreateAPIView, self).handle_exception(exc)
Esempio n. 16
0
 def get(self, request, format=None):
     try:
         initiatives = Initiative.objects.all()
         serializer = InitiativeSerializer(initiatives, many=True)
         return Response(serializer.data)
     except Exception as e:
         resp = Response(status=status.HTTP_400_BAD_REQUEST)
         resp.content = e
         return resp
Esempio n. 17
0
 def get(self, request, format=None):
     try:
         assemblies = Assembly.objects.all()
         serializer = AssemblySerializer(assemblies, many=True)
         return Response(serializer.data)
     except Exception as e:
         resp = Response(status=status.HTTP_400_BAD_REQUEST)
         resp.content = e
         return resp
Esempio n. 18
0
	def retrieve(self, *args, **kwargs):
		super(PassageRetrieveViewSet, self).retrieve(*args, **kwargs)
		if hasattr(self, 'object'):
			data = serializers.PassageSerializer(self.object).data
		else:
			data = self.object_data
		response = Response({'object':data})
		response.template_name = 'wb/detail.html'
		return response
Esempio n. 19
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     token, created = Token.objects.get_or_create(user=user)
     auth_login(request, user)
     response = Response({'token': token.key})
     csrf_token = _get_new_csrf_string()
     response.set_cookie('csrftoken', csrf_token)
     return response
Esempio n. 20
0
def custom_exception_handler(exc):
    response = exception_handler(exc)
    if response is None:
        response = Response(
            {'detail': 'Internal Server Error: %s' % (exc,)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )
    response.data['status_code'] = response.status_code
    response.data['success'] = False
    return response
Esempio n. 21
0
 def get(self, request, initiative_id, format=None):
     try:
         initiative = Initiative.objects.get(id=initiative_id)
         campaigns = cru_campaign(-100, initiative)
         serializer = CampaignSerializer(campaigns, many=True)
         return Response(serializer.data)
     except Exception as e:
         resp = Response(status=status.HTTP_400_BAD_REQUEST)
         resp.content = e
         return resp
Esempio n. 22
0
 def _prepare_paginated_response(self, paginator, total_items_count):
     response = Response(data=self._prepare_response(paginator.get_frame()))
     response.extra = dict(
         meta=camelize(self.pagination_meta_format(
             count_items=total_items_count,
             limit=(paginator.end - paginator.start
                    if paginator.end is not None
                    else next(iter(paginator.ALL_ITEMS_FLAGS), None)),
             offset=paginator.start)))
     return response
Esempio n. 23
0
 def get(self, request, initiative_id, format=None):
     assembly_id = initiative_id
     try:
         assembly = Assembly.objects.get(appcivist_id=assembly_id)
         campaigns = cru_campaign(-100, assembly)
         serializer = CampaignSerializer(campaigns, many=True)
         return Response(serializer.data)
     except Exception as e:
         resp = Response(status=status.HTTP_400_BAD_REQUEST)
         resp.content = e
         return resp
Esempio n. 24
0
def get_bitstream_data(request,id):
    """
    Return data from an especified bitstream.
    """
    try:
        bitstream_data =  Bitstream.retrieve(dspace,id,**dict(request.query_params))
        response = Response(status=status.HTTP_200_OK)
        response.content = bitstream_data
        return  response
    except Collection.DoesNotExist:
        raise Http404
Esempio n. 25
0
def custom_exception_handler(exc):

    if type(exc) is ValidationError:
        response = Response(status=status.HTTP_400_BAD_REQUEST)
        response.data = {'error': exc.messages}
    else:
        # Call REST framework's default exception handler first,
        # to get the standard error response.
        response = exception_handler(exc)

    return response
Esempio n. 26
0
 def get(self, request, obj_id, format=None):
     try:
         api = get_api_obj(self.assembly)
         obj_raw = getattr(api, self.api_method)(**self.api_method_params)
         obj = self.create_obj(find_obj_id(obj_raw), self.assembly, obj_raw)
         serializer = self.serializer_class(obj)
         return Response(serializer.data)
     except Exception as e:
         resp = Response(status=status.HTTP_400_BAD_REQUEST)
         resp.content = e
         return resp
Esempio n. 27
0
def custom_exception_handler(exc, context):
    if isinstance(exc, (TravelException)):
        r = Response(TravelExceptionSerializer(exc).data)
        r.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
        return r

    # Call REST framework's default exception handler,
    # to get the standard error response.
    response = exception_handler(exc, context)

    return response
Esempio n. 28
0
 def get(self, request):
     logger.info("Get.")
     try:
         response_data = {"id": 0}
         response = Response(response_data, status=status.HTTP_200_OK)
     except Exception as ex:
         logger.info("Error getting list.")
         response = HttpResponse()
         response.stats_code = 200
         response.write(str(ex))
     return response
Esempio n. 29
0
 def get(self, request):
   logger.info('Get.')
   try:
     response_data = {'count': 0, 'total': 0, 'index': 0}
     response = Response(response_data, status=status.HTTP_200_OK)
   except Exception as ex:
     logger.info('Error getting list.')
     response = HttpResponse()
     response.stats_code = 200
     response.write( str(ex) )
   return response
Esempio n. 30
0
 def get(self, request, *args, **kwargs):
     network = []
     for entity in Entity.objects.filter(match__isnull=False):
         entry = {
             'from': entity.user_profile.user.pk,
             'to': entity.match.user_profile.user.pk
         }
         network.append(entry)
     response = Response(network)
     response.status = 200
     return response
Esempio n. 31
0
 def get(self, request):
     games = Game.objects.all()
     serializer = GameSerializer(games, many=True)
     return Response(serializer.data)
Esempio n. 32
0
 def get(self, request):
     articles = Article.objects.all()
     serializer = ArticleSerializer(articles, many=True)
     return Response(serializer.data)
Esempio n. 33
0
 def get(self, request, format=None):
     return  Response([b.Title for b in Book.objects.all().order_by('Title')])
Esempio n. 34
0
 def retrieve(self, request, *args, **kwargs):
     serializer = self.serializer_class(request.user)
     return Response(serializer.data, status=status.HTTP_201_CREATED)
Esempio n. 35
0
 def get(self, request, id):
     article = self.get_object(id)
     serializer = ArticleSerializer(article)
     return Response(serializer.data)
Esempio n. 36
0
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })
Esempio n. 37
0
 def post(self, request):
     user = request.data.get('user', {})
     serializer = self.serializer_class(data=user)
     serializer.is_valid(raise_exception=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Esempio n. 38
0
 def get(self, request, user_id):
     order = self.get_object(user_id)
     serializer = OrderSerializer(order)
     return Response(serializer.data)
Esempio n. 39
0
 def like(self, request):
     return Response(self.get_serializer().data)  # pragma: no cover
Esempio n. 40
0
    def put(self, request, project):
        """
        Bulk Mutate a List of Issues
        ````````````````````````````

        Bulk mutate various attributes on issues.  The list of issues
        to modify is given through the `id` query parameter.  It is repeated
        for each issue that should be modified.

        - For non-status updates, the `id` query parameter is required.
        - For status updates, the `id` query parameter may be omitted
          for a batch "update all" query.
        - An optional `status` query parameter may be used to restrict
          mutations to only events with the given status.

        The following attributes can be modified and are supplied as
        JSON object in the body:

        If any ids are out of scope this operation will succeed without
        any data mutation.

        :qparam int id: a list of IDs of the issues to be mutated.  This
                        parameter shall be repeated for each issue.  It
                        is optional only if a status is mutated in which
                        case an implicit `update all` is assumed.
        :qparam string status: optionally limits the query to issues of the
                               specified status.  Valid values are
                               ``"resolved"``, ``"unresolved"`` and
                               ``"ignored"``.
        :pparam string organization_slug: the slug of the organization the
                                          issues belong to.
        :pparam string project_slug: the slug of the project the issues
                                     belong to.
        :param string status: the new status for the issues.  Valid values
                              are ``"resolved"``, ``resolvedInNextRelease``,
                              ``"unresolved"``, and ``"ignored"``.
        :param int ignoreDuration: the number of minutes to ignore this issue.
        :param boolean isPublic: sets the issue to public or private.
        :param boolean merge: allows to merge or unmerge different issues.
        :param string assignedTo: the username of the user that should be
                                  assigned to this issue.
        :param boolean hasSeen: in case this API call is invoked with a user
                                context this allows changing of the flag
                                that indicates if the user has seen the
                                event.
        :param boolean isBookmarked: in case this API call is invoked with a
                                     user context this allows changing of
                                     the bookmark flag.
        :auth: required
        """
        group_ids = request.GET.getlist('id')
        if group_ids:
            group_list = Group.objects.filter(
                project=project, id__in=group_ids)
            # filter down group ids to only valid matches
            group_ids = [g.id for g in group_list]
            if not group_ids:
                return Response(status=204)
        else:
            group_list = None

        serializer = GroupValidator(
            data=request.DATA,
            partial=True,
            context={'project': project},
        )
        if not serializer.is_valid():
            return Response(serializer.errors, status=400)
        result = dict(serializer.object)

        acting_user = request.user if request.user.is_authenticated() else None

        if not group_ids:
            try:
                query_kwargs = self._build_query_params_from_request(
                    request, project)
            except ValidationError as exc:
                return Response({'detail': six.text_type(exc)}, status=400)

            # bulk mutations are limited to 1000 items
            # TODO(dcramer): it'd be nice to support more than this, but its
            # a bit too complicated right now
            limit = 1000
            query_kwargs['limit'] = limit

            # the paginator has a default max_limit of 100, which must be overwritten.
            cursor_result = search.query(
                paginator_options={'max_limit': limit}, **query_kwargs)

            group_list = list(cursor_result)
            group_ids = [g.id for g in group_list]

        is_bulk = len(group_ids) > 1

        queryset = Group.objects.filter(
            id__in=group_ids,
        )

        discard = result.get('discard')
        if discard:

            if not features.has('projects:custom-filters', project, actor=request.user):
                return Response({'detail': ['You do not have that feature enabled']}, status=400)

            group_list = list(queryset)
            groups_to_delete = []

            for group in group_list:
                with transaction.atomic():
                    try:
                        tombstone = GroupTombstone.objects.create(
                            previous_group_id=group.id,
                            actor_id=acting_user.id if acting_user else None,
                            **{name: getattr(group, name) for name in TOMBSTONE_FIELDS_FROM_GROUP}
                        )
                    except IntegrityError:
                        # in this case, a tombstone has already been created
                        # for a group, so no hash updates are necessary
                        pass
                    else:
                        groups_to_delete.append(group)

                        GroupHash.objects.filter(
                            group=group,
                        ).update(
                            group=None,
                            group_tombstone_id=tombstone.id,
                        )

            self._delete_groups(request, project, groups_to_delete)

            return Response(status=204)

        statusDetails = result.pop('statusDetails', result)
        status = result.get('status')
        if status in ('resolved', 'resolvedInNextRelease'):
            if status == 'resolvedInNextRelease' or statusDetails.get('inNextRelease'):
                release = Release.objects.filter(
                    projects=project,
                    organization_id=project.organization_id,
                ).order_by('-date_added')[0]
                activity_type = Activity.SET_RESOLVED_IN_RELEASE
                activity_data = {
                    # no version yet
                    'version': '',
                }
                status_details = {
                    'inNextRelease': True,
                    'actor': serialize(extract_lazy_object(request.user), request.user),
                }
                res_type = GroupResolution.Type.in_next_release
                res_status = GroupResolution.Status.pending
            elif statusDetails.get('inRelease'):
                release = statusDetails['inRelease']
                activity_type = Activity.SET_RESOLVED_IN_RELEASE
                activity_data = {
                    # no version yet
                    'version': release.version,
                }
                status_details = {
                    'inRelease': release.version,
                    'actor': serialize(extract_lazy_object(request.user), request.user),
                }
                res_type = GroupResolution.Type.in_release
                res_status = GroupResolution.Status.resolved
            else:
                release = None
                activity_type = Activity.SET_RESOLVED
                activity_data = {}
                status_details = {}

            now = timezone.now()

            for group in group_list:
                with transaction.atomic():
                    if release:
                        resolution_params = {
                            'release': release,
                            'type': res_type,
                            'status': res_status,
                            'actor_id': request.user.id
                            if request.user.is_authenticated() else None,
                        }
                        resolution, created = GroupResolution.objects.get_or_create(
                            group=group,
                            defaults=resolution_params,
                        )
                        if not created:
                            resolution.update(
                                datetime=timezone.now(), **resolution_params)
                    else:
                        resolution = None

                    affected = Group.objects.filter(
                        id=group.id,
                    ).update(
                        status=GroupStatus.RESOLVED,
                        resolved_at=now,
                    )
                    if not resolution:
                        created = affected

                    group.status = GroupStatus.RESOLVED
                    group.resolved_at = now

                    self._subscribe_and_assign_issue(
                        acting_user, group, result)

                    if created:
                        activity = Activity.objects.create(
                            project=group.project,
                            group=group,
                            type=activity_type,
                            user=acting_user,
                            ident=resolution.id if resolution else None,
                            data=activity_data,
                        )
                        # TODO(dcramer): we need a solution for activity rollups
                        # before sending notifications on bulk changes
                        if not is_bulk:
                            activity.send_notification()

                issue_resolved_in_release.send(
                    group=group,
                    project=project,
                    sender=acting_user,
                )

            result.update({
                'status': 'resolved',
                'statusDetails': status_details,
            })

        elif status:
            new_status = STATUS_CHOICES[result['status']]

            with transaction.atomic():
                happened = queryset.exclude(
                    status=new_status,
                ).update(
                    status=new_status,
                )

                GroupResolution.objects.filter(
                    group__in=group_ids,
                ).delete()

                if new_status == GroupStatus.IGNORED:
                    ignore_duration = (
                        statusDetails.pop('ignoreDuration', None) or
                        statusDetails.pop('snoozeDuration', None)
                    ) or None
                    ignore_count = statusDetails.pop(
                        'ignoreCount', None) or None
                    ignore_window = statusDetails.pop(
                        'ignoreWindow', None) or None
                    ignore_user_count = statusDetails.pop(
                        'ignoreUserCount', None) or None
                    ignore_user_window = statusDetails.pop(
                        'ignoreUserWindow', None) or None
                    if ignore_duration or ignore_count or ignore_user_count:
                        if ignore_duration:
                            ignore_until = timezone.now() + timedelta(
                                minutes=ignore_duration,
                            )
                        else:
                            ignore_until = None
                        for group in group_list:
                            state = {}
                            if ignore_count and not ignore_window:
                                state['times_seen'] = group.times_seen
                            if ignore_user_count and not ignore_user_window:
                                state['users_seen'] = group.count_users_seen()
                            GroupSnooze.objects.create_or_update(
                                group=group,
                                values={
                                    'until':
                                    ignore_until,
                                    'count':
                                    ignore_count,
                                    'window':
                                    ignore_window,
                                    'user_count':
                                    ignore_user_count,
                                    'user_window':
                                    ignore_user_window,
                                    'state':
                                    state,
                                    'actor_id':
                                    request.user.id if request.user.is_authenticated() else None,
                                }
                            )
                            result['statusDetails'] = {
                                'ignoreCount': ignore_count,
                                'ignoreUntil': ignore_until,
                                'ignoreUserCount': ignore_user_count,
                                'ignoreUserWindow': ignore_user_window,
                                'ignoreWindow': ignore_window,
                                'actor': serialize(extract_lazy_object(request.user), request.user),
                            }
                    else:
                        GroupSnooze.objects.filter(
                            group__in=group_ids,
                        ).delete()
                        ignore_until = None
                        result['statusDetails'] = {}
                else:
                    result['statusDetails'] = {}

            if group_list and happened:
                if new_status == GroupStatus.UNRESOLVED:
                    activity_type = Activity.SET_UNRESOLVED
                    activity_data = {}
                elif new_status == GroupStatus.IGNORED:
                    activity_type = Activity.SET_IGNORED
                    activity_data = {
                        'ignoreCount': ignore_count,
                        'ignoreDuration': ignore_duration,
                        'ignoreUntil': ignore_until,
                        'ignoreUserCount': ignore_user_count,
                        'ignoreUserWindow': ignore_user_window,
                        'ignoreWindow': ignore_window,
                    }

                for group in group_list:
                    group.status = new_status

                    activity = Activity.objects.create(
                        project=group.project,
                        group=group,
                        type=activity_type,
                        user=acting_user,
                        data=activity_data,
                    )
                    # TODO(dcramer): we need a solution for activity rollups
                    # before sending notifications on bulk changes
                    if not is_bulk:
                        if acting_user:
                            GroupSubscription.objects.subscribe(
                                user=acting_user,
                                group=group,
                                reason=GroupSubscriptionReason.status_change,
                            )
                        activity.send_notification()

        if 'assignedTo' in result:
            if result['assignedTo']:
                for group in group_list:
                    GroupAssignee.objects.assign(
                        group, result['assignedTo'], acting_user)

                    if 'isSubscribed' not in result or result['assignedTo'] != request.user:
                        GroupSubscription.objects.subscribe(
                            group=group,
                            user=result['assignedTo'],
                            reason=GroupSubscriptionReason.assigned,
                        )
                result['assignedTo'] = serialize(result['assignedTo'])
            else:
                for group in group_list:
                    GroupAssignee.objects.deassign(group, acting_user)

        if result.get('hasSeen') and project.member_set.filter(user=acting_user).exists():
            for group in group_list:
                instance, created = create_or_update(
                    GroupSeen,
                    group=group,
                    user=acting_user,
                    project=group.project,
                    values={
                        'last_seen': timezone.now(),
                    }
                )
        elif result.get('hasSeen') is False:
            GroupSeen.objects.filter(
                group__in=group_ids,
                user=acting_user,
            ).delete()

        if result.get('isBookmarked'):
            for group in group_list:
                GroupBookmark.objects.get_or_create(
                    project=project,
                    group=group,
                    user=acting_user,
                )
                GroupSubscription.objects.subscribe(
                    user=acting_user,
                    group=group,
                    reason=GroupSubscriptionReason.bookmark,
                )
        elif result.get('isBookmarked') is False:
            GroupBookmark.objects.filter(
                group__in=group_ids,
                user=acting_user,
            ).delete()

        # TODO(dcramer): we could make these more efficient by first
        # querying for rich rows are present (if N > 2), flipping the flag
        # on those rows, and then creating the missing rows
        if result.get('isSubscribed') in (True, False):
            is_subscribed = result['isSubscribed']
            for group in group_list:
                # NOTE: Subscribing without an initiating event (assignment,
                # commenting, etc.) clears out the previous subscription reason
                # to avoid showing confusing messaging as a result of this
                # action. It'd be jarring to go directly from "you are not
                # subscribed" to "you were subscribed due since you were
                # assigned" just by clicking the "subscribe" button (and you
                # may no longer be assigned to the issue anyway.)
                GroupSubscription.objects.create_or_update(
                    user=acting_user,
                    group=group,
                    project=project,
                    values={
                        'is_active': is_subscribed,
                        'reason': GroupSubscriptionReason.unknown,
                    },
                )

            result['subscriptionDetails'] = {
                'reason': SUBSCRIPTION_REASON_MAP.get(
                    GroupSubscriptionReason.unknown,
                    'unknown',
                ),
            }

        if result.get('isPublic'):
            queryset.update(is_public=True)
            for group in group_list:
                if group.is_public:
                    continue
                group.is_public = True
                Activity.objects.create(
                    project=group.project,
                    group=group,
                    type=Activity.SET_PUBLIC,
                    user=acting_user,
                )
        elif result.get('isPublic') is False:
            queryset.update(is_public=False)
            for group in group_list:
                if not group.is_public:
                    continue
                group.is_public = False
                Activity.objects.create(
                    project=group.project,
                    group=group,
                    type=Activity.SET_PRIVATE,
                    user=acting_user,
                )

        # XXX(dcramer): this feels a bit shady like it should be its own
        # endpoint
        if result.get('merge') and len(group_list) > 1:
            primary_group = sorted(group_list, key=lambda x: -x.times_seen)[0]
            children = []
            transaction_id = uuid4().hex
            for group in group_list:
                if group == primary_group:
                    continue
                children.append(group)
                group.update(status=GroupStatus.PENDING_MERGE)
                merge_group.delay(
                    from_object_id=group.id,
                    to_object_id=primary_group.id,
                    transaction_id=transaction_id,
                )

            Activity.objects.create(
                project=primary_group.project,
                group=primary_group,
                type=Activity.MERGE,
                user=acting_user,
                data={
                    'issues': [{
                        'id': c.id
                    } for c in children],
                },
            )

            result['merge'] = {
                'parent': six.text_type(primary_group.id),
                'children': [six.text_type(g.id) for g in children],
            }

        return Response(result)
Esempio n. 41
0
    def get(self, request, project):
        """
        List a Project's Issues
        ```````````````````````

        Return a list of issues (groups) bound to a project.  All parameters are
        supplied as query string parameters.

        A default query of ``is:unresolved`` is applied. To return results
        with other statuses send an new query value (i.e. ``?query=`` for all
        results).

        The ``statsPeriod`` parameter can be used to select the timeline
        stats which should be present. Possible values are: '' (disable),
        '24h', '14d'

        :qparam string statsPeriod: an optional stat period (can be one of
                                    ``"24h"``, ``"14d"``, and ``""``).
        :qparam bool shortIdLookup: if this is set to true then short IDs are
                                    looked up by this function as well.  This
                                    can cause the return value of the function
                                    to return an event issue of a different
                                    project which is why this is an opt-in.
                                    Set to `1` to enable.
        :qparam querystring query: an optional Sentry structured search
                                   query.  If not provided an implied
                                   ``"is:unresolved"`` is assumed.)
        :pparam string organization_slug: the slug of the organization the
                                          issues belong to.
        :pparam string project_slug: the slug of the project the issues
                                     belong to.
        :auth: required
        """
        stats_period = request.GET.get('statsPeriod')
        if stats_period not in (None, '', '24h', '14d'):
            return Response({"detail": ERR_INVALID_STATS_PERIOD}, status=400)
        elif stats_period is None:
            # default
            stats_period = '24h'
        elif stats_period == '':
            # disable stats
            stats_period = None

        query = request.GET.get('query', '').strip()

        if query:
            matching_group = None
            matching_event = None
            if len(query) == 32:
                # check to see if we've got an event ID
                try:
                    mapping = EventMapping.objects.get(
                        project_id=project.id,
                        event_id=query,
                    )
                except EventMapping.DoesNotExist:
                    pass
                else:
                    matching_group = Group.objects.get(id=mapping.group_id)
                    try:
                        matching_event = Event.objects.get(
                            event_id=query, project_id=project.id)
                    except Event.DoesNotExist:
                        pass

            # If the query looks like a short id, we want to provide some
            # information about where that is.  Note that this can return
            # results for another project.  The UI deals with this.
            elif request.GET.get('shortIdLookup') == '1' and \
                    looks_like_short_id(query):
                try:
                    matching_group = Group.objects.by_qualified_short_id(
                        project.organization_id, query
                    )
                except Group.DoesNotExist:
                    matching_group = None

            if matching_group is not None:
                response = Response(
                    serialize(
                        [matching_group], request.user,
                        StreamGroupSerializer(
                            stats_period=stats_period,
                            matching_event_id=getattr(
                                matching_event, 'id', None)
                        )
                    )
                )
                response['X-Sentry-Direct-Hit'] = '1'
                return response

        try:
            query_kwargs = self._build_query_params_from_request(
                request, project)
        except ValidationError as exc:
            return Response({'detail': six.text_type(exc)}, status=400)

        count_hits = features.has(
            'projects:stream-hit-counts',
            project=project,
            actor=request.user)

        cursor_result = search.query(count_hits=count_hits, **query_kwargs)

        results = list(cursor_result)

        context = serialize(
            results, request.user, StreamGroupSerializer(
                stats_period=stats_period))

        # HACK: remove auto resolved entries
        if query_kwargs.get('status') == GroupStatus.UNRESOLVED:
            context = [r for r in context if r['status'] == 'unresolved']

        response = Response(context)

        self.add_cursor_headers(request, response, cursor_result)

        if results and query not in SAVED_SEARCH_QUERIES:
            advanced_search.send(project=project, sender=request.user)

        return response
Esempio n. 42
0
    def delete(self, request, contact_id):

        contact = Contact.objects.get(id=contact_id)
        contact.delete()

        return Response(status=status.HTTP_204_NO_CONTENT)
Esempio n. 43
0
 def highlight(self, request, *args, **kwargs):
     snippet = self.get_object()
     return Response(snippet.highlighted)
Esempio n. 44
0
 def get(self, request):
     todos = Todos.objects.all()
     serializer = TodosSerializer(todos, many=True)
     return Response(serializer.data)
Esempio n. 45
0
 def delete(self, request, id):
     article = self.get_object(id=id)
     article.delete()
     return Response(status=status.HTTP_204_NO_CONTENT)
Esempio n. 46
0
    def get(self, request, dataset_id, *args, **kwargs):
        d = get_formatted_data(dataset_id)

        return Response(d, status=status.HTTP_200_OK)
 def enroll(self, request, *args, **kwargs):
     # parametr pk podany w url pobrał nam obiekt.
     course = self.get_object()
     # dodanie user do związku "wiele do wielu"
     course.students.add(request.user)
     return Response({'enrolled': True})
Esempio n. 48
0
 def toggle_solved(self, request, pk=None):
     incident = self.get_object()
     incident.solved = not incident.solved
     incident.end = datetime.now()
     incident.save()
     return Response({'solved': incident.solved})
Esempio n. 49
0
 def get(self, request):
     return Response({
         'live': True,
     })
 def post(self, request, pk, format=None):
     course = get_object_or_404(Course, pk=pk)
     # Dodanie bieżącego użytkownika do związku students typu „wiele do wielu”
     course.students.add(request.user)
     # użytkownik po żądaniu dostaje wiadomość
     return Response({'enrolled': True})
Esempio n. 51
0
 def list(self, request):
     queryset = Book.objects.all()
     serializer = BookSerializer(queryset, many=True)
     return Response(serializer.data)
Esempio n. 52
0
 def retrieve(self, request, pk=None):
     queryset = Book.objects.all()
     book = get_object_or_404(queryset, pk=pk)
     serializer = BookSerializer(book)
     return Response(serializer.data)
Esempio n. 53
0
    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)

        return Response(serializer.data)
Esempio n. 54
0
    def delete(self, request, todos_id):
        todos = Todos.objects.get(id=todos_id)
        todos.delete()

        return Response({"msg": 'Eliminado'}, status=status.HTTP_200_OK)
Esempio n. 55
0
 def get_object(self, id):
     try:
         return User.objects.get(id=id)
     except User.DoesNotExist as e:
         return Response({'error': str(e)})
Esempio n. 56
0
 def get(self, request, id):
     user = self.get_object(id)
     serializer = UserSerializer(user)
     return Response(serializer.data)
Esempio n. 57
0
 def get(self, request, *args, **kwargs):
     content = self.list(request, *args, **kwargs).data
     return Response({'logs': content})
Esempio n. 58
0
 def delete(self, request, dataset_id, *args, **kwargs):
     dataset = Dataset.objects.all().get(id=dataset_id)
     dataset.delete()
     return Response({}, status=status.HTTP_200_OK)
Esempio n. 59
0
    def monthly_payment(self, allocations):
        validated_data = self.validated_data
        payment_mode = validated_data["payment_mode"]
        amount = validated_data["amount"]

        if validated_data["to"] == TO_2022:
            payment_type = Presidentielle2022Config.DONATION_SUBSCRIPTION_TYPE
        else:
            payment_type = DonsConfig.SUBSCRIPTION_TYPE

        # Confirm email if the user is unknown
        if self.person is None:
            email = validated_data.pop("email", None)

            if not "allocations" in validated_data:
                validated_data["allocations"] = "[]"

            confirmation_view_name = "monthly_donation_confirm"
            if validated_data["to"] == TO_2022:
                confirmation_view_name = "monthly_donation_2022_confirm"

            send_monthly_donation_confirmation_email.delay(
                confirmation_view_name=confirmation_view_name,
                email=email,
                subscription_total=amount,
                **validated_data,
            )
            self.clear_session()
            return Response(
                {"next": reverse("monthly_donation_confirmation_email_sent")}
            )

        # Redirect if user already monthly donator
        if Subscription.objects.filter(
            person=self.person,
            status=Subscription.STATUS_ACTIVE,
            mode=payment_mode,
        ):
            # stocker toutes les infos en session
            # attention à ne pas juste modifier le dictionnaire existant,
            # parce que la session ne se "rendrait pas compte" qu'elle a changé
            # et cela ne serait donc pas persisté
            self.request.session[DONATION_SESSION_NAMESPACE] = {
                "new_subscription": {
                    "type": payment_type,
                    "mode": payment_mode,
                    "subscription_total": amount,
                    "meta": validated_data,
                },
                **self.request.session.get(DONATION_SESSION_NAMESPACE, {}),
            }
            return Response({"next": reverse("already_has_subscription")})

        with transaction.atomic():
            subscription = create_monthly_donation(
                person=self.person,
                mode=payment_mode,
                subscription_total=amount,
                allocations=allocations,
                meta=validated_data,
                type=payment_type,
            )

        self.clear_session()
        return Response({"next": reverse("subscription_page", args=[subscription.pk])})
Esempio n. 60
0
 def get_object(self, user):
     try:
         return Order.objects.get(user=user)
     except Order.DoesNotExist as e:
         return Response({'error': str(e)})