16
16
title_re = re.compile('<title>(.*?)</title>')
17
17
log = logging.getLogger('tracking.middleware')
19
20
class VisitorTrackingMiddleware(object):
21
Keeps track of your active users. Anytime a visitor accesses a valid URL,
22
their unique record will be updated with the page they're on and the last
23
time they requested a page.
25
Records are considered to be unique when the session key and IP address
26
are unique together. Sometimes the same user used to have two different
27
records, so I added a check to see if the session key had changed for the
28
same IP and user agent in the last 5 minutes
21
"""Keeps track of your active users. Anytime a visitor accesses a valid
22
URL, their unique record will be updated with the page they're on and the
23
last time they requested a page.
25
Records are considered to be unique when the session key and IP
26
address are unique together. Sometimes the same user used to have
27
two different records, so I added a check to see if the session key
28
had changed for the same IP and user agent in the last 5 minutes
32
33
def prefixes(self):
33
"""Returns a list of URL prefixes that we should not track"""
34
"""Returns a list of URL prefixes that we should not track."""
35
36
if not hasattr(self, '_prefixes'):
36
37
self._prefixes = getattr(settings, 'NO_TRACKING_PREFIXES', [])
45
46
# finally, don't track requests to the tracker update pages
46
self._prefixes.append(reverse('tracking-refresh-active-users'))
47
self._prefixes.append(
48
reverse('tracking-refresh-active-users'))
47
49
except NoReverseMatch:
48
50
# django-tracking hasn't been included in the URLconf if we
49
51
# get here, which is not a bad thing
57
59
def process_request(self, request):
58
60
# don't process AJAX requests
59
if request.is_ajax(): return
61
64
# create some useful variables
62
65
ip_address = utils.get_ip(request)
63
user_agent = unicode(request.META.get('HTTP_USER_AGENT', '')[:255], errors='ignore')
66
user_agent = unicode(request.META.get(
67
'HTTP_USER_AGENT', '')[:255], errors='ignore')
65
69
# retrieve untracked user agents from cache
66
70
ua_key = '_tracking_untracked_uas'
74
78
for ua in untracked:
75
79
# if the keyword is found in the user agent, stop tracking
76
80
if user_agent.find(ua.keyword) != -1:
77
log.debug('Not tracking UA "%s" because of keyword: %s' % (user_agent, ua.keyword))
81
log.debug('Not tracking UA "%s" because of keyword: %s' %
82
(user_agent, ua.keyword))
80
85
if hasattr(request, 'session') and request.session.session_key:
116
121
if len(visitors):
117
122
visitor = visitors[0]
118
123
visitor.session_key = session_key
119
log.debug('Using existing visitor for IP %s / UA %s: %s' % (ip_address, user_agent, visitor.id))
124
log.debug('Using existing visitor for IP %s / UA %s: %s' %
125
(ip_address, user_agent, visitor.id))
121
127
# it's probably safe to assume that the visitor is brand new
122
128
visitor = Visitor(**attrs)
137
143
# at least an hour, update their referrer URL
138
144
one_hour_ago = now - timedelta(hours=1)
139
145
if not visitor.last_update or visitor.last_update <= one_hour_ago:
140
visitor.referrer = utils.u_clean(request.META.get('HTTP_REFERER', 'unknown')[:255])
146
visitor.referrer = utils.u_clean(
147
request.META.get('HTTP_REFERER', 'unknown')[:255])
142
149
# reset the number of pages they've been to
143
150
visitor.page_views = 0
151
158
except DatabaseError:
152
log.error('There was a problem saving visitor information:\n%s\n\n%s' % (traceback.format_exc(), locals()))
159
log.error('There was a problem saving visitor information:\n%s\n\n%s' % (
160
traceback.format_exc(), locals()))
154
163
class VisitorCleanUpMiddleware:
155
"""Clean up old visitor tracking records in the database"""
164
"""Clean up old visitor tracking records in the database."""
157
166
def process_request(self, request):
158
167
timeout = utils.get_cleanup_timeout()
162
171
timeout = datetime.now() - timedelta(hours=int(timeout))
163
172
Visitor.objects.filter(last_update__lte=timeout).delete()
165
175
class BannedIPMiddleware:
167
Raises an Http404 error for any page request from a banned IP. IP addresses
168
may be added to the list of banned IPs via the Django admin.
176
"""Raises an Http404 error for any page request from a banned IP. IP
177
addresses may be added to the list of banned IPs via the Django admin.
170
179
The banned users do not actually receive the 404 error--instead they get
171
180
an "Internal Server Error", effectively eliminating any access to the site.
174
184
def process_request(self, request):