Exemplo n.º 1
0
    def clean(self, *args, **kwargs):
        import markdown
        import html2text
        from agora_site.agora_core.templatetags.string_tags import urlify_markdown
        from django.template.defaultfilters import truncatewords_html

        cleaned_data = super(ElectionAdminForm, self).clean()
        if not self.instance.has_perms('edit_details', self.request.user):
            raise ImmediateHttpResponse(response=http.HttpForbidden())

        cleaned_data['pretty_name'] = clean_html(cleaned_data['pretty_name'], True)
        cleaned_data['description'] = clean_html(cleaned_data['description'])

        short_description = cleaned_data['short_description']
        short_description = html2text.html2text(short_description[:140]).strip()
        short_description = markdown.markdown(urlify_markdown(short_description),
                                     safe_mode="escape", enable_attributes=False)
        cleaned_data['short_description'] = truncatewords_html(short_description, 25)[:140]


        from_date = cleaned_data.get("from_date", None)
        to_date = cleaned_data.get("to_date", None)

        if not from_date and not to_date:
            return cleaned_data

        if from_date < timezone.now():
            raise django_forms.ValidationError(_('Invalid start date, must be '
                'in the future'))

        if from_date and to_date and ((to_date - from_date) < datetime.timedelta(hours=1)):
            raise django_forms.ValidationError(_('Voting time must be at least 1 hour'))

        return cleaned_data
Exemplo n.º 2
0
def send_mail_to_members(agora_id, user_id, is_secure, site_id, remote_addr,
        receivers, subject, body):
    sender = User.objects.get(pk=user_id)
    agora = Agora.objects.get(pk=agora_id)

    if receivers == 'members':
        receivers = agora.members.all()
    elif receivers == 'admins':
        receivers = agora.admins.all()
    elif receivers == 'delegates':
        receivers = agora.active_delegates()
    elif receivers == 'non-delegates':
        receivers = agora.non_delegates()
    elif receivers == 'requested-membership':
        receivers = agora.users_who_requested_membership()

    # Mail to the admins
    context = get_base_email_context_task(is_secure, site_id)
    context.update(dict(
        agora=agora,
        other_user=sender,
        notification_text=body
    ))
    context_html = context.copy()
    context_html["notification_text"] = markdown.markdown(urlify_markdown(body))

    for receiver in receivers:
        if not receiver.get_profile().has_perms('receive_email_updates'):
            continue

        translation.activate(receiver.get_profile().lang_code)
        context['to'] = receiver

        email = EmailMultiAlternatives(
            subject=subject,
            body=render_to_string('agora_core/emails/agora_notification.txt',
                context),
            to=[receiver.email])

        email.attach_alternative(
            render_to_string('agora_core/emails/agora_notification.html',
                context_html), "text/html")
        email.send()

    translation.deactivate()
Exemplo n.º 3
0
    def clean(self, *args, **kwargs):
        import markdown
        import html2text
        from agora_site.agora_core.templatetags.string_tags import urlify_markdown
        from django.template.defaultfilters import truncatewords_html

        cleaned_data = super(ElectionAdminForm, self).clean()
        if not self.instance.has_perms('edit_details', self.request.user):
            raise ImmediateHttpResponse(response=http.HttpForbidden())

        cleaned_data['pretty_name'] = clean_html(cleaned_data['pretty_name'],
                                                 True)
        cleaned_data['description'] = clean_html(cleaned_data['description'])

        short_description = cleaned_data['short_description']
        short_description = html2text.html2text(
            short_description[:140]).strip()
        short_description = markdown.markdown(
            urlify_markdown(short_description),
            safe_mode="escape",
            enable_attributes=False)
        cleaned_data['short_description'] = truncatewords_html(
            short_description, 25)[:140]

        from_date = cleaned_data.get("from_date", None)
        to_date = cleaned_data.get("to_date", None)

        if not from_date and not to_date:
            return cleaned_data

        if from_date < timezone.now():
            raise django_forms.ValidationError(
                _('Invalid start date, must be '
                  'in the future'))

        if from_date and to_date and (
            (to_date - from_date) < datetime.timedelta(hours=1)):
            raise django_forms.ValidationError(
                _('Voting time must be at least 1 hour'))

        return cleaned_data
Exemplo n.º 4
0
    def save(self, *args, **kwargs):
        import markdown
        import html2text
        from agora_site.agora_core.templatetags.string_tags import urlify_markdown
        from django.template.defaultfilters import truncatewords_html

        election = super(CreateElectionForm, self).save(commit=False)
        election.agora = self.agora
        election.create_name()
        election.uuid = str(uuid.uuid4())
        election.security_policy = self.cleaned_data['security_policy']
        election.created_at_date = timezone.now()
        if not election.is_secure():
            election.pubkey_created_at_date = election.created_at_date
        election.creator = self.request.user

        description_plaintext = html2text.html2text(election.description[:140]).strip()
        short_md = markdown.markdown(urlify_markdown(description_plaintext),
                                     safe_mode="escape", enable_attributes=False)
        election.short_description = truncatewords_html(short_md, 25)[:140]

        election.url = self.request.build_absolute_uri(reverse('election-view',
            kwargs=dict(username=election.agora.creator.username, agoraname=election.agora.name,
                electionname=election.name)))
        election.questions = self.cleaned_data['questions']
        election.election_type = election.questions[0]['tally_type']
        election.comments_policy = self.agora.comments_policy

        if ("from_date" in self.cleaned_data) and ("to_date" in self.cleaned_data):
            from_date = self.cleaned_data["from_date"]
            to_date = self.cleaned_data["to_date"]
            election.voting_starts_at_date = from_date
            election.voting_extended_until_date = election.voting_ends_at_date = to_date


        # Anyone can create a voting for a given agora, but if you're not the
        # admin, it must be approved
        if election.creator in election.agora.admins.all():
            election.is_approved = True
            election.approved_at_date = timezone.now()
        else:
            election.is_approved = False

        election.save()

        # create related action
        verb = 'created' if election.is_approved else 'proposed'
        actstream_action.send(self.request.user, verb=verb, action_object=election,
            target=election.agora, ipaddr=self.request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(self.request.META.get('REMOTE_ADDR'))))

        # send email to admins
        context = get_base_email_context(self.request)
        context.update(dict(
            election=election,
            action_user_url='/%s' % election.creator.username,
        ))

        for admin in election.agora.admins.all():
            context['to'] = admin

            if not admin.has_perms('receive_email_updates'):
                continue

            translation.activate(admin.get_profile().lang_code)

            email = EmailMultiAlternatives(
                subject=_('Election %s created') % election.pretty_name,
                body=render_to_string('agora_core/emails/election_created.txt',
                    context),
                to=[admin.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/election_created.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        follow(self.request.user, election, actor_only=False, request=self.request)

        # used for tasks
        kwargs=dict(
            election_id=election.id,
            is_secure=self.request.is_secure(),
            site_id=Site.objects.get_current().id,
            remote_addr=self.request.META.get('REMOTE_ADDR'),
            user_id=self.request.user.id
        )

        # make the election available to celery
        transaction.commit()

        # send email to admins
        send_election_created_mails.apply_async(kwargs=kwargs, task_id=election.task_id(send_election_created_mails))

        # schedule start and end of the election. note that if election is not
        # approved, the start and end of the election won't really happen
        if from_date and to_date:
            start_election.apply_async(kwargs=kwargs, task_id=election.task_id(start_election),
                eta=election.voting_starts_at_date)
            end_election.apply_async(kwargs=kwargs, task_id=election.task_id(end_election),
                eta=election.voting_ends_at_date)

        return election
Exemplo n.º 5
0
    def save(self, *args, **kwargs):
        import markdown
        from agora_site.agora_core.templatetags.string_tags import urlify_markdown
        from django.template.defaultfilters import truncatewords_html

        election = super(CreateElectionForm, self).save(commit=False)
        election.agora = self.agora
        election.create_name()
        election.uuid = str(uuid.uuid4())
        election.created_at_date = timezone.now()
        election.creator = self.request.user

        short_md = markdown.markdown(urlify_markdown(
            election.description[:140]),
                                     safe_mode="escape",
                                     enable_attributes=False)
        election.short_description = truncatewords_html(short_md, 25)[:140]

        election.url = self.request.build_absolute_uri(
            reverse('election-view',
                    kwargs=dict(username=election.agora.creator.username,
                                agoraname=election.agora.name,
                                electionname=election.name)))
        election.questions = self.cleaned_data['questions']
        election.election_type = election.questions[0]['tally_type']
        election.comments_policy = self.agora.comments_policy

        if ("from_date" in self.cleaned_data) and ("to_date"
                                                   in self.cleaned_data):
            from_date = self.cleaned_data["from_date"]
            to_date = self.cleaned_data["to_date"]
            election.voting_starts_at_date = from_date
            election.voting_extended_until_date = election.voting_ends_at_date = to_date

        # Anyone can create a voting for a given agora, but if you're not the
        # admin, it must be approved
        if election.creator in election.agora.admins.all():
            election.is_approved = True
            election.approved_at_date = timezone.now()
        else:
            election.is_approved = False

        election.save()

        # create related action
        verb = 'created' if election.is_approved else 'proposed'
        actstream_action.send(self.request.user,
                              verb=verb,
                              action_object=election,
                              target=election.agora,
                              ipaddr=self.request.META.get('REMOTE_ADDR'),
                              geolocation=json.dumps(
                                  geolocate_ip(
                                      self.request.META.get('REMOTE_ADDR'))))

        # send email to admins
        context = get_base_email_context(self.request)
        context.update(
            dict(
                election=election,
                action_user_url='/%s' % election.creator.username,
            ))

        for admin in election.agora.admins.all():
            context['to'] = admin

            if not admin.has_perms('receive_email_updates'):
                continue

            translation.activate(admin.get_profile().lang_code)

            email = EmailMultiAlternatives(
                subject=_('Election %s created') % election.pretty_name,
                body=render_to_string('agora_core/emails/election_created.txt',
                                      context),
                to=[admin.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/election_created.html',
                                 context), "text/html")
            email.send()
            translation.deactivate()

        follow(self.request.user,
               election,
               actor_only=False,
               request=self.request)

        # used for tasks
        kwargs = dict(election_id=election.id,
                      is_secure=self.request.is_secure(),
                      site_id=Site.objects.get_current().id,
                      remote_addr=self.request.META.get('REMOTE_ADDR'),
                      user_id=self.request.user.id)

        # send email to admins
        send_election_created_mails.apply_async(
            kwargs=kwargs,
            task_id=election.task_id(send_election_created_mails))

        # schedule start and end of the election. note that if election is not
        # approved, the start and end of the election won't really happen
        if from_date and to_date:
            start_election.apply_async(
                kwargs=kwargs,
                task_id=election.task_id(start_election),
                eta=election.voting_starts_at_date)
            end_election.apply_async(kwargs=kwargs,
                                     task_id=election.task_id(end_election),
                                     eta=election.voting_ends_at_date)

        return election
Exemplo n.º 6
0
def send_mail_to_members(agora_id, user_id, is_secure, site_id, remote_addr,
        receivers, subject, body):
    sender = User.objects.get(pk=user_id)
    agora = Agora.objects.get(pk=agora_id)

    base_tmpl = 'agora_core/emails/agora_notification'

    extra_notification_text_generator = None
    context = get_base_email_context_task(is_secure, site_id)

    if receivers == 'members':
        receivers = agora.members.all()
    elif receivers == 'admins':
        receivers = agora.admins.all()
    elif receivers == 'delegates':
        receivers = agora.active_delegates()
    elif receivers == 'non-delegates':
        receivers = agora.non_delegates()
    elif receivers == 'non-voters':
        receivers = agora.non_voters()
        base_tmpl = 'agora_core/emails/non_voters'

        def text_gen(user):
            token = default_token_generator.make_token(user)
            login_url = reverse('auto-login-token',
                    kwargs=dict(username=user, token=token))

            return _("\nHere we provide you a custom link so you can directly "
                "access the election:\n%(protocol)s://%(domain)s%(url)s") % dict(
                protocol=context['protocol'],
                domain=context['site'].domain,
                url=login_url
            ), _("<p>Here we provide you a custom link so you can directly access the election:</p>\n<a href=\"%(protocol)s://%(domain)s%(url)s\">%(protocol)s://%(domain)s%(url)s</a><br/>") % dict(
                protocol=context['protocol'],
                domain=context['site'].domain,
                url=login_url
            )

        extra_notification_text_generator = text_gen

    elif receivers == 'requested-membership':
        receivers = agora.users_who_requested_membership()
    elif receivers == 'unconfirmed-open-votes':
        election = agora.get_featured_election()
        if not election or not election.has_started() or election.has_ended():
            return

        receivers = []
        def text_gen(user):
            token = default_token_generator.make_token(user)
            confirm_vote_url = reverse('confirm-vote-token',
                    kwargs=dict(username=user, token=token))

            return _("You have a vote pending from confirmation. If you really emitted this vote, please confirm this vote click the following confirmation url:\n %(protocol)s://%(domain)s%(url)s\n") % dict(
                protocol=context['protocol'],
                domain=context['site'].domain,
                url=confirm_vote_url
            ), _("<p>You have a vote pending from confirmation. If you really emitted this vote, please confirm this vote click the following confirmation url:</p>\n<a href=\"%(protocol)s://%(domain)s%(url)s\">%(protocol)s://%(domain)s%(url)s</a><br/>") % dict(
                protocol=context['protocol'],
                domain=context['site'].domain,
                url=confirm_vote_url
            )

        extra_notification_text_generator = text_gen
        for v in CastVote.objects.filter(election__id=election.id,
            is_counted=False):
            if  CastVote.objects.filter(election__id=election.id, is_counted=False, voter__id=v.voter.id).count() > 0 and v.voter not in receivers and v.voter.is_active and election.has_perms("vote_counts", v.voter) and isinstance(v.voter.get_profile().extra, dict) and "pending_ballot_id" in v.voter.get_profile().extra:
                pbi = v.voter.get_profile().extra.get('pending_ballot_id')
                if v.voter.get_profile().extra.get('pending_ballot_status_%d' % pbi) != 'confirmed':
                    receivers.append(v.voter)

    # Mail to the admins
    context.update(dict(
        agora=agora,
        other_user=sender,
        notification_text=body
    ))
    context_html = context.copy()
    context_html["notification_text"] = markdown.markdown(urlify_markdown(body))
    notification_text_base = context["notification_text"]
    notification_text_base_html_base = context_html["notification_text"]
    notification_text_base_html_base = notification_text_base_html_base.replace("\n\n", "</p>\n\n<p>")

    for receiver in receivers:
        if not receiver.get_profile().has_perms('receive_email_updates'):
            continue

        lang_code = receiver.get_profile().lang_code
        print "lang_code = ", lang_code
        if not lang_code:
            lang_code = settings.LANGUAGE_CODE
        print "lang_code = ", lang_code

        translation.activate(lang_code)
        context['to'] = receiver
        context_html['to'] = receiver

        if extra_notification_text_generator is not None:
            extra_text, extra_html = extra_notification_text_generator(receiver)
            context["notification_text"] = notification_text_base + "\n" + extra_text
            context_html["notification_text"] = notification_text_base_html_base + "<br/>\n" + extra_html

        email = EmailMultiAlternatives(
            subject=subject,
            body=render_to_string(base_tmpl + '.txt',
                context),
            to=[receiver.email])

        email.attach_alternative(
            render_to_string(base_tmpl + '.html',
                context_html), "text/html")
        email.send()

    translation.deactivate()
Exemplo n.º 7
0
 def short_description_md(self):
     short_md = markdown.markdown(urlify_markdown(self.description),
                                  safe_mode="escape", enable_attributes=False)
     short_md = truncatewords_html(short_md, 25)
     return short_md