Added filter_distination to HistoryForm
[ais.git] / bin / djais / views.py
1 # -*- coding: utf-8 -*-
2
3 from __future__ import division
4
5 #TODO
6 #Normalize 403 errors
7
8 import os
9 import os.path
10 from datetime import *
11 import re
12 from time import time as get_timestamp, sleep
13 import logging
14 import crack
15 import struct
16 import operator
17 import rrdtool
18 import csv
19 from StringIO import StringIO
20 from django.http import *
21 from django.template import loader, RequestContext
22 from django import forms
23 from django.shortcuts import render_to_response, get_object_or_404
24 from django.utils.safestring import mark_safe
25
26 from decoratedstr import remove_decoration
27
28 from ais.area import list_areas
29 from ais.djais.basicauth import http_authenticate
30 from ais.djais.models import *
31 from ais.show_targets_ships import format_fleet, kml_to_kmz
32 from ais.common import COUNTRIES_MID, Nmea, NmeaFeeder, strmmsi_to_mmsi, SHIP_TYPES, STATUS_CODES, AIS_STATUS_NOT_AVAILABLE, AIS_ROT_NOT_AVAILABLE, AIS_LATLON_SCALE, AIS_LON_NOT_AVAILABLE, AIS_LAT_NOT_AVAILABLE, AIS_COG_SCALE, AIS_COG_NOT_AVAILABLE, AIS_NO_HEADING, AIS_SOG_SCALE, AIS_SOG_NOT_AVAILABLE, AIS_SOG_MAX_SPEED, add_nmea1, add_nmea5_partial, load_fleet_to_uset
33 from ais.ntools import datetime_to_timestamp, clean_ais_charset
34 from ais.inputs.common import is_id4_active
35 from ais.inputs.stats import STATS_DIR
36 from ais.inputs.config import peers_get_config
37 from ais import jobrunner
38 from ais.djais.widgets import *
39
40 def auth(username, raw_password):
41     try:
42         user = User.objects.get(login=username)
43     except User.DoesNotExist:
44         return None
45     if not user.check_password(raw_password):
46         return None
47     user.update_access_datetime()
48     return user
49
50
51 @http_authenticate(auth, 'ais')
52 def index(request):
53     news = News.objects.order_by('-created')[:5]
54     return render_to_response('index.html', {'news':news}, RequestContext(request))
55
56
57 class VesselSearchForm(forms.Form):
58     def country_choices():
59         choices = {}
60         for mid, countryname in COUNTRIES_MID.iteritems():
61             if choices.has_key(countryname):
62                 choices[countryname] += u','+unicode(mid)
63             else:
64                 choices[countryname] = unicode(mid)
65         choices = [ (countryname, mids) for mids, countryname in choices.iteritems() ]
66         choices = sorted(choices, key=operator.itemgetter(1))
67         return [(u'', u'Any')] + choices
68
69     name = forms.CharField(max_length=20, required=False)
70     mmsi = forms.CharField(help_text=u'Maritime Mobile Service Identity', min_length=9, max_length=9, required=False)
71     imo = forms.IntegerField(help_text=u'International Maritime Organization identifier assigned by Llyod', required=False)
72     callsign = forms.CharField(max_length=7, required=False)
73     flag = forms.ChoiceField(choices=country_choices(), required=False)
74     destination = forms.CharField(max_length=20, required=False)
75
76     def clean(self):
77         cleaned_data = self.cleaned_data
78         for value in cleaned_data.values():
79             if value:
80                 return cleaned_data
81         raise forms.ValidationError("You must enter at least one criteria")
82
83     def clean_mmsi(self):
84         mmsi = self.cleaned_data['mmsi']
85         if mmsi:
86             try:
87                 mmsi = strmmsi_to_mmsi(mmsi)
88             except AssertionError:
89                 raise forms.ValidationError("Invalid MMSI")
90         return mmsi
91
92
93 @http_authenticate(auth, 'ais')
94 def vessel_search(request):
95     if request.method == 'POST' or request.META['QUERY_STRING']:
96         form = VesselSearchForm(request.REQUEST)
97         if form.is_valid():
98             data = form.cleaned_data
99             vessels = Vessel.objects
100             if data['mmsi']:
101                 vessels = vessels.filter(mmsi=data['mmsi'])
102             if data['name']:
103                 vessels = vessels.filter(name__contains=data['name'].upper())
104             if data['imo']:
105                 vessels = vessels.filter(imo=data['imo'])
106             if data['callsign']:
107                 vessels = vessels.filter(callsign__contains=data['callsign'].upper())
108             if data['destination']:
109                 vessels = vessels.filter(destination__contains=data['destination'].upper())
110             if data['flag']:
111                 vessels = vessels.extra(where=['mmsi/1000000 IN (%s) ' % data['flag']])
112             return render_to_response('vessels.html', {'vessels': vessels}, RequestContext(request))
113     else: # GET
114         form = VesselSearchForm()
115
116     return render_to_response('vessel_index.html', {'form': form}, RequestContext(request))
117
118 class SecondsWidget(forms.MultiWidget):
119     '''
120     A widget that splits period number and period type in a integer and a choice widgets
121     Does not work well for more than a week, as month lengthes do vary.
122     '''
123     __periods = (
124         (u'1', u'second(s)'),
125         (u'60', u'minute(s)'),
126         (u'3600', u'hour(s)'),
127         (u'86400', u'day(s)'),
128         (u'604800', u'week(s)'),
129         (u'2592000', u'month(es)'))
130
131     def __init__(self, attrs=None):
132         textattrs = { 'size': 3 }
133         if attrs:
134             textattrs.update(attrs)
135         widgets = (
136             forms.TextInput(attrs=textattrs),
137             forms.Select(choices=self.__periods, attrs=attrs))
138         super(SecondsWidget, self).__init__(widgets, attrs)
139
140     def decompress(self, value):
141         if value:
142             for period_second in reversed([int(sec_txt[0]) for sec_txt in self.__periods]):
143                 if value >= period_second and not value % period_second:
144                     return [ unicode(value // period_second), unicode(period_second) ]
145         return [None, None]
146
147 class SecondsField(forms.MultiValueField):
148     widget = SecondsWidget
149
150     def __init__(self, *args, **kargs):
151         fields = (
152             forms.IntegerField(),
153             forms.CharField(),
154         )
155         forms.MultiValueField.__init__(self, fields=fields, *args, **kargs)
156
157     def compress(self, data_list):
158         #print 'data_list=', data_list
159         if data_list and data_list[0] is not None and data_list[1] is not None:
160             try:
161                 return data_list[0] * int(data_list[1])
162             except ValueError:
163                 pass
164         return None
165
166 class HistoryForm(forms.Form):
167     format = forms.ChoiceField(choices=(('animation', 'Animation (Google Earth v5)'), ('track', 'Track line (Google Earth)'), ('csv', 'Coma separated values (SpreadSheet)')), widget=forms.Select(attrs={'onchange': mark_safe("if (this.value=='csv') $('#csvhint').show(); else $('#csvhint').hide();")}))
168     period_type = forms.ChoiceField(choices=(('duration', 'Duration until now'), ('date_date','Between two dates'), ('start_duration', 'Start date and duration')), widget=forms.RadioSelect(attrs={'onchange': mark_safe("show_hide_start_end_time(this.value);")}))
169     start_date = forms.DateTimeField(required=False, widget=AisCalendarWidget(attrs={'class':'vDateField'}))
170     duration = SecondsField(required=False, label='Period length', initial=7*86400)
171     end_date = forms.DateTimeField(required=False, widget=AisCalendarWidget(attrs={'class':'vDateField'}))
172     grain = SecondsField(label='One position every', initial=3600)
173     filter_area = forms.ChoiceField(required=False, label='Only in area',
174         choices=[ (u'', u'(Not filtered)') ] + [ (fn[1], fn[0]) for fn in list_areas() ] )
175     filter_sog_le = forms.FloatField(required=False, label=u'Only if speed ≤ (knots)')
176     filter_sog_ge = forms.FloatField(required=False, label=u'Only if speed ≥ (knots)')
177     filter_destination = forms.CharField(required=False, label=u'Only if destination starts with', max_length=20, help=u'Use AIS upper case letters')
178
179     def clean_start_date(self):
180         period_type = self.cleaned_data.get('period_type', None)
181         start_date = self.cleaned_data.get('start_date', None)
182         if period_type in (u'date_date', u'start_duration') and start_date is None:
183             raise forms.ValidationError('That is field is required.')
184         return start_date
185
186     def clean_duration(self):
187         period_type = self.cleaned_data.get('period_type', None)
188         duration = self.cleaned_data.get('duration', None)
189         print 'duration=', duration
190         if period_type in (u'duration', u'start_duration') and duration is None:
191             raise forms.ValidationError('That is field is required.')
192         return duration
193     
194     def clean_end_date(self):
195         period_type = self.cleaned_data.get('period_type', None)
196         end_date = self.cleaned_data.get('end_date', None)
197         if period_type in (u'date_date',) and end_date is None:
198             raise forms.ValidationError('That is field is required.')
199         return end_date
200
201     def clean(self):
202         cleaned_data = self.cleaned_data
203         period_type = self.cleaned_data.get('period_type', None)
204         start_date = self.cleaned_data.get('start_date', None)
205         end_date = self.cleaned_data.get('end_date', None)
206         if period_type == u'date_date' and start_date is not None and end_date is not None:
207             if start_date >= end_date:
208                 self._errors["start_date"] = self.error_class(['Start date must be before end date.'])
209         return cleaned_data
210     
211     def get_cmdext(self):
212         '''
213         Must not be called unless is_valid
214         Returns (command, extension)
215         FIXME escape!
216         '''
217         data = self.cleaned_data
218         format = data['format']
219
220         if format == u'track':
221             command = u'show_targets_ships'
222             command += u' --format=track'
223             extension = u'kmz'
224
225         elif format == u'animation':
226             command = u'show_targets_ships'
227             command += u' --format=animation'
228             extension = u'kmz'
229         
230         elif format == u'csv':
231             command = u'common'
232             extension = u'csv'
233         else:
234             raise Http404(u'Invalid archive format')
235        
236         date_start = data.get('start_date', None)
237         if date_start:
238             command += u' --start \'' + date_start.strftime('%Y%m%d') + u'\''
239
240         date_end = data.get('end_date', None)
241         if date_end:
242             command += u' --end \'' + date_end.strftime('%Y%m%d') + u'\''
243
244         duration = data.get('duration', None)
245         if duration:
246             command += u' --duration \'' + unicode(duration) + u'\''
247
248         grain = data['grain']
249         command += u' --granularity ' + unicode(grain)
250
251         filter_area = data.get('filter_area', None)
252         if filter_area:
253             command += u' --filter-area \'' + filter_area + u'\''
254
255         filter_sog_le = data.get('filter_sog_le', None)
256         if filter_sog_le:
257             command += u' --filter-sog-le ' + unicode(filter_sog_le)
258
259         filter_sog_ge = data.get('filter_sog_ge', None)
260         if filter_sog_ge:
261             command += u' --filter-sog-ge ' + unicode(filter_sog_ge)
262
263         filter_destination = data.get('filter_destination', None)
264         if filter_destination:
265             command += u' --filter-destination \'' + filter_destination + u'\''
266
267         return command, extension
268
269
270 @http_authenticate(auth, 'ais')
271 def vessel(request, strmmsi):
272     mmsi = strmmsi_to_mmsi(strmmsi)
273     vessel = get_object_or_404(Vessel, pk=mmsi)
274     nmea = Nmea.new_from_lastinfo(strmmsi)
275     #if not nmea.timestamp_1 and not nmea.timestamp_5:
276     #    raise Http404
277     return render_to_response('vessel.html', {'nmea': nmea, 'form': HistoryForm()}, RequestContext(request))
278
279
280 class VesselManualInputForm(forms.Form):
281     timestamp = forms.DateTimeField(label=u'When', help_text=u'When was the observation made in GMT. Use YYYY-MM-DD HH:MM:SS format')
282     imo = forms.IntegerField(required=False, min_value=1000000, max_value=9999999)
283     name = forms.CharField(max_length=20, required=False)
284     callsign = forms.CharField(max_length=7, required=False)
285     type = forms.TypedChoiceField(required=False, choices = [ kv for kv in SHIP_TYPES.iteritems() if 'reserved' not in kv[1].lower()], coerce=int, empty_value=0, initial=0)
286     status = forms.TypedChoiceField(required=False, choices = [ kv for kv in STATUS_CODES.iteritems() if 'reserved' not in kv[1].lower()], coerce=int, empty_value=AIS_STATUS_NOT_AVAILABLE, initial=AIS_STATUS_NOT_AVAILABLE)
287     sog = forms.FloatField(label='Speed', help_text='Over ground, in knots', required=False, min_value=0, max_value=AIS_SOG_MAX_SPEED/AIS_SOG_SCALE)
288     latitude = forms.CharField(required=False)
289     longitude = forms.CharField(required=False)
290     cog = forms.FloatField(label='Course', help_text='Over ground', required=False, min_value=0.0, max_value=359.9)
291     heading = forms.IntegerField(required=False, min_value=0, max_value=359)
292
293     @staticmethod
294     def _clean_ais_charset(ustr):
295         ustr = remove_decoration(ustr) # benign cleaning, but can increase size (œ->oe)
296         ustr = ustr.upper() # benign cleaning
297         str = clean_ais_charset(ustr.encode('ascii', 'replace'))
298         if unicode(str) != ustr:
299             raise forms.ValidationError('Invalid character: AIS alphabet is @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^- !"#$%&\'()*+,-./0123456789:;<=>?')
300         return str
301
302     def clean_timestamp(self):
303         data = self.cleaned_data['timestamp']
304         if data is None:
305             return None
306         if data < datetime.utcnow() - timedelta(365):
307             raise forms.ValidationError('Date is too much is the past.')
308         if data > datetime.utcnow():
309             raise forms.ValidationError('Date is be in the future. This form is only for observed results.')
310         return datetime_to_timestamp(data)
311
312     def clean_imo(self):
313         data = self.cleaned_data['imo']
314         if data is None:
315             return 0
316         return data
317
318     def clean_name(self):
319         name = self.cleaned_data['name']
320         if name is None:
321             return ''
322         name = VesselManualInputForm._clean_ais_charset(name)
323         if len(name)>20:
324             raise forms.ValidationError('Ensure this value has at most 20 characters (it has %s).' % len(name))
325         return name
326
327     def clean_callsign(self):
328         callsign = self.cleaned_data['callsign']
329         if callsign is None:
330             return ''
331         callsign = VesselManualInputForm._clean_ais_charset(callsign)
332         if len(callsign)>7:
333             raise forms.ValidationError('Ensure this value has at most 7 characters (it has %s).' % len(callsign))
334         return callsign
335
336     def clean_sog(self):
337         sog = self.cleaned_data['sog']
338         if sog is None:
339             return AIS_SOG_NOT_AVAILABLE
340         return int(sog*AIS_SOG_SCALE)
341
342     def clean_latitude(self):
343         #TODO: use ntools.clean_latitude
344         data = self.cleaned_data['latitude']
345         data = data.replace(u"''", u'"') # common mistake
346         data = data.replace(u' ', u'') # remove spaces
347         sides = u'SN'
348         if not data:
349             return AIS_LAT_NOT_AVAILABLE
350         tmp, side = data[:-1], data[-1]
351         if side == sides[0]:
352             side = -1
353         elif side == sides[1]:
354             side = 1
355         else:
356             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
357         spl = tmp.split(u'°')
358         if len(spl) == 1:
359             raise forms.ValidationError(u'You need to use the ° character.')
360         d, tmp = spl
361         try:
362             d = float(d)
363         except ValueError:
364             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
365         spl = tmp.split(u"'", 1)
366         if len(spl) == 1:
367             # no ' sign: ok only if there is nothing but the side after °
368             # we don't accept seconds if there is no minutes:
369             # It might be an entry mistake
370             tmp = spl[0]
371             if len(tmp) == 0:
372                 m = s = 0
373             else:
374                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
375         else:
376             m, tmp = spl
377             try:
378                 m = float(m)
379             except ValueError:
380                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
381             if len(tmp) == 0:
382                 s = 0
383             else:
384                 if tmp[-1] != '"':
385                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
386                 s = tmp[:-1]
387                 try:
388                     s = float(s)
389                 except ValueError:
390                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
391         data = side * ( d + m / 60 + s / 3600)
392
393         if data < -90 or data > 90:
394             raise forms.ValidationError(u'%s in not in -90..90 range' % data)
395         return int(data * AIS_LATLON_SCALE)
396
397     def clean_longitude(self):
398         #TODO: use ntools.clean_latitude
399         data = self.cleaned_data['longitude']
400         data = data.replace(u"''", u'"') # common mistake
401         data = data.replace(u' ', u'') # remove spaces
402         sides = u'WE'
403         if not data:
404             return AIS_LON_NOT_AVAILABLE
405         tmp, side = data[:-1], data[-1]
406         if side == sides[0]:
407             side = -1
408         elif side == sides[1]:
409             side = 1
410         else:
411             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
412         spl = tmp.split(u'°')
413         if len(spl) == 1:
414             raise forms.ValidationError(u'You need to use the ° character.')
415         d, tmp = spl
416         try:
417             d = float(d)
418         except ValueError:
419             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
420         spl = tmp.split(u"'", 1)
421         if len(spl) == 1:
422             # no ' sign: ok only if there is nothing but the side after °
423             # we don't accept seconds if there is no minutes:
424             # It might be an entry mistake
425             tmp = spl[0]
426             if len(tmp) == 0:
427                 m = s = 0
428             else:
429                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
430         else:
431             m, tmp = spl
432             try:
433                 m = float(m)
434             except ValueError:
435                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
436             if len(tmp) == 0:
437                 s = 0
438             else:
439                 if tmp[-1] != '"':
440                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
441                 s = tmp[:-1]
442                 try:
443                     s = float(s)
444                 except ValueError:
445                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
446         data = side * ( d + m / 60 + s / 3600)
447
448         if data < -180 or data > 180:
449             raise forms.ValidationError(u'%s in not in -180..180 range' % data)
450         return int(data * AIS_LATLON_SCALE)
451
452     def clean_cog(self):
453         data = self.cleaned_data['cog']
454         if data is None:
455             return AIS_COG_NOT_AVAILABLE
456         return int(data * AIS_COG_SCALE)
457     
458     def clean_heading(self):
459         #raise forms.ValidationError(u'clean_heading called')
460         data = self.cleaned_data['heading']
461         if data is None:
462             return AIS_NO_HEADING
463         return data
464
465     def clean(self):
466         cleaned_data = self.cleaned_data
467         if (cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE ) ^ ( cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE):
468             raise forms.ValidationError('It makes no sense to enter just a latitude or a longitude. Enter both or none.')
469         if cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE:
470             if cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) != AIS_STATUS_NOT_AVAILABLE:
471                 raise forms.ValidationError('It makes no sense to enter a status without coordinates. Please enter latitute and longitude too.')
472             if cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) != AIS_SOG_NOT_AVAILABLE:
473                 raise forms.ValidationError('It makes no sense to enter a speed without coordinates. Please enter latitute and longitude too.')
474             if cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) != AIS_COG_NOT_AVAILABLE:
475                 raise forms.ValidationError('It makes no sense to enter a course without coordinates. Please enter latitute and longitude too.')
476             if cleaned_data.get('heading', AIS_NO_HEADING) != AIS_NO_HEADING:
477                 raise forms.ValidationError('It makes no sense to enter a heading without coordinates. Please enter latitute and longitude too.')
478
479         if cleaned_data.get('timestamp', None) \
480         and cleaned_data.get('imo', 0) == 0 \
481         and cleaned_data.get('name', '') == '' \
482         and cleaned_data.get('callsign', '') == '' \
483         and cleaned_data.get('type', 0) == 0 \
484         and cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) == AIS_STATUS_NOT_AVAILABLE \
485         and cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) == AIS_SOG_NOT_AVAILABLE \
486         and cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE \
487         and cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE \
488         and cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) == AIS_COG_NOT_AVAILABLE \
489         and cleaned_data.get('heading', AIS_NO_HEADING) == AIS_NO_HEADING:
490             raise forms.ValidationError("You must enter some data, beside when.")
491         return cleaned_data
492
493 @http_authenticate(auth, 'ais')
494 def vessel_manual_input(request, strmmsi):
495     strmmsi = strmmsi.encode('utf-8')
496     nmea = Nmea.new_from_lastinfo(strmmsi)
497     if request.method == 'POST' or request.META['QUERY_STRING']:
498         form = VesselManualInputForm(request.REQUEST)
499         if form.is_valid():
500             data = form.cleaned_data
501             source = 'U' +  struct.pack('<I', request.user.id)[0:3]
502             result = u''
503             if data['imo'] != 0 \
504             or data['name'] != '' \
505             or data['callsign'] != '' \
506             or data['type'] != 0:
507                 toto = (strmmsi, data['timestamp'], data['imo'], data['name'], data['callsign'], data['type'], 0,0,0,0, 0,0,24,60, 0, '', source)
508                 result += 'UPDATING NMEA 5: '+repr(toto)+'<br>'
509                 add_nmea5_partial(*toto)
510             if data['status'] != AIS_STATUS_NOT_AVAILABLE \
511             or data['sog'] != AIS_SOG_NOT_AVAILABLE \
512             or data['latitude'] != AIS_LAT_NOT_AVAILABLE \
513             or data['longitude'] != AIS_LON_NOT_AVAILABLE \
514             or data['cog'] != AIS_COG_NOT_AVAILABLE \
515             or data['heading'] != AIS_NO_HEADING:
516                 
517                 toto = (strmmsi, data['timestamp'], data['status'], AIS_ROT_NOT_AVAILABLE, data['sog'], data['latitude'], data['longitude'], data['cog'], data['heading'], source)
518                 result += 'UPDATING NMEA 1: '+repr(toto)+'<br>'
519                 add_nmea1(*toto)
520             return HttpResponse('Not fully implemented: '+repr(data) + '<br>' + result)
521     else: # GET
522         form = VesselManualInputForm()
523     return render_to_response('vessel_manual_input.html', {'form': form, 'nmea': nmea}, RequestContext(request))
524
525
526 @http_authenticate(auth, 'ais')
527 def vessel_lastpos(request, strmmsi):
528     value = kml_to_kmz(format_fleet([ strmmsi ], document_name=strmmsi).encode('utf-8'))
529     response = HttpResponse(value, mimetype="application/vnd.google-earth.kmz")
530     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
531     return response
532
533 @http_authenticate(auth, 'ais')
534 def vessel_history(request, strmmsi):
535     """
536     TODO
537     That view is called from Google Earth, so that it must support GET method.  
538     """
539     initial = {}
540     if request.method == 'POST':
541         form = HistoryForm(request.POST, initial=initial)
542         if form.is_valid():
543             command, extension = form.get_cmdext()
544
545             command += u' ' + strmmsi
546
547             job = Job()
548             job.queue_time = datetime.utcnow()
549             job.friendly_filename = u'%s.%s' % (strmmsi, extension)
550             job.user = request.user
551             job.command = command
552             job.save()
553             if not jobrunner.wakeup_daemon():
554                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
555             return HttpResponseRedirect('/job/%s/download' % job.id)
556     else: # GET
557         form = HistoryForm(initial=initial)
558     strmmsi = strmmsi.encode('utf-8')
559     nmea = Nmea.new_from_lastinfo(strmmsi)
560     return render_to_response('vessel_history.html', {'nmea': nmea, 'form':form}, RequestContext(request))
561
562
563 @http_authenticate(auth, 'ais')
564 def fleets(request):
565     fleetusers = request.user.fleetuser_set.order_by('fleet')
566     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
567
568
569 @http_authenticate(auth, 'ais')
570 def fleet(request, fleetname):
571     fleet = get_object_or_404(Fleet, name=fleetname)
572     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
573         return HttpResponseForbidden('<h1>Forbidden</h1>')
574     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
575
576
577 class FleetEditForm(forms.Form):
578     name = forms.CharField(max_length=50)
579     description = forms.CharField(widget=forms.Textarea)
580
581     def clean_name(self):
582         name = self.cleaned_data['name']
583         if name == u'add':
584             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
585         if name != self.initial.get('name', None):
586             if Fleet.objects.filter(name=name).count():
587                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
588         return remove_decoration(name).replace(u' ', u'_')
589         
590
591 @http_authenticate(auth, 'ais')
592 def fleet_edit(request, fleetname):
593     initial = {}
594     if fleetname is not None:
595         fleet = get_object_or_404(Fleet, name=fleetname)
596         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
597             return HttpResponseForbidden('<h1>Forbidden</h1>')
598
599         initial['name'] = fleet.name
600         initial['description'] = fleet.description
601     else:
602         fleet = Fleet()
603
604     if request.method == 'POST':
605         form = FleetEditForm(request.POST, initial=initial)
606         if form.is_valid():
607             fleet.name = form.cleaned_data['name']
608             fleet.description = form.cleaned_data['description']
609             fleet.save()
610             if not fleetname: # new one
611                 fu = FleetUser()
612                 fu.fleet = fleet
613                 fu.user = request.user
614                 fu.save()
615             request.user.info('Fleet updated')
616             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
617     else: # GET
618         form = FleetEditForm(initial=initial)
619     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
620
621
622 @http_authenticate(auth, 'ais')
623 def fleet_vessels(request, fleetname):
624     fleet = get_object_or_404(Fleet, name=fleetname)
625     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
626         return HttpResponseForbidden('<h1>Forbidden</h1>')
627     vessels = fleet.vessel.all()
628     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
629
630
631 @http_authenticate(auth, 'ais')
632 def fleet_vessel_add(request, fleetname):
633     fleet = get_object_or_404(Fleet, name=fleetname)
634     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
635         return HttpResponseForbidden('<h1>Forbidden</h1>')
636     strmmsi = request.REQUEST['mmsi']
637     mmsi = strmmsi_to_mmsi(strmmsi)
638     try:
639         vessel = Vessel.objects.get(pk=mmsi)
640     except Vessel.DoesNotExist:
641         request.user.error('No such vessel')
642     else:
643         try:
644             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
645         except FleetVessel.DoesNotExist:
646             FleetVessel(fleet=fleet, vessel=vessel).save()
647             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
648         else:
649             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
650     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
651
652
653 class FleetAddVessel(forms.Form):
654     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
655     #name = forms.CharField(max_length=20, required=False)
656     #imo = forms.IntegerField(required=False)
657     #callsign = forms.CharField(max_length=7, required=False)
658     #destination = forms.CharField(max_length=20, required=False)
659     def clean(self):
660         cleaned_data = self.cleaned_data
661         for value in cleaned_data.values():
662             if value:
663                 return cleaned_data
664         raise forms.ValidationError("You must enter at least one criteria")
665
666 @http_authenticate(auth, 'ais')
667 def fleet_vessel_add2(request, fleetname):
668     fleet = get_object_or_404(Fleet, name=fleetname)
669     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
670         return HttpResponseForbidden('<h1>Forbidden</h1>')
671     if request.method == 'POST' or request.META['QUERY_STRING']:
672         form = FleetAddVessel(request.REQUEST)
673         if form.is_valid():
674             data = form.cleaned_data
675             result = []
676             a_strmmsi = request.REQUEST['mmsi']
677             if a_strmmsi:
678                 for strmmsi in a_strmmsi.split('\n'):
679                     strmmsi = strmmsi.strip('\r')
680                     if not strmmsi:
681                         continue
682                     try:
683                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
684                     except AssertionError:
685                         result.append('Invalid mmsi %s' % strmmsi)
686                         continue
687                     try:
688                         vessel = Vessel.objects.get(pk=sqlmmsi)
689                     except Vessel.DoesNotExist:
690                         result.append('No vessel with MMSI '+strmmsi)
691                         continue
692                     try:
693                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
694                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
695                     except FleetVessel.DoesNotExist:
696                         FleetVessel(fleet=fleet, vessel=vessel).save()
697                         result.append('Vessel with MMSI %s added' % strmmsi)
698
699             return HttpResponse('<br>'.join(result))
700     else: # GET
701         form = FleetAddVessel()
702
703     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
704
705
706 @http_authenticate(auth, 'ais')
707 def fleet_users(request, fleetname):
708     fleet = get_object_or_404(Fleet, name=fleetname)
709     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
710         return HttpResponseForbidden('<h1>Forbidden</h1>')
711
712     if request.method == 'POST' or request.META['QUERY_STRING']:
713         action = request.REQUEST['action']
714         userlogin = request.REQUEST['user']
715         try:
716             user = User.objects.get(login=userlogin)
717         except User.DoesNotExist:
718             request.user.error(u'User %s does not exist.' % userlogin)
719         else:
720             if action == u'add':
721                 try:
722                     fu = FleetUser.objects.get(fleet=fleet, user=user)
723                     request.user.error(u'User %s already has access.' % user.login)
724                 except FleetUser.DoesNotExist:
725                     FleetUser(fleet=fleet, user=user).save()
726                     #TODO log
727                     request.user.info(u'Granted access to user %s.' % user.login)
728             elif action == u'revoke':
729                 try:
730                     fu = FleetUser.objects.get(fleet=fleet, user=user)
731                     fu.delete()
732                     #TODO log
733                     request.user.info(u'Revoked access to user %s.' % user.login)
734                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
735                         fleet.delete()
736                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
737                         return HttpResponseRedirect('/fleet/')
738                 except FleetUser.DoesNotExist:
739                     request.user.error(u'User %s didn\'t have access.' % user.login)
740             else:
741                 request.user.error(u'Unknown action %s' % action)
742
743     fleetusers = fleet.fleetuser_set.all()
744     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
745     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
746
747
748 @http_authenticate(auth, 'ais')
749 def fleet_lastpos(request, fleetname):
750     fleet = get_object_or_404(Fleet, name=fleetname)
751     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
752         return HttpResponseForbidden('<h1>Forbidden</h1>')
753     fleet_uset = load_fleet_to_uset(fleet.id)
754     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
755     response = HttpResponse(value, mimetype="application/vnd.google-earth.kmz")
756     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
757     return response
758
759 @http_authenticate(auth, 'ais')
760 def fleet_history(request, fleetname):
761     fleet = get_object_or_404(Fleet, name=fleetname)
762     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
763         return HttpResponseForbidden('<h1>Forbidden</h1>')
764     initial = {}
765     if request.method == 'POST':
766         form = HistoryForm(request.POST, initial=initial)
767         if form.is_valid():
768             command, extension = form.get_cmdext()
769
770             command += u' @' + fleetname
771
772             job = Job()
773             job.queue_time = datetime.utcnow()
774             job.friendly_filename = u'%s.%s' % (fleetname, extension)
775             job.user = request.user
776             job.command = command
777             job.save()
778             if not jobrunner.wakeup_daemon():
779                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
780             return HttpResponseRedirect('/job/%s/download' % job.id)
781     else: # GET
782         form = HistoryForm(initial=initial)
783     return render_to_response('fleet_history.html', {'fleet': fleet, 'form':form}, RequestContext(request))
784
785
786 @http_authenticate(auth, 'ais')
787 def jobs_index(request):
788     show_archive = request.REQUEST.has_key('archive')
789     if show_archive:
790         jobs = request.user.job_set.all()
791     else:
792         jobs = request.user.job_set.filter(archive_time__isnull=True)
793     
794     response = render_to_response('jobs.html', {'jobs': jobs, 'queue_size': Job.queue_size(), 'archive': show_archive }, RequestContext(request))
795     response['Refresh'] = 15
796     return response
797
798 @http_authenticate(auth, 'ais')
799 def job_detail(request, jobid):
800     job = get_object_or_404(Job, id=jobid)
801     if job.user != request.user:
802         return HttpResponseForbidden('403 Forbidden')
803     response = render_to_response('job.html', {'job': job, 'queue_size': Job.queue_size()}, RequestContext(request))
804     if not job.finish_time:
805         response['Refresh'] = 5
806     elif not job.archive_time:
807         # finished but not archived:
808         response['Refresh'] = '0;url=https://' + request.get_host() + '/job/%s/download' % job.id
809         # careful not to modify other unschronized columns
810         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
811     return response
812
813 @http_authenticate(auth, 'ais')
814 def job_get(request, jobid):
815     job = get_object_or_404(Job, id=jobid)
816     if job.user != request.user:
817         return HttpResponseForbidden('403 Forbidden')
818     total_wait = 0
819     while not job.finish_time:
820         sleep(1)
821         total_wait += 1
822         if total_wait > 15:
823             request.user.info('Your query is slow. Please be patient.')
824             # TODO: Do not overwrite job.finishtime / result
825             if not job.notify:
826                 # careful not to modify other unschronized columns
827                 Job.objects.filter(id=jobid).update(notify = 'W') # Web
828             return HttpResponseRedirect('/job/%s/' % job.id)
829         job = get_object_or_404(Job, id=jobid)
830     
831     if not job.archive_time:
832         # careful not to modify other unschronized columns
833         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
834
835     if job.result:
836         # Error occured
837          return HttpResponseRedirect('/job/%s/' % job.id)
838     extension = os.path.splitext(job.friendly_filename)[-1]
839     return HttpResponseRedirect('/job_result/%s%s/%s' % (job.id, extension, job.friendly_filename))
840
841 @http_authenticate(auth, 'ais')
842 def users(request):
843     users = User.objects.order_by('name')
844     for user in users:
845         user.admin_ok = user.is_admin_by(request.user.id)
846     if request.REQUEST.has_key('showtree'):
847         local_users = {}
848         for user in users:
849             user.children = []
850             local_users[user.id] = user
851         for user in users:
852             if user.father_id == None:
853                 root = user
854             else:
855                 local_users[user.father_id].children.append(user)
856         assert root
857         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
858     else:
859         return render_to_response('users.html', {'users':users}, RequestContext(request))
860
861 phone_re = re.compile('^\\+.+')
862
863 class UserEditForm(forms.Form):
864     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
865         error_message ='Login must only contain letters, numbers and underscores')
866     name = forms.CharField(max_length=50)
867     email = forms.EmailField()
868     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
869         error_message ='Phones must start with a \'+\'')
870     def __init__(self, *args, **kargs):
871         forms.Form.__init__(self, *args, **kargs)
872         self.old_login = kargs['initial']['login']
873     def clean_login(self):
874         new_login = self.cleaned_data['login']
875         if new_login != self.old_login:
876             if User.objects.filter(login=new_login).count():
877                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
878             if new_login == u'add':
879                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
880         return new_login
881
882 @http_authenticate(auth, 'ais')
883 def user_detail(request, login):
884     user = get_object_or_404(User, login=login)
885     user.admin_ok = user.is_admin_by(request.user.id)
886     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
887
888 @http_authenticate(auth, 'ais')
889 def user_edit(request, login):
890     initial = {}
891     if login:
892         user = get_object_or_404(User, login=login)
893         if not user.is_admin_by(request.user.id):
894             return HttpResponseForbidden('403 Forbidden')
895     else:
896         user = User()
897         user.father_id = request.user.id;
898     initial['login'] = user.login
899     initial['name'] = user.name
900     initial['email'] = user.email
901     initial['phone'] = user.phone
902     if request.method == 'POST':
903         form = UserEditForm(request.POST, initial=initial)
904         if form.is_valid():
905             user.login = form.cleaned_data['login']
906             user.name = form.cleaned_data['name']
907             user.email = form.cleaned_data['email']
908             user.phone = form.cleaned_data['phone']
909             user.save()
910             user.check_sandbox_access(request.user)
911             return HttpResponseRedirect('/user/')
912     else: # GET
913         form = UserEditForm(initial=initial)
914
915     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
916
917
918 class ChangePasswordForm(forms.Form):
919     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
920     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
921
922     def clean_generic_password(self, field_name):
923         password = self.cleaned_data[field_name]
924         try:
925             crack.FascistCheck(password)
926         except ValueError, err:
927             raise forms.ValidationError(err.message)
928         return password
929
930     def clean_new_password(self):
931         return self.clean_generic_password('new_password')
932
933     def clean_new_password_check(self):
934         return self.clean_generic_password('new_password_check')
935
936     def clean(self):
937         cleaned_data = self.cleaned_data
938         pass1 = cleaned_data.get('new_password')
939         pass2 = cleaned_data.get('new_password_check')
940         if pass1 != pass2 and pass2:
941             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
942             del cleaned_data['new_password_check'] # FIXME
943         return cleaned_data
944
945
946 @http_authenticate(auth, 'ais')
947 def user_change_password(request, login):
948     user = get_object_or_404(User, login=login)
949     if not user.is_admin_by(request.user.id):
950         return HttpResponseForbidden('403 Forbidden')
951     if request.method == 'POST':
952         form = ChangePasswordForm(request.POST)
953         if form.is_valid():
954             user.set_password(form.cleaned_data['new_password'])
955             user.save()
956             return HttpResponseRedirect('/user/')
957     else: # GET
958         form = ChangePasswordForm()
959     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
960
961
962 @http_authenticate(auth, 'ais')
963 def user_delete(request, login):
964     user = get_object_or_404(User, login=login)
965     if not user.is_admin_by(request.user.id):
966         return HttpResponseForbidden('403 Forbidden')
967     if request.REQUEST.get('confirm', None):
968         user.delete()
969         return HttpResponseRedirect('/user/')
970     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
971
972
973 def logout(request):
974     # TODO
975     return HttpResponse('Not implemented')
976     #response = render_to_response('logout.html', {}, RequestContext(request))
977     #return response
978
979 periods = ({
980     'name_tiny': '2h',
981     'name_long': '2 hours',
982     'seconds': 2*60*60
983     }, {
984     'name_tiny': '6h',
985     'name_long': '6 hours',
986     'seconds': 6*60*60,
987     'default': True,
988     }, {
989     'name_tiny': '2d',
990     'name_long': '2 days',
991     'seconds': 2*24*60*60
992     }, {
993     'name_tiny': '14d',
994     'name_long': '2 weeks',
995     'seconds': 14*24*60*60
996     }, {
997     'name_tiny': '90d',
998     'name_long': '3 monthes',
999     'seconds': 90*24*60*60
1000     }, {
1001     'name_tiny': '180d',
1002     'name_long': '6 monthes',
1003     'seconds': 180*24*60*60
1004     })
1005         
1006 class StatsSelectorForm(forms.Form):
1007     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
1008     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
1009     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
1010
1011 @http_authenticate(auth, 'ais')
1012 def sources_index(request):
1013     ACTIVE_MINUTES = 5
1014     peers_config = peers_get_config()
1015     peers_display = []
1016     for id4, peer in peers_config.iteritems():
1017         peer['id4'] = id4
1018         peer['id2'] = id4[2:]
1019         peer['active'] = is_id4_active(id4, 60*ACTIVE_MINUTES)
1020         peers_display.append(peer)
1021         
1022     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1023
1024     form = StatsSelectorForm()
1025
1026     response = render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': ACTIVE_MINUTES, 'form': form}, RequestContext(request))
1027     response['Refresh'] = 60*ACTIVE_MINUTES
1028     return response
1029
1030
1031 @http_authenticate(auth, 'ais')
1032 def sources_stats(request):
1033     filter_peers = request.REQUEST.get('peers', None)
1034     if filter_peers:
1035         filter_peers = filter_peers.split(u',')
1036
1037     peers_config = peers_get_config()
1038     peers_display = []
1039
1040     for id4, peer in peers_config.iteritems():
1041         if filter_peers:
1042             if unicode(id4) not in filter_peers:
1043                 continue
1044         peer['id4'] = id4
1045         peers_display.append(peer)
1046
1047     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1048
1049     filter_types = request.REQUEST.get('types', None)
1050     if filter_types:
1051         filter_types = filter_types.split(u',')
1052     else:
1053         filter_types = [ 'bytes', 'counts' ]
1054     logging.error('filter_types=%s', filter_types)
1055
1056     filter_periods = request.REQUEST.get('periods', None)
1057     if filter_periods:
1058         display_periods = []
1059         for period_name in filter_periods.split(u','):
1060             for period in periods:
1061                 if period['name_tiny'] == period_name:
1062                     display_periods.append(period)
1063     else:
1064         display_periods = periods
1065     #logging.error('display_periods=%s', display_periods)
1066
1067
1068     now = int(get_timestamp())
1069     for config in peers_display:
1070         id4 = config['id4']
1071         for period in periods:
1072             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
1073                 '--lazy', \
1074                 '-l', '0', \
1075                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
1076                 '--start', '%d' % (now - period['seconds']), \
1077                 '--end', '%d' % now, \
1078                 '--vertical-label', 'bps', \
1079                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1080                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1081                 'CDEF:bits=bytes,8,*', \
1082                 'CDEF:rawbits=rawbytes,8,*', \
1083                 'LINE:bits#00FF00:IP payload', \
1084                 'LINE:rawbits#FF0000:IP with headers'
1085             rrdtool.graph(*args)
1086             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
1087                 '--lazy', \
1088                 '-l', '0', \
1089                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
1090                 '--start', '%d' % (now-period['seconds']), \
1091                 '--end', '%d' % now, \
1092                 '--vertical-label', 'Hz', \
1093                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1094                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1095                 'LINE:packets#FF0000:input packets', \
1096                 'LINE:lines#00FF00:AIVDM lines'
1097             rrdtool.graph(*args)
1098     return render_to_response('sources.html', {'sources':peers_display, 'show_bytes': 'bytes' in filter_types,  'show_counts': 'counts' in filter_types, 'periods': display_periods}, RequestContext(request))
1099
1100
1101 @http_authenticate(auth, 'ais')
1102 def news(request, page):
1103     NEWS_PER_PAGE = 5
1104     if page:
1105         page = int(page)
1106     else:
1107         page = 1
1108     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) // NEWS_PER_PAGE)
1109     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
1110     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
1111
1112 @http_authenticate(auth, 'ais')
1113 def news_atom(request):
1114     from django.db import connection
1115
1116     news = News.objects.order_by('-created')
1117
1118     cursor = connection.cursor()
1119     cursor.execute("SELECT MAX(updated) FROM news")
1120     row = cursor.fetchone()
1121     last_update = row[0]
1122
1123     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')