Fixed vessel search with empty mmsi
[ais.git] / bin / djais / views.py
1 # -*- coding: utf-8 -*-
2
3 #from __future__ import division
4
5 import os
6 from datetime import *
7 import re
8 from time import time as get_timestamp
9 import logging
10 import crack
11 import struct
12 import operator
13 import rrdtool
14 import csv
15 from StringIO import StringIO
16 from django.http import *
17 from django.template import loader, RequestContext
18 from django import forms
19 from django.shortcuts import render_to_response, get_object_or_404
20 from django.db import IntegrityError
21
22 from decoratedstr import remove_decoration
23
24 from ais.djais.basicauth import http_authenticate
25 from ais.djais.models import *
26 from ais.show_targets_ships import *
27 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
28 from ais.ntools import datetime_to_timestamp, clean_ais_charset
29 from ais.inputs.common import is_id4_active
30 from ais.inputs.stats import STATS_DIR
31 from ais.inputs.config import peers_get_config
32
33 def auth(username, raw_password):
34     try:
35         user = User.objects.get(login=username)
36     except User.DoesNotExist:
37         return None
38     if not user.check_password(raw_password):
39         return None
40     user.update_access_datetime()
41     return user
42
43
44 @http_authenticate(auth, 'ais')
45 def index(request):
46     news = News.objects.order_by('-created')[:5]
47     return render_to_response('index.html', {'news':news}, RequestContext(request))
48
49
50 class VesselSearchForm(forms.Form):
51     def country_choices():
52         choices = {}
53         for mid, countryname in COUNTRIES_MID.iteritems():
54             if choices.has_key(countryname):
55                 choices[countryname] += u','+unicode(mid)
56             else:
57                 choices[countryname] = unicode(mid)
58         choices = [ (countryname, mids) for mids, countryname in choices.iteritems() ]
59         choices = sorted(choices, key=operator.itemgetter(1))
60         return [(u'', u'Any')] + choices
61
62     mmsi = forms.CharField(max_length=9, required=False)
63     name = forms.CharField(max_length=20, required=False)
64     imo = forms.IntegerField(required=False)
65     callsign = forms.CharField(max_length=7, required=False)
66     flag = forms.ChoiceField(choices=country_choices(), required=False)
67     destination = forms.CharField(max_length=20, required=False)
68
69
70     def clean(self):
71         cleaned_data = self.cleaned_data
72         for value in cleaned_data.values():
73             if value:
74                 return cleaned_data
75         raise forms.ValidationError("You must enter at least one criteria")
76
77     def clean_mmsi(self):
78         mmsi = self.cleaned_data['mmsi']
79         if mmsi:
80             try:
81                 mmsi = strmmsi_to_mmsi(mmsi)
82             except AssertionError:
83                 raise forms.ValidationError("Invalid MMSI")
84         return mmsi
85
86
87 @http_authenticate(auth, 'ais')
88 def vessel_search(request):
89     if request.method == 'POST' or request.META['QUERY_STRING']:
90         form = VesselSearchForm(request.REQUEST)
91         if form.is_valid():
92             data = form.cleaned_data
93             vessels = Vessel.objects
94             if data['mmsi']:
95                 vessels = vessels.filter(mmsi=data['mmsi'])
96             if data['name']:
97                 vessels = vessels.filter(name__contains=data['name'].upper())
98             if data['imo']:
99                 vessels = vessels.filter(imo=data['imo'])
100             if data['callsign']:
101                 vessels = vessels.filter(callsign__contains=data['callsign'].upper())
102             if data['destination']:
103                 vessels = vessels.filter(destination__contains=data['destination'].upper())
104             if data['flag']:
105                 vessels = vessels.extra(where=['mmsi/1000000 IN (%s) ' % data['flag']])
106             return render_to_response('vessels.html', {'vessels': vessels}, RequestContext(request))
107     else: # GET
108         form = VesselSearchForm()
109
110     return render_to_response('vessel_index.html', {'form': form}, RequestContext(request))
111
112 @http_authenticate(auth, 'ais')
113 def vessel(request, strmmsi):
114     mmsi = strmmsi_to_mmsi(strmmsi)
115     vessel = get_object_or_404(Vessel, pk=mmsi)
116     nmea = Nmea.new_from_lastinfo(strmmsi)
117     #if not nmea.timestamp_1 and not nmea.timestamp_5:
118     #    raise Http404
119     return render_to_response('vessel.html', {'nmea': nmea}, RequestContext(request))
120
121
122 class VesselManualInputForm(forms.Form):
123     timestamp = forms.DateTimeField(label=u'When', help_text=u'When was the observation made in GMT. Use YYYY-MM-DD HH:MM:SS format')
124     imo = forms.IntegerField(required=False, min_value=1000000, max_value=9999999)
125     name = forms.CharField(max_length=20, required=False)
126     callsign = forms.CharField(max_length=7, required=False)
127     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)
128     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)
129     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)
130     latitude = forms.CharField(required=False)
131     longitude = forms.CharField(required=False)
132     cog = forms.FloatField(label='Course', help_text='Over ground', required=False, min_value=0.0, max_value=359.9)
133     heading = forms.IntegerField(required=False, min_value=0, max_value=359)
134
135     @staticmethod
136     def _clean_ais_charset(ustr):
137         ustr = remove_decoration(ustr) # benign cleaning, but can increase size (œ->oe)
138         ustr = ustr.upper() # benign cleaning
139         str = clean_ais_charset(ustr.encode('ascii', 'replace'))
140         if unicode(str) != ustr:
141             raise forms.ValidationError('Invalid character: AIS alphabet is @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^- !"#$%&\'()*+,-./0123456789:;<=>?')
142         return str
143
144     def clean_timestamp(self):
145         data = self.cleaned_data['timestamp']
146         if data is None:
147             return None
148         if data < datetime.utcnow() - timedelta(365):
149             raise forms.ValidationError('Date is too much is the past.')
150         if data > datetime.utcnow():
151             raise forms.ValidationError('Date is be in the future. This form is only for observed results.')
152         return datetime_to_timestamp(data)
153
154     def clean_imo(self):
155         data = self.cleaned_data['imo']
156         if data is None:
157             return 0
158         return data
159
160     def clean_name(self):
161         name = self.cleaned_data['name']
162         if name is None:
163             return ''
164         name = VesselManualInputForm._clean_ais_charset(name)
165         if len(name)>20:
166             raise forms.ValidationError('Ensure this value has at most 20 characters (it has %s).' % len(name))
167         return name
168
169     def clean_callsign(self):
170         callsign = self.cleaned_data['callsign']
171         if callsign is None:
172             return ''
173         callsign = VesselManualInputForm._clean_ais_charset(callsign)
174         if len(callsign)>7:
175             raise forms.ValidationError('Ensure this value has at most 7 characters (it has %s).' % len(callsign))
176         return callsign
177
178     def clean_sog(self):
179         sog = self.cleaned_data['sog']
180         if sog is None:
181             return AIS_SOG_NOT_AVAILABLE
182         return int(sog*AIS_SOG_SCALE)
183
184     def clean_latitude(self):
185         data = self.cleaned_data['latitude']
186         data = data.replace(u"''", u'"') # commong mistake
187         data = data.replace(u' ', u'') # remove spaces
188         sides = u'SN'
189         if not data:
190             return AIS_LAT_NOT_AVAILABLE
191         tmp, side = data[:-1], data[-1]
192         if side == sides[0]:
193             side = -1
194         elif side == sides[1]:
195             side = 1
196         else:
197             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
198         spl = tmp.split(u'°')
199         if len(spl) == 1:
200             raise forms.ValidationError(u'You need to use the ° character.')
201         d, tmp = spl
202         try:
203             d = float(d)
204         except ValueError:
205             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
206         spl = tmp.split(u"'", 1)
207         if len(spl) == 1:
208             # no ' sign: ok only if there is nothing but the side after °
209             # we don't accept seconds if there is no minutes:
210             # It might be an entry mistake
211             tmp = spl[0]
212             if len(tmp) == 0:
213                 m = s = 0
214             else:
215                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
216         else:
217             m, tmp = spl
218             try:
219                 m = float(m)
220             except ValueError:
221                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
222             if len(tmp) == 0:
223                 s = 0
224             else:
225                 if tmp[-1] != '"':
226                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
227                 s = tmp[:-1]
228                 try:
229                     s = float(s)
230                 except ValueError:
231                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
232         data = side * ( d + m / 60 + s / 3600)
233
234         if data < -90 or data > 90:
235             raise forms.ValidationError(u'%s in not in -90..90 range' % data)
236         return int(data * AIS_LATLON_SCALE)
237
238     def clean_longitude(self):
239         data = self.cleaned_data['longitude']
240         data = data.replace(u"''", u'"') # commong mistake
241         data = data.replace(u' ', u'') # remove spaces
242         sides = u'WE'
243         if not data:
244             return AIS_LON_NOT_AVAILABLE
245         tmp, side = data[:-1], data[-1]
246         if side == sides[0]:
247             side = -1
248         elif side == sides[1]:
249             side = 1
250         else:
251             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
252         spl = tmp.split(u'°')
253         if len(spl) == 1:
254             raise forms.ValidationError(u'You need to use the ° character.')
255         d, tmp = spl
256         try:
257             d = float(d)
258         except ValueError:
259             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
260         spl = tmp.split(u"'", 1)
261         if len(spl) == 1:
262             # no ' sign: ok only if there is nothing but the side after °
263             # we don't accept seconds if there is no minutes:
264             # It might be an entry mistake
265             tmp = spl[0]
266             if len(tmp) == 0:
267                 m = s = 0
268             else:
269                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
270         else:
271             m, tmp = spl
272             try:
273                 m = float(m)
274             except ValueError:
275                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
276             if len(tmp) == 0:
277                 s = 0
278             else:
279                 if tmp[-1] != '"':
280                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
281                 s = tmp[:-1]
282                 try:
283                     s = float(s)
284                 except ValueError:
285                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
286         data = side * ( d + m / 60 + s / 3600)
287
288         if data < -180 or data > 180:
289             raise forms.ValidationError(u'%s in not in -180..180 range' % data)
290         return int(data * AIS_LATLON_SCALE)
291
292     def clean_cog(self):
293         data = self.cleaned_data['cog']
294         if data is None:
295             return AIS_COG_NOT_AVAILABLE
296         return int(data * AIS_COG_SCALE)
297     
298     def clean_heading(self):
299         #raise forms.ValidationError(u'clean_heading called')
300         data = self.cleaned_data['heading']
301         if data is None:
302             return AIS_NO_HEADING
303         return data
304
305     def clean(self):
306         cleaned_data = self.cleaned_data
307         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):
308             raise forms.ValidationError('It makes no sense to enter just a latitude or a longitude. Enter both or none.')
309         if cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE:
310             if cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) != AIS_STATUS_NOT_AVAILABLE:
311                 raise forms.ValidationError('It makes no sense to enter a status without coordinates. Please enter latitute and longitude too.')
312             if cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) != AIS_SOG_NOT_AVAILABLE:
313                 raise forms.ValidationError('It makes no sense to enter a speed without coordinates. Please enter latitute and longitude too.')
314             if cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) != AIS_COG_NOT_AVAILABLE:
315                 raise forms.ValidationError('It makes no sense to enter a course without coordinates. Please enter latitute and longitude too.')
316             if cleaned_data.get('heading', AIS_NO_HEADING) != AIS_NO_HEADING:
317                 raise forms.ValidationError('It makes no sense to enter a heading without coordinates. Please enter latitute and longitude too.')
318
319         if cleaned_data.get('timestamp', None) \
320         and cleaned_data.get('imo', 0) == 0 \
321         and cleaned_data.get('name', '') == '' \
322         and cleaned_data.get('callsign', '') == '' \
323         and cleaned_data.get('type', 0) == 0 \
324         and cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) == AIS_STATUS_NOT_AVAILABLE \
325         and cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) == AIS_SOG_NOT_AVAILABLE \
326         and cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE \
327         and cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE \
328         and cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) == AIS_COG_NOT_AVAILABLE \
329         and cleaned_data.get('heading', AIS_NO_HEADING) == AIS_NO_HEADING:
330             raise forms.ValidationError("You must enter some data, beside when.")
331         return cleaned_data
332
333 @http_authenticate(auth, 'ais')
334 def vessel_manual_input(request, strmmsi):
335     strmmsi = strmmsi.encode('utf-8')
336     nmea = Nmea.new_from_lastinfo(strmmsi)
337     if request.method == 'POST' or request.META['QUERY_STRING']:
338         form = VesselManualInputForm(request.REQUEST)
339         if form.is_valid():
340             data = form.cleaned_data
341             source = 'U' +  struct.pack('<I', request.user.id)[0:3]
342             result = u''
343             if data['imo'] != 0 \
344             or data['name'] != '' \
345             or data['callsign'] != '' \
346             or data['type'] != 0:
347                 toto = (strmmsi, data['timestamp'], data['imo'], data['name'], data['callsign'], data['type'], 0,0,0,0, 0,0,24,60, 0, '', source)
348                 result += 'UPDATING NMEA 5: '+repr(toto)+'<br>'
349                 add_nmea5_partial(*toto)
350             if data['status'] != AIS_STATUS_NOT_AVAILABLE \
351             or data['sog'] != AIS_SOG_NOT_AVAILABLE \
352             or data['latitude'] != AIS_LAT_NOT_AVAILABLE \
353             or data['longitude'] != AIS_LON_NOT_AVAILABLE \
354             or data['cog'] != AIS_COG_NOT_AVAILABLE \
355             or data['heading'] != AIS_NO_HEADING:
356                 
357                 toto = (strmmsi, data['timestamp'], data['status'], AIS_ROT_NOT_AVAILABLE, data['sog'], data['latitude'], data['longitude'], data['cog'], data['heading'], source)
358                 result += 'UPDATING NMEA 1: '+repr(toto)+'<br>'
359                 add_nmea1(*toto)
360             return HttpResponse('Not fully implemented: '+repr(data) + '<br>' + result)
361     else: # GET
362         form = VesselManualInputForm()
363     return render_to_response('vessel_manual_input.html', {'form': form, 'nmea': nmea}, RequestContext(request))
364
365
366 @http_authenticate(auth, 'ais')
367 def vessel_history(request, strmmsi, format=None):
368     """
369     That view is called from Google Earth, so that it must support GET method.  
370     """
371     ndays = request.REQUEST.get('ndays', None)
372     if ndays is not None:
373         try:
374             ndays = int(ndays)
375         except ValueError:
376             ndays = 90
377         period = ndays * 86400
378     else:
379         period = request.REQUEST.get('period', u'1')
380         try:
381             period = int(period)
382         except ValueError:
383             period = 1
384         period_type = request.REQUEST.get('period_type', u'86400')
385         try:
386             period_type = int(period_type)
387         except ValueError:
388             period_type = 86400
389
390     grain = request.REQUEST.get('grain', 1)
391     try:
392         grain = int(grain)
393     except ValueError:
394         grain = 1
395     grain_type = request.REQUEST.get('grain_type', 3600)
396     try:
397         grain_type = int(grain_type)
398     except ValueError:
399         grain_type = 3600
400
401     date_end = datetime.utcnow()
402     date_start = date_end - timedelta(0,period*period_type)
403     print date_start
404     nmea_iterator = NmeaFeeder(strmmsi, date_end, date_start, granularity=grain*grain_type)
405     
406     if format is None:
407         format = request.REQUEST.get('format', u'track')
408     if format == u'track':
409         value = kml_to_kmz(format_boat_track(nmea_iterator))
410         response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
411         response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
412         return response
413
414     elif format == u'animation':
415         value = kml_to_kmz(format_boat_intime(nmea_iterator))
416         response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
417         response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
418         return response
419
420     elif format == u'csv':
421         value = StringIO()
422         output = csv.writer(value)
423         output.writerow(Nmea.csv_headers)
424         for nmea in nmea_iterator:
425             output.writerow(nmea.get_dump_row())
426         response = HttpResponse(value.getvalue(), mimetype='text/csv; charset="UTF-8"')
427         response['Content-Disposition'] = 'attachment; filename=%s.csv' % strmmsi
428         return response
429     else:
430         request.user.error(u'Invalid archive format')
431         return HttpResponseRedirect('/vessel/%s/' % strmmsi)
432
433
434 @http_authenticate(auth, 'ais')
435 def fleets(request):
436     fleetusers = request.user.fleetuser_set.order_by('fleet')
437     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
438
439
440 @http_authenticate(auth, 'ais')
441 def fleet(request, fleetname):
442     fleet = get_object_or_404(Fleet, name=fleetname)
443     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
444         return HttpResponseForbidden('<h1>Forbidden</h1>')
445     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
446
447
448 class FleetEditForm(forms.Form):
449     name = forms.CharField(max_length=50)
450     description = forms.CharField(widget=forms.Textarea)
451
452     def clean_name(self):
453         name = self.cleaned_data['name']
454         if name == u'add':
455             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
456         if name != self.initial.get('name', None):
457             if Fleet.objects.filter(name=name).count():
458                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
459         return remove_decoration(name).replace(u' ', u'_')
460         
461
462 @http_authenticate(auth, 'ais')
463 def fleet_edit(request, fleetname):
464     initial = {}
465     if fleetname is not None:
466         fleet = get_object_or_404(Fleet, name=fleetname)
467         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
468             return HttpResponseForbidden('<h1>Forbidden</h1>')
469
470         initial['name'] = fleet.name
471         initial['description'] = fleet.description
472     else:
473         fleet = Fleet()
474
475     if request.method == 'POST':
476         form = FleetEditForm(request.POST, initial=initial)
477         if form.is_valid():
478             fleet.name = form.cleaned_data['name']
479             fleet.description = form.cleaned_data['description']
480             fleet.save()
481             if not fleetname: # new one
482                 fu = FleetUser()
483                 fu.fleet = fleet
484                 fu.user = request.user
485                 fu.save()
486             request.user.info('Fleet updated')
487             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
488     else: # GET
489         form = FleetEditForm(initial=initial)
490     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
491
492
493 @http_authenticate(auth, 'ais')
494 def fleet_vessels(request, fleetname):
495     fleet = get_object_or_404(Fleet, name=fleetname)
496     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
497         return HttpResponseForbidden('<h1>Forbidden</h1>')
498     vessels = fleet.vessel.all()
499     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
500
501
502 @http_authenticate(auth, 'ais')
503 def fleet_vessel_add(request, fleetname):
504     fleet = get_object_or_404(Fleet, name=fleetname)
505     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
506         return HttpResponseForbidden('<h1>Forbidden</h1>')
507     strmmsi = request.REQUEST['mmsi']
508     mmsi = strmmsi_to_mmsi(strmmsi)
509     try:
510         vessel = Vessel.objects.get(pk=mmsi)
511     except Vessel.DoesNotExist:
512         request.user.error('No such vessel')
513     else:
514         try:
515             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
516         except FleetVessel.DoesNotExist:
517             FleetVessel(fleet=fleet, vessel=vessel).save()
518             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
519         else:
520             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
521     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
522
523
524 class FleetAddVessel(forms.Form):
525     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
526     #name = forms.CharField(max_length=20, required=False)
527     #imo = forms.IntegerField(required=False)
528     #callsign = forms.CharField(max_length=7, required=False)
529     #destination = forms.CharField(max_length=20, required=False)
530     def clean(self):
531         cleaned_data = self.cleaned_data
532         for value in cleaned_data.values():
533             if value:
534                 return cleaned_data
535         raise forms.ValidationError("You must enter at least one criteria")
536
537 @http_authenticate(auth, 'ais')
538 def fleet_vessel_add2(request, fleetname):
539     fleet = get_object_or_404(Fleet, name=fleetname)
540     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
541         return HttpResponseForbidden('<h1>Forbidden</h1>')
542     if request.method == 'POST' or request.META['QUERY_STRING']:
543         form = FleetAddVessel(request.REQUEST)
544         if form.is_valid():
545             data = form.cleaned_data
546             result = []
547             a_strmmsi = request.REQUEST['mmsi']
548             if a_strmmsi:
549                 for strmmsi in a_strmmsi.split('\n'):
550                     strmmsi = strmmsi.strip('\r')
551                     if not strmmsi:
552                         continue
553                     try:
554                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
555                     except AssertionError:
556                         result.append('Invalid mmsi %s' % strmmsi)
557                         continue
558                     try:
559                         vessel = Vessel.objects.get(pk=sqlmmsi)
560                     except Vessel.DoesNotExist:
561                         result.append('No vessel with MMSI '+strmmsi)
562                         continue
563                     try:
564                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
565                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
566                     except FleetVessel.DoesNotExist:
567                         FleetVessel(fleet=fleet, vessel=vessel).save()
568                         result.append('Vessel with MMSI %s added' % strmmsi)
569
570             return HttpResponse('<br>'.join(result))
571     else: # GET
572         form = FleetAddVessel()
573
574     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
575
576
577 @http_authenticate(auth, 'ais')
578 def fleet_users(request, fleetname):
579     fleet = get_object_or_404(Fleet, name=fleetname)
580     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
581         return HttpResponseForbidden('<h1>Forbidden</h1>')
582
583     if request.method == 'POST' or request.META['QUERY_STRING']:
584         action = request.REQUEST['action']
585         userlogin = request.REQUEST['user']
586         try:
587             user = User.objects.get(login=userlogin)
588         except User.DoesNotExist:
589             request.user.error(u'User %s does not exist.' % userlogin)
590         else:
591             if action == u'add':
592                 try:
593                     fu = FleetUser.objects.get(fleet=fleet, user=user)
594                     request.user.error(u'User %s already has access.' % user.login)
595                 except FleetUser.DoesNotExist:
596                     FleetUser(fleet=fleet, user=user).save()
597                     #TODO log
598                     request.user.info(u'Granted access to user %s.' % user.login)
599             elif action == u'revoke':
600                 try:
601                     fu = FleetUser.objects.get(fleet=fleet, user=user)
602                     fu.delete()
603                     #TODO log
604                     request.user.info(u'Revoked access to user %s.' % user.login)
605                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
606                         fleet.delete()
607                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
608                         return HttpResponseRedirect('/fleet/')
609                 except FleetUser.DoesNotExist:
610                     request.user.error(u'User %s didn\'t have access.' % user.login)
611             else:
612                 request.user.error(u'Unknown action %s' % action)
613
614     fleetusers = fleet.fleetuser_set.all()
615     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
616     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
617
618
619 @http_authenticate(auth, 'ais')
620 def fleet_lastpos(request, fleetname):
621     fleet = get_object_or_404(Fleet, name=fleetname)
622     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
623         return HttpResponseForbidden('<h1>Forbidden</h1>')
624     fleet_uset = load_fleet_to_uset(fleet.id)
625     # = set([mmsi_to_strmmsi(vessel.mmsi) for vessel in fleet.vessel.all()])
626     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
627     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
628     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
629     return response
630
631
632 @http_authenticate(auth, 'ais')
633 def users(request):
634     users = User.objects.order_by('name')
635     for user in users:
636         user.admin_ok = user.is_admin_by(request.user.id)
637     if request.REQUEST.has_key('showtree'):
638         local_users = {}
639         for user in users:
640             user.children = []
641             local_users[user.id] = user
642         for user in users:
643             if user.father_id == None:
644                 root = user
645             else:
646                 local_users[user.father_id].children.append(user)
647         assert root
648         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
649     else:
650         return render_to_response('users.html', {'users':users}, RequestContext(request))
651
652 phone_re = re.compile('^\\+.+')
653
654 class UserEditForm(forms.Form):
655     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
656         error_message ='Login must only contain letters, numbers and underscores')
657     name = forms.CharField(max_length=50)
658     email = forms.EmailField()
659     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
660         error_message ='Phones must start with a \'+\'')
661     def __init__(self, *args, **kargs):
662         forms.Form.__init__(self, *args, **kargs)
663         self.old_login = kargs['initial']['login']
664     def clean_login(self):
665         new_login = self.cleaned_data['login']
666         if new_login != self.old_login:
667             if User.objects.filter(login=new_login).count():
668                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
669             if new_login == u'add':
670                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
671         return new_login
672
673 @http_authenticate(auth, 'ais')
674 def user_detail(request, login):
675     user = get_object_or_404(User, login=login)
676     user.admin_ok = user.is_admin_by(request.user.id)
677     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
678
679 @http_authenticate(auth, 'ais')
680 def user_edit(request, login):
681     initial = {}
682     if login:
683         user = get_object_or_404(User, login=login)
684         if not user.is_admin_by(request.user.id):
685             return HttpResponseForbidden('403 Forbidden')
686     else:
687         user = User()
688         user.father_id = request.user.id;
689     initial['login'] = user.login
690     initial['name'] = user.name
691     initial['email'] = user.email
692     initial['phone'] = user.phone
693     if request.method == 'POST':
694         form = UserEditForm(request.POST, initial=initial)
695         if form.is_valid():
696             user.login = form.cleaned_data['login']
697             user.name = form.cleaned_data['name']
698             user.email = form.cleaned_data['email']
699             user.phone = form.cleaned_data['phone']
700             user.save()
701             user.check_sandbox_access(request.user)
702             return HttpResponseRedirect('/user/')
703     else: # GET
704         form = UserEditForm(initial=initial)
705
706     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
707
708
709 class ChangePasswordForm(forms.Form):
710     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
711     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
712
713     def clean_generic_password(self, field_name):
714         password = self.cleaned_data[field_name]
715         try:
716             crack.FascistCheck(password)
717         except ValueError, err:
718             raise forms.ValidationError(err.message)
719         return password
720
721     def clean_new_password(self):
722         return self.clean_generic_password('new_password')
723
724     def clean_new_password_check(self):
725         return self.clean_generic_password('new_password_check')
726
727     def clean(self):
728         cleaned_data = self.cleaned_data
729         pass1 = cleaned_data.get('new_password')
730         pass2 = cleaned_data.get('new_password_check')
731         if pass1 != pass2 and pass2:
732             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
733             del cleaned_data['new_password_check'] # FIXME
734         return cleaned_data
735
736
737 @http_authenticate(auth, 'ais')
738 def user_change_password(request, login):
739     user = get_object_or_404(User, login=login)
740     if not user.is_admin_by(request.user.id):
741         return HttpResponseForbidden('403 Forbidden')
742     if request.method == 'POST':
743         form = ChangePasswordForm(request.POST)
744         if form.is_valid():
745             user.set_password(form.cleaned_data['new_password'])
746             user.save()
747             return HttpResponseRedirect('/user/')
748     else: # GET
749         form = ChangePasswordForm()
750     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
751
752
753 @http_authenticate(auth, 'ais')
754 def user_delete(request, login):
755     user = get_object_or_404(User, login=login)
756     if not user.is_admin_by(request.user.id):
757         return HttpResponseForbidden('403 Forbidden')
758     if request.REQUEST.get('confirm', None):
759         user.delete()
760         return HttpResponseRedirect('/user/')
761     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
762
763
764 def logout(request):
765     # TODO
766     return HttpResponse('Not implemented')
767     #response = render_to_response('logout.html', {}, RequestContext(request))
768     #return response
769
770 periods = ({
771     'name_tiny': '2h',
772     'name_long': '2 hours',
773     'seconds': 2*60*60
774     }, {
775     'name_tiny': '6h',
776     'name_long': '6 hours',
777     'seconds': 6*60*60,
778     'default': True,
779     }, {
780     'name_tiny': '2d',
781     'name_long': '2 days',
782     'seconds': 2*24*60*60
783     }, {
784     'name_tiny': '14d',
785     'name_long': '2 weeks',
786     'seconds': 14*24*60*60
787     }, {
788     'name_tiny': '90d',
789     'name_long': '3 monthes',
790     'seconds': 90*24*60*60
791     }, {
792     'name_tiny': '180d',
793     'name_long': '6 monthes',
794     'seconds': 180*24*60*60
795     })
796         
797 class StatsSelectorForm(forms.Form):
798     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
799     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
800     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
801
802 @http_authenticate(auth, 'ais')
803 def sources_index(request):
804     active_minutes = 5
805     peers_config = peers_get_config()
806     peers_display = []
807     for id4, peer in peers_config.iteritems():
808         peer['id4'] = id4
809         peer['id2'] = id4[2:]
810         peer['active'] = is_id4_active(id4, 60*active_minutes)
811         peers_display.append(peer)
812         
813     peers_display = sorted(peers_display, key=lambda k: k['id4'])
814
815     form = StatsSelectorForm()
816
817     return render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': active_minutes, 'form': form}, RequestContext(request))
818
819
820 @http_authenticate(auth, 'ais')
821 def sources_stats(request):
822     filter_peers = request.REQUEST.get('peers', None)
823     if filter_peers:
824         filter_peers = filter_peers.split(u',')
825
826     peers_config = peers_get_config()
827     peers_display = []
828
829     for id4, peer in peers_config.iteritems():
830         if filter_peers:
831             if unicode(id4) not in filter_peers:
832                 continue
833         peer['id4'] = id4
834         peers_display.append(peer)
835
836     peers_display = sorted(peers_display, key=lambda k: k['id4'])
837
838     filter_types = request.REQUEST.get('types', None)
839     if filter_types:
840         filter_types = filter_types.split(u',')
841     else:
842         filter_types = [ 'bytes', 'counts' ]
843     logging.error('filter_types=%s', filter_types)
844
845     filter_periods = request.REQUEST.get('periods', None)
846     if filter_periods:
847         display_periods = []
848         for period_name in filter_periods.split(u','):
849             for period in periods:
850                 if period['name_tiny'] == period_name:
851                     display_periods.append(period)
852     else:
853         display_periods = periods
854     #logging.error('display_periods=%s', display_periods)
855
856
857     now = int(get_timestamp())
858     for config in peers_display:
859         id4 = config['id4']
860         for period in periods:
861             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
862                 '--lazy', \
863                 '-l', '0', \
864                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
865                 '--start', '%d' % (now - period['seconds']), \
866                 '--end', '%d' % now, \
867                 '--vertical-label', 'bps', \
868                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
869                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
870                 'CDEF:bits=bytes,8,*', \
871                 'CDEF:rawbits=rawbytes,8,*', \
872                 'LINE:bits#00FF00:IP payload', \
873                 'LINE:rawbits#FF0000:IP with headers'
874             rrdtool.graph(*args)
875             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
876                 '--lazy', \
877                 '-l', '0', \
878                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
879                 '--start', '%d' % (now-period['seconds']), \
880                 '--end', '%d' % now, \
881                 '--vertical-label', 'Hz', \
882                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
883                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
884                 'LINE:packets#FF0000:input packets', \
885                 'LINE:lines#00FF00:AIVDM lines'
886             rrdtool.graph(*args)
887     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))
888
889
890 @http_authenticate(auth, 'ais')
891 def news(request, page):
892     NEWS_PER_PAGE = 10
893     if page:
894         page = int(page)
895     else:
896         page = 1
897     # TODO __future__
898     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) / NEWS_PER_PAGE)
899     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
900     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
901
902 @http_authenticate(auth, 'ais')
903 def news_atom(request):
904     from django.db import connection
905
906     news = News.objects.order_by('-created')
907
908     cursor = connection.cursor()
909     cursor.execute("SELECT MAX(updated) FROM news")
910     row = cursor.fetchone()
911     last_update = row[0]
912
913     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')