43e532c760a1c4b8b2447d724100d553036e26fd
[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, 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     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             command += u' ' + strmmsi
634
635             job = Job()
636             job.queue_time = datetime.utcnow()
637             job.friendly_filename = u'%s.%s' % (strmmsi, extension)
638             job.user = request.user
639             job.command = command
640             job.save()
641             if not jobrunner.wakeup_daemon():
642                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
643             return HttpResponseRedirect('/job/%s/download' % job.id)
644     else: # GET
645         form = HistoryForm(initial=initial)
646     strmmsi = strmmsi.encode('utf-8')
647     nmea = Nmea.new_from_lastinfo(strmmsi)
648     return render_to_response('vessel_history.html', {'nmea': nmea, 'form':form}, RequestContext(request))
649
650
651 @http_authenticate(auth, 'ais')
652 def fleets(request):
653     fleetusers = request.user.fleetuser_set.order_by('fleet')
654     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
655
656
657 @http_authenticate(auth, 'ais')
658 def fleet(request, fleetname):
659     fleet = get_object_or_404(Fleet, name=fleetname)
660     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
661         return HttpResponseForbidden('<h1>Forbidden</h1>')
662     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
663
664
665 class FleetEditForm(forms.Form):
666     name = forms.CharField(max_length=50)
667     description = forms.CharField(widget=forms.Textarea)
668
669     def clean_name(self):
670         name = self.cleaned_data['name']
671         if name == u'add':
672             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
673         if name != self.initial.get('name', None):
674             if Fleet.objects.filter(name=name).count():
675                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
676         return remove_decoration(name).replace(u' ', u'_')
677         
678
679 @http_authenticate(auth, 'ais')
680 def fleet_edit(request, fleetname):
681     initial = {}
682     if fleetname is not None:
683         fleet = get_object_or_404(Fleet, name=fleetname)
684         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
685             return HttpResponseForbidden('<h1>Forbidden</h1>')
686
687         initial['name'] = fleet.name
688         initial['description'] = fleet.description
689     else:
690         fleet = Fleet()
691
692     if request.method == 'POST':
693         form = FleetEditForm(request.POST, initial=initial)
694         if form.is_valid():
695             fleet.name = form.cleaned_data['name']
696             fleet.description = form.cleaned_data['description']
697             fleet.save()
698             if not fleetname: # new one
699                 fu = FleetUser()
700                 fu.fleet = fleet
701                 fu.user = request.user
702                 fu.save()
703             request.user.info('Fleet updated')
704             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
705     else: # GET
706         form = FleetEditForm(initial=initial)
707     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
708
709
710 @http_authenticate(auth, 'ais')
711 def fleet_vessels(request, fleetname):
712     fleet = get_object_or_404(Fleet, name=fleetname)
713     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
714         return HttpResponseForbidden('<h1>Forbidden</h1>')
715     vessels = fleet.vessel.all()
716     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
717
718
719 @http_authenticate(auth, 'ais')
720 def fleet_vessel_add(request, fleetname):
721     fleet = get_object_or_404(Fleet, name=fleetname)
722     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
723         return HttpResponseForbidden('<h1>Forbidden</h1>')
724     strmmsi = request.REQUEST['mmsi']
725     mmsi = strmmsi_to_mmsi(strmmsi)
726     try:
727         vessel = Vessel.objects.get(pk=mmsi)
728     except Vessel.DoesNotExist:
729         request.user.error('No such vessel')
730     else:
731         try:
732             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
733         except FleetVessel.DoesNotExist:
734             FleetVessel(fleet=fleet, vessel=vessel).save()
735             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
736         else:
737             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
738     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
739
740
741 class FleetAddVessel(forms.Form):
742     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
743     #name = forms.CharField(max_length=20, required=False)
744     #imo = forms.IntegerField(required=False)
745     #callsign = forms.CharField(max_length=7, required=False)
746     #destination = forms.CharField(max_length=20, required=False)
747     def clean(self):
748         cleaned_data = self.cleaned_data
749         for value in cleaned_data.values():
750             if value:
751                 return cleaned_data
752         raise forms.ValidationError("You must enter at least one criteria")
753
754 @http_authenticate(auth, 'ais')
755 def fleet_vessel_add2(request, fleetname):
756     fleet = get_object_or_404(Fleet, name=fleetname)
757     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
758         return HttpResponseForbidden('<h1>Forbidden</h1>')
759     if request.method == 'POST' or request.META['QUERY_STRING']:
760         form = FleetAddVessel(request.REQUEST)
761         if form.is_valid():
762             data = form.cleaned_data
763             result = []
764             a_strmmsi = request.REQUEST['mmsi']
765             if a_strmmsi:
766                 for strmmsi in a_strmmsi.split('\n'):
767                     strmmsi = strmmsi.strip('\r')
768                     if not strmmsi:
769                         continue
770                     try:
771                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
772                     except AssertionError:
773                         result.append('Invalid mmsi %s' % strmmsi)
774                         continue
775                     try:
776                         vessel = Vessel.objects.get(pk=sqlmmsi)
777                     except Vessel.DoesNotExist:
778                         result.append('No vessel with MMSI '+strmmsi)
779                         continue
780                     try:
781                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
782                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
783                     except FleetVessel.DoesNotExist:
784                         FleetVessel(fleet=fleet, vessel=vessel).save()
785                         result.append('Vessel with MMSI %s added' % strmmsi)
786
787             return HttpResponse('<br>'.join(result))
788     else: # GET
789         form = FleetAddVessel()
790
791     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
792
793
794 @http_authenticate(auth, 'ais')
795 def fleet_users(request, fleetname):
796     fleet = get_object_or_404(Fleet, name=fleetname)
797     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
798         return HttpResponseForbidden('<h1>Forbidden</h1>')
799
800     if request.method == 'POST' or request.META['QUERY_STRING']:
801         action = request.REQUEST['action']
802         userlogin = request.REQUEST['user']
803         try:
804             user = User.objects.get(login=userlogin)
805         except User.DoesNotExist:
806             request.user.error(u'User %s does not exist.' % userlogin)
807         else:
808             if action == u'add':
809                 try:
810                     fu = FleetUser.objects.get(fleet=fleet, user=user)
811                     request.user.error(u'User %s already has access.' % user.login)
812                 except FleetUser.DoesNotExist:
813                     FleetUser(fleet=fleet, user=user).save()
814                     #TODO log
815                     request.user.info(u'Granted access to user %s.' % user.login)
816             elif action == u'revoke':
817                 try:
818                     fu = FleetUser.objects.get(fleet=fleet, user=user)
819                     fu.delete()
820                     #TODO log
821                     request.user.info(u'Revoked access to user %s.' % user.login)
822                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
823                         fleet.delete()
824                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
825                         return HttpResponseRedirect('/fleet/')
826                 except FleetUser.DoesNotExist:
827                     request.user.error(u'User %s didn\'t have access.' % user.login)
828             else:
829                 request.user.error(u'Unknown action %s' % action)
830
831     fleetusers = fleet.fleetuser_set.order_by('user__name')
832     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
833     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
834
835
836 @http_authenticate(auth, 'ais')
837 def fleet_lastpos(request, fleetname):
838     fleet = get_object_or_404(Fleet, name=fleetname)
839     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
840         return HttpResponseForbidden('<h1>Forbidden</h1>')
841     display_options = 0
842     if request.user.flag_allowhidden:
843         display_options = KML_DISPLAYOPT_SHOWHIDDEN
844     fleet_uset = load_fleet_to_uset(fleet.id)
845     value = kml_to_kmz(format_fleet_lastpos(fleet_uset, document_name=fleetname+' fleet', display_options=display_options).encode('utf-8'))
846     response = HttpResponse(value, mimetype="application/vnd.google-earth.kmz")
847     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
848     return response
849
850 @http_authenticate(auth, 'ais')
851 def fleet_history(request, fleetname):
852     fleet = get_object_or_404(Fleet, name=fleetname)
853     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
854         return HttpResponseForbidden('<h1>Forbidden</h1>')
855     initial = {}
856     if request.method == 'POST':
857         form = HistoryForm(request.POST, initial=initial)
858         if form.is_valid():
859             command, extension = form.get_cmdext()
860
861             command += u' @' + fleetname
862
863             job = Job()
864             job.queue_time = datetime.utcnow()
865             job.friendly_filename = u'%s.%s' % (fleetname, extension)
866             job.user = request.user
867             job.command = command
868             job.save()
869             if not jobrunner.wakeup_daemon():
870                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
871             return HttpResponseRedirect('/job/%s/download' % job.id)
872     else: # GET
873         form = HistoryForm(initial=initial)
874     return render_to_response('fleet_history.html', {'fleet': fleet, 'form':form}, RequestContext(request))
875
876
877 @http_authenticate(auth, 'ais')
878 def jobs_index(request):
879     show_archive = request.REQUEST.has_key('archive')
880     if show_archive:
881         jobs = request.user.job_set.all()
882     else:
883         jobs = request.user.job_set.filter(archive_time__isnull=True)
884     
885     response = render_to_response('jobs.html', {'jobs': jobs, 'queue_size': Job.queue_size(), 'archive': show_archive }, RequestContext(request))
886     response['Refresh'] = 15
887     return response
888
889 @http_authenticate(auth, 'ais')
890 def job_detail(request, jobid):
891     job = get_object_or_404(Job, id=jobid)
892     if job.user != request.user:
893         return HttpResponseForbidden('403 Forbidden')
894     response = render_to_response('job.html', {'job': job, 'queue_size': Job.queue_size()}, RequestContext(request))
895     if not job.finish_time:
896         response['Refresh'] = 5
897     elif not job.archive_time:
898         # finished but not archived:
899         response['Refresh'] = '0;url=https://' + request.get_host() + '/job/%s/download' % job.id
900         # careful not to modify other unschronized columns
901         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
902     return response
903
904 @http_authenticate(auth, 'ais')
905 def job_get(request, jobid):
906     job = get_object_or_404(Job, id=jobid)
907     if job.user != request.user:
908         return HttpResponseForbidden('403 Forbidden')
909     total_wait = 0
910     while not job.finish_time:
911         sleep(1)
912         total_wait += 1
913         if total_wait > 15:
914             request.user.info('Your query is slow. Please be patient.')
915             if not job.notify:
916                 # careful not to modify other unschronized columns
917                 Job.objects.filter(id=jobid).update(notify = 'W') # Web
918             return HttpResponseRedirect('/job/%s/' % job.id)
919         job = get_object_or_404(Job, id=jobid)
920     
921     if not job.archive_time:
922         # careful not to modify other unschronized columns
923         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
924
925     if job.result:
926         # Error occured
927          return HttpResponseRedirect('/job/%s/' % job.id)
928     extension = os.path.splitext(job.friendly_filename)[-1]
929     return HttpResponseRedirect('/job_result/%s%s/%s' % (job.id, extension, job.friendly_filename))
930
931
932 @http_authenticate(auth, 'ais')
933 def job_log(request, jobid):
934     job = get_object_or_404(Job, id=jobid)
935     if job.user != request.user:
936         return HttpResponseForbidden('403 Forbidden')
937     log = u''
938     try:
939         log = file(jobrunner.RESULT_DIR+unicode(jobid)+'.log').read()
940     except IOError, err:
941         if err.errno != 2: # No such file
942             raise
943     return render_to_response('job_log.html', {'job': job, 'log': log}, RequestContext(request))
944
945
946 @http_authenticate(auth, 'ais')
947 def users(request):
948     users = User.objects.order_by('name')
949     for user in users:
950         user.admin_ok = user.is_admin_by(request.user.id)
951     if request.REQUEST.has_key('showtree'):
952         local_users = {}
953         for user in users:
954             user.children = []
955             local_users[user.id] = user
956         for user in users:
957             if user.father_id == None:
958                 root = user
959             else:
960                 local_users[user.father_id].children.append(user)
961         assert root
962         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
963     else:
964         return render_to_response('users.html', {'users':users}, RequestContext(request))
965
966 phone_re = re.compile('^\\+.+')
967
968 class UserEditForm(forms.Form):
969     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
970         error_message ='Login must only contain letters, numbers and underscores')
971     name = forms.CharField(max_length=50)
972     email = forms.EmailField()
973     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
974         error_message ='Phones must start with a \'+\'')
975     def __init__(self, show_flag_showhidden, *args, **kargs):
976         forms.Form.__init__(self, *args, **kargs)
977         self.old_login = kargs['initial']['login']
978         if show_flag_showhidden:
979             self.fields['show_hidden_ships'] = forms.BooleanField(required=False)
980
981     def clean_login(self):
982         new_login = self.cleaned_data['login']
983         if new_login != self.old_login:
984             if User.objects.filter(login=new_login).count():
985                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
986             if new_login == u'add':
987                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
988         return new_login
989
990 @http_authenticate(auth, 'ais')
991 def user_detail(request, login):
992     user = get_object_or_404(User, login=login)
993     user.admin_ok = user.is_admin_by(request.user.id)
994     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
995
996 @http_authenticate(auth, 'ais')
997 def user_edit(request, login):
998     initial = {}
999     if login:
1000         user = get_object_or_404(User, login=login)
1001         if not user.is_admin_by(request.user.id):
1002             return HttpResponseForbidden('403 Forbidden')
1003     else:
1004         user = User()
1005         user.father_id = request.user.id;
1006     initial['login'] = user.login
1007     initial['name'] = user.name
1008     initial['email'] = user.email
1009     initial['phone'] = user.phone
1010     initial['show_hidden_ships'] = user.flag_allowhidden
1011     if request.method == 'POST':
1012         form = UserEditForm(request.user.flag_allowhidden, request.POST, initial=initial)
1013         if form.is_valid():
1014             user.login = form.cleaned_data['login']
1015             user.name = form.cleaned_data['name']
1016             user.email = form.cleaned_data['email']
1017             user.phone = form.cleaned_data['phone']
1018             if request.user.flag_allowhidden:
1019                 user.flag_allowhidden = form.cleaned_data['show_hidden_ships']
1020             user.save()
1021             user.check_sandbox_access(request.user)
1022             return HttpResponseRedirect('/user/')
1023     else: # GET
1024         form = UserEditForm(request.user.flag_allowhidden, initial=initial)
1025
1026     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
1027
1028
1029 class ChangePasswordForm(forms.Form):
1030     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
1031     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
1032
1033     def clean_generic_password(self, field_name):
1034         password = self.cleaned_data[field_name]
1035         try:
1036             crack.FascistCheck(password)
1037         except ValueError, err:
1038             raise forms.ValidationError(err.message)
1039         return password
1040
1041     def clean_new_password(self):
1042         return self.clean_generic_password('new_password')
1043
1044     def clean_new_password_check(self):
1045         return self.clean_generic_password('new_password_check')
1046
1047     def clean(self):
1048         cleaned_data = self.cleaned_data
1049         pass1 = cleaned_data.get('new_password')
1050         pass2 = cleaned_data.get('new_password_check')
1051         if pass1 != pass2 and pass2:
1052             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
1053             del cleaned_data['new_password_check'] # FIXME
1054         return cleaned_data
1055
1056
1057 @http_authenticate(auth, 'ais')
1058 def user_change_password(request, login):
1059     user = get_object_or_404(User, login=login)
1060     if not user.is_admin_by(request.user.id):
1061         return HttpResponseForbidden('403 Forbidden')
1062     if request.method == 'POST':
1063         form = ChangePasswordForm(request.POST)
1064         if form.is_valid():
1065             user.set_password(form.cleaned_data['new_password'])
1066             user.save()
1067             return HttpResponseRedirect('/user/')
1068     else: # GET
1069         form = ChangePasswordForm()
1070     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
1071
1072
1073 @http_authenticate(auth, 'ais')
1074 def user_delete(request, login):
1075     user = get_object_or_404(User, login=login)
1076     if not user.is_admin_by(request.user.id):
1077         return HttpResponseForbidden('403 Forbidden')
1078     if request.REQUEST.get('confirm', None):
1079         user.delete()
1080         return HttpResponseRedirect('/user/')
1081     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
1082
1083
1084 def logout(request):
1085     # TODO
1086     return HttpResponse('Not implemented')
1087     #response = render_to_response('logout.html', {}, RequestContext(request))
1088     #return response
1089
1090 periods = ({
1091     'name_tiny': '2h',
1092     'name_long': '2 hours',
1093     'seconds': 2*60*60
1094     }, {
1095     'name_tiny': '6h',
1096     'name_long': '6 hours',
1097     'seconds': 6*60*60,
1098     'default': True,
1099     }, {
1100     'name_tiny': '2d',
1101     'name_long': '2 days',
1102     'seconds': 2*24*60*60
1103     }, {
1104     'name_tiny': '14d',
1105     'name_long': '2 weeks',
1106     'seconds': 14*24*60*60
1107     }, {
1108     'name_tiny': '90d',
1109     'name_long': '3 monthes',
1110     'seconds': 90*24*60*60
1111     }, {
1112     'name_tiny': '180d',
1113     'name_long': '6 monthes',
1114     'seconds': 180*24*60*60
1115     })
1116         
1117 class StatsSelectorForm(forms.Form):
1118     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
1119     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
1120     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
1121
1122 @http_authenticate(auth, 'ais')
1123 def sources_index(request):
1124     ACTIVE_MINUTES = 5
1125     peers_config = peers_get_config()
1126     peers_display = []
1127     for id4, peer in peers_config.iteritems():
1128         peer['id4'] = id4
1129         peer['id2'] = id4[2:]
1130         peer['active'] = is_id4_active(id4, 60*ACTIVE_MINUTES)
1131         peers_display.append(peer)
1132         
1133     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1134
1135     form = StatsSelectorForm()
1136
1137     response = render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': ACTIVE_MINUTES, 'form': form}, RequestContext(request))
1138     response['Refresh'] = 60*ACTIVE_MINUTES
1139     return response
1140
1141
1142 @http_authenticate(auth, 'ais')
1143 def sources_stats(request):
1144     filter_peers = request.REQUEST.get('peers', None)
1145     if filter_peers:
1146         filter_peers = filter_peers.split(u',')
1147
1148     peers_config = peers_get_config()
1149     peers_display = []
1150
1151     for id4, peer in peers_config.iteritems():
1152         if filter_peers:
1153             if unicode(id4) not in filter_peers:
1154                 continue
1155         peer['id4'] = id4
1156         peers_display.append(peer)
1157
1158     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1159
1160     filter_types = request.REQUEST.get('types', None)
1161     if filter_types:
1162         filter_types = filter_types.split(u',')
1163     else:
1164         filter_types = [ 'bytes', 'counts' ]
1165     logging.error('filter_types=%s', filter_types)
1166
1167     filter_periods = request.REQUEST.get('periods', None)
1168     if filter_periods:
1169         display_periods = []
1170         for period_name in filter_periods.split(u','):
1171             for period in periods:
1172                 if period['name_tiny'] == period_name:
1173                     display_periods.append(period)
1174     else:
1175         display_periods = periods
1176     #logging.error('display_periods=%s', display_periods)
1177
1178
1179     now = int(get_timestamp())
1180     for config in peers_display:
1181         id4 = config['id4']
1182         for period in periods:
1183             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
1184                 '--lazy', \
1185                 '-l', '0', \
1186                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
1187                 '--start', '%d' % (now - period['seconds']), \
1188                 '--end', '%d' % now, \
1189                 '--vertical-label', 'bps', \
1190                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1191                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1192                 'CDEF:bits=bytes,8,*', \
1193                 'CDEF:rawbits=rawbytes,8,*', \
1194                 'LINE:bits#00FF00:IP payload', \
1195                 'LINE:rawbits#FF0000:IP with headers'
1196             rrdtool.graph(*args)
1197             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
1198                 '--lazy', \
1199                 '-l', '0', \
1200                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
1201                 '--start', '%d' % (now-period['seconds']), \
1202                 '--end', '%d' % now, \
1203                 '--vertical-label', 'Hz', \
1204                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1205                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1206                 'LINE:packets#FF0000:input packets', \
1207                 'LINE:lines#00FF00:AIVDM lines'
1208             rrdtool.graph(*args)
1209     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))
1210
1211
1212 @http_authenticate(auth, 'ais')
1213 def news(request, page):
1214     NEWS_PER_PAGE = 5
1215     if page:
1216         page = int(page)
1217     else:
1218         page = 1
1219     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) // NEWS_PER_PAGE)
1220     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
1221     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
1222
1223 @http_authenticate(auth, 'ais')
1224 def news_atom(request):
1225     from django.db import connection
1226
1227     news = News.objects.order_by('-created')
1228
1229     cursor = connection.cursor()
1230     cursor.execute("SELECT MAX(updated) FROM news")
1231     row = cursor.fetchone()
1232     last_update = row[0]
1233
1234     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')