Example #1
0
    def post(self, request):
        if not MarkAccess(request.user).can_upload:
            raise exceptions.PermissionDenied(
                _("You don't have an access to create new marks"))

        marks_links = []
        marks_uploader = MarksUploader(request.user)
        for f in self.request.FILES.getlist('file'):
            with zipfile.ZipFile(f, 'r') as zfp:
                if all(
                        file_name.endswith('.zip')
                        for file_name in zfp.namelist()):
                    marks_dir = extract_archive(f)
                    for arch_name in os.listdir(marks_dir.name):
                        with open(os.path.join(marks_dir.name, arch_name),
                                  mode='rb') as fp:
                            marks_links.append(
                                marks_uploader.upload_mark(
                                    File(fp, name=arch_name))[1])
                    pass
                else:
                    marks_links.append(marks_uploader.upload_mark(f)[1])

        if len(marks_links) == 1:
            return Response({'url': marks_links[0]})
        return Response({
            'message': _('Number of created marks: %(number)s') % {
                'number': len(marks_links)
            }
        })
Example #2
0
 def get_context_data(self, **kwargs):
     access = MarkAccess(self.request.user, mark=self.object)
     if not access.can_edit:
         raise BridgeException(
             _("You don't have an access to edit this mark"))
     context = super().get_context_data(**kwargs)
     mark_version = self.version_model.objects.select_related('mark')\
         .get(mark=self.object, version=int(self.request.GET.get('version', self.object.version)))
     context.update({
         'access':
         access,
         'versions':
         self.versions_serializer_class(mark=self.object).data,
         'cancel_url':
         reverse('marks:{}'.format(self.mark_type), args=[self.object.id]),
         'save_url':
         reverse('marks:api-{mtype}-detail'.format(mtype=self.mark_type),
                 args=[self.object.id]),
         'save_method':
         'PUT',
         'data':
         MarkVersionFormData(self.mark_type, mark_version=mark_version),
         'attrs':
         mark_version.attrs.all()
     })
     return context
Example #3
0
    def get_context_data(self, **kwargs):
        mark_version = MarkUnsafeHistory.objects.select_related('mark', 'author')\
            .get(mark=self.object, version=F('mark__version'))
        with self.object.error_trace.file.file as fp:
            error_trace = fp.read().decode('utf-8')

        return {
            'mark':
            self.object,
            'mark_version':
            mark_version,
            'access':
            MarkAccess(self.request.user, mark=self.object),
            'versions':
            UMVlistSerializerRO(mark=self.object).data,
            'tags':
            MarkTagsTree(mark_version),
            'reports':
            UnsafeAssociationsTable(self.request.user, self.object,
                                    self.get_view(VIEW_TYPES[13]),
                                    self.request.GET),
            'error_trace':
            error_trace,
            'compare_func': {
                'name': self.object.function,
                'desc': COMPARE_FUNCTIONS[self.object.function]['desc']
            },
            'convert_func': {
                'name':
                COMPARE_FUNCTIONS[self.object.function]['convert'],
                'desc':
                CONVERT_FUNCTIONS[COMPARE_FUNCTIONS[self.object.function]
                                  ['convert']]
            }
        }
Example #4
0
 def __init__(self, user, report, view):
     self.user = user
     self.report = report
     self.view = view
     self.titles = MARK_TITLES
     self.can_mark = MarkAccess(user, report=report).can_create
     self.ass_types = ASSOCIATION_TYPE
     self.statuses = self.verdicts = None
Example #5
0
 def __init__(self, user, report, view):
     self.user = user
     self.report = report
     self.view = view
     self.can_mark = MarkAccess(user, report=report).can_create
     self.ass_types = ASSOCIATION_TYPE
     self.statuses = self.verdicts = None
     self.values, self.header = self.__get_values()
Example #6
0
    def destroy(self, request, *args, **kwargs):
        mark = self.get_object()
        access = MarkAccess(request.user, mark=mark)
        if not access.can_edit:
            raise exceptions.ValidationError(
                _("You don't have an access to edit this mark"))

        checked_versions = mark.versions.filter(
            version__in=json.loads(request.data['versions']))
        if len(checked_versions) == 0:
            raise exceptions.ValidationError(_('There is nothing to delete'))
        if not access.can_remove_versions(checked_versions):
            raise exceptions.ValidationError(
                _("You don't have an access to remove one of the selected version"
                  ))
        checked_versions.delete()

        return Response(
            {'message': _('Selected versions were successfully deleted')})
Example #7
0
    def post(self, request):
        if not MarkAccess(request.user).can_upload:
            raise exceptions.PermissionDenied(
                _("You don't have an access to create new marks"))

        marks_links = []
        failed_mark_uploads = 0
        marks_uploader = MarksUploader(request.user)
        for f in self.request.FILES.getlist('file'):
            with zipfile.ZipFile(f, 'r') as zfp:
                if all(
                        file_name.endswith('.zip')
                        for file_name in zfp.namelist()):
                    marks_dir = extract_archive(f)
                    for arch_name in os.listdir(marks_dir.name):
                        with open(os.path.join(marks_dir.name, arch_name),
                                  mode='rb') as fp:
                            try:
                                marks_links.append(
                                    marks_uploader.upload_mark(
                                        File(fp, name=arch_name))[1])
                            except Exception as e:
                                logger.exception(e)
                                logger.error(
                                    'Uploading of mark "{}" has failed.'.
                                    format(arch_name))
                                failed_mark_uploads += 1
                else:
                    marks_links.append(marks_uploader.upload_mark(f)[1])

        if len(marks_links) == 1:
            return Response({'url': marks_links[0]})

        if failed_mark_uploads:
            return Response({
                'message':
                _('Number of created marks: %(number)s.'
                  ' Number of marks which uploading failed: %(failed_number)s.'
                  ' See logs for details.') % {
                      'number': len(marks_links),
                      'failed_number': failed_mark_uploads
                  }
            })
        else:
            return Response({
                'message': _('Number of created marks: %(number)s') % {
                    'number': len(marks_links)
                }
            })
Example #8
0
    def create(self, request, *args, **kwargs):
        report = get_object_or_404(ReportSafe,
                                   pk=request.data.get('report_id', 0))
        if not MarkAccess(request.user, report=report).can_create:
            raise exceptions.PermissionDenied(
                _("You don't have an access to create new marks"))

        serializer = self.get_serializer(data=request.data,
                                         fields=('is_modifiable', 'verdict',
                                                 'mark_version'))
        serializer.is_valid(raise_exception=True)
        mark, cache_id = perform_safe_mark_create(self.request.user, report,
                                                  serializer)
        changes_url = '{}?mark_id={}'.format(
            reverse('marks:safe-ass-changes', args=[cache_id]), mark.id)
        return Response({'url': changes_url}, status=status.HTTP_201_CREATED)
Example #9
0
 def get_context_data(self, **kwargs):
     mark_version = MarkUnknownHistory.objects.select_related('mark', 'author')\
         .get(mark=self.object, version=F('mark__version'))
     return {
         'mark':
         self.object,
         'mark_version':
         mark_version,
         'access':
         MarkAccess(self.request.user, mark=self.object),
         'versions':
         FMVlistSerializerRO(mark=self.object).data,
         'reports':
         UnknownAssociationsTable(self.request.user, self.object,
                                  self.get_view(VIEW_TYPES[15]),
                                  self.request.GET)
     }
Example #10
0
    def update(self, request, *args, **kwargs):
        # Partial update is not allowed
        instance = self.get_object()
        if not MarkAccess(request.user, mark=instance).can_edit:
            raise exceptions.PermissionDenied(
                _("You don't have an access to edit this mark"))

        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         fields=('is_modifiable', 'verdict',
                                                 'mark_version'))
        serializer.is_valid(raise_exception=True)
        cache_id = perform_safe_mark_update(self.request.user, serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        changes_url = '{}?mark_id={}'.format(
            reverse('marks:safe-ass-changes', args=[cache_id]), instance.id)
        return Response({'url': changes_url})
Example #11
0
 def get_context_data(self, **kwargs):
     access = MarkAccess(self.request.user, report=self.object)
     if not access.can_create:
         raise BridgeException(
             _("You don't have an access to create new mark"))
     context = super().get_context_data(**kwargs)
     context.update({
         'access':
         access,
         'cancel_url':
         reverse('reports:{}'.format(self.mark_type),
                 args=[self.object.id]),
         'save_url':
         reverse('marks:api-{mtype}-list'.format(mtype=self.mark_type)),
         'save_method':
         'POST',
         'data':
         MarkVersionFormData(self.mark_type),
         'attrs':
         self.object.attrs.all()
     })
     return context
Example #12
0
    def __init__(self, user, report, view):
        self.user = user
        self.report = report
        self.view = view
        self.can_mark = MarkAccess(user, report=report).can_create()
        self.statuses = MARK_STATUS
        self.ass_types = ASSOCIATION_TYPE
        if isinstance(report, ReportUnsafe):
            self.type = 'unsafe'
            self.verdicts = MARK_UNSAFE
        elif isinstance(report, ReportSafe):
            self.type = 'safe'
            self.verdicts = MARK_SAFE
        elif isinstance(report, ReportUnknown):
            self.type = 'unknown'
        else:
            return

        self.selected_columns = self.__selected()
        self.available_columns = self.__available()

        self.columns = self.__get_columns()
        self.header = Header(self.columns, MARK_TITLES).struct
        self.values = self.__get_values()
Example #13
0
 def get_context_data(self, **kwargs):
     mark_version = MarkSafeHistory.objects.select_related('mark', 'author') \
         .get(mark=self.object, version=F('mark__version'))
     return {
         'mark':
         self.object,
         'mark_version':
         mark_version,
         'verdict': {
             'id': mark_version.verdict,
             'text': mark_version.get_verdict_display(),
             'color': safe_color(mark_version.verdict, inverted=True)
         },
         'access':
         MarkAccess(self.request.user, mark=self.object),
         'versions':
         SMVlistSerializerRO(mark=self.object).data,
         'tags':
         MarkTagsTree(mark_version),
         'reports':
         SafeAssociationsTable(self.request.user, self.object,
                               self.get_view(VIEW_TYPES[14]),
                               self.request.GET)
     }
Example #14
0
 def perform_destroy(self, instance):
     if not MarkAccess(self.request.user, mark=instance).can_delete:
         raise exceptions.PermissionDenied(
             _("You don't have an access to remove this mark"))
     reports_ids = RemoveUnknownMark(instance).destroy()
     RecalculateUnknownCache(reports_ids)