示例#1
0
 def test_save_admin_settings(self):
     """
     Saving the form should save the admin's settings.
     """
     for username in 'admin', 'superuser':
         admin = User.objects.get(username=username)
         form = forms.NotificationsForm({'notifications': [
                     'admin_new_comment',
                     'admin_new_submission',
                     'admin_new_playlist',
                     'admin_queue_daily',
                     'admin_queue_weekly']}, instance=admin)
         self.assertTrue(form.is_valid(), form.errors)
         form.save()
         for label in ('video_comment', 'video_approved',
                       'comment_post_comment'):
             notice_type = notification.NoticeType.objects.get(label=label)
             self.assertFalse(notification.should_send(admin, notice_type,
                                                       "1"))
         for label in ('admin_new_comment', 'admin_new_submission',
                       'admin_new_playlist', 'admin_queue_daily',
                       'admin_queue_weekly'):
             notice_type = notification.NoticeType.objects.get(label=label)
             self.assertTrue(notification.should_send(admin, notice_type,
                                                      "1"))
def approve_video(request):
    current_video = get_object_or_404(models.Video, id=request.GET["video_id"], site=request.sitelocation().site)

    # If the site would exceed its video allotment, then fail
    # with a HTTP 403 and a clear message about why.
    if models.SiteLocation.enforce_tiers() and request.sitelocation().get_tier().remaining_videos() < 1:
        return HttpResponse(
            content="You are over the video limit. You will need to upgrade to approve that video.", status=402
        )

    current_video.status = models.VIDEO_STATUS_ACTIVE
    current_video.when_approved = datetime.datetime.now()

    if request.GET.get("feature"):
        current_video.last_featured = datetime.datetime.now()

    current_video.save()

    if current_video.user and current_video.user.email:
        video_approved = notification.NoticeType.objects.get(label="video_approved")
        if notification.should_send(current_video.user, video_approved, "1"):
            subject = '[%s] "%s" was approved!' % (current_video.site.name, current_video)
            t = loader.get_template("localtv/submit_video/approval_notification_email.txt")
            c = Context({"current_video": current_video})
            message = t.render(c)
            EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [current_video.user.email]).send(
                fail_silently=True
            )

    return HttpResponse("SUCCESS")
示例#3
0
def approve_video(request):
    site_settings = SiteSettings.objects.get_current()
    current_video = get_object_or_404(
        Video,
        id=request.GET['video_id'],
        site=site_settings.site)

    current_video.status = Video.ACTIVE
    current_video.when_approved = datetime.datetime.now()

    if request.GET.get('feature'):
        current_video.last_featured = datetime.datetime.now()

    current_video.save()

    if current_video.user and current_video.user.email:
        video_approved = notification.NoticeType.objects.get(
            label="video_approved")
        if notification.should_send(current_video.user, video_approved, "1"):
            subject = '[%s] "%s" was approved!' % (
                current_video.site.name,
                current_video)
            t = loader.get_template(
                'localtv/submit_video/approval_notification_email.txt')
            c = Context({'current_video': current_video})
            message = t.render(c)
            EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL,
                         [current_video.user.email]).send(fail_silently=True)

    return HttpResponse('SUCCESS')
def approve_video(request):
    current_video = get_object_or_404(
        models.Video,
        id=request.GET['video_id'],
        site=request.sitelocation.site)
    current_video.status = models.VIDEO_STATUS_ACTIVE
    current_video.when_approved = datetime.datetime.now()

    if request.GET.get('feature'):
        current_video.last_featured = datetime.datetime.now()

    current_video.save()

    if current_video.user and current_video.user.email:
        video_approved = notification.NoticeType.objects.get(
            label="video_approved")
        if notification.should_send(current_video.user, video_approved, "1"):
            subject = '[%s] "%s" was approved!' % (
                current_video.site.name,
                current_video)
            t = loader.get_template(
                'localtv/submit_video/approval_notification_email.txt')
            c = Context({'current_video': current_video})
            message = t.render(c)
            EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL,
                         [current_video.user.email]).send(fail_silently=True)

    return HttpResponse('SUCCESS')
 def can_send(self, user, notice_type):
     """
     Determines whether this backend is allowed to send a notification to
     the given user and notice_type.
     """
     from notification.models import should_send
     if should_send(user, notice_type, self.medium_id):
         return True
     return False
示例#6
0
    def test_save_user_settings(self):
        """
        Saving the form should save the user's settings.
        """
        user = User.objects.get(username='******')
        form = forms.NotificationsForm({'notifications': []}, instance=user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()
        for label in 'video_comment', 'video_approved', 'comment_post_comment':
            notice_type = notification.NoticeType.objects.get(label=label)
            self.assertFalse(notification.should_send(user, notice_type, "1"))

        form = forms.NotificationsForm({'notifications': ['video_approved']},
                                       instance=user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()
        notice_type = notification.NoticeType.objects.get(
            label='video_approved')
        self.assertTrue(notification.should_send(user, notice_type, "1"))
示例#7
0
 def can_send(self, user, notice_type):
     """
     Determines whether this backend is allowed to send a notification to
     the given user and notice_type.
     """
     # XXX should be placed here to avoid circular import dependency
     from notification.models import should_send
     if should_send(user, notice_type, self.medium_id):
         return True
     return False
示例#8
0
    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)
        forms.Form.__init__(self, *args, **kwargs)
        if self.instance:
            field = self.fields['notifications']
            site_settings = models.SiteSettings.objects.get_current()
            if site_settings.user_is_admin(self.instance):
                field.choices = self.CHOICES + self.ADMIN_CHOICES

            initial = []
            for choice, label in field.choices:
                notice_type = notification.NoticeType.objects.get(label=choice)
                if notification.should_send(self.instance, notice_type, "1"):
                    initial.append(choice)
            self.initial.setdefault('notifications', initial)
示例#9
0
    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)
        forms.Form.__init__(self, *args, **kwargs)
        if self.instance:
            field = self.fields['notifications']
            site_settings = models.SiteSettings.objects.get_current()
            if site_settings.user_is_admin(self.instance):
                field.choices = self.CHOICES + self.ADMIN_CHOICES

            initial = []
            for choice, label in field.choices:
                notice_type = notification.NoticeType.objects.get(label=choice)
                if notification.should_send(self.instance, notice_type, "1"):
                    initial.append(choice)
            self.initial.setdefault('notifications', initial)
示例#10
0
 def handle(self, *args, **options):
     notice_setting = NoticeType.objects.get(label="calendars_weekly_summary")
     for user in User.objects.filter(is_active=True):
         if should_send(user, notice_setting, "1"):
             content_type = ContentType.objects.get_for_model(Calendar)
             events = Event.objects.filter(
                 start_time__gte=get_today(),
                 start_time__lte=get_next_week(),
                 content_type=content_type,
                 object_id__in=user.calendars.all().values_list("id", flat=True),
             ).order_by("start_time")
             if events:
                 subject = "Weekly events"
                 context = {"user": user, "events": events}
                 message = render_to_string("events/events_weekly_notice.html", context)
                 send_mail(subject, message, None, [user.email])
示例#11
0
def approve_video(request):
    current_video = get_object_or_404(models.Video,
                                      id=request.GET['video_id'],
                                      site=request.sitelocation().site)

    # If the site would exceed its video allotment, then fail
    # with a HTTP 403 and a clear message about why.
    if (models.SiteLocation.enforce_tiers()
            and request.sitelocation().get_tier().remaining_videos() < 1):
        return HttpResponse(
            content=
            "You are over the video limit. You will need to upgrade to approve that video.",
            status=402)

    current_video.status = models.VIDEO_STATUS_ACTIVE
    current_video.when_approved = datetime.datetime.now()

    if request.GET.get('feature'):
        current_video.last_featured = datetime.datetime.now()

    current_video.save()

    if current_video.user and current_video.user.email:
        video_approved = notification.NoticeType.objects.get(
            label="video_approved")
        if notification.should_send(current_video.user, video_approved, "1"):
            subject = '[%s] "%s" was approved!' % (current_video.site.name,
                                                   current_video)
            t = loader.get_template(
                'localtv/submit_video/approval_notification_email.txt')
            c = Context({'current_video': current_video})
            message = t.render(c)
            EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL,
                         [current_video.user.email]).send(fail_silently=True)

    return HttpResponse('SUCCESS')
def approve_video(request):
    site_settings = SiteSettings.objects.get_current()
    current_video = get_object_or_404(Video, id=request.GET["video_id"], site=site_settings.site)

    current_video.status = Video.ACTIVE
    current_video.when_approved = datetime.datetime.now()

    if request.GET.get("feature"):
        current_video.last_featured = datetime.datetime.now()

    current_video.save()

    if current_video.user and current_video.user.email:
        video_approved = notification.NoticeType.objects.get(label="video_approved")
        if notification.should_send(current_video.user, video_approved, "1"):
            subject = '[%s] "%s" was approved!' % (current_video.site.name, current_video)
            t = loader.get_template("localtv/submit_video/approval_notification_email.txt")
            c = Context({"current_video": current_video})
            message = t.render(c)
            EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [current_video.user.email]).send(
                fail_silently=True
            )

    return HttpResponse("SUCCESS")
示例#13
0
 def handle_noargs(self, **options):
     current_site = Site.objects.get_current()
     # use low level SMTP object to improve performance
     smtp = SMTPConnection()
     smtp.open()
     notices_count = 0
     for user in User.objects.filter(email__isnull=False):
         notices = {}
         for notice in Notice.objects.notices_for(user).order_by('-notice_type__default', 'notice_type'):
             if should_send(user, notice.notice_type, DIGEST_MEDIUM):
                 if notice.notice_type.display in notices:
                     notices[notice.notice_type.display].append(notice)
                 else:
                     notices[notice.notice_type.display] = [notice]
                 notices_count += 1
                 notice.archive()
         if notices:
             context = Context({'notices': notices, 'user': user})
             body =  render_to_string ('notification/digest_email_body.html', context_instance=context)
             subject = render_to_string ('notification/digest_email_subject.txt', {'count': notices_count})
             msg = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])
             msg.content_subtype = "html"  # Main content is now text/html
             smtp._send(msg)
     smtp.close()    
示例#14
0
def send_now(users, label, extra_context=None, on_site=True, sender=None):
    """
    GvH: Modified version of notification.models.send_now

    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """
    logger.debug("Entering: %s()" % who_am_i())
    if extra_context is None:
        extra_context = {}

    notice_type = NoticeType.objects.get(label=label)

    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = getattr(settings, 'RSR_DOMAIN', 'rsr.akvo.org')

    notices_url = u"%s://%s%s" % (
        protocol,
        unicode(current_site),
        reverse("notification_notices"),
    )

    current_language = get_language()

    formats = (
        'short.txt',
        'full.txt',
        'sms.txt',
        'notice.html',
        'full.html',
    )  # TODO make formats configurable

    for user in users:
        recipients = []
        # get user language for user from language store defined in
        # NOTIFICATION_LANGUAGE_MODULE setting
        try:
            language = get_notification_language(user)
        except LanguageStoreNotAvailable:
            language = None

        if language is not None:
            # activate the user's language
            activate(language)

        # update context with user specific translations
        context = Context({
            "recipient": user,
            "sender": sender,
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)

        # get prerendered format messages
        messages = get_formatted_messages(formats, label, context)

        # Strip newlines from subject
        subject = ''.join(
            render_to_string('notification/email_subject.txt', {
                'message': messages['short.txt'],
            }, context).splitlines())

        body = render_to_string('notification/email_body.txt', {
            'message': messages['full.txt'],
        }, context)

        notice = Notice.objects.create(recipient=user,
                                       message=messages['notice.html'],
                                       notice_type=notice_type,
                                       on_site=on_site,
                                       sender=sender)
        if user.is_active:
            if should_send(user, notice_type, "email") and user.email:  # Email
                recipients.append(user.email)
            logger.info("Sending email notification of type %s to %s" % (
                notice_type,
                recipients,
            ))
            # don't send anything in debug/develop mode
            if not getattr(settings, 'SMS_DEBUG', False):
                send_mail(
                    subject, body,
                    getattr(settings, "DEFAULT_FROM_EMAIL",
                            "*****@*****.**"), recipients)
            if should_send(user, notice_type,
                           "sms") and user.phone_number:  # SMS
                # strip newlines
                sms = ''.join(
                    render_to_string('notification/email_subject.txt', {
                        'message': messages['sms.txt'],
                    }, context).splitlines())
                #extra_context['gw_number'] holds a GatewayNumber object
                logger.info(
                    "Sending SMS notification of type %s to %s, mobile phone number: %s."
                    % (
                        notice_type,
                        user,
                        extra_context['phone_number'],
                    ))
                # don't send anything in debug/develop mode
                if not getattr(settings, 'SMS_DEBUG', False):
                    extra_context['gw_number'].send_sms(
                        extra_context['phone_number'], sms)

    # reset environment to original language
    activate(current_language)
    logger.debug("Exiting: %s()" % who_am_i())
示例#15
0
文件: utils.py 项目: caetie/akvo-rsr
def send_now(users, label, extra_context=None, on_site=True, sender=None):
    """
    GvH: Modified version of notification.models.send_now
    
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    
    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """
    logger.debug("Entering: %s()" % who_am_i())
    if extra_context is None:
        extra_context = {}

    notice_type = NoticeType.objects.get(label=label)

    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = getattr(settings, "DOMAIN_NAME", "www.akvo.org")

    notices_url = u"%s://%s%s" % (protocol, unicode(current_site), reverse("notification_notices"))

    current_language = get_language()

    formats = ("short.txt", "full.txt", "sms.txt", "notice.html", "full.html")  # TODO make formats configurable

    for user in users:
        recipients = []
        # get user language for user from language store defined in
        # NOTIFICATION_LANGUAGE_MODULE setting
        try:
            language = get_notification_language(user)
        except LanguageStoreNotAvailable:
            language = None

        if language is not None:
            # activate the user's language
            activate(language)

        # update context with user specific translations
        context = Context(
            {
                "recipient": user,
                "sender": sender,
                "notice": ugettext(notice_type.display),
                "notices_url": notices_url,
                "current_site": current_site,
            }
        )
        context.update(extra_context)

        # get prerendered format messages
        messages = get_formatted_messages(formats, label, context)

        # Strip newlines from subject
        subject = "".join(
            render_to_string("notification/email_subject.txt", {"message": messages["short.txt"]}, context).splitlines()
        )

        body = render_to_string("notification/email_body.txt", {"message": messages["full.txt"]}, context)

        notice = Notice.objects.create(
            recipient=user, message=messages["notice.html"], notice_type=notice_type, on_site=on_site, sender=sender
        )
        if user.is_active:
            if should_send(user, notice_type, "email") and user.email:  # Email
                recipients.append(user.email)
            logger.info("Sending email notification of type %s to %s" % (notice_type, recipients))
            # don't send anything in debug/develop mode
            if not getattr(settings, "SMS_DEBUG", False):
                send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, recipients)

            if should_send(user, notice_type, "sms") and user.get_profile().phone_number:  # SMS
                # strip newlines
                sms = "".join(
                    render_to_string(
                        "notification/email_subject.txt", {"message": messages["sms.txt"]}, context
                    ).splitlines()
                )
                # extra_context['gw_number'] holds a GatewayNumber object
                logger.info(
                    "Sending SMS notification of type %s to %s, mobile phone number: %s."
                    % (notice_type, user, extra_context["phone_number"])
                )
                # don't send anything in debug/develop mode
                if not getattr(settings, "SMS_DEBUG", False):
                    extra_context["gw_number"].send_sms(extra_context["phone_number"], sms)

    # reset environment to original language
    activate(current_language)
    logger.debug("Exiting: %s()" % who_am_i())