]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/updater/base.py
calculate the active users count since the latest update check
[osqa.git] / forum_modules / updater / base.py
1 import os
2 import sys
3 import bz2
4 import urllib2, urllib
5 import binascii
6 import string
7 import random
8 import re
9 import urllib2
10 import settings
11 import datetime
12 import logging
13
14
15 from xml.dom.minidom import parse, parseString
16 from forum.models import Question, User
17 from forum.settings import APP_URL, SVN_REVISION
18 from django import VERSION as DJANGO_VERSION
19 from django.utils import simplejson
20 from django.utils.encoding import smart_unicode
21 from django.conf import settings as django_settings
22 from django.utils.translation import ugettext as _
23
24
25 def generate_installation_key():
26     gen = lambda length: "".join( [random.choice(string.digits+string.letters) for i in xrange(length)])
27     return '%s-%s-%s-%s' % (gen(4), gen(4), gen(4), gen(4))
28
29 # To get the site views count we get the SUM of all questions views.
30 def get_site_views():
31     views = 0
32
33     # Go through all questions and increase the views count
34     for question in Question.objects.all():
35         views += question.view_count
36
37     return views
38
39 # Gets the active users count since the last visit
40 def get_active_users():
41     users_count = 0
42
43     try:
44         if settings.LATEST_UPDATE_DATETIME:
45             users_count = User.objects.filter(last_login__gt=settings.LATEST_UPDATE_DATETIME).count()
46     except:
47         pass
48
49     return users_count
50
51 def get_server_name():
52     url = '%s/' % APP_URL
53
54     try:
55         # Make the request
56         request = urllib2.Request(url)
57         response = urllib2.urlopen(request)
58
59         # Get the response information
60         response_info = response.info()
61
62         server_name = re.findall("Server: (?P<server_name>.*)$", str(response_info))[0]
63         server_name = ''.join(server_name.splitlines())
64
65         return server_name
66     except:
67         return 'Unknown'
68
69 def get_admin_emails():
70     emails = []
71
72     for user in User.objects.filter(is_superuser=True):
73         emails.append(user.email)
74
75     return emails
76
77 def check_for_updates():
78     # Get the SVN Revision
79     try:
80         svn_revision = int(SVN_REVISION.replace('SVN-', ''))
81     except ValueError:
82         # Here we'll have to find another way of getting the SVN revision
83         svn_revision = 0
84
85     admin_emails_xml = '<emails>'
86     for email in get_admin_emails():
87         admin_emails_xml += '<email value="%s" />' % email
88     admin_emails_xml += '</emails>'
89
90     statistics = """<check>
91     <key value="%(site_key)s" />
92     <app_url value="%(app_url)s" />
93     <svn_revision value="%(svn_revision)d" />
94     <views value="%(site_views)d" />
95     <active_users value="%(active_users)d" />
96     <server value="%(server_name)s" />
97     <python_version value="%(python_version)s" />
98     <django_version value="%(django_version)s" />
99     <database value="%(database)s" />
100     <os value="%(os)s" />
101     %(emails)s
102 </check> """ % {
103         'site_key' : settings.SITE_KEY,
104         'app_url' : APP_URL,
105         'svn_revision' : svn_revision,
106         'site_views' : get_site_views(),
107         'server_name' : get_server_name(),
108         'active_users' : get_active_users(),
109         'python_version' : ''.join(sys.version.splitlines()),
110         'django_version' : str(DJANGO_VERSION),
111         'database' : django_settings.DATABASE_ENGINE,
112         'os' : str(os.uname()),
113         'emails' : admin_emails_xml,
114     }
115
116     # Compress the statistics XML dump
117     statistics_compressed = bz2.compress(statistics)
118
119     # Pass the compressed statistics to the update server
120     post_data = {
121         'statistics' : binascii.b2a_base64(statistics_compressed),
122     }
123     data = urllib.urlencode(post_data)
124
125     # We simulate some browser, otherwise the server can return 403 response
126     user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/5'
127     headers={ 'User-Agent' : user_agent,}
128
129     try:
130         check_request = urllib2.Request('%s%s' % (settings.UPDATE_SERVER_URL, '/site_check/'), data, headers=headers)
131         check_response = urllib2.urlopen(check_request)
132         content = check_response.read()
133     except urllib2.HTTPError, error:
134         content = error.read()
135     except:
136         return _("Wasn't able to check to the update server.")
137
138     # Read the messages from the Update Server
139     try:
140         messages_xml_url = '%s%s' % (settings.UPDATE_SERVER_URL, '/messages/xml/')
141         messages_request = urllib2.Request(messages_xml_url, headers=headers)
142         messages_response = urllib2.urlopen(messages_request)
143         messages_xml = messages_response.read()
144     except:
145         return _("Wasn't able to retreive the update messages.")
146
147     # Store the messages XML in a Setting object
148     settings.UPDATE_MESSAGES_XML.set_value(messages_xml)
149
150     messages_dom = parseString(messages_xml)
151     messages_count = len(messages_dom.getElementsByTagName('message'))
152
153     # Set the latest update datetime to now.
154     now = datetime.datetime.now()
155     settings.LATEST_UPDATE_DATETIME.set_value(now)
156
157     return _('%d update messages have been downloaded.') % messages_count
158
159 def update_trigger():
160     # Trigger the update process
161     now = datetime.datetime.now()
162     if (now - settings.LATEST_UPDATE_DATETIME) > datetime.timedelta(days=1):
163         update_status = check_for_updates()
164
165         logging.error(smart_unicode("Update process has been triggered: %s" % update_status))
166