Remove legacy search.
[wolnelektury.git] / src / experiments / base.py
1 import hashlib
2 from django.conf import settings
3
4
5 class Experiment:
6     slug = None
7     name = 'experiment'
8     explicit = False
9     size = 0
10     switchable = True
11
12     def qualify(self, request):
13         return True
14
15     def __init__(self, request):
16         self.value, self.manual = self.get_value(request)
17
18     def override(self, value):
19         self.value = value
20         self.manual = False
21         
22     def get_value(self, request):
23         overrides = getattr(settings, 'EXPERIMENTS_OVERRIDES', {})
24         slug = self.slug
25         if slug in overrides:
26             return overrides[slug], False
27
28         if self.qualify(request) is False:
29             return None, False
30
31         if self.switchable or request.user.is_staff:
32             cookie_value = request.COOKIES.get(f'EXPERIMENT_{slug}')
33             if cookie_value is not None:
34                 if cookie_value == 'on':
35                     return True, True
36                 elif cookie_value == 'off':
37                     return False, True
38
39         number = int(
40             hashlib.md5(
41                 (slug + request.META['REMOTE_ADDR']).encode('utf-8')
42             ).hexdigest(),
43             16
44         ) % 10e6 / 10e6
45         return number < self.size, False