Esempio n. 1
0
def edit_file_revisions(request, code, step='edit_revisions', template='mdtui/indexing.html'):
    """Editing file revisions for given code"""
    form = DocumentUploadForm(request.POST or None, request.FILES or None)
    revision_file = request.FILES.get('file', None)
    errors = []
    context = {
        'step': step,
        'doc_name': code,
        'upload_form': form,
        'barcode': None,  # for compatibility with scripts (We are reusing modal scripts in templates)
    }
    processor = DocumentProcessor()
    doc = processor.read(code, {'user': request.user, 'only_metadata': True})
    frd = doc.get_file_revisions_data()
    db_info = doc.get_db_info()
    if not processor.errors and not doc.marked_deleted:
        if revision_file and form.is_valid():
            options = {
                'user': request.user,
                'update_file': revision_file,
            }
            processor.update(code, options)
            if not processor.errors:
                return HttpResponseRedirect(request.path)
            else:
                errors.append(processor.errors)
        context.update({
            'file_revision_data': frd,
            'file_revision_data_order_list': sorted(frd.iterkeys()),
            'index_data': db_info,
        })
    if processor.errors or doc.marked_deleted or (not frd and not db_info['mdt_indexes']):
        errors = [MDTUI_ERROR_STRINGS['NO_DOC'] + '. Maybe you should go index it first?']
    context.update({'error_warnings': errors})
    return render(request, template, context)
Esempio n. 2
0
def upload(request, template_name='browser/upload.html', extra_context=None):
    """Upload file processing.

    Uploaded file will be check against available rules to
    determine storage, validator, and security plugins.
    """
    extra_context = extra_context or {}

    form = UploadForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            processor = DocumentProcessor()
            upl_file = form.files['file']
            # finding file in system. Updating if found and storing new if not or uncategorized.
            dms_file = processor.read(upl_file.name, {'user': request.user, 'only_metadata': True})
            if not processor.errors and not dms_file.get_docrule().uncategorized:
                processor.update(upl_file.name, {'user': request.user, 'update_file': upl_file})
            else:
                processor.errors = []
                processor.create(upl_file, {'user': request.user})
            # Handling processor errors in interactions.
            if not processor.errors:
                if dms_file.get_docrule().uncategorized:
                    messages.success(request, 'File has been uploaded into uncategorized.')
                else:
                    messages.success(request, 'File has been uploaded.')
                log.info('browser.upload file: %s sucess' % form.files['file'].name)
            else:
                error_string = "; ".join([unicode(x) for x in processor.errors])
                messages.error(request, error_string)
                log.error('browser.upload errror: %s' % error_string)

    extra_context['form'] = form
    return render(request, template_name, extra_context)
Esempio n. 3
0
def edit_file_revisions(request,
                        code,
                        step='edit_revisions',
                        template='mdtui/indexing.html'):
    """Editing file revisions for given code

    @param request: is a Django request object
    @param code: is a DMS Object() code for view interactions
    @param step: is a current step name (for template rendering)
    @param template: is a name of template for this view"""
    form = DocumentUploadForm(request.POST or None, request.FILES or None)
    revision_file = request.FILES.get('file', None)
    errors = []
    context = {
        'step': step,
        'doc_name': code,
        'upload_form': form,
        'barcode':
        None,  # for compatibility with scripts (We are reusing modal scripts in templates)
    }
    processor = DocumentProcessor()
    doc = processor.read(code, {'user': request.user, 'only_metadata': True})
    frd = doc.get_file_revisions_data()
    db_info = doc.get_db_info()
    if not processor.errors and not doc.marked_deleted:
        if revision_file and form.is_valid():
            options = {
                'user': request.user,
                'update_file': revision_file,
            }
            processor.update(code, options)
            if not processor.errors:
                return HttpResponseRedirect(request.path)
            else:
                errors.append(processor.errors)
        context.update({
            'file_revision_data': frd,
            'file_revision_data_order_list': sorted(frd.iterkeys()),
            'index_data': db_info,
        })
    if not db_info:
        errors = [
            MDTUI_ERROR_STRINGS['NO_DOC'] +
            '. Maybe you should go index it first?'
        ]
    elif processor.errors or doc.marked_deleted or (
            not frd and not db_info['mdt_indexes']):
        errors = [
            MDTUI_ERROR_STRINGS['NO_DOC'] +
            '. Maybe you should go index it first?'
        ]
    context.update({'error_warnings': errors})
    return render(request, template, context)
Esempio n. 4
0
def edit_result(request, step='edit_finish', template='mdtui/indexing.html'):
    """Confirmation step for editing indexes"""
    # initialising context
    required_vars = ('edit_processor_indexes', 'edit_index_barcode', 'old_document_keys', 'edit_return', "edit_mdts")
    variables = {}
    warnings = []
    for var in required_vars:
        try:
            variables[var] = request.session[var]
        except KeyError:
            variables[var] = ''
            # Error handling into warnings
            if not var == 'edit_return':
                error_name = MDTUI_ERROR_STRINGS['ERROR_EDIT_INDEXES_FINISHED']
                log.error('indexing_finished error: variable: %s,  %s' % (var, error_name))
                if not error_name in warnings:
                    warnings.append(error_name)
            pass
    log.debug('indexing_edit_result called with: step: "%s", variables: "%s",' % (step, variables))

    if request.POST:
        code = variables['edit_index_barcode']
        processor = DocumentProcessor()
        options = {
            'new_indexes': variables['edit_processor_indexes'],
            'user': request.user,
        }
        processor.update(code, options=options)
        if not processor.errors:
            # cleanup session here because editing is finished
            for var in required_vars:
                _cleanup_session_var(request, var)
            return HttpResponseRedirect(variables['edit_return'])
        else:
            for error in processor.errors:
                warnings.append(error)
    # Building new indexes for confirmation rendering
    context_secondary_indexes = {}
    if 'edit_processor_indexes' in variables.iterkeys() and variables['edit_processor_indexes']:
        for index, value in variables['edit_processor_indexes'].iteritems():
            if not index in ['metadata_user_name', 'metadata_user_id']:
                context_secondary_indexes[index] = value
    context = {
        'step': step,
        'document_keys': context_secondary_indexes,
        'barcode': variables['edit_index_barcode'],
        'old_document_keys': variables['old_document_keys'],
        'edit_return': variables['edit_return'],
        'warnings': warnings,
    }
    return render(request, template, context)
Esempio n. 5
0
 def post(self, request, code, suggested_format=None):
     if 'file' in request.FILES:
         uploaded_file = request.FILES['file']
     else:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     processor = DocumentProcessor()
     options = {
         'user': request.user,
         'barcode': code,
     }
     if uploaded_file.size == 0:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     document = processor.create(uploaded_file, options)
     if len(processor.errors) > 0:
         log.error('OldFileHandler.create errors: %s' % processor.errors)
         error = processor.errors[0]
         if error.__class__.__name__ in ['unicode', 'str']:
             return Response(status=status.HTTP_400_BAD_REQUEST)
         if error.code == 409:
             new_processor = DocumentProcessor()
             options['update_file'] = uploaded_file
             document = new_processor.update(code, options)
             if len(new_processor.errors) > 0:
                 return Response(status=status.HTTP_400_BAD_REQUEST)
     log.info('OldFileHandler.create request fulfilled for %s' %
              document.get_filename())
     return Response(document.get_filename(), status=status.HTTP_200_OK)
Esempio n. 6
0
 def post(self, request, code, suggested_format=None):
     if 'file' in request.FILES:
         uploaded_file = request.FILES['file']
     else:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     processor = DocumentProcessor()
     options = {
         'user': request.user,
         'barcode': code,
     }
     if uploaded_file.size == 0:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     document = processor.create(uploaded_file, options)
     if len(processor.errors) > 0:
         log.error('OldFileHandler.create errors: %s' % processor.errors)
         error = processor.errors[0]
         if error.__class__.__name__ in ['unicode', 'str']:
             return Response(status=status.HTTP_400_BAD_REQUEST)
         if error.code == 409:
             new_processor = DocumentProcessor()
             options['update_file'] = uploaded_file
             document = new_processor.update(code, options)
             if len(new_processor.errors) > 0:
                 return Response(status=status.HTTP_400_BAD_REQUEST)
     log.info('OldFileHandler.create request fulfilled for %s' % document.get_filename())
     return Response(document.get_filename(), status=status.HTTP_200_OK)
Esempio n. 7
0
    def put(self, request, code, suggested_format=None):
        """Used to work with "update" sequence of DMS code.

        to update a code you need to send a PUT request here.
        PUT must contain:

        @param code: the DMS "code" of file to be updated. e.g.: ADL-0001
        @param suggested_format: format of file for code to be updated. To have ability to post files in certain format.
        """
        context = {'request': request}
        conten_type = request.content_type
        uploaded_obj = None
        if 'multipart/form-data' in conten_type:
            # We have a file upload encoded with multipart/form-data
            file_content = StringIO(request.body)
            parser = MultiPartParser()
            dnf = parser.parse(file_content,
                               media_type=conten_type,
                               parser_context=context)
            extra = dnf.data
            if 'file' in dnf.files:
                uploaded_obj = dnf.files['file']
        else:
            extra = request.QUERY_PARAMS
        # TODO: do we require SQL tagging logic in this API call?
        sql_tag_string = extra.get('tag_string', None)
        sql_remove_tag_string = extra.get('remove_tag_string', None)
        new_name = extra.get('new_name', None)
        new_type = extra.get('new_type', None)
        index_data = extra.get('indexing_data', None)
        if index_data:
            index_data = json.loads(index_data)
        processor = DocumentProcessor()
        options = {
            'tag_string': sql_tag_string,
            'remove_tag_string': sql_remove_tag_string,
            'extension': suggested_format,
            'new_name': new_name,
            'new_type': new_type,
            'new_indexes': index_data,
            'update_file': uploaded_obj,
            'user': request.user,
        }
        document = processor.update(code, options)
        if len(processor.errors) > 0:
            log.error('FileHandler.update manager errors %s' %
                      processor.errors)
            if settings.DEBUG:
                print processor.errors
                raise Exception('FileHandler.update manager errors')
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        log.info(
            'FileHandler.update request fulfilled for code: %s, extension: %s'
            % (code, suggested_format))
        resp = DMSOBjectRevisionsData(document).data
        return Response(resp, status=status.HTTP_200_OK)
Esempio n. 8
0
def upload(request, template_name='browser/upload.html', extra_context=None):
    """Upload file processing.

    Uploaded file will be check against available rules to
    determine storage, validator, and security plugins.
    """
    extra_context = extra_context or {}

    form = UploadForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            processor = DocumentProcessor()
            upl_file = form.files['file']
            # finding file in system. Updating if found and storing new if not or uncategorized.
            dms_file = processor.read(upl_file.name, {
                'user': request.user,
                'only_metadata': True
            })
            if not processor.errors and not dms_file.get_docrule(
            ).uncategorized:
                processor.update(upl_file.name, {
                    'user': request.user,
                    'update_file': upl_file
                })
            else:
                processor.errors = []
                processor.create(upl_file, {'user': request.user})
            # Handling processor errors in interactions.
            if not processor.errors:
                if dms_file.get_docrule().uncategorized:
                    messages.success(
                        request, 'File has been uploaded into uncategorized.')
                else:
                    messages.success(request, 'File has been uploaded.')
                log.info('browser.upload file: %s sucess' %
                         form.files['file'].name)
            else:
                error_string = "; ".join(
                    [unicode(x) for x in processor.errors])
                messages.error(request, error_string)
                log.error('browser.upload errror: %s' % error_string)

    extra_context['form'] = form
    return render(request, template_name, extra_context)
Esempio n. 9
0
def edit_type(request, code, step='edit_type', template='mdtui/indexing.html'):
    """Indexing step: Edit. Editing document type (in fact document rename)

    @param request: is a Django request object
    @param code: is a DMS Object() code for view interactions
    @param step: is a current step name (for template rendering)
    @param template: is a name of template for this view"""
    context = {}
    warnings = [
        MDTUI_ERROR_STRINGS['EDIT_TYPE_WARNING'],
    ]
    error_warnings = []
    form = False
    processor = DocumentProcessor()
    return_url = reverse('mdtui-edit', kwargs={'code': code})

    log.debug('indexing_edit_type view called with code: %s' % code)
    doc = processor.read(code, {
        'user': request.user,
    })
    if not processor.errors:
        empty_form = make_document_type_select_form(
            request.user, docrule_initial=doc.get_docrule())
        form = empty_form(request.POST or None)
        if request.POST:
            if form.is_valid():
                docrule = form.cleaned_data['docrule']
                current_docrule = doc.get_docrule()
                if not docrule == current_docrule:
                    options = {
                        'user': request.user,
                        'new_type': docrule,
                    }
                    doc = processor.update(code, options)
                    if not processor.errors:
                        return HttpResponseRedirect(
                            reverse('mdtui-edit',
                                    kwargs={'code': doc.get_filename()}))
                else:
                    warnings = [
                        MDTUI_ERROR_STRINGS['EDIT_TYPE_ERROR'],
                    ]
    # Can cause errors in two places here (on doc read and update)
    if processor.errors:
        for error in processor.errors:
            error_warnings.append(error)
    context.update({
        'step': step,
        'doc_name': code,
        'docrule': doc.get_docrule(),
        'warnings': warnings,
        'form': form,
        'type_edit_return': return_url,
        'error_warnings': error_warnings,
    })
    return render(request, template, context)
Esempio n. 10
0
    def put(self, request, code, suggested_format=None):
        """Used to work with "update" sequence of DMS code.

        to update a code you need to send a PUT request here.
        PUT must contain:

        @param code: the DMS "code" of file to be updated. e.g.: ADL-0001
        @param suggested_format: format of file for code to be updated. To have ability to post files in certain format.
        """
        context = {'request': request}
        conten_type = request.content_type
        uploaded_obj = None
        if 'multipart/form-data' in conten_type:
            # We have a file upload encoded with multipart/form-data
            file_content = StringIO(request.body)
            parser = MultiPartParser()
            dnf = parser.parse(file_content, media_type=conten_type, parser_context=context)
            extra = dnf.data
            if 'file' in dnf.files:
                uploaded_obj = dnf.files['file']
        else:
            extra = request.QUERY_PARAMS
        # TODO: do we require SQL tagging logic in this API call?
        sql_tag_string = extra.get('tag_string', None)
        sql_remove_tag_string = extra.get('remove_tag_string', None)
        new_name = extra.get('new_name', None)
        new_type = extra.get('new_type', None)
        index_data = extra.get('indexing_data', None)
        if index_data:
            index_data = json.loads(index_data)
        processor = DocumentProcessor()
        options = {
            'tag_string': sql_tag_string,
            'remove_tag_string': sql_remove_tag_string,
            'extension': suggested_format,
            'new_name': new_name,
            'new_type': new_type,
            'new_indexes': index_data,
            'update_file': uploaded_obj,
            'user': request.user,
        }
        document = processor.update(code, options)
        if len(processor.errors) > 0:
            log.error('FileHandler.update manager errors %s' % processor.errors)
            if settings.DEBUG:
                print processor.errors
                raise Exception('FileHandler.update manager errors')
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        log.info('FileHandler.update request fulfilled for code: %s, extension: %s'
                 % (code, suggested_format))
        resp = DMSOBjectRevisionsData(document).data
        return Response(resp, status=status.HTTP_200_OK)
Esempio n. 11
0
def edit_type(request, code, step='edit_type', template='mdtui/indexing.html'):
    """Indexing step: Edit. Editing document type (in fact document rename)

    @param request: is a Django request object
    @param code: is a DMS Object() code for view interactions
    @param step: is a current step name (for template rendering)
    @param template: is a name of template for this view"""
    context = {}
    warnings = [MDTUI_ERROR_STRINGS['EDIT_TYPE_WARNING'], ]
    error_warnings = []
    form = False
    processor = DocumentProcessor()
    return_url = reverse('mdtui-edit', kwargs={'code': code})

    log.debug('indexing_edit_type view called with code: %s' % code)
    doc = processor.read(code, {'user': request.user, })
    if not processor.errors:
        empty_form = make_document_type_select_form(request.user, docrule_initial=doc.get_docrule())
        form = empty_form(request.POST or None)
        if request.POST:
            if form.is_valid():
                docrule = form.cleaned_data['docrule']
                current_docrule = doc.get_docrule()
                if not docrule == current_docrule:
                    options = {
                        'user': request.user,
                        'new_type': docrule,
                    }
                    doc = processor.update(code, options)
                    if not processor.errors:
                        return HttpResponseRedirect(reverse('mdtui-edit', kwargs={'code': doc.get_filename()}))
                else:
                    warnings = [MDTUI_ERROR_STRINGS['EDIT_TYPE_ERROR'], ]
    # Can cause errors in two places here (on doc read and update)
    if processor.errors:
        for error in processor.errors:
            error_warnings.append(error)
    context.update({
        'step': step,
        'doc_name': code,
        'docrule': doc.get_docrule(),
        'warnings': warnings,
        'form': form,
        'type_edit_return': return_url,
        'error_warnings': error_warnings,
    })
    return render(request, template, context)
Esempio n. 12
0
 def create(self, request, code, suggested_format=None):
     if 'file' in request.FILES:
         uploaded_file = request.FILES['file']
     else:
         return rc.BAD_REQUEST
     processor = DocumentProcessor()
     options = {
         'user': request.user,
         'barcode': code,
     }
     document = processor.create(uploaded_file, options)
     if len(processor.errors) > 0:
         log.error('OldFileHandler.create errors: %s' % processor.errors)
         error = processor.errors[0]
         if error.__class__.__name__ in ['unicode', 'str']:
             return rc.BAD_REQUEST  # Should be "No such document type error"
         if error.code == 409:
             new_processor = DocumentProcessor()
             options['update_file'] = uploaded_file
             document = new_processor.update(code, options)
             if len(new_processor.errors) > 0:
                 return rc.BAD_REQUEST
     log.info('OldFileHandler.create request fulfilled for %s' % document.get_filename())
     return document.get_filename()
Esempio n. 13
0
 def update(self, request, code, suggested_format=None):
     revision, hashcode, extra = self._get_info(request)
     uploaded_obj = None
     if 'file' in request.FILES:
         uploaded_obj = request.FILES['file']
     # TODO refactor these verbs
     tag_string = request.PUT.get('tag_string', None)
     remove_tag_string = request.PUT.get('remove_tag_string', None)
     new_name = request.PUT.get('new_name', None)
     new_type = extra.get('new_type', None)
     index_data = extra.get('indexing_data', None)
     if index_data:
         index_data = json.loads(index_data)
     processor = DocumentProcessor()
     options = {
         'tag_string': tag_string,
         'remove_tag_string': remove_tag_string,
         'extension': suggested_format,
         'new_name': new_name,
         'new_type': new_type,
         'new_indexes': index_data,
         'update_file': uploaded_obj,
         'user': request.user,
     }  # FIXME hashcode missing?
     document = processor.update(code, options)
     if len(processor.errors) > 0:
         print processor.errors
         log.error('FileHandler.update manager errors %s' % processor.errors)
         if settings.DEBUG:
             raise Exception('FileHandler.update manager errors')
         else:
             return rc.BAD_REQUEST
     log.info('FileHandler.update request fulfilled for code: %s, format: %s, rev: %s, hash: %s.'
              % (code, suggested_format, revision, hashcode))
     resp = DMSOBjectRevisionsData(document).jsons
     return HttpResponse(resp)   # FIXME should be rc.ALL_OK
Esempio n. 14
0
def edit_result(request, step='edit_finish', template='mdtui/indexing.html'):
    """Confirmation step for editing indexes

    @param request: is a Django request object
    @param step: is a current step name (for template rendering)
    @param template: is a name of template for this view"""
    # initialising context
    required_vars = ('edit_processor_indexes', 'edit_index_barcode',
                     'old_document_keys', 'edit_return', "edit_mdts")
    variables = {}
    warnings = []
    for var in required_vars:
        try:
            variables[var] = request.session[var]
        except KeyError:
            variables[var] = ''
            # Error handling into warnings
            if not var == 'edit_return':
                error_name = MDTUI_ERROR_STRINGS['ERROR_EDIT_INDEXES_FINISHED']
                log.error('indexing_finished error: variable: %s,  %s' %
                          (var, error_name))
                if not error_name in warnings:
                    warnings.append(error_name)
            pass
    log.debug(
        'indexing_edit_result called with: step: "%s", variables: "%s",' %
        (step, variables))

    if request.POST:
        code = variables['edit_index_barcode']
        processor = DocumentProcessor()
        options = {
            'new_indexes': variables['edit_processor_indexes'],
            'user': request.user,
        }
        processor.update(code, options=options)
        if not processor.errors:
            # cleanup session here because editing is finished
            for var in required_vars:
                _cleanup_session_var(request, var)
            return HttpResponseRedirect(variables['edit_return'])
        else:
            for error in processor.errors:
                warnings.append(error)
    # Building new indexes for confirmation rendering
    context_secondary_indexes = {}
    if 'edit_processor_indexes' in variables.iterkeys(
    ) and variables['edit_processor_indexes']:
        for index, value in variables['edit_processor_indexes'].iteritems():
            if not index in ['metadata_user_name', 'metadata_user_id']:
                context_secondary_indexes[index] = value
    if 'description' in variables['edit_processor_indexes']:
        old_description = variables['old_document_keys']['description']
    else:
        old_description = ''
    context = {
        'step': step,
        'document_keys': context_secondary_indexes,
        'new_description': context_secondary_indexes.get('description', None),
        'barcode': variables['edit_index_barcode'],
        'old_document_keys': variables['old_document_keys'],
        'old_description': old_description,
        'edit_return': variables['edit_return'],
        'warnings': warnings,
    }
    return render(request, template, context)