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