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