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