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