Пример #1
0
    def __init__(self, request, *args, **kwargs):
        super(JobBinaryCreateForm, self).__init__(request, *args, **kwargs)

        self.help_text_template = "job_binaries/_create_job_binary_help.html"

        self.fields["job_binary_name"] = forms.CharField(label=_("Name"))

        self.fields["job_binary_type"] = forms.ChoiceField(
            label=_("Storage type"),
            widget=forms.Select(attrs={
                'class': 'switchable',
                'data-slug': 'jb_type'
            }))

        self.fields["job_binary_url"] = forms.CharField(
            label=_("URL"),
            required=False,
            widget=LabeledInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('URL')
                }))

        self.fields["job_binary_manila_share"] = forms.ChoiceField(
            label=_("Share"),
            required=False,
            widget=forms.Select(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-manila': _('Share')
                }))

        self.fields["job_binary_manila_path"] = forms.CharField(
            label=_("Path"),
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-manila': _('Path')
                }))

        self.fields["job_binary_internal"] = forms.ChoiceField(
            label=_("Internal binary"),
            required=False,
            widget=forms.Select(
                attrs={
                    'class': 'switched switchable',
                    'data-slug': 'jb_internal',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-internal-db': _('Internal Binary')
                }))

        self.fields["job_binary_file"] = forms.FileField(
            label=_("Upload File"),
            required=False,
            widget=forms.ClearableFileInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-uploadfile': _("Upload File")
                }))

        self.fields["job_binary_script_name"] = forms.CharField(
            label=_("Script name"),
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-newscript': _("Script name")
                }))

        self.fields["job_binary_script"] = forms.CharField(
            label=_("Script text"),
            required=False,
            widget=forms.Textarea(
                attrs={
                    'rows': 4,
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-newscript': _("Script text")
                }))

        self.fields["job_binary_username"] = forms.CharField(
            label=_("Username"),
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('Username')
                }))

        self.fields["job_binary_password"] = forms.CharField(
            label=_("Password"),
            required=False,
            widget=forms.PasswordInput(
                attrs={
                    'autocomplete': 'off',
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('Password')
                }))

        self.fields["job_binary_description"] = (forms.CharField(
            label=_("Description"), required=False, widget=forms.Textarea()))

        self.fields["is_public"] = acl_utils.get_is_public_form(
            _("job binary"))
        self.fields["is_protected"] = acl_utils.get_is_protected_form(
            _("job binary"))

        self.fields["job_binary_type"].choices =\
            [("internal-db", "Internal database"),
             ("swift", "Swift")]

        self.fields["job_binary_internal"].choices =\
            self.populate_job_binary_internal_choices(request)

        if saharaclient.base.is_service_enabled(request, 'share'):
            self.fields["job_binary_type"].choices.append(("manila", "Manila"))
            self.fields["job_binary_manila_share"].choices = (
                self.populate_job_binary_manila_share_choices(request))

        self.load_form_values()
Пример #2
0
    def __init__(self, request, *args, **kwargs):
        super(JobBinaryCreateForm, self).__init__(request, *args, **kwargs)

        self.help_text_template = ("project/data_processing.job_binaries/"
                                   "_create_job_binary_help.html")

        self.fields["job_binary_name"] = forms.CharField(label=_("Name"))

        self.fields["job_binary_type"] = forms.ChoiceField(
            label=_("Storage type"),
            widget=forms.Select(
                attrs={
                    'class': 'switchable',
                    'data-slug': 'jb_type'
                }))

        self.fields["job_binary_url"] = forms.CharField(
            label=_("URL"),
            required=False,
            widget=LabeledInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('URL')
                }))

        self.fields["job_binary_internal"] = forms.ChoiceField(
            label=_("Internal binary"),
            required=False,
            widget=forms.Select(
                attrs={
                    'class': 'switched switchable',
                    'data-slug': 'jb_internal',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-internal-db': _('Internal Binary')
                }))

        self.fields["job_binary_file"] = forms.FileField(
            label=_("Upload File"),
            required=False,
            widget=forms.ClearableFileInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-uploadfile': _("Upload File")
                }))

        self.fields["job_binary_script_name"] = forms.CharField(
            label=_("Script name"),
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-newscript': _("Script name")
                }))

        self.fields["job_binary_script"] = forms.CharField(
            label=_("Script text"),
            required=False,
            widget=forms.Textarea(
                attrs={
                    'rows': 4,
                    'class': 'switched',
                    'data-switch-on': 'jb_internal',
                    'data-jb_internal-newscript': _("Script text")
                }))

        self.fields["job_binary_username"] = forms.CharField(
            label=_("Username"),
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('Username')
                }))

        self.fields["job_binary_password"] = forms.CharField(
            label=_("Password"),
            required=False,
            widget=forms.PasswordInput(
                attrs={
                    'autocomplete': 'off',
                    'class': 'switched',
                    'data-switch-on': 'jb_type',
                    'data-jb_type-swift': _('Password')
                }))

        self.fields["job_binary_description"] = (
            forms.CharField(label=_("Description"),
                            required=False,
                            widget=forms.Textarea()))

        self.fields["job_binary_type"].choices =\
            [("internal-db", "Internal database"),
             ("swift", "Swift")]

        self.fields["job_binary_internal"].choices =\
            self.populate_job_binary_internal_choices(request)

        self.load_form_values()
Пример #3
0
class JobBinaryCreateForm(forms.SelfHandlingForm):
    NEW_SCRIPT = "newscript"
    UPLOAD_BIN = "uploadfile"

    job_binary_name = forms.CharField(label=_("Name"))

    job_binary_type = forms.ChoiceField(
        label=_("Storage type"),
        widget=forms.Select(
            attrs={
                'class': 'switchable',
                'data-slug': 'jb_type'
            }))

    job_binary_url = forms.CharField(
        label=_("URL"),
        required=False,
        widget=LabeledInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'jb_type',
                'data-jb_type-swift': _('URL')
            }))

    job_binary_internal = forms.ChoiceField(
        label=_("Internal binary"),
        required=False,
        widget=forms.Select(
            attrs={
                'class': 'switched switchable',
                'data-slug': 'jb_internal',
                'data-switch-on': 'jb_type',
                'data-jb_type-internal-db': _('Internal Binary')
            }))

    job_binary_file = forms.FileField(
        label=_("Upload File"),
        required=False,
        widget=forms.ClearableFileInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'jb_internal',
                'data-jb_internal-uploadfile': _("Upload File")
            }))

    job_binary_script_name = forms.CharField(
        label=_("Script name"),
        required=False,
        widget=forms.TextInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'jb_internal',
                'data-jb_internal-newscript': _("Script name")
            }))

    job_binary_script = forms.CharField(
        label=_("Script text"),
        required=False,
        widget=forms.Textarea(
            attrs={
                'rows': 4,
                'class': 'switched',
                'data-switch-on': 'jb_internal',
                'data-jb_internal-newscript': _("Script text")
            }))

    job_binary_username = forms.CharField(
        label=_("Username"),
        required=False,
        widget=forms.TextInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'jb_type',
                'data-jb_type-swift': _('Username')
            }))

    job_binary_password = forms.CharField(
        label=_("Password"),
        required=False,
        widget=forms.PasswordInput(
            attrs={
                'autocomplete': 'off',
                'class': 'switched',
                'data-switch-on': 'jb_type',
                'data-jb_type-swift': _('Password')
            }))

    job_binary_description = forms.CharField(label=_("Description"),
                                             required=False,
                                             widget=forms.Textarea())

    def __init__(self, request, *args, **kwargs):
        super(JobBinaryCreateForm, self).__init__(request, *args, **kwargs)

        self.help_text_template = ("project/data_processing.job_binaries/"
                                   "_create_job_binary_help.html")

        self.fields["job_binary_type"].choices =\
            [("internal-db", "Internal database"),
             ("swift", "Swift")]

        self.fields["job_binary_internal"].choices =\
            self.populate_job_binary_internal_choices(request)

    def populate_job_binary_internal_choices(self, request):
        try:
            job_binaries = saharaclient.job_binary_internal_list(request)
        except Exception:
            exceptions.handle(request,
                              _("Failed to get list of internal binaries."))
            job_binaries = []

        choices = [(job_binary.id, job_binary.name)
                   for job_binary in job_binaries]
        choices.insert(0, (self.NEW_SCRIPT, '*Create a script'))
        choices.insert(0, (self.UPLOAD_BIN, '*Upload a new file'))

        return choices

    def handle(self, request, context):
        try:
            extra = {}
            bin_url = "%s://%s" % (context["job_binary_type"],
                                   context["job_binary_url"])
            if(context["job_binary_type"] == "internal-db"):
                bin_url = self.handle_internal(request, context)
            elif(context["job_binary_type"] == "swift"):
                extra = self.handle_swift(request, context)

            saharaclient.job_binary_create(
                request,
                context["job_binary_name"],
                bin_url,
                context["job_binary_description"],
                extra)
            messages.success(request, "Successfully created job binary")
            return True
        except Exception:
            exceptions.handle(request,
                              _("Unable to create job binary"))
            return False

    def get_help_text(self, extra_context=None):
        text = ""
        extra_context = extra_context or {}
        if self.help_text_template:
            tmpl = template.loader.get_template(self.help_text_template)
            context = template.RequestContext(self.request, extra_context)
            text += tmpl.render(context)
        else:
            text += defaultfilters.linebreaks(force_text(self.help_text))
        return defaultfilters.safe(text)

    class Meta:
        name = _("Create Job Binary")
        help_text_template = ("project/data_processing.job_binaries/"
                              "_create_job_binary_help.html")

    def handle_internal(self, request, context):
        result = ""

        bin_id = context["job_binary_internal"]
        if(bin_id == self.UPLOAD_BIN):
            try:
                result = saharaclient.job_binary_internal_create(
                    request,
                    self.get_unique_binary_name(
                        request, request.FILES["job_binary_file"].name),
                    request.FILES["job_binary_file"].read())
            except Exception:
                exceptions.handle(request,
                                  _("Unable to upload job binary"))
                return None
        elif(bin_id == self.NEW_SCRIPT):
            try:
                result = saharaclient.job_binary_internal_create(
                    request,
                    self.get_unique_binary_name(
                        request, context["job_binary_script_name"]),
                    context["job_binary_script"])
            except Exception:
                exceptions.handle(request,
                                  _("Unable to create job binary"))
                return None

        bin_id = result.id
        return "internal-db://%s" % bin_id

    def handle_swift(self, request, context):
        username = context["job_binary_username"]
        password = context["job_binary_password"]

        extra = {
            "user": username,
            "password": password
        }
        return extra

    def get_unique_binary_name(self, request, base_name):
        try:
            internals = saharaclient.job_binary_internal_list(request)
        except Exception:
            internals = []
            exceptions.handle(request,
                              _("Failed to fetch internal binary list"))
        names = [internal.name for internal in internals]
        if base_name in names:
            return "%s_%s" % (base_name, uuid.uuid1())
        return base_name
Пример #4
0
class CreateTicketForm(BaseUserForm):
    """
    # | Form Class to handel the ticket create form
    """

    #Creating the fields
    subject = forms.CharField(label=_("Subject of your issue"),
                              required=True,
                              widget=forms.TextInput)
    priority = forms.ChoiceField(label=_("Priority"),
                                 required=True,
                                 widget=forms.Select,
                                 choices=TICKET_PRIORITY_CHOICES)
    description = forms.CharField(label=_("Describe your issue"),
                                  required=True,
                                  widget=forms.Textarea)
    attachments = forms.FileField(
        label=_("Attachments (Max size 1MB)"),
        required=False,
        widget=forms.ClearableFileInput(attrs={'multiple': True}))
    user = forms.DynamicChoiceField(
        label=_("User list"),
        required=False,
    )

    def handle(self, request, data):
        """ 
        * Form to handle the create ticket request
        *
        * @Arguments:
        *   <request>: Request object
        *   <data>:    Data containg form data
        """
        subject = data['subject']
        description = data['description']
        priority = data['priority']
        user = data['user']
        files = request.FILES.getlist('attachments')

        folder = 'zendesk_user_uploads'
        BASE_PATH = '/tmp/'

        #Initializing
        attachment_list = []

        #Create the folder if it doesn't exist.
        try:
            os.mkdir(os.path.join(BASE_PATH, folder))
        except:
            pass
        '''
        #Looping through each file
        for file in files:
            uploaded_filename = file.name
            full_filename = os.path.join(BASE_PATH, folder, uploaded_filename)
            fout = open(full_filename, 'wb+')
            file_content = ContentFile(file.read())
                
            #Iterate through the chunks.
            for chunk in file_content.chunks():
               fout.write(chunk)
            fout.close()
            
            #Inserting the files to list
            attachment_list.append(str(full_filename))
        
        zenpy_obj = zendesk_api.Zendesk(request)
        '''
        # Okay, now we need to call our zenpy to create the
        # ticket, with admin credential, on behalf of user
        try:

            #Looping through each file
            for file in files:
                uploaded_filename = file.name
                uploaded_filesize = file.size
                if file.size >= 1000000:
                    raise Exception(
                        '%s is too large. Please attach files that are less than 1MB.'
                        % uploaded_filename)

                full_filename = os.path.join(BASE_PATH, folder,
                                             uploaded_filename)
                fout = open(full_filename, 'wb+')
                file_content = ContentFile(file.read())

                #Iterate through the chunks.
                for chunk in file_content.chunks():
                    fout.write(chunk)
                fout.close()

                #Inserting the files to list
                attachment_list.append(str(full_filename))

                zenpy_obj = zendesk_api.Zendesk(request)

            zendesk = zendesk_api.Zendesk(self.request)

            #Setting the data to be passed for ticket creation
            api_data = {
                "subject": subject,
                "priority": priority,
                "description": description,
                "user": user
            }

            #Calling the method to create the tickets
            ticket_audit = zendesk.create_ticket(api_data, request)
            ticket = ticket_audit.ticket

            #Enter loop only if attachments are present during ticket creation
            if attachment_list:

                #Get the count of attachments
                attachment_count = len(attachment_list)

                #Create an automated comment for adding the attachments
                #(Only in the case of attachments added during initial ticket creation step)
                zendesk.create_comment(
                    ticket.id,
                    'User has added %s attachments with this ticket.' %
                    attachment_count, True, attachment_list)

            return redirect(
                reverse_lazy(
                    "horizon:zendesk_support_dashboard:tickets:ticket_detail",
                    args=[ticket.id]))
        except Exception as err:
            error_message = _(str(err))
            exceptions.handle(request, error_message)
            return []