Completed
Push — master ( 67eae9...f0f1ec )
by
unknown
01:23
created

make_discrete_bar_chart()   A

Complexity

Conditions 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 9.2
cc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A is_new_install() 0 3 1
1
# coding: utf8
2
3
"""
4
This software is licensed under the Apache 2 license, quoted below.
5
6
Copyright 2014 Crystalnix Limited
7
8
Licensed under the Apache License, Version 2.0 (the "License"); you may not
9
use this file except in compliance with the License. You may obtain a copy of
10
the License at
11
12
    http://www.apache.org/licenses/LICENSE-2.0
13
14
Unless required by applicable law or agreed to in writing, software
15
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
License for the specific language governing permissions and limitations under
18
the License.
19
"""
20
21
from functools import wraps
22
import datetime
23
import calendar
24
25
from singledispatch import singledispatch
26
from django_redis import get_redis_connection
27
from redis.exceptions import WatchError
28
from django.utils import timezone
29
30
from omaha.settings import KEY_PREFIX, KEY_LAST_ID
31
32
__all__ = ['get_sec_since_midnight', 'get_id']
33
34
redis = get_redis_connection('statistics')
35
36
37
def get_sec_since_midnight(date):
38
    """
39
    Return seconds since midnight
40
41
    >>> from datetime import datetime
42
    >>> get_sec_since_midnight(datetime(year=2014, month=1, day=1, second=42))
43
    42
44
    """
45
    midnight = date.replace(hour=0, minute=0, second=0, microsecond=0)
46
    delta = date - midnight
47
    return delta.seconds
48
49
50
def get_id(uuid):
51
    """
52
    >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
53
    1
54
    >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
55
    1
56
    """
57
    id = redis.get('{}:{}'.format(KEY_PREFIX, uuid))
58
    if id is None:
59
        id = create_id(uuid)
60
    return int(id)
61
62
63
def create_id(uuid):
64
    """
65
    >>> create_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
66
    1
67
    """
68
    with redis.pipeline() as pipe:
69
        while True:
70
            try:
71
                pipe.watch(KEY_LAST_ID)
72
                current_id = pipe.get(KEY_LAST_ID) or 0
73
                next_id = int(current_id) + 1
74
                pipe.multi()
75
                pipe.set(KEY_LAST_ID, next_id)
76
                pipe.execute()
77
78
                redis.set('{}:{}'.format(KEY_PREFIX, uuid), next_id)
79
                return next_id
80
            except WatchError:
81
                continue
82
            except:
83
                raise
84
85
86
def valuedispatch(func):
87
    _func = singledispatch(func)
88
89
    @wraps(func)
90
    def wrapper(*args, **kwargs):
91
        return _func.registry.get(args[0], _func)(*args, **kwargs)
92
93
    wrapper.register = _func.register
94
    wrapper.dispatch = _func.dispatch
95
    wrapper.registry = _func.registry
96
    return wrapper
97
98
99
def make_piechart(id, data, unit='users'):
100
    xdata = [i[0] for i in data]
101
    ydata = [i[1] for i in data]
102
103
    extra_serie = {
104
        "tooltip": {"y_start": "", "y_end": " " + unit},
105
    }
106
    chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
107
    charttype = "pieChart"
108
    chartcontainer = 'chart_container_%s' % id  # container name
109
110
    data = {
111
        'charttype': charttype,
112
        'chartdata': chartdata,
113
        'chartcontainer': chartcontainer,
114
        'extra': {
115
            'x_is_date': False,
116
            'x_axis_format': '',
117
            'tag_script_js': True,
118
            'jquery_on_ready': False,
119
        }
120
    }
121
    return data
122
123
124
def get_month_range_from_dict(source):
125
    """
126
    :param source: dictionary with keys 'start' and 'end
127
    :return: a tuple of datatime objects in the form (start, end)
128
    """
129
    now = timezone.now()
130
    start = source.get('start')
131
132
    end = source.get('end', datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]))
133
134
    if not start:
135
        start = datetime.datetime(end.year-1, end.month+1, 1) if end.month != 12 else datetime.datetime(end.year, 1, 1)
136
137
    return start, end
138
139
140
def is_new_install(appid, userid):
141
    event = "known_users:{}"
142
    return not redis.getbit(event.format(appid), userid)
143