Ejemplo n.º 1
0
def stream(request):

    SELECT_OPTIONS = OrderedDict([("last_week", "Last week"),
                                  ("last_month", "Last month"),
                                  ("specific_dates", "Specify dates...")])

    SELECT_OPTIONS_DAYS = {
        "last_week": 7,
        "last_month": 30,
        "specific_dates": 0
    }

    user = request.user

    if request.method == "POST":
        select_value = request.POST.get("time_lapse")
        if select_value != "specific_dates":
            date_from = datetime.now() - timedelta(
                days=SELECT_OPTIONS_DAYS[select_value])
            date_to = datetime.now()
            time_lapse = follow_utils.build_time_lapse(date_from, date_to)
            date_to = date_to.strftime("%Y-%m-%d")
            date_from = date_from.strftime("%Y-%m-%d")
        else:
            date_from = request.POST.get("date_from")
            date_to = request.POST.get("date_to")
            if not date_from or not date_to:
                if not date_from and not date_to:  # Set it to last week (default)
                    date_to = datetime.now().strftime("%Y-%m-%d")
                    date_from = (datetime.now() -
                                 timedelta(days=7)).strftime("%Y-%m-%d")
                else:
                    if not date_from:
                        date_from = (datetime.strptime(date_to, "%Y-%m-%d") -
                                     timedelta(days=7)).strftime(
                                         "%Y-%m-%d")  # A week before date to
                    if not date_to:
                        date_to = (datetime.strptime(date_from, "%Y-%m-%d") +
                                   timedelta(days=7)).strftime(
                                       "%Y-%m-%d")  # A week after date from
            time_lapse = "[%sT00:00:00Z TO %sT23:59:59.999Z]" % (date_from,
                                                                 date_to)

    # if first time going into the page, the default is last week
    else:
        select_value = ''
        date_from = datetime.now() - timedelta(
            days=SELECT_OPTIONS_DAYS["last_week"])
        date_to = datetime.now()
        time_lapse = follow_utils.build_time_lapse(date_from, date_to)
        date_to = date_to.strftime("%Y-%m-%d")
        date_from = date_from.strftime("%Y-%m-%d")

    errors_getting_data = False
    try:
        users_sounds, tags_sounds = follow_utils.get_stream_sounds(
            user, time_lapse)
    except Exception, e:
        # Could not connect to solr
        errors_getting_data = True
Ejemplo n.º 2
0
    def handle(self, *args, **options):

        date_today_minus_notification_timedelta = datetime.datetime.now() - settings.NOTIFICATION_TIMEDELTA_PERIOD

        # Get all the users that have notifications active
        # and exclude the ones that have the last email sent for less than settings.NOTIFICATION_TIMEDELTA_PERIOD
        # (because they have been sent an email already)
        users_enabled_notifications = Profile.objects.filter(enabled_stream_emails=True).exclude(last_stream_email_sent__gt=date_today_minus_notification_timedelta).order_by("last_stream_email_sent")[:settings.MAX_EMAILS_PER_COMMAND_RUN]

        logger.info("Sending stream updates notification for %i potential users" % len(users_enabled_notifications))

        email_tuples = ()
        n_emails_sent = 0
        for profile in users_enabled_notifications:

            username = profile.user.username
            email_to = profile.user.email

            # Variable names use the terminology "week" because settings.NOTIFICATION_TIMEDELTA_PERIOD defaults to a
            # week, but a more generic terminology could be used
            week_first_day = profile.last_stream_email_sent
            week_last_day = datetime.datetime.now()

            week_first_day_str = week_first_day.strftime("%d %b").lstrip("0")
            week_last_day_str = week_last_day.strftime("%d %b").lstrip("0")

            subject_str = u'new sounds from users and tags you are following ('
            subject_str += unicode(week_first_day_str) + u' - ' + unicode(week_last_day_str) + u')'

            # Set date range from which to get upload notifications
            time_lapse = follow_utils.build_time_lapse(week_first_day, week_last_day)

            # construct message
            user = User.objects.get(username=username)
            try:
                users_sounds, tags_sounds = follow_utils.get_stream_sounds(user, time_lapse)
            except Exception, e:
                # If error occur do not send the email
                print "could not get new sounds data for", username
                continue

            if not users_sounds and not tags_sounds:
                print "no news sounds for", username
                continue

            # print users_sound_ids
            # print tags_sound_ids

            text_content = render_mail_template('follow/email_stream.txt', locals())

            email_tuples += (subject_str, text_content, settings.DEFAULT_FROM_EMAIL, [email_to]),

            # send email
            try:
                send_mail(subject_str, text_content, email_from=settings.DEFAULT_FROM_EMAIL, email_to=[email_to], reply_to=None)
            except Exception, e:
                logger.info("An error occurred sending notification stream email to %s (%s)" % (str(email_to),str(e)) )
                # Do not send the email and do not update the profile
                continue
Ejemplo n.º 3
0
def stream(request):

    SELECT_OPTIONS = OrderedDict([
        ("last_week", "Last week"),
        ("last_month", "Last month"),
        ("specific_dates", "Specify dates...")
    ])

    SELECT_OPTIONS_DAYS = {
        "last_week": 7,
        "last_month": 30,
        "specific_dates": 0
    }

    user = request.user

    if request.method == "POST":
        select_value = request.POST.get("time_lapse")
        if select_value != "specific_dates":
            date_from = datetime.now() - timedelta(days=SELECT_OPTIONS_DAYS[select_value])
            date_to = datetime.now()
            time_lapse = follow_utils.build_time_lapse(date_from, date_to)
            date_to = date_to.strftime("%Y-%m-%d")
            date_from = date_from.strftime("%Y-%m-%d")
        else:
            date_from = request.POST.get("date_from")
            date_to = request.POST.get("date_to")
            if not date_from or not date_to:
                if not date_from and not date_to: # Set it to last week (default)
                    date_to = datetime.now().strftime("%Y-%m-%d")
                    date_from = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
                else:
                    if not date_from:
                        date_from = (datetime.strptime(date_to,"%Y-%m-%d") - timedelta(days=7)).strftime("%Y-%m-%d") # A week before date to
                    if not date_to:
                        date_to = (datetime.strptime(date_from,"%Y-%m-%d") + timedelta(days=7)).strftime("%Y-%m-%d") # A week after date from
            time_lapse = "[%sT00:00:00Z TO %sT23:59:59.999Z]" % (date_from, date_to)

    # if first time going into the page, the default is last week
    else:
        select_value = ''
        date_from = datetime.now() - timedelta(days=SELECT_OPTIONS_DAYS["last_week"])
        date_to = datetime.now()
        time_lapse = follow_utils.build_time_lapse(date_from, date_to)
        date_to = date_to.strftime("%Y-%m-%d")
        date_from = date_from.strftime("%Y-%m-%d")

    errors_getting_data = False
    try:
        users_sounds, tags_sounds = follow_utils.get_stream_sounds(user, time_lapse)
    except Exception, e:
        # Could not connect to solr
        errors_getting_data = True
Ejemplo n.º 4
0
    def handle(self, *args, **options):

        date_today_minus_notification_timedelta = datetime.datetime.now(
        ) - settings.NOTIFICATION_TIMEDELTA_PERIOD

        # Get all the users that have notifications active
        # and exclude the ones that have the last email sent for less than settings.NOTIFICATION_TIMEDELTA_PERIOD
        # (because they have been sent an email already)
        users_enabled_notifications = Profile.objects.filter(
            enabled_stream_emails=True
        ).exclude(
            last_stream_email_sent__gt=date_today_minus_notification_timedelta
        ).order_by("-last_attempt_of_sending_stream_email"
                   )[:settings.MAX_EMAILS_PER_COMMAND_RUN]

        logger.info(
            "Sending stream updates notification for %i potential users" %
            len(users_enabled_notifications))

        email_tuples = ()
        n_emails_sent = 0
        for profile in users_enabled_notifications:

            username = profile.user.username
            email_to = profile.user.email
            profile.last_attempt_of_sending_stream_email = datetime.datetime.now(
            )

            # Variable names use the terminology "week" because settings.NOTIFICATION_TIMEDELTA_PERIOD defaults to a
            # week, but a more generic terminology could be used
            week_first_day = profile.last_stream_email_sent
            week_last_day = datetime.datetime.now()

            week_first_day_str = week_first_day.strftime("%d %b").lstrip("0")
            week_last_day_str = week_last_day.strftime("%d %b").lstrip("0")

            subject_str = u'new sounds from users and tags you are following ('
            subject_str += unicode(week_first_day_str) + u' - ' + unicode(
                week_last_day_str) + u')'

            # Set date range from which to get upload notifications
            time_lapse = follow_utils.build_time_lapse(week_first_day,
                                                       week_last_day)

            # construct message
            user = User.objects.get(username=username)
            try:
                users_sounds, tags_sounds = follow_utils.get_stream_sounds(
                    user, time_lapse)
            except Exception, e:
                # If error occur do not send the email
                print "could not get new sounds data for", username
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            if not users_sounds and not tags_sounds:
                print "no news sounds for", username
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            text_content = render_mail_template('follow/email_stream.txt',
                                                locals())
            email_tuples += (subject_str, text_content,
                             settings.DEFAULT_FROM_EMAIL, [email_to]),

            # Send email
            try:
                send_mail(subject_str,
                          text_content,
                          email_from=settings.DEFAULT_FROM_EMAIL,
                          email_to=[email_to],
                          reply_to=None)
            except Exception, e:
                logger.info(
                    "An error occurred sending notification stream email to %s (%s)"
                    % (str(email_to), str(e)))
                # Do not send the email and do not update the last email sent field in the profile
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue
Ejemplo n.º 5
0
    def handle(self, *args, **options):

        date_today_minus_notification_timedelta = datetime.datetime.now(
        ) - settings.NOTIFICATION_TIMEDELTA_PERIOD

        # Get all the users that have notifications active
        # and exclude the ones that have the last email sent for less than settings.NOTIFICATION_TIMEDELTA_PERIOD
        # (because they have been sent an email already)
        email_type = EmailPreferenceType.objects.get(name="stream_emails")
        user_ids = email_type.useremailsetting_set.values_list('user_id')

        users_enabled_notifications = Profile.objects.filter(
            user_id__in=user_ids
        ).exclude(
            last_stream_email_sent__gt=date_today_minus_notification_timedelta
        ).order_by("-last_attempt_of_sending_stream_email"
                   )[:settings.MAX_EMAILS_PER_COMMAND_RUN]

        logger.info(
            "Sending stream updates notification for %i potential users" %
            len(users_enabled_notifications))

        n_emails_sent = 0
        for profile in users_enabled_notifications:

            username = profile.user.username
            profile.last_attempt_of_sending_stream_email = datetime.datetime.now(
            )

            # Variable names use the terminology "week" because settings.NOTIFICATION_TIMEDELTA_PERIOD defaults to a
            # week, but a more generic terminology could be used
            week_first_day = profile.last_stream_email_sent
            week_last_day = datetime.datetime.now()

            week_first_day_str = week_first_day.strftime("%d %b").lstrip("0")
            week_last_day_str = week_last_day.strftime("%d %b").lstrip("0")

            subject_str = u'new sounds from users and tags you are following ('
            subject_str += unicode(week_first_day_str) + u' - ' + unicode(
                week_last_day_str) + u')'

            # Set date range from which to get upload notifications
            time_lapse = follow_utils.build_time_lapse(week_first_day,
                                                       week_last_day)

            # construct message
            user = User.objects.get(username=username)
            try:
                users_sounds, tags_sounds = follow_utils.get_stream_sounds(
                    user, time_lapse)
            except Exception as e:
                # If error occur do not send the email
                print "could not get new sounds data for", username.encode(
                    'utf-8')
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            if not users_sounds and not tags_sounds:
                print "no news sounds for", username.encode('utf-8')
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            text_content = render_mail_template('follow/email_stream.txt',
                                                locals())
            tvars = {
                'username': username,
                'users_sounds': users_sounds,
                'tags_sounds': tags_sounds
            }
            text_content = render_mail_template('follow/email_stream.txt',
                                                tvars)

            # Send email
            try:
                send_mail(subject_str, text_content, user_to=user)
            except Exception as e:
                # Do not send the email and do not update the last email sent field in the profile
                profile.save()  # Save last_attempt_of_sending_stream_email
                logger.info(
                    "An error occurred sending notification stream email to %s (%s)"
                    % (profile.get_email_for_delivery(), str(e)))
                continue
            n_emails_sent += 1

            # update last stream email sent date
            profile.last_stream_email_sent = datetime.datetime.now()
            profile.save()

        logger.info(
            "Sent stream updates notification to %i users (others had no updates)"
            % n_emails_sent)
Ejemplo n.º 6
0
    def handle(self, *args, **options):
        self.log_start()

        date_today_minus_notification_timedelta = datetime.datetime.now(
        ) - settings.NOTIFICATION_TIMEDELTA_PERIOD

        # Get all the users that have notifications active
        # and exclude the ones that have the last email sent for less than settings.NOTIFICATION_TIMEDELTA_PERIOD
        # (because they have been sent an email already)
        email_type = EmailPreferenceType.objects.get(name="stream_emails")
        user_ids = email_type.useremailsetting_set.values_list('user_id')

        users_enabled_notifications = Profile.objects.filter(
            user_id__in=user_ids
        ).exclude(
            last_stream_email_sent__gt=date_today_minus_notification_timedelta
        ).order_by("-last_attempt_of_sending_stream_email"
                   )[:settings.MAX_EMAILS_PER_COMMAND_RUN]

        n_emails_sent = 0
        for profile in users_enabled_notifications:

            username = profile.user.username
            profile.last_attempt_of_sending_stream_email = datetime.datetime.now(
            )

            # Variable names use the terminology "week" because settings.NOTIFICATION_TIMEDELTA_PERIOD defaults to a
            # week, but a more generic terminology could be used
            week_first_day = profile.last_stream_email_sent
            week_last_day = datetime.datetime.now()

            week_first_day_str = week_first_day.strftime("%d %b").lstrip("0")
            week_last_day_str = week_last_day.strftime("%d %b").lstrip("0")

            extra_email_subject = unicode(
                week_first_day_str) + u' to ' + unicode(week_last_day_str)

            # Set date range from which to get upload notifications
            time_lapse = follow_utils.build_time_lapse(week_first_day,
                                                       week_last_day)

            # construct message
            user = User.objects.get(username=username)
            try:
                users_sounds, tags_sounds = follow_utils.get_stream_sounds(
                    user, time_lapse)
            except Exception as e:
                # If error occur do not send the email
                console_logger.info(
                    "could not get new sounds data for {0}".format(username))
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            if not users_sounds and not tags_sounds:
                console_logger.info("no news sounds for {0}".format(username))
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            tvars = {
                'username': username,
                'users_sounds': users_sounds,
                'tags_sounds': tags_sounds
            }
            text_content = render_mail_template('follow/email_stream.txt',
                                                tvars)

            # Send email
            try:
                send_mail(settings.EMAIL_SUBJECT_STREAM_EMAILS,
                          text_content,
                          extra_subject=extra_email_subject,
                          user_to=user)
            except Exception as e:
                # Do not send the email and do not update the last email sent field in the profile
                profile.save()  # Save last_attempt_of_sending_stream_email
                commands_logger.error(
                    "Unexpected error while sending stream notification email (%s)"
                    % json.dumps({
                        'email_to': profile.get_email_for_delivery(),
                        'username': profile.user.username,
                        'error': str(e)
                    }))
                continue
            n_emails_sent += 1

            # update last stream email sent date
            profile.last_stream_email_sent = datetime.datetime.now()
            profile.save()

        self.log_end({'n_users_notified': n_emails_sent})
Ejemplo n.º 7
0
    def handle(self, *args, **options):

        date_today_minus_notification_timedelta = datetime.datetime.now() - settings.NOTIFICATION_TIMEDELTA_PERIOD

        # Get all the users that have notifications active
        # and exclude the ones that have the last email sent for less than settings.NOTIFICATION_TIMEDELTA_PERIOD
        # (because they have been sent an email already)
        email_type = EmailPreferenceType.objects.get(name="stream_emails")
        user_ids = email_type.useremailsetting_set.values_list('user_id')

        users_enabled_notifications = Profile.objects.filter(user_id__in=user_ids).exclude(
            last_stream_email_sent__gt=date_today_minus_notification_timedelta).order_by(
            "-last_attempt_of_sending_stream_email")[:settings.MAX_EMAILS_PER_COMMAND_RUN]

        logger.info("Sending stream updates notification for %i potential users" % len(users_enabled_notifications))

        n_emails_sent = 0
        for profile in users_enabled_notifications:

            username = profile.user.username
            profile.last_attempt_of_sending_stream_email = datetime.datetime.now()

            # Variable names use the terminology "week" because settings.NOTIFICATION_TIMEDELTA_PERIOD defaults to a
            # week, but a more generic terminology could be used
            week_first_day = profile.last_stream_email_sent
            week_last_day = datetime.datetime.now()

            week_first_day_str = week_first_day.strftime("%d %b").lstrip("0")
            week_last_day_str = week_last_day.strftime("%d %b").lstrip("0")

            subject_str = u'new sounds from users and tags you are following ('
            subject_str += unicode(week_first_day_str) + u' - ' + unicode(week_last_day_str) + u')'

            # Set date range from which to get upload notifications
            time_lapse = follow_utils.build_time_lapse(week_first_day, week_last_day)

            # construct message
            user = User.objects.get(username=username)
            try:
                users_sounds, tags_sounds = follow_utils.get_stream_sounds(user, time_lapse)
            except Exception as e:
                # If error occur do not send the email
                print "could not get new sounds data for", username.encode('utf-8')
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            if not users_sounds and not tags_sounds:
                print "no news sounds for", username.encode('utf-8')
                profile.save()  # Save last_attempt_of_sending_stream_email
                continue

            text_content = render_mail_template('follow/email_stream.txt', locals())
            tvars = {'username': username,
                     'users_sounds': users_sounds,
                     'tags_sounds': tags_sounds}
            text_content = render_mail_template('follow/email_stream.txt', tvars)

            # Send email
            try:
                send_mail(subject_str, text_content, user_to=user)
            except Exception as e:
                # Do not send the email and do not update the last email sent field in the profile
                profile.save()  # Save last_attempt_of_sending_stream_email
                logger.info("An error occurred sending notification stream email to %s (%s)"
                            % (profile.get_email_for_delivery(), str(e)))
                continue
            n_emails_sent += 1

            # update last stream email sent date
            profile.last_stream_email_sent = datetime.datetime.now()
            profile.save()

        logger.info("Sent stream updates notification to %i users (others had no updates)" % n_emails_sent)