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