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