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