Commits

Josh VanderLinden committed e9a498c Merge

Merging branches

Comments (0)

Files changed (3)

tracking/__init__.py

 import listeners
 
-VERSION = (0, 3, 7)
+VERSION = (0, 4, 0)
 
 def get_version():
     "Returns the version as a human-format string."
     return '.'.join([str(i) for i in VERSION])
 
-# initialize the URL prefixes that we shouldn't track
-try:
-    from django.conf import settings
-    prefixes = getattr(settings, 'NO_TRACKING_PREFIXES', [])
-except ImportError:
-    pass
-else:
-    if '!!initialized!!' not in prefixes:
-        from django.core.urlresolvers import reverse, NoReverseMatch
-        if settings.MEDIA_URL and settings.MEDIA_URL != '/':
-            prefixes.append(settings.MEDIA_URL)
-
-        if settings.ADMIN_MEDIA_PREFIX:
-            prefixes.append(settings.ADMIN_MEDIA_PREFIX)
-
-        try:
-            # finally, don't track requests to the tracker update pages
-            prefixes.append(reverse('tracking-refresh-active-users'))
-        except NoReverseMatch:
-            # django-tracking hasn't been included in the URLconf if we get here
-            pass
-
-        prefixes.append('!!initialized!!')
-
-        settings.NO_TRACKING_PREFIXES = prefixes

tracking/middleware.py

 from datetime import datetime, timedelta
 import logging
-import random
 import re
-import time
 import traceback
-import urllib, urllib2
 
 from django.conf import settings
 from django.contrib.auth.models import AnonymousUser
 from django.core.cache import cache
+from django.core.urlresolvers import reverse, NoReverseMatch
 from django.db.utils import DatabaseError
 from django.http import Http404
+
 from tracking import utils
 from tracking.models import Visitor, UntrackedUserAgent, BannedIP
 
 title_re = re.compile('<title>(.*?)</title>')
 log = logging.getLogger('tracking.middleware')
 
-class VisitorTrackingMiddleware:
+class VisitorTrackingMiddleware(object):
     """
     Keeps track of your active users.  Anytime a visitor accesses a valid URL,
     their unique record will be updated with the page they're on and the last
     same IP and user agent in the last 5 minutes
     """
 
+    @property
+    def prefixes(self):
+        """Returns a list of URL prefixes that we should not track"""
+
+        if not hasattr(self, '_prefixes'):
+            self._prefixes = getattr(settings, 'NO_TRACKING_PREFIXES', [])
+
+            if not getattr(settings, '_FREEZE_TRACKING_PREFIXES', False):
+                for name in ('MEDIA_URL', 'ADMIN_MEDIA_PREFIX'):
+                    url = getattr(settings, name)
+                    if url and url != '/':
+                        self._prefixes.append(url)
+
+                try:
+                    # finally, don't track requests to the tracker update pages
+                    self._prefixes.append(reverse('tracking-refresh-active-users'))
+                except NoReverseMatch:
+                    # django-tracking hasn't been included in the URLconf if we
+                    # get here, which is not a bad thing
+                    pass
+
+                settings.NO_TRACKING_PREFIXES = self._prefixes
+                settings._FREEZE_TRACKING_PREFIXES = True
+
+        return self._prefixes
+
     def process_request(self, request):
         # don't process AJAX requests
         if request.is_ajax(): return
             # otherwise just fake a session key
             session_key = '%s:%s' % (ip_address, user_agent)
 
-        prefixes = getattr(settings, 'NO_TRACKING_PREFIXES', [])
-
         # ensure that the request.path does not begin with any of the prefixes
-        for prefix in prefixes:
+        for prefix in self.prefixes:
             if request.path.startswith(prefix):
                 log.debug('Not tracking request to: %s' % request.path)
                 return

tracking/templates/tracking/_active_users.js

 });
 $(document).unload(GUnload);
 
+$('html').ajaxSend(function(event, xhr, settings) {
+    function getCookie(name) {
+        var cookieValue = null;
+        if (document.cookie && document.cookie != '') {
+            var cookies = document.cookie.split(';');
+            for (var i = 0; i < cookies.length; i++) {
+                var cookie = jQuery.trim(cookies[i]);
+                // Does this cookie string begin with the name we want?
+                if (cookie.substring(0, name.length + 1) == (name + '=')) {
+                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+                    break;
+                }
+            }
+        }
+        return cookieValue;
+    }
+    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
+        // Only send the token to relative URLs i.e. locally.
+        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
+    }
+});
+
 function createMarkers() {
     // Pull back all active users and create markers for them
     $.ajax({