Automatically grant access to sandbox fleet on user creation
[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     # TODO: update access_datetime
41     user.update_access_datetime()
42     return user
43
44
45 @http_authenticate(auth, 'ais')
46 def index(request):
47     news = News.objects.order_by('-created')[:5]
48     return render_to_response('index.html', {'news':news}, RequestContext(request))
49
50
51 class VesselSearchForm(forms.Form):
52     def country_choices():
53         choices = {}
54         for mid, countryname in COUNTRIES_MID.iteritems():
55             if choices.has_key(countryname):
56                 choices[countryname] += u','+unicode(mid)
57             else:
58                 choices[countryname] = unicode(mid)
59         choices = [ (countryname, mids) for mids, countryname in choices.iteritems() ]
60         choices = sorted(choices, key=operator.itemgetter(1))
61         return [(u'', u'Any')] + choices
62
63     mmsi = forms.CharField(max_length=9, required=False)
64     name = forms.CharField(max_length=20, required=False)
65     imo = forms.IntegerField(required=False)
66     callsign = forms.CharField(max_length=7, required=False)
67     flag = forms.ChoiceField(choices=country_choices(), required=False)
68     destination = forms.CharField(max_length=20, required=False)
69
70
71     def clean(self):
72         cleaned_data = self.cleaned_data
73         for value in cleaned_data.values():
74             if value:
75                 return cleaned_data
76         raise forms.ValidationError("You must enter at least one criteria")
77
78     def clean_mmsi(self):
79         mmsi = self.cleaned_data['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 @http_authenticate(auth, 'ais')
366 def vessel_track(request, strmmsi):
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     value = kml_to_kmz(format_boat_track(nmea_iterator))
381     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
382     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
383     return response
384
385
386 @http_authenticate(auth, 'ais')
387 def vessel_animation(request, strmmsi):
388     ndays = request.REQUEST.get('ndays', 90)
389     try:
390         ndays = int(ndays)
391     except ValueError:
392         ndays = 90
393     grain = request.REQUEST.get('grain', 3600)
394     try:
395         grain = int(grain)
396     except ValueError:
397         grain = 3600
398     date_end = datetime.utcnow()
399     date_start = date_end - timedelta(ndays)
400     nmea_iterator = NmeaFeeder(strmmsi, date_end, date_start, granularity=grain)
401     value = kml_to_kmz(format_boat_intime(nmea_iterator))
402     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
403     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
404     return response
405
406
407 @http_authenticate(auth, 'ais')
408 def vessel_csv(request, strmmsi):
409     ndays = request.REQUEST.get('ndays', 90)
410     try:
411         ndays = int(ndays)
412     except ValueError:
413         ndays = 90
414     grain = request.REQUEST.get('grain', 3600)
415     try:
416         grain = int(grain)
417     except ValueError:
418         grain = 3600
419     date_end = datetime.utcnow()
420     date_start = date_end - timedelta(ndays)
421     nmea_iterator = NmeaFeeder(strmmsi, date_end, date_start, granularity=grain)
422     
423     value = StringIO()
424     output = csv.writer(value)
425     output.writerow(Nmea.csv_headers)
426     for nmea in nmea_iterator:
427         output.writerow(nmea.get_dump_row())
428     response = HttpResponse(value.getvalue(), mimetype='text/csv; charset="UTF-8"')
429     response['Content-Disposition'] = 'attachment; filename=%s.csv' % strmmsi
430     return response
431
432
433 @http_authenticate(auth, 'ais')
434 def fleets(request):
435     fleetusers = request.user.fleetuser_set.order_by('fleet')
436     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
437
438
439 @http_authenticate(auth, 'ais')
440 def fleet(request, fleetname):
441     fleet = get_object_or_404(Fleet, pk=fleetname)
442     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
443         return HttpResponseForbidden('<h1>Forbidden</h1>')
444     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
445
446
447 class FleetEditForm(forms.Form):
448     description = forms.CharField(widget=forms.Textarea)
449
450 @http_authenticate(auth, 'ais')
451 def fleet_edit(request, fleetname):
452     fleet = get_object_or_404(Fleet, pk=fleetname)
453     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
454         return HttpResponseForbidden('<h1>Forbidden</h1>')
455
456     initial = {}
457     initial['description'] = fleet.description
458     if request.method == 'POST':
459         form = FleetEditForm(request.POST, initial=initial)
460         if form.is_valid():
461             fleet.description = form.cleaned_data['description']
462             fleet.save()
463             request.user.info('Fleet description updated')
464             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
465     else: # GET
466         form = FleetEditForm(initial=initial)
467     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
468
469
470 @http_authenticate(auth, 'ais')
471 def fleet_vessels(request, fleetname):
472     fleet = get_object_or_404(Fleet, pk=fleetname)
473     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
474         return HttpResponseForbidden('<h1>Forbidden</h1>')
475     vessels = fleet.vessel.all()
476     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
477
478
479 @http_authenticate(auth, 'ais')
480 def fleet_vessel_add(request, fleetname):
481     fleet = get_object_or_404(Fleet, pk=fleetname)
482     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
483         return HttpResponseForbidden('<h1>Forbidden</h1>')
484     strmmsi = request.REQUEST['mmsi']
485     mmsi = strmmsi_to_mmsi(strmmsi)
486     try:
487         vessel = Vessel.objects.get(pk=mmsi)
488     except Vessel.DoesNotExist:
489         request.user.info('No such vessel', category_id='error')
490     else:
491         try:
492             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
493         except FleetVessel.DoesNotExist:
494             FleetVessel(fleet=fleet, vessel=vessel).save()
495             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
496         else:
497             request.user.info('Vessel with MMSI %s is already in that fleet' % strmmsi, category_id='error')
498     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
499
500
501 class FleetAddVessel(forms.Form):
502     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
503     #name = forms.CharField(max_length=20, required=False)
504     #imo = forms.IntegerField(required=False)
505     #callsign = forms.CharField(max_length=7, required=False)
506     #destination = forms.CharField(max_length=20, required=False)
507     def clean(self):
508         cleaned_data = self.cleaned_data
509         for value in cleaned_data.values():
510             if value:
511                 return cleaned_data
512         raise forms.ValidationError("You must enter at least one criteria")
513
514 @http_authenticate(auth, 'ais')
515 def fleet_vessel_add2(request, fleetname):
516     fleet = get_object_or_404(Fleet, pk=fleetname)
517     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
518         return HttpResponseForbidden('<h1>Forbidden</h1>')
519     if request.method == 'POST' or request.META['QUERY_STRING']:
520         form = FleetAddVessel(request.REQUEST)
521         if form.is_valid():
522             data = form.cleaned_data
523             result = []
524             a_strmmsi = request.REQUEST['mmsi']
525             if a_strmmsi:
526                 for strmmsi in a_strmmsi.split('\n'):
527                     strmmsi = strmmsi.strip('\r')
528                     if not strmmsi:
529                         continue
530                     try:
531                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
532                     except AssertionError:
533                         result.append('Invalid mmsi %s' % strmmsi)
534                         continue
535                     try:
536                         vessel = Vessel.objects.get(pk=sqlmmsi)
537                     except Vessel.DoesNotExist:
538                         result.append('No vessel with MMSI '+strmmsi)
539                         continue
540                     try:
541                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
542                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
543                     except FleetVessel.DoesNotExist:
544                         FleetVessel(fleet=fleet, vessel=vessel).save()
545                         result.append('Vessel with MMSI %s added' % strmmsi)
546
547             return HttpResponse('<br>'.join(result))
548     else: # GET
549         form = FleetAddVessel()
550
551     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
552
553
554 @http_authenticate(auth, 'ais')
555 def fleet_users(request, fleetname):
556     fleet = get_object_or_404(Fleet, pk=fleetname)
557     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
558         return HttpResponseForbidden('<h1>Forbidden</h1>')
559
560     message = u''
561     if request.method == 'POST' or request.META['QUERY_STRING']:
562         action = request.REQUEST['action']
563         userlogin = request.REQUEST['user']
564         try:
565             user = User.objects.get(login=userlogin)
566         except User.DoesNotExist:
567             message = u'User %s does not exist.' % userlogin
568         else:
569             if action == u'add':
570                 try:
571                     fu = FleetUser.objects.get(fleet=fleet, user=user)
572                     message = u'User %s already has access.' % user.login
573                 except FleetUser.DoesNotExist:
574                     FleetUser(fleet=fleet, user=user).save()
575                     #TODO log
576                     request.user.info(u'Granted access to user %s.' % user.login)
577             elif action == u'revoke':
578                 try:
579                     fu = FleetUser.objects.get(fleet=fleet, user=user)
580                     fu.delete()
581                     #TODO log
582                     request.user.info(u'Revoked access to user %s.' % user.login)
583                 except FleetUser.DoesNotExist:
584                     message = u'User %s didn\'t have access.' % user.login
585             else:
586                 message = u'Unknown action %s' % action
587
588     fleetusers = fleet.fleetuser_set.all()
589     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
590     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers, 'message': message }, RequestContext(request))
591
592
593 @http_authenticate(auth, 'ais')
594 def fleet_lastpos(request, fleetname):
595     fleet = get_object_or_404(Fleet, pk=fleetname)
596     if not FleetUser.objects.filter(fleet=fleetname, user=request.user.id).all():
597         return HttpResponseForbidden('<h1>Forbidden</h1>')
598     fleet_uset = load_fleet_to_uset(fleetname)
599     # = set([mmsi_to_strmmsi(vessel.mmsi) for vessel in fleet.vessel.all()])
600     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
601     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
602     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
603     return response
604
605
606 @http_authenticate(auth, 'ais')
607 def users(request):
608     users = User.objects.order_by('name')
609     for user in users:
610         user.admin_ok = user.is_admin_by(request.user.id)
611     if request.REQUEST.has_key('showtree'):
612         local_users = {}
613         for user in users:
614             user.children = []
615             local_users[user.id] = user
616         for user in users:
617             if user.father_id == None:
618                 root = user
619             else:
620                 local_users[user.father_id].children.append(user)
621         assert root
622         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
623     else:
624         return render_to_response('users.html', {'users':users}, RequestContext(request))
625
626 phone_re = re.compile('^\\+.+')
627
628 class UserEditForm(forms.Form):
629     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
630         error_message ='Login must only contain letters, numbers and underscores')
631     name = forms.CharField(max_length=50)
632     email = forms.EmailField()
633     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
634         error_message ='Phones must start with a \'+\'')
635     def __init__(self, *args, **kargs):
636         forms.Form.__init__(self, *args, **kargs)
637         self.old_login = kargs['initial']['login']
638     def clean_login(self):
639         new_login = self.cleaned_data['login']
640         if new_login != self.old_login:
641             if User.objects.filter(login=new_login).count():
642                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
643             if new_login == u'add':
644                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
645         return new_login
646
647 @http_authenticate(auth, 'ais')
648 def user_detail(request, login):
649     user = get_object_or_404(User, login=login)
650     user.admin_ok = user.is_admin_by(request.user.id)
651     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
652
653 @http_authenticate(auth, 'ais')
654 def user_edit(request, login):
655     initial = {}
656     if login:
657         user = get_object_or_404(User, login=login)
658         if not user.is_admin_by(request.user.id):
659             return HttpResponseForbidden('403 Forbidden')
660     else:
661         user = User()
662         user.father_id = request.user.id;
663     initial['login'] = user.login
664     initial['name'] = user.name
665     initial['email'] = user.email
666     initial['phone'] = user.phone
667     if request.method == 'POST':
668         form = UserEditForm(request.POST, initial=initial)
669         if form.is_valid():
670             user.login = form.cleaned_data['login']
671             user.name = form.cleaned_data['name']
672             user.email = form.cleaned_data['email']
673             user.phone = form.cleaned_data['phone']
674             user.save()
675             user.check_sandbox_access(request.user)
676             return HttpResponseRedirect('/user/')
677     else: # GET
678         form = UserEditForm(initial=initial)
679
680     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
681
682
683 class ChangePasswordForm(forms.Form):
684     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
685     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
686
687     def clean_generic_password(self, field_name):
688         password = self.cleaned_data[field_name]
689         try:
690             crack.FascistCheck(password)
691         except ValueError, err:
692             raise forms.ValidationError(err.message)
693         return password
694
695     def clean_new_password(self):
696         return self.clean_generic_password('new_password')
697
698     def clean_new_password_check(self):
699         return self.clean_generic_password('new_password_check')
700
701     def clean(self):
702         cleaned_data = self.cleaned_data
703         pass1 = cleaned_data.get('new_password')
704         pass2 = cleaned_data.get('new_password_check')
705         if pass1 != pass2 and pass2:
706             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
707             del cleaned_data['new_password_check'] # FIXME
708         return cleaned_data
709
710
711 @http_authenticate(auth, 'ais')
712 def user_change_password(request, login):
713     user = get_object_or_404(User, login=login)
714     if not user.is_admin_by(request.user.id):
715         return HttpResponseForbidden('403 Forbidden')
716     if request.method == 'POST':
717         form = ChangePasswordForm(request.POST)
718         if form.is_valid():
719             user.set_password(form.cleaned_data['new_password'])
720             user.save()
721             return HttpResponseRedirect('/user/')
722     else: # GET
723         form = ChangePasswordForm()
724     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
725
726
727 @http_authenticate(auth, 'ais')
728 def user_delete(request, login):
729     user = get_object_or_404(User, login=login)
730     if not user.is_admin_by(request.user.id):
731         return HttpResponseForbidden('403 Forbidden')
732     if request.REQUEST.get('confirm', None):
733         user.delete()
734         return HttpResponseRedirect('/user/')
735     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
736
737
738 def logout(request):
739     # TODO
740     return HttpResponse('Not implemented')
741     #response = render_to_response('logout.html', {}, RequestContext(request))
742     #return response
743
744 periods = ({
745     'name_tiny': '2h',
746     'name_long': '2 hours',
747     'seconds': 2*60*60
748     }, {
749     'name_tiny': '6h',
750     'name_long': '6 hours',
751     'seconds': 6*60*60,
752     'default': True,
753     }, {
754     'name_tiny': '2d',
755     'name_long': '2 days',
756     'seconds': 2*24*60*60
757     }, {
758     'name_tiny': '14d',
759     'name_long': '2 weeks',
760     'seconds': 14*24*60*60
761     }, {
762     'name_tiny': '90d',
763     'name_long': '3 monthes',
764     'seconds': 90*24*60*60
765     }, {
766     'name_tiny': '180d',
767     'name_long': '6 monthes',
768     'seconds': 180*24*60*60
769     })
770         
771 class StatsSelectorForm(forms.Form):
772     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
773     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
774     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
775
776 @http_authenticate(auth, 'ais')
777 def sources_index(request):
778     active_minutes = 5
779     peers_config = peers_get_config()
780     peers_display = []
781     for id4, peer in peers_config.iteritems():
782         peer['id4'] = id4
783         peer['id2'] = id4[2:]
784         peer['active'] = is_id4_active(id4, 60*active_minutes)
785         peers_display.append(peer)
786         
787     peers_display = sorted(peers_display, key=lambda k: k['id4'])
788
789     form = StatsSelectorForm()
790
791     return render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': active_minutes, 'form': form}, RequestContext(request))
792
793
794 @http_authenticate(auth, 'ais')
795 def sources_stats(request):
796     filter_peers = request.REQUEST.get('peers', None)
797     if filter_peers:
798         filter_peers = filter_peers.split(u',')
799
800     peers_config = peers_get_config()
801     peers_display = []
802
803     for id4, peer in peers_config.iteritems():
804         if filter_peers:
805             if unicode(id4) not in filter_peers:
806                 continue
807         peer['id4'] = id4
808         peers_display.append(peer)
809
810     peers_display = sorted(peers_display, key=lambda k: k['id4'])
811
812     filter_types = request.REQUEST.get('types', None)
813     if filter_types:
814         filter_types = filter_types.split(u',')
815     else:
816         filter_types = [ 'bytes', 'counts' ]
817     logging.error('filter_types=%s', filter_types)
818
819     filter_periods = request.REQUEST.get('periods', None)
820     if filter_periods:
821         display_periods = []
822         for period_name in filter_periods.split(u','):
823             for period in periods:
824                 if period['name_tiny'] == period_name:
825                     display_periods.append(period)
826     else:
827         display_periods = periods
828     #logging.error('display_periods=%s', display_periods)
829
830
831     now = int(get_timestamp())
832     for config in peers_display:
833         id4 = config['id4']
834         for period in periods:
835             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
836                 '--lazy', \
837                 '-l', '0', \
838                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
839                 '--start', '%d' % (now - period['seconds']), \
840                 '--end', '%d' % now, \
841                 '--vertical-label', 'bps', \
842                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
843                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
844                 'CDEF:bits=bytes,8,*', \
845                 'CDEF:rawbits=rawbytes,8,*', \
846                 'LINE:bits#00FF00:IP payload', \
847                 'LINE:rawbits#FF0000:IP with headers'
848             rrdtool.graph(*args)
849             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
850                 '--lazy', \
851                 '-l', '0', \
852                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
853                 '--start', '%d' % (now-period['seconds']), \
854                 '--end', '%d' % now, \
855                 '--vertical-label', 'Hz', \
856                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
857                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
858                 'LINE:packets#FF0000:input packets', \
859                 'LINE:lines#00FF00:AIVDM lines'
860             rrdtool.graph(*args)
861     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))
862
863
864 @http_authenticate(auth, 'ais')
865 def news(request, page):
866     NEWS_PER_PAGE = 10
867     if page:
868         page = int(page)
869     else:
870         page = 1
871     # TODO __future__
872     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) / NEWS_PER_PAGE)
873     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
874     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
875
876 @http_authenticate(auth, 'ais')
877 def news_atom(request):
878     from django.db import connection
879
880     news = News.objects.order_by('-created')
881
882     cursor = connection.cursor()
883     cursor.execute("SELECT MAX(updated) FROM news")
884     row = cursor.fetchone()
885     last_update = row[0]
886
887     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')