Example #1
0
def general(request):
    toggleableSettings = [
        {"dashboard_administration_atom_dip_enabled": "Hide AtoM DIP upload link"},
        {"dashboard_administration_contentdm_dip_enabled": "Hide CONTENTdm DIP upload link"},
        {"dashboard_administration_dspace_enabled": "Hide DSpace transfer type"},
    ]

    if request.method == "POST":
        for setting in toggleableSettings:
            name = setting.keys()[0]
            if request.POST.get(name) == "on":
                setting = True
            else:
                setting = False

            # settings indicate whether or not something is enabled so if we want
            # do disable it we do a boolean not
            setting = not setting

            helpers.set_setting(name, setting)

    form = ToggleSettingsForm(extra=toggleableSettings)

    hide_features = hidden_features()
    return render(request, "administration/general.html", locals())
Example #2
0
def general(request):
    toggleableSettings = [
        {
            'dashboard_administration_atom_dip_enabled':
            'Hide AtoM DIP upload link'
        },
        {
            'dashboard_administration_contentdm_dip_enabled':
            'Hide CONTENTdm DIP upload link'
        },
        {
            'dashboard_administration_dspace_enabled':
            'Hide DSpace transfer type'
        },
    ]

    if request.method == 'POST':
        for setting in toggleableSettings:
            name = setting.keys()[0]
            if request.POST.get(name) == 'on':
                setting = True
            else:
                setting = False

            # settings indicate whether or not something is enabled so if we want
            # do disable it we do a boolean not
            setting = not setting

            helpers.set_setting(name, setting)

    form = ToggleSettingsForm(extra=toggleableSettings)

    hide_features = hidden_features()
    return render(request, 'administration/general.html', locals())
Example #3
0
def general(request):
    toggleableSettings = {
        'dashboard_administration_atom_dip_enabled':
        'Hide AtoM DIP upload link',
        'dashboard_administration_dspace_enabled': 'Hide DSpace transfer type',
    }
    initial_data = _intial_settings_data()
    interface_form = SettingsForm(request.POST or None,
                                  prefix='interface',
                                  reverse_checkboxes=toggleableSettings)
    storage_form = StorageSettingsForm(request.POST or None,
                                       prefix='storage',
                                       initial=initial_data)

    if interface_form.is_valid() and storage_form.is_valid():
        interface_form.save()
        storage_form.save()
        messages.info(request, 'Saved.')

    dashboard_uuid = helpers.get_setting('dashboard_uuid')
    try:
        pipeline = storage_service._get_pipeline(dashboard_uuid)
    except Exception:
        messages.warning(
            request,
            "Storage server inaccessible.  Please contact an administrator or update storage service URL below."
        )
    else:
        if not pipeline:
            messages.warning(
                request,
                "This pipeline is not registered with the storage service or has been disabled in the storage service.  Please contact an administrator."
            )
    hide_features = helpers.hidden_features()
    return render(request, 'administration/general.html', locals())
Example #4
0
def api(request):
    if request.method == "POST":
        whitelist = request.POST.get("whitelist", "")
        helpers.set_setting("api_whitelist", whitelist)
    else:
        whitelist = helpers.get_setting("api_whitelist", "127.0.0.1")

    hide_features = hidden_features()
    return render(request, "administration/api.html", locals())
Example #5
0
def api(request):
    if request.method == 'POST':
        whitelist = request.POST.get('whitelist', '')
        helpers.set_setting('api_whitelist', whitelist)
    else:
        whitelist = helpers.get_setting('api_whitelist', '127.0.0.1')

    hide_features = hidden_features()
    return render(request, 'administration/api.html', locals())
Example #6
0
def grid(request):
    if models.SourceDirectory.objects.count() > 0:
        source_directories = models.SourceDirectory.objects.all()

    polling_interval = django_settings.POLLING_INTERVAL
    microservices_help = django_settings.MICROSERVICES_HELP
    uid = request.user.id
    hide_features = helpers.hidden_features()
    return render(request, 'transfer/grid.html', locals())
Example #7
0
def grid(request):
    if models.SourceDirectory.objects.count() > 0:
        source_directories = models.SourceDirectory.objects.all()

    polling_interval = django_settings.POLLING_INTERVAL
    microservices_help = django_settings.MICROSERVICES_HELP
    uid = request.user.id
    hide_features = helpers.hidden_features()
    return render(request, 'transfer/grid.html', locals())
Example #8
0
def atom_dips(request):
    upload_setting = models.StandardTaskConfig.objects.get(
        execute="upload-qubit_v0.0")
    form = AtomSettingsForm(request.POST or None, instance=upload_setting)
    if form.is_valid():
        form.save()
        messages.info(request, 'Saved.')

    hide_features = helpers.hidden_features()
    return render(request, 'administration/dips_atom_edit.html', locals())
Example #9
0
def premis_agent(request):
    agent = models.Agent.objects.get(pk=2)
    if request.POST:
        form = AgentForm(request.POST, instance=agent)
        if form.is_valid():
            form.save()
    else:
        form = AgentForm(instance=agent)

    hide_features = hidden_features()
    return render(request, "administration/premis_agent.html", locals())
Example #10
0
def premis_agent(request):
    agent = models.Agent.objects.get(pk=2)
    if request.POST:
        form = AgentForm(request.POST, instance=agent)
        if form.is_valid():
            form.save()
    else:
        form = AgentForm(instance=agent)

    hide_features = hidden_features()
    return render(request, 'administration/premis_agent.html', locals())
Example #11
0
def contentdm_dips(request):
    link_id = contentdm_dip_destination_select_link_id()
    ReplaceDirChoices = models.MicroServiceChoiceReplacementDic.objects.filter(choiceavailableatlink=link_id)

    ReplaceDirChoiceFormSet = dips_formset()

    valid_submission, formset, add_form = dips_handle_updates(request, link_id, ReplaceDirChoiceFormSet)

    if request.method != "POST" or valid_submission:
        formset = ReplaceDirChoiceFormSet(queryset=ReplaceDirChoices)

    hide_features = hidden_features()
    return render(request, "administration/dips_contentdm_edit.html", locals())
Example #12
0
def contentdm_dips(request):
    link_id = contentdm_dip_destination_select_link_id()
    ReplaceDirChoices = models.MicroServiceChoiceReplacementDic.objects.filter(
        choiceavailableatlink=link_id)

    ReplaceDirChoiceFormSet = dips_formset()

    valid_submission, formset, add_form = dips_handle_updates(
        request, link_id, ReplaceDirChoiceFormSet)

    if request.method != 'POST' or valid_submission:
        formset = ReplaceDirChoiceFormSet(queryset=ReplaceDirChoices)

    hide_features = hidden_features()
    return render(request, 'administration/dips_contentdm_edit.html', locals())
Example #13
0
def add(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            newuser = form.save(commit=False)
            newuser.is_staff = True
            newuser.save()
            api_key = ApiKey.objects.create(user=newuser)
            api_key.key = api_key.generate_key()
            api_key.save()
            return HttpResponseRedirect(reverse("components.accounts.views.list"))
        else:
            print "%s" % repr(form.errors)
    else:
        # clearing out values that are getting inherited from currently logged in user
        data = {"email": " "}
        form = UserCreationForm(initial=data)

    return render(request, "accounts/add.html", {"hide_features": hidden_features(), "form": form})
Example #14
0
def add(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            newuser = form.save(commit=False)
            newuser.is_staff = True
            newuser.save()
            api_key = ApiKey.objects.create(user=newuser)
            api_key.key = api_key.generate_key()
            api_key.save()

            messages.info(request, 'Saved.')
            return redirect('components.accounts.views.list')
    else:
        #clearing out values that are getting inherited from currently logged in user
        data = {'email': ' '}
        form = UserCreationForm(initial=data)

    return render(request, 'accounts/add.html', {
        'hide_features': hidden_features(),
        'form': form
    })
Example #15
0
def grid(request):
    try:
        source_directories = storage_service.get_location(purpose="TS")
    except:
        messages.warning(
            request,
            'Error retrieving source directories: is the storage server running? Please contact an administrator.'
        )
    else:
        logging.debug(
            "Source directories found: {}".format(source_directories))
        if not source_directories:
            msg = "No <a href='{source_admin}'>transfer source locations</a> are available. Please contact an administrator.".format(
                source_admin=reverse(
                    'components.administration.views.sources'))
            messages.warning(request, mark_safe(msg))

    polling_interval = django_settings.POLLING_INTERVAL
    microservices_help = django_settings.MICROSERVICES_HELP
    uid = request.user.id
    hide_features = helpers.hidden_features()
    return render(request, 'transfer/grid.html', locals())
Example #16
0
def atom_dips(request):
    """ View to configure AtoM DIP upload. """
    initial_data = _intial_settings_data()
    form = AtomDipUploadSettingsForm(request.POST or None,
                                     prefix='storage',
                                     initial=initial_data)
    if form.is_valid():
        # Produce a set of commandline arguments for the AtoM upload job
        upload_setting = models.StandardTaskConfig.objects.get(
            execute="upload-qubit_v0.0")
        opts = []
        char_fields = [
            'dip_upload_atom_url', 'dip_upload_atom_email',
            'dip_upload_atom_password', 'dip_upload_atom_rsync_target',
            'dip_upload_atom_rsync_command', 'dip_upload_atom_version'
        ]
        for field in char_fields:
            value = form.cleaned_data.get(field)
            if not value:
                continue
            optname = field.replace('dip_upload_atom_', '').replace('_', '-')
            opts.append('--{}="{}"'.format(optname, value))
        if form.cleaned_data['dip_upload_atom_debug'] == 'True':
            opts.append('--debug')
        # Add file UUID
        opts.append('--uuid="%SIPUUID%"')
        arguments = ' '.join(opts)
        upload_setting.arguments = arguments
        upload_setting.save()

        form.save()
        messages.info(request, 'Saved.')

    hide_features = helpers.hidden_features()
    return render(request, 'administration/dips_atom_edit.html', {
        'form': form,
        'hide_features': hide_features,
    })
Example #17
0
def grid(request):
    polling_interval = django_settings.POLLING_INTERVAL
    microservices_help = django_settings.MICROSERVICES_HELP
    uid = request.user.id
    hide_features = helpers.hidden_features()
    return render(request, 'transfer/grid.html', locals())
Example #18
0
def administration_dip(request):
    upload_setting = models.StandardTaskConfig.objects.get(execute="upload-qubit_v0.0")
    hide_features = hidden_features()
    return render(request, "administration/dip.html", locals())
Example #19
0
def edit(request, id=None):
    # Forbidden if user isn't an admin and is trying to edit another user
    if str(request.user.id) != str(id) and id != None:
        if request.user.is_superuser is False:
            return HttpResponseRedirect(reverse('main.views.forbidden'))

    # Load user
    if id is None:
        user = request.user
        #id = request.user.id
        title = 'Edit your profile (%s)' % user
    else:
        try:
            user = User.objects.get(pk=id)
            title = 'Edit user %s' % user
        except:
            raise Http404

    # Form
    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save(commit=False)

            # change password if requested
            password = request.POST.get('password', '')
            if password != '':
                user.set_password(password)
            user.save()

            # regenerate API key if requested
            regenerate_api_key = request.POST.get('regenerate_api_key', '')
            if regenerate_api_key != '':
                try:
                    api_key = ApiKey.objects.get(user_id=user.pk)
                except ApiKey.DoesNotExist:
                    api_key = ApiKey.objects.create(user=user)
                api_key.key = api_key.generate_key()
                api_key.save()

            # determine where to redirect to
            if request.user.is_superuser is False:
                return_view = 'components.accounts.views.edit'
            else:
                return_view = 'components.accounts.views.list'

            return HttpResponseRedirect(reverse(return_view))
    else:
        form = UserChangeForm(instance=user)

    # load API key for display
    try:
        api_key_data = ApiKey.objects.get(user_id=user.pk)
        api_key = api_key_data.key
    except:
        api_key = '<no API key generated>'

    return render(
        request, 'accounts/edit.html', {
            'hide_features': hidden_features(),
            'form': form,
            'user': user,
            'api_key': api_key,
            'title': title
        })
Example #20
0
def sources(request):
    picker_js_file = "source_directory_picker.js"
    system_directory_description = "Transfer source"
    hide_features = hidden_features()
    return render(request, "administration/sources.html", locals())
Example #21
0
def sources(request):
    picker_js_file = 'source_directory_picker.js'
    system_directory_description = 'Transfer source'
    hide_features = hidden_features()
    return render(request, 'administration/sources.html', locals())
Example #22
0
def edit(request, id=None):
    # Forbidden if user isn't an admin and is trying to edit another user
    if str(request.user.id) != str(id) and id != None:
        if request.user.is_superuser is False:
            return HttpResponseRedirect(reverse("main.views.forbidden"))

    # Load user
    if id is None:
        user = request.user
        # id = request.user.id
        title = "Edit your profile (%s)" % user
    else:
        try:
            user = User.objects.get(pk=id)
            title = "Edit user %s" % user
        except:
            raise Http404

    # Form
    if request.method == "POST":
        form = UserChangeForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save(commit=False)

            # change password if requested
            password = request.POST.get("password", "")
            if password != "":
                user.set_password(password)
            user.save()

            # regenerate API key if requested
            regenerate_api_key = request.POST.get("regenerate_api_key", "")
            if regenerate_api_key != "":
                try:
                    api_key = ApiKey.objects.get(user_id=user.pk)
                except ApiKey.DoesNotExist:
                    api_key = ApiKey.objects.create(user=user)
                api_key.key = api_key.generate_key()
                api_key.save()

            # determine where to redirect to
            if request.user.is_superuser is False:
                return_view = "components.accounts.views.edit"
            else:
                return_view = "components.accounts.views.list"

            return HttpResponseRedirect(reverse(return_view))
    else:
        form = UserChangeForm(instance=user)

    # load API key for display
    try:
        api_key_data = ApiKey.objects.get(user_id=user.pk)
        api_key = api_key_data.key
    except:
        api_key = "<no API key generated>"

    return render(
        request,
        "accounts/edit.html",
        {"hide_features": hidden_features(), "form": form, "user": user, "api_key": api_key, "title": title},
    )
Example #23
0
def list(request):
    users = User.objects.all()
    hide_features = hidden_features()
    return render(request, "accounts/list.html", locals())
Example #24
0
def edit(request, id=None):
    if get_client_config_value('kioskMode') == 'True':
        return redirect('main.views.forbidden')

    # Forbidden if user isn't an admin and is trying to edit another user
    if str(request.user.id) != str(id) and id != None:
        if request.user.is_superuser is False:
            return redirect('main.views.forbidden')

    # Load user
    if id is None:
        user = request.user
        title = 'Edit your profile (%s)' % user
    else:
        try:
            user = User.objects.get(pk=id)
            title = 'Edit user %s' % user
        except:
            raise Http404

    # Form
    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=user)
        if form.is_valid():
            user = form.save(commit=False)

            # change password if requested
            password = request.POST.get('password', '')
            if password != '':
                user.set_password(password)

            # prevent non-admin from self-promotion
            if not request.user.is_superuser:
                user.is_superuser = False

            user.save()

            # regenerate API key if requested
            regenerate_api_key = request.POST.get('regenerate_api_key', '')
            if regenerate_api_key != '':
                try:
                    api_key = ApiKey.objects.get(user_id=user.pk)
                except ApiKey.DoesNotExist:
                    api_key = ApiKey.objects.create(user=user)
                api_key.key = api_key.generate_key()
                api_key.save()

            # determine where to redirect to
            if request.user.is_superuser is False:
                return_view = 'components.accounts.views.edit'
            else:
                return_view = 'components.accounts.views.list'

            messages.info(request, 'Saved.')
            return redirect(return_view)
    else:
        suppress_administrator_toggle = True
        if request.user.is_superuser:
            suppress_administrator_toggle = False
        form = UserChangeForm(
            instance=user,
            suppress_administrator_toggle=suppress_administrator_toggle)

    # load API key for display
    try:
        api_key_data = ApiKey.objects.get(user_id=user.pk)
        api_key = api_key_data.key
    except:
        api_key = '<no API key generated>'

    return render(
        request, 'accounts/edit.html', {
            'hide_features': hidden_features(),
            'form': form,
            'user': user,
            'api_key': api_key,
            'title': title
        })
Example #25
0
def list(request):
    users = User.objects.all()
    hide_features = hidden_features()
    return render(request, 'accounts/list.html', locals())
Example #26
0
def administration_dip(request):
    upload_setting = models.StandardTaskConfig.objects.get(
        execute="upload-qubit_v0.0")
    hide_features = hidden_features()
    return render(request, 'administration/dip.html', locals())
Example #27
0
def index(request):
    file_path = helpers.default_processing_config_path()

    # Lists of dicts declare what options to display, and where to look for
    # the options
    # name: Value of the `name` attribute in the <input> HTML element
    # choice_uuid: UUID of the microservice chainlink at which the choice occurs
    # label: Human-readable label to be displayed to the user
    # yes_option and no_option: UUIDs for the yes and no choice chains, respectively
    boolean_select_fields = [
        {
            "name": "quarantine_transfer",
            "choice_uuid":
            "755b4177-c587-41a7-8c52-015277568302",  # Workflow decision - send transfer to quarantine
            "label": "Send transfer to quarantine",
            "yes_option": "97ea7702-e4d5-48bc-b4b5-d15d897806ab",  # Quarantine
            "no_option":
            "d4404ab1-dc7f-4e9e-b1f8-aa861e766b8e"  # Skip quarantine
        },
        {
            "name": "normalize_transfer",
            "choice_uuid": "de909a42-c5b5-46e1-9985-c031b50e9d30",
            "label": "Approve normalization",
            "yes_option": "1e0df175-d56d-450d-8bee-7df1dc7ae815",  # Approve
            "action": "Approve"
        },
        {
            "name": "store_aip",
            "choice_uuid": "2d32235c-02d4-4686-88a6-96f4d6c7b1c3",
            "label": "Store AIP",
            "yes_option": "9efab23c-31dc-4cbd-a39d-bb1665460cbe",  # Store AIP
            "action": "Store AIP"
        },
        {
            "name": "transcribe_file",
            "choice_uuid": "7079be6d-3a25-41e6-a481-cee5f352fe6e",
            "label": "Transcribe files (OCR)",
            "yes_option": "5a9985d3-ce7e-4710-85c1-f74696770fa9",
            "no_option": "1170e555-cd4e-4b2f-a3d6-bfb09e8fcc53",
        },
        {
            "name": "tree",
            "choice_uuid": "56eebd45-5600-4768-a8c2-ec0114555a3d",
            "label": "Generate transfer structure report",
            "yes_option":
            "df54fec1-dae1-4ea6-8d17-a839ee7ac4a7",  # Generate transfer structure report
            "no_option": "e9eaef1e-c2e0-4e3b-b942-bfb537162795",
            "action": "Generate transfer structure report"
        },
    ]

    # name: Value of the `name` attribute in the <input> HTML element
    # label: Human-readable label to be displayed to the user
    # choice_uuid: UUID of the microservice chainlink at which the choice occurs
    chain_choice_fields = [
        {
            "name": "create_sip",
            "label": "Create SIP(s)",
            "choice_uuid": "bb194013-597c-4e4a-8493-b36d190f8717"
        },
        {
            "name": "extract_packages",
            "label": "Extract packages",
            "choice_uuid": "dec97e3c-5598-4b99-b26e-f87a435a6b7f",
            "uuid": "01d80b27-4ad1-4bd1-8f8d-f819f18bf685"
        },
        {
            "name": "normalize",
            "label": "Normalize",
            "choice_uuid": "cb8e5706-e73f-472f-ad9b-d1236af8095f",
        },
        {
            "name": "reminder",
            "label": "Reminder: add metadata if desired",
            "choice_uuid": "eeb23509-57e2-4529-8857-9d62525db048",
        },
        {
            "name": "examine",
            "label": "Examine contents",
            "choice_uuid": "accea2bf-ba74-4a3a-bb97-614775c74459"
        },
    ]

    populate_select_fields_with_chain_choice_options(chain_choice_fields)

    # name: Value of the `name` attribute in the <input> HTML element
    # choice_uuid: UUID of the microservice chainlink at which the choice occurs
    replace_dict_fields = [{
        "name":
        "select_format_id_tool_transfer",
        "label":
        "Select file format identification command (Transfer)",
        "choice_uuid":
        'f09847c2-ee51-429a-9478-a860477f6b8d'
    }, {
        "name":
        "select_format_id_tool_ingest",
        "label":
        "Select file format identification command (Ingest)",
        "choice_uuid":
        '7a024896-c4f7-4808-a240-44c87c762bc5'
    }, {
        "name":
        "select_format_id_tool_submissiondocs",
        "label":
        "Select file format identification command (Submission documentation & metadata)",
        "choice_uuid":
        '087d27be-c719-47d8-9bbb-9a7d8b609c44'
    }, {
        "name": "delete_packages",
        "label": "Delete packages after extraction",
        "choice_uuid": "f19926dd-8fb5-4c79-8ade-c83f61f55b40",
        "uuid": "85b1e45d-8f98-4cae-8336-72f40e12cbef"
    }, {
        "name":
        "compression_algo",
        "label":
        "Select compression algorithm",
        "choice_uuid":
        "01d64f58-8295-4b7b-9cab-8f1b153a504f"
    }, {
        "name":
        "compression_level",
        "label":
        "Select compression level",
        "choice_uuid":
        "01c651cb-c174-4ba4-b985-1d87a44d6754"
    }]

    def storage_dir_cb(storage_dir):
        return {
            'value': storage_dir['resource_uri'],
            'label': storage_dir['description']
        }

    """ Return a dict of AIP Storage Locations and their descriptions."""
    storage_directory_options = [{'value': '', 'label': '--Actions--'}]
    dip_directory_options = [{'value': '', 'label': '--Actions--'}]
    try:
        storage_directories = storage_service.get_location(purpose="AS")
        dip_directories = storage_service.get_location(purpose="DS")
        if None in (storage_directories, dip_directories):
            raise Exception("Storage server improperly configured.")
    except Exception:
        messages.warning(
            request,
            'Error retrieving AIP/DIP storage locations: is the storage server running? Please contact an administrator.'
        )
    else:
        storage_directory_options += [
            storage_dir_cb(d) for d in storage_directories
        ]
        dip_directory_options += [storage_dir_cb(d) for d in dip_directories]

    storage_service_options = [
        {
            "name": "store_aip_location",
            "label": "Store AIP location",
            "choice_uuid": "b320ce81-9982-408a-9502-097d0daa48fa",
            "options": storage_directory_options,
            # Unlike other options, the correct value here is a literal string,
            # not a pointer to a chain or dict in the database.
            "do_not_lookup": True
        },
        {
            "name": "store_dip_location",
            "label": "Store DIP location",
            "choice_uuid": "b7a83da6-ed5a-47f7-a643-1e9f9f46e364",
            "options": dip_directory_options,
            # Unlike other options, the correct value here is a literal string,
            # not a pointer to a chain or dict in the database.
            "do_not_lookup": True
        }
    ]

    populate_select_fields_with_replace_dict_options(replace_dict_fields)

    select_fields = chain_choice_fields + replace_dict_fields + storage_service_options

    if request.method == 'POST':
        # render XML using request data
        xmlChoices = PreconfiguredChoices()

        # use toggle field submissions to add to XML
        for field in boolean_select_fields:
            enabled = request.POST.get(field['name'])
            if enabled == 'yes':
                if 'yes_option' in field:
                    # can be set to either yes or no
                    toggle = request.POST.get(field['name'] + '_toggle', '')
                    if toggle == 'yes':
                        go_to_chain_text = field['yes_option']
                    elif 'no_option' in field:
                        go_to_chain_text = field['no_option']

                    if 'no_option' in field:
                        xmlChoices.add_choice(field['choice_uuid'],
                                              go_to_chain_text)
                    else:
                        if toggle == 'yes':
                            xmlChoices.add_choice(field['choice_uuid'],
                                                  go_to_chain_text)

        # set quarantine duration if applicable
        quarantine_expiry_enabled = request.POST.get(
            'quarantine_expiry_enabled', '')
        quarantine_expiry = request.POST.get('quarantine_expiry', '')
        if quarantine_expiry_enabled == 'yes' and quarantine_expiry != '':
            xmlChoices.add_choice(
                '19adb668-b19a-4fcb-8938-f49d7485eaf3',  # Remove from quarantine
                '333643b7-122a-4019-8bef-996443f3ecc5',  # Unquarantine
                str(float(quarantine_expiry) * (24 * 60 * 60)))

        # use select field submissions to add to XML
        for field in select_fields:
            enabled = request.POST.get(field['name'] + '_enabled')
            if enabled == 'yes':
                field_value = request.POST.get(field['name'], '')
                if field_value != '':
                    if field.get('do_not_lookup', False):
                        target = field_value
                    else:
                        target = uuid_from_description(field_value,
                                                       field['choice_uuid'])

                    xmlChoices.add_choice(field['choice_uuid'], target)

        xmlChoices.write_to_file(file_path)

        messages.info(request, 'Saved!')

        return redirect('components.administration.views.processing')
    else:
        debug = request.GET.get('debug', '')
        quarantine_expiry = ''

        file = open(file_path, 'r')
        xml = file.read()

        # parse XML to work out locals()
        root = etree.fromstring(xml)
        choices = root.findall('.//preconfiguredChoice')

        for item in boolean_select_fields:
            item['checked'] = ''
            item['yes_checked'] = ''
            item['no_checked'] = ''

        for choice in choices:
            applies_to = choice.find('appliesTo').text
            go_to_chain = choice.find('goToChain').text

            # use toggle field submissions to add to XML
            for field in boolean_select_fields:
                if applies_to == field['choice_uuid']:
                    set_field_property_by_name(boolean_select_fields,
                                               field['name'], 'checked',
                                               'checked')

                    if 'yes_option' in field:
                        if go_to_chain == field['yes_option']:
                            set_field_property_by_name(boolean_select_fields,
                                                       field['name'],
                                                       'yes_checked',
                                                       'selected')
                        else:
                            set_field_property_by_name(boolean_select_fields,
                                                       field['name'],
                                                       'no_checked',
                                                       'selected')

            # a quarantine expiry was found
            if applies_to == 'Remove from quarantine':
                quarantine_expiry_enabled_checked = 'checked'
                quarantine_expiry = float(
                    choice.find('delay').text) / (24 * 60 * 60)

            # check select fields for defaults
            for field in select_fields:
                if applies_to == field['choice_uuid'] and go_to_chain:
                    try:
                        chain = models.MicroServiceChain.objects.get(
                            pk=go_to_chain)
                        choice = chain.description
                    except models.MicroServiceChain.DoesNotExist:
                        try:
                            choice = models.MicroServiceChoiceReplacementDic.objects.get(
                                pk=go_to_chain).description
                        except models.MicroServiceChoiceReplacementDic.DoesNotExist:
                            # fallback for storage service options, which are
                            # strings that don't map to chains or dicts in
                            # the database
                            choice = go_to_chain

                    field['selected'] = choice
                    field['checked'] = 'checked'

    hide_features = hidden_features()
    return render(request, 'administration/processing.html', locals())
Example #28
0
def index(request):
    file_path = os.path.join(
        helpers.get_server_config_value('sharedDirectory'),
        'sharedMicroServiceTasksConfigs/processingMCPConfigs/defaultProcessingMCP.xml'
    )

    boolean_select_fields = [
        {
            "name":       "quarantine_transfer",
            "label":      "Send transfer to quarantine",
            "yes_option": "Quarantine",
            "no_option":  "Skip quarantine",
            "applies_to": "Workflow decision - send transfer to quarantine"
        },
        {
            "name":       "normalize_transfer",
            "label":      "Approve normalization",
            "applies_to": "Approve normalization",
            "yes_option": "Approve",
            "action":     "Approve"
        },
        {
            "name":       "store_aip",
            "label":      "Store AIP",
            "yes_option": "Store AIP",
            "applies_to": "Store AIP",
            "action":     "Store AIP"
        }
    ]

    chain_choice_fields = [
        {
            "name":  "create_sip",
            "label": "Create SIP(s)"
        },
        {
            "name":  "select_format_id_tool",
            "label": "Select format identification tool"
        },
        {
            "name":  "normalize",
            "label": "Normalize"
        }
    ]

    populate_select_fields_with_chain_choice_options(chain_choice_fields)

    replace_dict_fields = [
        {
            "name":  "compression_algo",
            "label": "Select compression algorithm"
        },
        {
            "name":  "compression_level",
           "label": "Select compression level"
        },
        {
            "name":  "store_aip_location",
            "label": "Store AIP location"
        }
    ]

    populate_select_fields_with_replace_dict_options(replace_dict_fields)

    select_fields = chain_choice_fields + replace_dict_fields

    if request.method == 'POST':
        # render XML using request data
        xmlChoices = PreconfiguredChoices()

        # use toggle field submissions to add to XML
        for field in boolean_select_fields:
            enabled = request.POST.get(field['name'])
            if enabled == 'yes':
                if 'yes_option' in field:
                    # can be set to either yes or no
                    toggle = request.POST.get(field['name'] + '_toggle', '')
                    if toggle == 'yes':
                        go_to_chain_text = field['yes_option']
                    elif 'no_option' in field:
                        go_to_chain_text = field['no_option']

                    if 'no_option' in field:
                        xmlChoices.add_choice(
                            field['applies_to'],
                            go_to_chain_text
                        )
                    else:
                        if toggle == 'yes':
                            xmlChoices.add_choice(
                                field['applies_to'],
                                go_to_chain_text
                            )
                else:
                    xmlChoices.add_choice(
                        field['label'],
                        field['action']
                    )

        # set quarantine duration if applicable
        quarantine_expiry_enabled = request.POST.get('quarantine_expiry_enabled', '')
        quarantine_expiry         = request.POST.get('quarantine_expiry', '')
        if quarantine_expiry_enabled == 'yes' and quarantine_expiry != '':
            xmlChoices.add_choice(
                'Remove from quarantine',
                'Unquarantine',
                str(float(quarantine_expiry) * (24 * 60 * 60))
            )

        # use select field submissions to add to XML
        for field in select_fields:
            enabled = request.POST.get(field['name'] + '_enabled')
            if enabled == 'yes':
                field_value = request.POST.get(field['name'], '')
                if field_value != '':
                    xmlChoices.add_choice(
                        field['label'],
                        field_value
                    )

        xmlChoices.write_to_file(file_path)

        return HttpResponseRedirect(reverse('components.administration.views.processing'))
    else:
        debug = request.GET.get('debug', '')
        quarantine_expiry = ''

        file = open(file_path, 'r')
        xml = file.read()

        # parse XML to work out locals()
        root = etree.fromstring(xml)
        choices = root.find('preconfiguredChoices')

        for item in boolean_select_fields:
            item['checked']     = ''
            item['yes_checked'] = ''
            item['no_checked']  = ''

        for choice in choices:
            applies_to = choice.find('appliesTo').text
            go_to_chain = choice.find('goToChain').text

            # use toggle field submissions to add to XML
            for field in boolean_select_fields:
                if applies_to == field['applies_to']:
                    set_field_property_by_name(boolean_select_fields, field['name'], 'checked', 'checked')

                    if 'yes_option' in field:
                        if go_to_chain == field['yes_option']:
                            set_field_property_by_name(boolean_select_fields, field['name'], 'yes_checked', 'selected')
                        else:
                            set_field_property_by_name(boolean_select_fields, field['name'], 'no_checked', 'selected')

            # a quarantine expiry was found
            if applies_to == 'Remove from quarantine':
                quarantine_expiry_enabled_checked = 'checked'
                quarantine_expiry = float(choice.find('delay').text) / (24 * 60 * 60)

            # check select fields for defaults
            for field in select_fields:
                if applies_to == field['label']:
                    field['selected'] = go_to_chain
                    field['checked'] = 'checked'

    hide_features = hidden_features()
    return render(request, 'administration/processing.html', locals())