Beispiel #1
0
    def test_user_login(self):

        user = random.randrange(0, 100000)
        date = datetime_now_utc().strftime(self.DATE_FORMAT)
        key = self.LOGIN_METRICS_FORMAT.format(date)

        self.assertEquals(LoginMetrics.FLAG_DOWN, self.r.getbit(key, user))

        ls = LoginMetrics(datetime_now_utc())
        ls.save_user_login(user)

        self.assertEquals(LoginMetrics.FLAG_UP, self.r.getbit(key, user))
Beispiel #2
0
    def test_users_login(self):

        users_ids = [random.randrange(0, 100000) for i in range(100)]
        date = datetime_now_utc().strftime(self.DATE_FORMAT)
        key = self.LOGIN_METRICS_FORMAT.format(date)

        for i in users_ids:
            self.assertEquals(LoginMetrics.FLAG_DOWN, self.r.getbit(key, i))

        ls = LoginMetrics(datetime_now_utc())
        ls.save_users_login(users_ids)

        for i in users_ids:
            self.assertEquals(LoginMetrics.FLAG_UP, self.r.getbit(key, i))
Beispiel #3
0
def ask_reset_password(request):
    if request.method == 'POST':
        form = AskResetPasswordForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = User.objects.get(email=data['email'])
            profile = Profile.objects.get(user=user)

            # Set hash and date
            profile.password_reset_token = get_random_hash()
            profile.password_reset_token_date = datetime_now_utc()
            profile.save()

            logger.debug("Reset password in: " +\
                reverse(reset_password, args=[user.id, profile.password_reset_token]))

            # Send email
            messages.success(request, "An email has been sent to your account")
            return redirect("/")
    else:
        form = AskResetPasswordForm()

    context = {
        'form': form,
    }

    return render_to_response('userprofile/ask-reset-password.html',
                            context,
                            context_instance=RequestContext(request))
Beispiel #4
0
    def test_datetime_now_utc(self):
        now = dateutils.datetime_now_utc()
        almost_now = datetime.utcnow()

        self.assertEquals(almost_now.year, now.year)
        self.assertEquals(almost_now.month, now.month)
        self.assertEquals(almost_now.day, now.day)
        self.assertEquals(almost_now.hour, now.hour)
        self.assertEquals(almost_now.minute, now.minute)
        self.assertEquals(almost_now.second, now.second)
Beispiel #5
0
def reset_password(request, user_id, token):

    context = {
        'user_id': user_id,
        'token': token
    }
    user = User.objects.get(id=user_id)

    # Means that the form has been submitted
    if request.method == 'POST':
        form = ResetPasswordForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user.set_password(data['password1'])
            user.profile.password_reset_token = ""
            user.profile.password_reset_token_date = None

            user.profile.save()
            user.save()

            messages.success(request, "Password changed!")
        else:
            context['form'] = form

            return render_to_response('userprofile/reset-password.html',
                        context,
                        context_instance=RequestContext(request))

    else:
        # check the token correct
        if user.profile.password_reset_token == token:
            # Check the date correct
            now = datetime_now_utc()
            temp_date = user.profile.password_reset_token_date
            rel_delta = relativedelta(now, temp_date)

            # We need to compare, relativedelta can't and timedelta yes
            rel_delta = datetime.timedelta(days=rel_delta.days,
                                           minutes=rel_delta.minutes,
                                           seconds=rel_delta.seconds)

            if settings.PASSWORD_RESET_TOKEN_MAX_TIME > rel_delta:

                context['form'] = ResetPasswordForm()

                return render_to_response('userprofile/reset-password.html',
                            context,
                            context_instance=RequestContext(request))
            else:
                messages.error(request,
                            "Your token has expired, ask for a new one")
        else:
            messages.error(request, "Error changing password, try again")

    return redirect("/")
Beispiel #6
0
    def test_get_sharedlinks_metrics(self):
        setup = random.randrange(0, 10000)

        now = datetime_now_utc()
        date = now.strftime(self.DATE_FORMAT)

        key = self.SHAREDLINKS_METRICS_FORMAT.format(date)
        self.r.incr(key, setup)

        # Check the data
        self.assertEquals(setup, SharedLinkMetrics.get_count(key))
Beispiel #7
0
    def test_sharedlinks_metrics_increment_bulk(self):
        good_result = random.randrange(0, 10000)
        now = datetime_now_utc()

        redis_result = SharedLinkMetrics(now).increment(good_result)

        # Check the data
        date = now.strftime(self.DATE_FORMAT)
        key = self.SHAREDLINKS_METRICS_FORMAT.format(date)
        self.assertEquals(good_result, int(self.r.get(key)))
        self.assertEquals(good_result, redis_result)
Beispiel #8
0
    def test_sharedlinks_metrics_decrement(self):
        setup = random.randrange(0, 10000)

        now = datetime_now_utc()
        date = now.strftime(self.DATE_FORMAT)

        key = self.SHAREDLINKS_METRICS_FORMAT.format(date)
        self.r.incr(key, setup)
        redis_result = SharedLinkMetrics(now).decrement()

        # Check the data
        self.assertEquals(setup - 1, int(self.r.get(key)))
        self.assertEquals(setup - 1, redis_result)
Beispiel #9
0
    def __init__(self, metrics_date=None, total=None,  metrics_key_format=None,
                 date_format=None):
        super(CounterTimeMetrics, self).__init__(total=total)

        self._METRICS_KEY = metrics_key_format
        self._DATE_FORMAT = date_format  # Use Standard ISO-8601

        if not metrics_date:
            metrics_date = datetime_now_utc()
        self._metrics_date = metrics_date

        time = self._metrics_date.strftime(self._DATE_FORMAT)
        key = self._METRICS_KEY.format(time)

        self._key = key
Beispiel #10
0
    def test_sharedlinks_count_day(self):
        good_result = 0
        now = datetime_now_utc()

        # Fill data
        for i in range(24):
            shared_links = random.randrange(0, 10000)
            good_result += shared_links
            now = datetime(year=now.year,
                           month=int(now.month),
                           day=now.day,
                           hour=i)

            SharedLinkMetrics(now).increment(shared_links)

        # Check the data

        result = SharedLinkMetrics(now).total_counts_per_day()
        self.assertEquals(good_result, result)
Beispiel #11
0
    def test_login_count_day(self):
        good_result = 0
        now = datetime_now_utc()

        # Fill data
        for i in range(24):
            logins = [j for j in range(random.randrange(0, 10000))]
            good_result += len(logins)
            now = datetime(year=now.year,
                           month=int(now.month),
                           day=now.day,
                           hour=i)

            LoginMetrics(now).set_flags(logins)

        # Check the data

        result = LoginMetrics(now).total_counts_per_day()
        self.assertEquals(good_result, result)
Beispiel #12
0
    def handle(self, *args, **options):
        max_users = 5000 if len(args) < 1 else int(args[0])
        min_users = 0 if len(args) < 2 else int(args[1])
        day = None if len(args) < 3 else int(args[2])

        # Populate the DB for one day
        for hour in range(24):
            # Create the datetime for the key
            now = datetime_now_utc()
            if not day:
                day = now.day
            date = datetime(year=now.year,
                            month=now.month,
                            day=day,
                            hour=hour)

            # Get random login users
            logins = range(random.randrange(min_users, max_users))
            users = [random.randrange(min_users, max_users) for i in logins]

            # Save the users
            ls = LoginMetrics(date)
            ls.save_users_login(users)
Beispiel #13
0
def day_logins(request):
    now = datetime_now_utc()
    today = datetime(year=now.year, month=int(now.month), day=now.day)
    yesterday = datetime(year=now.year, month=int(now.month), day=now.day - 1)
    two_days_ago = datetime(year=now.year, month=int(now.month), day=now.day - 2)
    three_days_ago = datetime(year=now.year, month=int(now.month), day=now.day - 3)
    four_days_ago = datetime(year=now.year, month=int(now.month), day=now.day - 4)
    five_days_ago = datetime(year=now.year, month=int(now.month), day=now.day - 5)

    results_today = (today.strftime("%Y-%m-%d"),
                     LoginMetrics(today).count_hours_logins())
    results_yesterday = (yesterday.strftime("%Y-%m-%d"),
                         LoginMetrics(yesterday).count_hours_logins())
    results_two_days = (two_days_ago.strftime("%Y-%m-%d"),
                        LoginMetrics(two_days_ago).count_hours_logins())
    results_three_days = (three_days_ago.strftime("%Y-%m-%d"),
                          LoginMetrics(three_days_ago).count_hours_logins())
    results_four_days = (four_days_ago.strftime("%Y-%m-%d"),
                         LoginMetrics(four_days_ago).count_hours_logins())
    results_five_days = (five_days_ago.strftime("%Y-%m-%d"),
                         LoginMetrics(five_days_ago).count_hours_logins())

    data = day_metrics_linechart_json_transform(results_today,
                                                results_yesterday,
                                                results_two_days,
                                                results_three_days,
                                                results_four_days,
                                                results_five_days,
                                                )
    context = {
        "data": data,
    }

    return render_to_response('metrics/daylogins.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #14
0
def links_info(request, token):

    sl = ShortLink.find(token=token)

    clicks = Click.findall(token)

    # get browsers:
    browsers = {}
    os = {}
    languages = {}
    countries = {}
    countries_map = {}  # The countries map doesn't have unknown
    dates_tmp = {}
    dates = []
    date_format = "Date({0}, {1}, {2})"

    for i in clicks:

        # Browsers
        try:
            browsers[i.browser] += 1
        except KeyError:
            browsers[i.browser] = 1

        # Operative Systems
        try:
            os[i.os] += 1
        except KeyError:
            os[i.os] = 1

        # Languages (Browser)
        try:
            languages[i.language] += 1
        except KeyError:
            languages[i.language] = 1

        # Countries
        try:
            countries[i.location] += 1

            if i.location:
                countries_map[i.location] += 1

        except KeyError:
            countries[i.location] = 1

            if i.location:
                countries_map[i.location] = 1

        # dates
        dt = unix_to_datetime(i.click_date)
        dt_str = date_format.format(dt.year, dt.month-1, dt.day)
        try:
            dates_tmp[dt_str] += 1
        except KeyError:
            dates_tmp[dt_str] = 1

    # Fill the dates until now
    now = datetime_now_utc()
    temp_date = unix_to_datetime(sl.creation_date)

    # If the date doesn't have enough days in between then create a new range
    # of dates with more days (For graph visualization)
    rel_delta = relativedelta(now, temp_date)

    if rel_delta.year == 0 and rel_delta.month == 0 and rel_delta.day < 5 or\
       rel_delta.hours < 24:
        try:
            days = MINIMUN_DAYS_FOR_CHART-rel_delta.day
        except TypeError:
            days = MINIMUN_DAYS_FOR_CHART
        now = now + relativedelta(days=days)

    while (temp_date.day != now.day or
            temp_date.month != now.month or
            temp_date.year != now.year):

        dt_str = date_format.format(temp_date.year,
                                    temp_date.month-1,
                                    temp_date.day)
        try:
            dates.append((dt_str, dates_tmp[dt_str]))
        except KeyError:
            dates.append((dt_str, 0))

        temp_date += relativedelta(days=1)

    # Change None for unknown for the countries
    try:
        countries[_("Unknown")] = countries[None]
        del countries[None]
    except KeyError:
        pass

    context = {
        'browser_data': pie_chart_json_transform("Browsers", browsers),
        'os_data': pie_chart_json_transform("Operative systems", os),
        'languages_data': pie_chart_json_transform("Languages", languages),
        'countries_data': pie_chart_json_transform("Countries", countries),
        'countries_map_data': pie_chart_json_transform("Countries", countries_map),
        'dates_data': single_linechart_json_transform_with_list("Clicks", "Days", dates),
        'short_link': sl
    }

    return render_to_response('links/link_info.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #15
0
 def pre_save(self, model_instance, add):
     return datetime_now_utc()