Beispiel #1
0
class PostalAttachmentForm(AttachmentSaverMixin, forms.Form):
    files = forms.FileField(
        label=_("Scanned Document"),
        help_text=PostalBaseForm.scan_help_text,
        validators=[validate_upload_document],
        widget=BootstrapFileInput(attrs={'multiple': True}))

    def save(self, message):
        files = self.files.getlist('%s-files' % self.prefix)
        result = self.save_attachments(files, message, replace=True)
        return result
Beispiel #2
0
class PostalBaseForm(MessageEditMixin, AttachmentSaverMixin, forms.Form):
    scan_help_text = _('Uploaded scans can be PDF, JPG, PNG or GIF.')
    publicbody = forms.ModelChoiceField(
        label=_('Public body'),
        queryset=PublicBody.objects.all(),
        widget=PublicBodySelect
    )

    files = forms.FileField(label=_("Scanned Letter"), required=False,
            validators=[validate_upload_document],
            help_text=scan_help_text,
            widget=BootstrapFileInput(attrs={'multiple': True}))
    FIELD_ORDER = ['publicbody', 'date', 'subject', 'text', 'files']

    def __init__(self, *args, **kwargs):
        self.foirequest = kwargs.pop('foirequest')
        super().__init__(*args, **kwargs)
        self.fields['publicbody'].label = self.PUBLICBODY_LABEL
        self.fields['publicbody'].initial = self.foirequest.public_body
        self.fields['publicbody'].widget.set_initial_object(self.foirequest.public_body)
        self.order_fields(self.FIELD_ORDER)

    def clean(self):
        cleaned_data = self.cleaned_data
        text = cleaned_data.get("text")
        if '%s-files' % self.prefix in self.files:
            files = self.files.getlist('%s-files' % self.prefix)
        else:
            files = None
        if not (text or files):
            raise forms.ValidationError(
                _(
                    "You need to provide either the letter text or "
                    "a scanned document."
                )
            )
        return cleaned_data

    def save(self):
        foirequest = self.foirequest
        message = FoiMessage(
            request=foirequest,
            kind='post',
        )
        message = self.set_data_on_message(message)
        message = self.contribute_to_message(message)
        message.save()

        foirequest._messages = None
        foirequest.status = 'awaiting_classification'
        foirequest.save()

        if self.cleaned_data.get('files'):
            self.save_attachments(self.files.getlist('%s-files' % self.prefix), message)

        if message.is_response:
            foirequest.message_received.send(sender=foirequest, message=message)
        else:
            foirequest.message_sent.send(sender=foirequest, message=message)

        return message
Beispiel #3
0
class SendMessageForm(AttachmentSaverMixin, forms.Form):
    to = forms.ChoiceField(
        label=_("To"),
        choices=[],
        required=True,
        widget=BootstrapRadioSelect
    )
    subject = forms.CharField(
        label=_("Subject"),
        max_length=230,
        widget=forms.TextInput(attrs={"class": "form-control"})
    )
    message = forms.CharField(
        widget=forms.Textarea(attrs={"class": "form-control"}),
        label=_("Your message"),
        help_text=_(
            "Don't include personal information. "
            "If you need to give your postal address "
            "enter it below."
        )
    )

    files_help_text = _('Uploaded scans can be PDF, JPG, PNG or GIF.')
    files = forms.FileField(
        label=_("Attachments"),
        required=False,
        validators=[validate_upload_document],
        help_text=files_help_text,
        widget=BootstrapFileInput(attrs={'multiple': True})
    )

    def __init__(self, *args, **kwargs):
        foirequest = kwargs.pop('foirequest')
        self.message_ready = kwargs.pop('message_ready')
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest

        self.fields['to'].choices = possible_reply_addresses(foirequest)

        address_optional = foirequest.law and foirequest.law.email_only

        self.fields['send_address'] = forms.BooleanField(
            label=_("Send physical address"),
            widget=BootstrapCheckboxInput,
            help_text=_(
                'If the public body is asking for your post '
                'address, check this and we will append the '
                'address below.'
            ),
            required=False,
            initial=not address_optional
        )

        self.fields['address'] = forms.CharField(
            max_length=300,
            required=False,
            initial=foirequest.user.address,
            label=_('Mailing Address'),
            help_text=_(
                'Optional. Your address will not be displayed publicly.'
            ),
            widget=forms.Textarea(attrs={
                'rows': '3',
                'class': 'form-control',
                'placeholder': _('Street, Post Code, City'),
            })
        )

    def clean_message(self):
        message = self.cleaned_data['message']
        if not self.message_ready:
            # Initial message needs to be filled out
            # Check if submitted message is still the initial
            message = message.replace('\r\n', '\n').strip()
            empty_form = get_send_message_form(foirequest=self.foirequest)
            if message == empty_form.initial['message'].strip():
                raise forms.ValidationError(
                    _('You need to fill in the blanks in the template!')
                )
        return message

    def clean(self):
        if (self.cleaned_data.get('send_address', False) and
                not self.cleaned_data['address'].strip()):
            raise forms.ValidationError('You need to give a postal address, '
                                        'if you want to send it.')

    def add_message_body(self, message,
                         attachment_names=(), attachment_missing=()):
        message_body = self.cleaned_data['message']
        send_address = self.cleaned_data.get('send_address', True)
        message.plaintext = construct_message_body(
            self.foirequest,
            message_body,
            send_address=send_address,
            attachment_names=attachment_names,
            attachment_missing=attachment_missing,
        )
        message.plaintext_redacted = redact_plaintext(
            message.plaintext,
            is_response=False,
            user=self.foirequest.user
        )

    def make_message(self):
        user = self.foirequest.user

        address = self.cleaned_data.get('address', '')
        if address.strip() and address != user.address:
            user.address = address
            user.save()

        recipient_email = self.cleaned_data["to"]
        recipient_info = get_info_for_email(self.foirequest, recipient_email)
        recipient_name = recipient_info.name
        recipient_pb = recipient_info.publicbody

        subject = re.sub(
            r'\s*\[#%s\]\s*$' % self.foirequest.pk, '',
            self.cleaned_data["subject"]
        )
        subject = '%s [#%s]' % (subject, self.foirequest.pk)
        subject_redacted = redact_subject(subject, user=user)

        message = FoiMessage(
            request=self.foirequest,
            subject=subject,
            kind='email',
            subject_redacted=subject_redacted,
            is_response=False,
            sender_user=user,
            sender_name=user.display_name(),
            sender_email=self.foirequest.secret_address,
            recipient_email=recipient_email.strip(),
            recipient_public_body=recipient_pb,
            recipient=recipient_name,
            timestamp=timezone.now(),
        )
        return message

    def save(self):
        message = self.make_message()
        message.save()

        if self.cleaned_data.get('files'):
            self.save_attachments(self.files.getlist('%s-files' % self.prefix), message)

        message._attachments = None
        files = message.get_mime_attachments()
        att_gen = MailAttachmentSizeChecker(files)
        attachments = list(att_gen)

        self.add_message_body(
            message,
            attachment_names=att_gen.send_files,
            attachment_missing=att_gen.non_send_files,
        )
        message.save()

        message.send(attachments=attachments)
        return message
Beispiel #4
0
class PostalBaseForm(AttachmentSaverMixin, forms.Form):
    scan_help_text = _('Uploaded scans can be PDF, JPG, PNG or GIF.')
    publicbody = forms.ModelChoiceField(label=_('Public body'),
                                        queryset=PublicBody.objects.all(),
                                        widget=PublicBodySelect)
    date = forms.DateField(
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _('mm/dd/YYYY')
        }),
        label=_("Send Date"),
        help_text=_("Please give the date the reply was sent."),
        localize=True)
    subject = forms.CharField(
        label=_("Subject"),
        required=False,
        max_length=230,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Subject")
        }))
    text = forms.CharField(
        label=_("Letter"),
        widget=forms.Textarea(attrs={
            "placeholder": _("Letter text"),
            "class": "form-control"
        }),
        required=False,
        help_text=
        _("The text can be left empty, instead you can upload scanned documents."
          ))
    files = forms.FileField(
        label=_("Scanned Letter"),
        required=False,
        validators=[validate_upload_document],
        help_text=scan_help_text,
        widget=BootstrapFileInput(attrs={'multiple': True}))
    FIELD_ORDER = ['publicbody', 'date', 'subject', 'text', 'files']

    def __init__(self, *args, **kwargs):

        self.foirequest = kwargs.pop('foirequest')
        super(PostalBaseForm, self).__init__(*args, **kwargs)
        self.fields['publicbody'].label = self.PUBLICBODY_LABEL
        self.fields['publicbody'].initial = self.foirequest.public_body
        self.order_fields(self.FIELD_ORDER)

    def clean_date(self):
        date = self.cleaned_data['date']
        now = timezone.now().date()
        if date > now:
            raise forms.ValidationError(
                _("Your reply date is in the future, that is not possible."))
        return date

    def clean(self):
        cleaned_data = self.cleaned_data
        text = cleaned_data.get("text")
        if '%s-files' % self.prefix in self.files:
            files = self.files.getlist('%s-files' % self.prefix)
        else:
            files = None
        if not (text or files):
            raise forms.ValidationError(
                _("You need to provide either the letter text or a scanned document."
                  ))
        return cleaned_data

    def save(self):
        foirequest = self.foirequest
        message = FoiMessage(
            request=foirequest,
            kind='post',
        )
        # TODO: Check if timezone support is correct
        date = datetime.datetime.combine(self.cleaned_data['date'],
                                         datetime.datetime.now().time())
        message.timestamp = timezone.get_current_timezone().localize(date)
        message.subject = self.cleaned_data.get('subject', '')
        subject_redacted = redact_subject(message.subject,
                                          user=foirequest.user)
        message.subject_redacted = subject_redacted
        message.plaintext = ''
        if self.cleaned_data.get('text'):
            message.plaintext = self.cleaned_data.get('text')
        message.plaintext_redacted = message.get_content()

        message = self.contribute_to_message(message)
        message.save()

        foirequest._messages = None
        foirequest.status = 'awaiting_classification'
        foirequest.save()

        if self.cleaned_data.get('files'):
            self.save_attachments(self.files.getlist('%s-files' % self.prefix),
                                  message)

        if message.is_response:
            foirequest.message_received.send(sender=foirequest,
                                             message=message)
        else:
            foirequest.message_sent.send(sender=foirequest, message=message)

        return message
Beispiel #5
0
class SendMessageForm(AttachmentSaverMixin, forms.Form):
    to = forms.TypedChoiceField(label=_("To"),
                                choices=[],
                                coerce=int,
                                required=True,
                                widget=BootstrapRadioSelect)
    subject = forms.CharField(
        label=_("Subject"),
        max_length=230,
        widget=forms.TextInput(attrs={"class": "form-control"}))
    message = forms.CharField(
        widget=forms.Textarea(attrs={"class": "form-control"}),
        label=_("Your message"))

    files_help_text = _('Uploaded scans can be PDF, JPG, PNG or GIF.')
    files = forms.FileField(
        label=_("Attachments"),
        required=False,
        validators=[validate_upload_document],
        help_text=files_help_text,
        widget=BootstrapFileInput(attrs={'multiple': True}))

    def __init__(self, *args, **kwargs):
        foirequest = kwargs.pop('foirequest')
        self.message_ready = kwargs.pop('message_ready')
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest

        choices = []
        if foirequest.public_body and foirequest.public_body.email:
            choices.append((0, _("Default address of %(publicbody)s") % {
                "publicbody": foirequest.public_body.name
            }))
        choices.extend([
            (m.id, m.reply_address_entry)
            for k, m in foirequest.possible_reply_addresses().items()
        ])
        self.fields['to'].choices = choices

        if foirequest.law and foirequest.law.email_only:
            self.fields['send_address'] = forms.BooleanField(
                label=_("Send physical address"),
                help_text=(_(
                    'If the public body is asking for your post '
                    'address, check this and we will append it to your message.'
                )),
                required=False)

    def clean_message(self):
        message = self.cleaned_data['message']
        if not self.message_ready:
            # Initial message needs to be filled out
            # Check if submitted message is still the initial
            message = message.replace('\r\n', '\n').strip()
            empty_form = get_send_message_form(foirequest=self.foirequest)
            if message == empty_form.initial['message'].strip():
                raise forms.ValidationError(
                    _('You need to fill in the blanks in the template!'))
        return message

    def make_message(self):
        user = self.foirequest.user

        if self.cleaned_data["to"] == 0:
            recipient_name = self.foirequest.public_body.name
            recipient_email = self.foirequest.public_body.email
            recipient_pb = self.foirequest.public_body
        else:
            message = list(
                filter(lambda x: x.id == self.cleaned_data["to"],
                       list(self.foirequest.messages)))[0]
            recipient_name = message.sender_name
            recipient_email = message.sender_email
            recipient_pb = message.sender_public_body

        message_body = self.cleaned_data['message']
        subject = re.sub(r'\s*\[#%s\]\s*$' % self.foirequest.pk, '',
                         self.cleaned_data["subject"])
        subject = '%s [#%s]' % (subject, self.foirequest.pk)
        subject_redacted = redact_subject(subject, user=user)

        send_address = self.cleaned_data.get('send_address', True)
        plaintext = construct_message_body(self.foirequest,
                                           message_body,
                                           send_address=send_address)
        plaintext_redacted = redact_plaintext(plaintext,
                                              is_response=False,
                                              user=self.foirequest.user)

        return FoiMessage(request=self.foirequest,
                          subject=subject,
                          kind='email',
                          subject_redacted=subject_redacted,
                          is_response=False,
                          sender_user=user,
                          sender_name=user.display_name(),
                          sender_email=self.foirequest.secret_address,
                          recipient_email=recipient_email.strip(),
                          recipient_public_body=recipient_pb,
                          recipient=recipient_name,
                          timestamp=timezone.now(),
                          plaintext=plaintext,
                          plaintext_redacted=plaintext_redacted)

    def save(self):
        message = self.make_message()
        message.save()

        if self.cleaned_data.get('files'):
            self.save_attachments(self.files.getlist('%s-files' % self.prefix),
                                  message)

        message.send()
        return message